hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
fa492905fb125ca0c75a842e3ef0c326fc54635d
395
cpp
C++
taint/src/riscv/targetcontext.cpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
taint/src/riscv/targetcontext.cpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
taint/src/riscv/targetcontext.cpp
ClasSun9/riscv-dynamic-taint-analysis
8a96f5ea8d07580315253dc074f60955fc633da9
[ "MIT" ]
null
null
null
#include "./targetcontext.hpp" namespace riscv { addr_t targetcontext::pc() { return _pc; } const instruction& targetcontext::insn() { return _insn; } const registerset& targetcontext::regs() { return _regs; } targetcontext::targetcontext() { } targetcontext::targetcontext(addr_t pc, instruction insn, registerset regs) : _pc(pc) , _insn(insn) , _regs(regs) { } }
17.173913
76
0.678481
ClasSun9
fa4ad8c3c50f540ea9be50d2aababf37cee4df09
1,216
cpp
C++
Sources/AGEngine/Utils/RWLock.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
47
2015-03-29T09:44:25.000Z
2020-11-30T10:05:56.000Z
Sources/AGEngine/Utils/RWLock.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
313
2015-01-01T18:16:30.000Z
2015-11-30T07:54:07.000Z
Sources/AGEngine/Utils/RWLock.cpp
Another-Game-Engine/AGE
d5d9e98235198fe580a43007914f515437635830
[ "MIT" ]
9
2015-06-07T13:21:54.000Z
2020-08-25T09:50:07.000Z
#include "RWLock.hpp" #include "Debug.hpp" #include <thread> namespace AGE { RWLock::RWLock() { _sharedLock.store(0, std::memory_order_relaxed); _uniqueLock.store(false, std::memory_order_relaxed); } void RWLock::ReadLock() { while (_uniqueLock.exchange(true, std::memory_order_relaxed)) { std::this_thread::yield(); } _sharedLock.fetch_add(1, std::memory_order_relaxed); _uniqueLock.store(false, std::memory_order_relaxed); } void RWLock::ReadUnlock() { _sharedLock.fetch_sub(1, std::memory_order_relaxed); } void RWLock::WriteLock() { while (_uniqueLock.exchange(true, std::memory_order_relaxed)) { std::this_thread::yield(); } while (_sharedLock.load(std::memory_order_relaxed) > 0) { std::this_thread::yield(); } } void RWLock::WriteUnlock() { _uniqueLock.store(false, std::memory_order_relaxed); } // RWLockGuard RWLockGuard::RWLockGuard(RWLock &lock, bool exclusive) : _lock(lock) , _exclusive(exclusive) { if (_exclusive) { _lock.WriteLock(); } else { _lock.ReadLock(); } } RWLockGuard::~RWLockGuard() { if (_exclusive) { _lock.WriteUnlock(); } else { _lock.ReadUnlock(); } } // End RWLockGuard }
16
63
0.67352
Another-Game-Engine
fa4b496856d8b1dd0603e81b68db90914b6b423d
6,969
cpp
C++
model/mosesdecoder/moses/FF/GlobalLexicalModel.cpp
saeedesm/UNMT_AH
cc171bf66933b5c0ad8a0ab87e57f7364312a7df
[ "Apache-2.0" ]
3
2020-02-28T21:42:44.000Z
2021-03-12T13:56:16.000Z
tools/mosesdecoder-master/moses/FF/GlobalLexicalModel.cpp
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2020-11-06T14:40:10.000Z
2020-12-29T19:03:11.000Z
tools/mosesdecoder-master/moses/FF/GlobalLexicalModel.cpp
Pangeamt/nectm
6b84f048698f2530b9fdbb30695f2e2217c3fbfe
[ "Apache-2.0" ]
2
2019-11-26T05:27:16.000Z
2019-12-17T01:53:43.000Z
#include <fstream> #include "GlobalLexicalModel.h" #include "moses/StaticData.h" #include "moses/InputFileStream.h" #include "moses/TranslationOption.h" #include "moses/TranslationTask.h" #include "moses/FactorCollection.h" #include "util/exception.hh" using namespace std; namespace Moses { GlobalLexicalModel::GlobalLexicalModel(const std::string &line) : StatelessFeatureFunction(1, line) { std::cerr << "Creating global lexical model...\n"; ReadParameters(); // define bias word FactorCollection &factorCollection = FactorCollection::Instance(); m_bias = new Word(); const Factor* factor = factorCollection.AddFactor( Input, m_inputFactorsVec[0], "**BIAS**" ); m_bias->SetFactor( m_inputFactorsVec[0], factor ); } void GlobalLexicalModel::SetParameter(const std::string& key, const std::string& value) { if (key == "path") { m_filePath = value; } else if (key == "input-factor") { m_inputFactorsVec = Tokenize<FactorType>(value,","); } else if (key == "output-factor") { m_outputFactorsVec = Tokenize<FactorType>(value,","); } else { StatelessFeatureFunction::SetParameter(key, value); } } GlobalLexicalModel::~GlobalLexicalModel() { // delete words in the hash data structure DoubleHash::const_iterator iter; for(iter = m_hash.begin(); iter != m_hash.end(); iter++ ) { boost::unordered_map< const Word*, float, UnorderedComparer<Word>, UnorderedComparer<Word> >::const_iterator iter2; for(iter2 = iter->second.begin(); iter2 != iter->second.end(); iter2++ ) { delete iter2->first; // delete input word } delete iter->first; // delete output word } } void GlobalLexicalModel::Load(AllOptions::ptr const& opts) { m_options = opts; FactorCollection &factorCollection = FactorCollection::Instance(); const std::string& oFactorDelimiter = opts->output.factor_delimiter; const std::string& iFactorDelimiter = opts->input.factor_delimiter; VERBOSE(2, "Loading global lexical model from file " << m_filePath << endl); m_inputFactors = FactorMask(m_inputFactorsVec); m_outputFactors = FactorMask(m_outputFactorsVec); InputFileStream inFile(m_filePath); // reading in data one line at a time size_t lineNum = 0; string line; while(getline(inFile, line)) { ++lineNum; vector<string> token = Tokenize<string>(line, " "); if (token.size() != 3) { // format checking UTIL_THROW2("Syntax error at " << m_filePath << ":" << lineNum << ":" << line); } // create the output word Word *outWord = new Word(); vector<string> factorString = Tokenize( token[0], oFactorDelimiter ); for (size_t i=0 ; i < m_outputFactorsVec.size() ; i++) { const FactorDirection& direction = Output; const FactorType& factorType = m_outputFactorsVec[i]; const Factor* factor = factorCollection.AddFactor( direction, factorType, factorString[i] ); outWord->SetFactor( factorType, factor ); } // create the input word Word *inWord = new Word(); factorString = Tokenize( token[1], iFactorDelimiter ); for (size_t i=0 ; i < m_inputFactorsVec.size() ; i++) { const FactorDirection& direction = Input; const FactorType& factorType = m_inputFactorsVec[i]; const Factor* factor = factorCollection.AddFactor( direction, factorType, factorString[i] ); inWord->SetFactor( factorType, factor ); } // maximum entropy feature score float score = Scan<float>(token[2]); // std::cerr << "storing word " << *outWord << " " << *inWord << " " << score << endl; // store feature in hash DoubleHash::iterator keyOutWord = m_hash.find( outWord ); if( keyOutWord == m_hash.end() ) { m_hash[outWord][inWord] = score; } else { // already have hash for outword, delete the word to avoid leaks (keyOutWord->second)[inWord] = score; delete outWord; } } } void GlobalLexicalModel::InitializeForInput(ttasksptr const& ttask) { UTIL_THROW_IF2(ttask->GetSource()->GetType() != SentenceInput, "GlobalLexicalModel works only with sentence input."); Sentence const* s = reinterpret_cast<Sentence const*>(ttask->GetSource().get()); m_local.reset(new ThreadLocalStorage); m_local->input = s; } float GlobalLexicalModel::ScorePhrase( const TargetPhrase& targetPhrase ) const { const Sentence& input = *(m_local->input); float score = 0; for(size_t targetIndex = 0; targetIndex < targetPhrase.GetSize(); targetIndex++ ) { float sum = 0; const Word& targetWord = targetPhrase.GetWord( targetIndex ); VERBOSE(2,"glm " << targetWord << ": "); const DoubleHash::const_iterator targetWordHash = m_hash.find( &targetWord ); if( targetWordHash != m_hash.end() ) { SingleHash::const_iterator inputWordHash = targetWordHash->second.find( m_bias ); if( inputWordHash != targetWordHash->second.end() ) { VERBOSE(2,"*BIAS* " << inputWordHash->second); sum += inputWordHash->second; } boost::unordered_set< const Word*, UnorderedComparer<Word>, UnorderedComparer<Word> > alreadyScored; // do not score a word twice for(size_t inputIndex = 0; inputIndex < input.GetSize(); inputIndex++ ) { const Word& inputWord = input.GetWord( inputIndex ); if ( alreadyScored.find( &inputWord ) == alreadyScored.end() ) { SingleHash::const_iterator inputWordHash = targetWordHash->second.find( &inputWord ); if( inputWordHash != targetWordHash->second.end() ) { VERBOSE(2," " << inputWord << " " << inputWordHash->second); sum += inputWordHash->second; } alreadyScored.insert( &inputWord ); } } } // Hal Daume says: 1/( 1 + exp [ - sum_i w_i * f_i ] ) VERBOSE(2," p=" << FloorScore( log(1/(1+exp(-sum))) ) << endl); score += FloorScore( log(1/(1+exp(-sum))) ); } return score; } float GlobalLexicalModel::GetFromCacheOrScorePhrase( const TargetPhrase& targetPhrase ) const { LexiconCache& m_cache = m_local->cache; const LexiconCache::const_iterator query = m_cache.find( &targetPhrase ); if ( query != m_cache.end() ) { return query->second; } float score = ScorePhrase( targetPhrase ); m_cache.insert( pair<const TargetPhrase*, float>(&targetPhrase, score) ); //VERBOSE(2, "add to cache " << targetPhrase << ": " << score << endl); return score; } void GlobalLexicalModel::EvaluateWithSourceContext(const InputType &input , const InputPath &inputPath , const TargetPhrase &targetPhrase , const StackVec *stackVec , ScoreComponentCollection &scoreBreakdown , ScoreComponentCollection *estimatedScores) const { scoreBreakdown.PlusEquals( this, GetFromCacheOrScorePhrase(targetPhrase) ); } bool GlobalLexicalModel::IsUseable(const FactorMask &mask) const { for (size_t i = 0; i < m_outputFactors.size(); ++i) { if (m_outputFactors[i]) { if (!mask[i]) { return false; } } } return true; } }
34.845
135
0.671402
saeedesm
fa51378664eecd4a1bb9ef10d04f177fb4fe41a2
2,335
cpp
C++
cmfe/compute_sdk/examples/sample/kernel.cpp
dmitryryintel/cm-compiler
1ef7651dc1c33d3e4853f8779d6a720e45e20e19
[ "Intel", "MIT" ]
115
2018-02-01T18:56:44.000Z
2022-03-21T13:23:00.000Z
cmfe/compute_sdk/examples/sample/kernel.cpp
dmitryryintel/cm-compiler
1ef7651dc1c33d3e4853f8779d6a720e45e20e19
[ "Intel", "MIT" ]
27
2018-09-17T17:49:49.000Z
2021-11-03T04:31:51.000Z
cmfe/compute_sdk/examples/sample/kernel.cpp
dmitryryintel/cm-compiler
1ef7651dc1c33d3e4853f8779d6a720e45e20e19
[ "Intel", "MIT" ]
55
2018-02-01T07:11:49.000Z
2022-03-04T01:20:23.000Z
/*===================== begin_copyright_notice ================================== Copyright (c) 2021, Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ======================= end_copyright_notice ==================================*/ #include <cm/cm.h> #ifdef SHIM #include "shim_support.h" #else #define SHIM_API_EXPORT #endif extern "C" SHIM_API_EXPORT void vector_add(SurfaceIndex, SurfaceIndex, SurfaceIndex); // shim layer (CM kernel, OpenCL runtime, GPU) #ifdef SHIM EXPORT_SIGNATURE(vector_add); #endif #define SURFACE_TYPE [[type("buffer_t")]] #if defined(SHIM) || defined(CMRT_EMU) #undef SURFACE_TYPE #define SURFACE_TYPE #endif #define SZ 16 _GENX_MAIN_ void vector_add( SurfaceIndex isurface1 SURFACE_TYPE, SurfaceIndex isurface2 SURFACE_TYPE, SurfaceIndex osurface SURFACE_TYPE ) { vector<int, SZ> ivector1; vector<int, SZ> ivector2; vector<int, SZ> ovector; //printf("gid(0)=%d, gid(1)=%d, lid(0)=%d, lid(1)=%d\n", cm_group_id(0), cm_group_id(1), cm_local_id(0), cm_local_id(1)); unsigned offset = sizeof(unsigned) * SZ * cm_group_id(0); // // read-in the arguments read(isurface1, offset, ivector1); read(isurface2, offset, ivector2); // perform addition ovector = ivector1 + ivector2; // write-out the results write (osurface, offset, ovector); }
34.850746
125
0.71606
dmitryryintel
fa54286fcc62fa3538bbf968e29a5b4093dfce47
8,310
cpp
C++
examples/fast_fourier_transform/test.cpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
10
2018-10-03T09:19:48.000Z
2021-09-15T14:46:32.000Z
examples/fast_fourier_transform/test.cpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
1
2019-09-24T17:38:25.000Z
2019-09-24T17:38:25.000Z
examples/fast_fourier_transform/test.cpp
drichmond/HOPS
9684c0c9ebe5511fe0c202219a0bcd51fbf61079
[ "BSD-3-Clause" ]
null
null
null
// ---------------------------------------------------------------------- // Copyright (c) 2018, The Regents of the University of California 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 Regents of the University of California // 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 REGENTS OF THE // UNIVERSITY OF CALIFORNIA 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 <iostream> #include <complex> #include "utility.hpp" #include "fft.hpp" #ifdef BIT_ACCURATE #include "hls_math.h" #include "ap_fixed.h" #include "ap_int.h" #define DTYPE ap_fixed<32, 16, AP_RND> #else #define DTYPE float #endif #define LOG_LIST_LENGTH 4 #define LIST_LENGTH (1<<LOG_LIST_LENGTH) std::array<std::complex<DTYPE>, LIST_LENGTH> fft_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE return loop::fft(IN); } std::array<std::complex<DTYPE>, LIST_LENGTH> bitreverse_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE return loop::bitreverse(IN); } std::array<std::complex<DTYPE>, LIST_LENGTH> nptfft_loop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH/2> const& L, std::array<std::complex<DTYPE>, LIST_LENGTH/2> const& R){ return loop::nPtFFT(L, R); } std::array<std::complex<DTYPE>, LIST_LENGTH> fft_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> IN){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE #pragma HLS_INLINE return fft(IN); } std::array<std::complex<DTYPE>, LIST_LENGTH> bitreverse_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH> const& IN){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=IN._M_instance COMPLETE return bitreverse(IN); } std::array<std::complex<DTYPE>, LIST_LENGTH> nptfft_hop_synth(std::array<std::complex<DTYPE>, LIST_LENGTH/2> L, std::array<std::complex<DTYPE>, LIST_LENGTH/2> R){ #pragma HLS PIPELINE #pragma HLS ARRAY_PARTITION variable=L._M_instance COMPLETE #pragma HLS ARRAY_PARTITION variable=R._M_instance COMPLETE return nPtFFT(L, R); } void bit_reverse(DTYPE X_R[LIST_LENGTH], DTYPE X_I[LIST_LENGTH]){ for(unsigned int t = 0; t < LIST_LENGTH; t++){ DTYPE temp; unsigned int b = 0; for(int j = 0; j < LOG_LIST_LENGTH; j++){ b = b << 1; b |= ((t >> j) &1); } if(t > b){ temp = X_R[t]; X_R[t] = X_R[b]; X_R[b] = temp; temp = X_I[t]; X_I[t] = X_I[b]; X_I[b] = temp; } } } void fft(DTYPE X_R[LIST_LENGTH], DTYPE X_I[LIST_LENGTH]) { DTYPE temp_R; /*temporary storage complex variable*/ DTYPE temp_I; /*temporary storage complex variable*/ int i,j,k; /* loop indexes */ int i_lower; /* Index of lower point in butterfly */ int step; int stage; int DFTpts; int BFSkip; /*Butterfly Width*/ int N2 = LIST_LENGTH>>1; /* N2=N>>1 */ /*=====================BEGIN BIT REVERSAL===========================*/ unsigned int t, b; DTYPE temp; bit_reverse(X_R, X_I); /*++++++++++++++++++++++END OF BIT REVERSAL++++++++++++++++++++++++++*/ /*=======================BEGIN: FFT=========================*/ // Do M stages of butterflies step=N2; DTYPE a, e, c, s; int counter; stages: for(stage=1; stage<= LOG_LIST_LENGTH; ++stage){ DFTpts = 1 << stage; // DFT = 2^stage = points in sub DFT BFSkip = DFTpts/2; // Butterfly WIDTHS in sub-DFT k=0; e = -2*M_PI/DFTpts; a = 0.0; counter = 0; // Perform butterflies for j-th stage butterfly: for(j=0; j<BFSkip; ++j){ c = cos((double)a); s = sin((double)a); // Compute butterflies that use same W**k DFTpts: for(i=j; i<LIST_LENGTH; i += DFTpts){ counter ++; i_lower = i + BFSkip; //index of lower point in butterfly //printf("%d %d %d a:%4f \tr:%4f \ti:%4f \trl:%4f \til:%4f\n", stage, i, i_lower, a, X_R[i], X_I[i], X_R[i_lower], X_I[i_lower]); temp_R = X_R[i_lower]*c+ X_I[i_lower]*s; temp_I = X_I[i_lower]*c- X_R[i_lower]*s; X_R[i_lower] = X_R[i] - temp_R; X_I[i_lower] = X_I[i] - temp_I; X_R[i] = X_R[i] + temp_R; X_I[i] = X_I[i] + temp_I; } a = a + e; k+=step; } step=step/2; } } int fft_test(){ std::array<std::complex<DTYPE>, LIST_LENGTH> in, out; DTYPE gold_real[LIST_LENGTH]; DTYPE gold_imag[LIST_LENGTH]; for(int i = 0; i < LIST_LENGTH; i ++){ in[i] = {(DTYPE)(i + 1), (DTYPE)0}; gold_real[i] = i + 1; gold_imag[i] = 0; } fft(gold_real, gold_imag); out = fft_hop_synth(in); for(int i = 0; i < LIST_LENGTH; i ++){ if(std::abs(float(gold_real[i] - out[i].real())) > .25){ std::cout << "Error! Recursive Real FFT Values at index " << i << "did not match" << std::endl; return -1; } if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){ std::cout << "Error! Recursive Imaginary FFT Values at index " << i << "did not match" << std::endl; return -1; } } out = fft_loop_synth(in); for(int i = 0; i < LIST_LENGTH; i ++){ if(std::abs(float(gold_real[i] - out[i].real())) > .25){ std::cout << "Error! Loop Real FFT Values at index " << i << "did not match" << std::endl; return -1; } if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){ std::cout << "Error! Loop Imaginary FFT Values at index " << i << "did not match" << std::endl; return -1; } } std::cout << "Passed FFT tests!" << std::endl; return 0; } int bitreverse_test(){ std::array<std::complex<DTYPE>, LIST_LENGTH> in, out; DTYPE gold_real[LIST_LENGTH]; DTYPE gold_imag[LIST_LENGTH]; for(int i = 0; i < LIST_LENGTH; i ++){ in[i] = {(DTYPE)(i + 1), (DTYPE)0}; gold_real[i] = i + 1; gold_imag[i] = 0; } bit_reverse(gold_real, gold_imag); out = bitreverse_hop_synth(in); for(int i = 0; i < LIST_LENGTH; i ++){ if(std::abs(float(gold_real[i] - out[i].real())) > .25){ std::cout << "Error! Loop Real Bitreverse Values at index " << i << "did not match" << std::endl; return -1; } if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){ std::cout << "Error! Loop Imaginary Bitreverse Values at index " << i << "did not match" << std::endl; return -1; } } out = bitreverse_loop_synth(in); for(int i = 0; i < LIST_LENGTH; i ++){ if(std::abs(float(gold_real[i] - out[i].real())) > .25){ std::cout << "Error! Loop Real Bitreverse Values at index " << i << "did not match" << std::endl; return -1; } if(std::abs(float(gold_imag[i] - out[i].imag())) > .25){ std::cout << "Error! Loop Imaginary Bitreverse Values at index " << i << "did not match" << std::endl; return -1; } } std::cout << "Passed Bitreverse tests!" << std::endl; return 0; } int main(){ int err; if((err = bitreverse_test())){ return err; } if((err = fft_test())){ return err; } std::cout << "FFT Tests Passed!" << std::endl; return 0; }
30.43956
162
0.633213
drichmond
fa594fe597bfb13624c70b7b714310278eecc85b
776
hpp
C++
android-28/javax/security/auth/SubjectDomainCombiner.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/javax/security/auth/SubjectDomainCombiner.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/javax/security/auth/SubjectDomainCombiner.hpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#pragma once #include "../../../JObject.hpp" class JArray; class JArray; class JString; namespace java::security { class ProtectionDomain; } namespace javax::security::auth { class Subject; } namespace javax::security::auth { class SubjectDomainCombiner : public JObject { public: // Fields // QJniObject forward template<typename ...Ts> explicit SubjectDomainCombiner(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {} SubjectDomainCombiner(QJniObject obj); // Constructors SubjectDomainCombiner(javax::security::auth::Subject arg0); // Methods JArray combine(JArray arg0, JArray arg1) const; javax::security::auth::Subject getSubject() const; }; } // namespace javax::security::auth
20.972973
162
0.716495
YJBeetle
fa5f68bd119be7aae46a424a7fce80d94573cbae
551
cpp
C++
Sources/Pipeline/RenderPass.cpp
IvanPleshkov/RedLiliumEngine
5e7c14d9c750db8054bde53b772e30e3682c2f1d
[ "Apache-2.0" ]
null
null
null
Sources/Pipeline/RenderPass.cpp
IvanPleshkov/RedLiliumEngine
5e7c14d9c750db8054bde53b772e30e3682c2f1d
[ "Apache-2.0" ]
1
2019-02-09T09:53:01.000Z
2019-02-09T09:53:01.000Z
Sources/Pipeline/RenderPass.cpp
IvanPleshkov/RedLiliumEngine
5e7c14d9c750db8054bde53b772e30e3682c2f1d
[ "Apache-2.0" ]
null
null
null
#include "pch.h" #include "RenderPass.h" #include "RenderPipeline.h" using namespace RED_LILIUM_NAMESPACE; RenderPass::RenderPass(ptr<RenderPipeline> pipeline) : RedLiliumObject() , m_pipeline(pipeline) {} ptr<RenderDevice> RenderPass::GetRenderDevice() { return m_pipeline->m_renderDevice; } const std::vector<ptr<const CameraComponent>>& RenderPass::GetCameraComponents() const { return m_pipeline->m_cameraComponents; } const std::vector<RenderComponentsPair>& RenderPass::GetMeshRenderers() const { return m_pipeline->m_meshRenderers; }
21.192308
86
0.787659
IvanPleshkov
fa60e041eac01f3fb44db8322fce99f975a32b55
926
cpp
C++
OOP - Laborator 9/Problema 1/Problema 1/main.cpp
alexrobert02/oop-2022
277655132fb8618b1ce1bd4bb53edc147a53028b
[ "MIT" ]
null
null
null
OOP - Laborator 9/Problema 1/Problema 1/main.cpp
alexrobert02/oop-2022
277655132fb8618b1ce1bd4bb53edc147a53028b
[ "MIT" ]
null
null
null
OOP - Laborator 9/Problema 1/Problema 1/main.cpp
alexrobert02/oop-2022
277655132fb8618b1ce1bd4bb53edc147a53028b
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <vector> #include <map> #include "map.h" int main() { Map<int, const char*> m; m[10] = "C++"; m[20] = "test"; m[30] = "Poo"; for (auto [key, value, index] : m) { printf("Index:%d, Key=%d, Value=%s\n", index, key, value); } m[20] = "result"; for (auto [key, value, index] : m) { printf("Index:%d, Key=%d, Value=%s\n", index, key, value); } Map<int, const char*> n; n[20] = "examen"; printf("%d\n", m.Includes(n)); m.Set(10, "licenta"); for (auto [key, value, index] : m) { printf("Index:%d, Key=%d, Value=%s\n", index, key, value); } m.Delete(20); for (auto [key, value, index] : m) { printf("Index:%d, Key=%d, Value=%s\n", index, key, value); } printf("%d\n", m.Count()); const char* value; m.Get(10, value); printf("%s\n", value); return 0; }
19.702128
66
0.5
alexrobert02
fa61a1793e2b57b94e64326851a048b2a43f300f
1,172
hpp
C++
source/NanairoCore/Data/intersection_test_result.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
30
2015-09-06T03:14:29.000Z
2021-06-18T11:00:19.000Z
source/NanairoCore/Data/intersection_test_result.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
31
2016-01-14T14:50:34.000Z
2018-06-25T13:21:48.000Z
source/NanairoCore/Data/intersection_test_result.hpp
byzin/Nanairo
23fb6deeec73509c538a9c21009e12be63e8d0e4
[ "MIT" ]
6
2017-04-09T13:07:47.000Z
2021-05-29T21:17:34.000Z
/*! \file intersection_test_result.hpp \author Sho Ikeda Copyright (c) 2015-2018 Sho Ikeda This software is released under the MIT License. http://opensource.org/licenses/mit-license.php */ #ifndef NANAIRO_INTERSECTION_TEST_RESULT_HPP #define NANAIRO_INTERSECTION_TEST_RESULT_HPP // Nanairo #include "NanairoCore/nanairo_core_config.hpp" namespace nanairo { /*! */ class IntersectionTestResult { public: //! Create a failure result IntersectionTestResult() noexcept; //! Create a success result with the distance IntersectionTestResult(const Float d) noexcept; //! Check if the result is success explicit operator bool() const noexcept; //! Return the failure distance static constexpr Float failureDistance() noexcept; //! Check if the result is success bool isSuccess() const noexcept; //! Return the distance of the intersection point Float rayDistance() const noexcept; //! Set the distance of the intersection point void setRayDistance(const Float d) noexcept; private: Float distance_; }; } // namespace nanairo #include "intersection_test_result-inl.hpp" #endif // NANAIRO_INTERSECTION_TEST_RESULT_HPP
21.309091
52
0.756826
byzin
fa63f29fe52e415cd068788f3ad21da08e907982
17,604
cpp
C++
src/GenCVisitor.cpp
jkolek/cparser
13a18cdfdd1e3fc4104b7def1dc7d81bdd8a8164
[ "MIT" ]
10
2017-12-16T14:40:30.000Z
2022-02-20T09:09:02.000Z
src/GenCVisitor.cpp
jkolek/cparser
13a18cdfdd1e3fc4104b7def1dc7d81bdd8a8164
[ "MIT" ]
3
2018-04-27T08:16:02.000Z
2018-09-01T16:01:41.000Z
src/GenCVisitor.cpp
jkolek/cparser
13a18cdfdd1e3fc4104b7def1dc7d81bdd8a8164
[ "MIT" ]
2
2019-02-06T14:02:31.000Z
2021-11-02T02:34:21.000Z
// Generate C visitor - implementation file. // Copyright (C) 2017, 2018 Jozef Kolek <jkolek@gmail.com> // // All rights reserved. // // See the LICENSE file for more details. #include "../include/GenCVisitor.h" #include "../include/ASTNode.h" #include "../include/TreeVisitor.h" #include <iostream> #define TAB_SIZE 4 namespace cparser { static void printTab(int n) { int i, x; x = n * TAB_SIZE; for (i = 0; i < x; i++) std::cout << " "; } void GenCVisitor::visit(IdentASTNode *n) { std::cout << n->getValue(); } void GenCVisitor::visit(IntegerConstASTNode *n) { std::cout << n->getValue(); } void GenCVisitor::visit(StringConstASTNode *n) { std::cout << "\"" << n->getValue() << "\""; } void GenCVisitor::visit(CharConstASTNode *n) { if (n->getValue() == '\n') std::cout << "'\\n'"; else std::cout << "'" << (char) n->getValue() << "'"; } void GenCVisitor::visit(SizeOfExprASTNode *n) { std::cout << "sizeof("; if (n->getExpr() != NULL_AST_NODE) n->getExpr()->accept(this); std::cout << ")"; } void GenCVisitor::visit(AlignOfExprASTNode *n) { std::cout << "_Alignof("; if (n->getExpr() != NULL_AST_NODE) n->getExpr()->accept(this); std::cout << ")"; } void GenCVisitor::visit(TypeDeclASTNode *n) { std::cout << "typedef "; n->getBody()->accept(this); std::cout << " "; n->getName()->accept(this); } void GenCVisitor::visit(FunctionDeclASTNode *n) { n->getType()->accept(this); std::cout << " "; n->getName()->accept(this); std::cout << "("; _inList++; n->getPrms()->accept(this); _inList--; std::cout << ")" << std::endl; n->getBody()->accept(this); } void GenCVisitor::visit(VarDeclASTNode *n) { // if (n->getType()->getKind() == NK_FUNCTION_TYPE) // { // static_cast<FunctionTypeASTNode *>(n->getType())->getType()->accept(this); // std::cout << "(*"; // n->getName()->accept(this); // std::cout << ")"; // std::cout << "("; // _inList++; // static_cast<FunctionTypeASTNode *>(n->getType())->getPrms()->accept(this); // _inList--; // std::cout << ")"; // } // else // { n->getType()->accept(this); std::cout << " "; // if (n->getType()->getKind() == NK_POINTER_TYPE) // std::cout << "*"; n->getName()->accept(this); if (n->getType()->getKind() == NK_ARRAY_TYPE) { std::cout << "["; // Print out type expression static_cast<ArrayTypeASTNode *>(n->getType())->getExpr()->accept(this); std::cout << "]"; } if (n->getInit() != NULL_AST_NODE) { std::cout << " = "; n->getInit()->accept(this); } // } } void GenCVisitor::visit(ParmDeclASTNode *n) { if (n->getType() != NULL_AST_NODE) n->getType()->accept(this); std::cout << " "; // if (n->getType()->getKind() == NK_POINTER_TYPE) // std::cout << "*"; if (n->getName() != NULL_AST_NODE) n->getName()->accept(this); } void GenCVisitor::visit(FieldDeclASTNode *n) { // _level++; // printTab(_level); // std::cout << "NK_FIELD_DECL" << std::endl; // if (n->getName() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Name:" << std::endl; // n->getName()->accept(this); // } // if (n->getType() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Type:" << std::endl; // n->getType()->accept(this); // } // _level--; if (n->getType() != NULL_AST_NODE) n->getType()->accept(this); std::cout << " "; if (n->getName() != NULL_AST_NODE) n->getName()->accept(this); } void GenCVisitor::visit(AsmStmtASTNode *n) { printTab(_level + 1); std::cout << "NK_ASM_STMT" << std::endl; printTab(_level + 1); std::cout << "Data:" << std::endl; printTab(_level + 2); std::cout << n->getData() << std::endl; } void GenCVisitor::visit(BreakStmtASTNode *n) { std::cout << "break"; } void GenCVisitor::visit(CaseLabelASTNode *n) { _level++; printTab(_level); std::cout << "CASE_LABEL" << std::endl; if (n->getExpr() != NULL_AST_NODE) { printTab(_level); std::cout << "Expression:" << std::endl; n->getExpr()->accept(this); } if (n->getStmt() != NULL_AST_NODE) { printTab(_level); std::cout << "Statement:" << std::endl; n->getStmt()->accept(this); } _level--; } void GenCVisitor::visit(CompoundStmtASTNode *n) { printTab(_level); std::cout << "{" << std::endl; _level++; if (n->getDecls() != NULL_AST_NODE) { n->getDecls()->accept(this); } if (n->getStmts() != NULL_AST_NODE) { n->getStmts()->accept(this); } _level--; printTab(_level); std::cout << "}" << std::endl; } void GenCVisitor::visit(ContinueStmtASTNode *n) { std::cout << "continue"; } void GenCVisitor::visit(DoStmtASTNode *n) { std::cout << "do" << std::endl; n->getBody()->accept(this); printTab(_level); std::cout << "while ("; n->getCondition()->accept(this); std::cout << ");" << std::endl; } void GenCVisitor::visit(ForStmtASTNode *n) { std::cout << "for ("; if (n->getInit() != NULL_AST_NODE) n->getInit()->accept(this); std::cout << ";"; if (n->getCondition() != NULL_AST_NODE) { std::cout << " "; n->getCondition()->accept(this); } std::cout << ";"; if (n->getStep() != NULL_AST_NODE) { std::cout << " "; n->getStep()->accept(this); } std::cout << ")" << std::endl; n->getBody()->accept(this); } void GenCVisitor::visit(GotoStmtASTNode *n) { std::cout << "goto "; n->getLabel()->accept(this); } void GenCVisitor::visit(IfStmtASTNode *n) { std::cout << "if ("; if (n->getCondition() != NULL_AST_NODE) n->getCondition()->accept(this); std::cout << ")" << std::endl; if (n->getThenClause() != NULL_AST_NODE) { if (n->getThenClause()->getKind() != NK_COMPOUND_STMT) printTab(_level+1); n->getThenClause()->accept(this); } if (n->getElseClause() != NULL_AST_NODE) { printTab(_level); std::cout << "else"; if (n->getElseClause()->getKind() == NK_IF_STMT) std::cout << " "; else std::cout << std::endl; if (n->getElseClause()->getKind() != NK_COMPOUND_STMT && n->getElseClause()->getKind() != NK_IF_STMT) printTab(_level+1); n->getElseClause()->accept(this); } std::cout << std::endl; } void GenCVisitor::visit(LabelStmtASTNode *n) { int prevLevel = _level; _level = 0; n->getLabel()->accept(this); _level = prevLevel; std::cout << ":" << std::endl; printTab(_level); n->getStmt()->accept(this); } void GenCVisitor::visit(ReturnStmtASTNode *n) { std::cout << "return"; if (n->getExpr() != NULL_AST_NODE) { std::cout << " "; n->getExpr()->accept(this); } } void GenCVisitor::visit(SwitchStmtASTNode *n) { _level++; printTab(_level); std::cout << "SWITCH_STMT" << std::endl; if (n->getExpr() != NULL_AST_NODE) { printTab(_level); std::cout << "Expression:" << std::endl; n->getExpr()->accept(this); } if (n->getStmt() != NULL_AST_NODE) { printTab(_level); std::cout << "Statement:" << std::endl; n->getStmt()->accept(this); } _level--; } void GenCVisitor::visit(WhileStmtASTNode *n) { std::cout << "while ("; if (n->getCondition() != NULL_AST_NODE) n->getCondition()->accept(this); std::cout << ")" << std::endl; if (n->getBody() != NULL_AST_NODE) n->getBody()->accept(this); } void GenCVisitor::visit(CastExprASTNode *n) { // _level++; // printTab(_level); // std::cout << "NK_CAST_EXPR" << std::endl; // if (n->getExpr() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Expression:" << std::endl; // n->getExpr()->accept(this); // } // if (n->getType() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Type:" << std::endl; // n->getType()->accept(this); // } // _level--; std::cout << "("; n->getType()->accept(this); std::cout << ") "; n->getExpr()->accept(this); } void GenCVisitor::visit(BitNotExprASTNode *n) { std::cout << "~"; n->getExpr()->accept(this); } void GenCVisitor::visit(LogNotExprASTNode *n) { std::cout << "!"; n->getExpr()->accept(this); } void GenCVisitor::visit(PredecrementExprASTNode *n) { std::cout << "--"; n->getExpr()->accept(this); } void GenCVisitor::visit(PreincrementExprASTNode *n) { std::cout << "++"; n->getExpr()->accept(this); } void GenCVisitor::visit(PostdecrementExprASTNode *n) { n->getExpr()->accept(this); std::cout << "--"; } void GenCVisitor::visit(PostincrementExprASTNode *n) { n->getExpr()->accept(this); std::cout << "++"; } void GenCVisitor::visit(AddrExprASTNode *n) { std::cout << "&"; n->getExpr()->accept(this); } void GenCVisitor::visit(IndirectRefASTNode *n) { if (n->getField() == NULL_AST_NODE) std::cout << "*"; if (n->getExpr() != NULL_AST_NODE) n->getExpr()->accept(this); if (n->getField() != NULL_AST_NODE) { std::cout << "->"; n->getField()->accept(this); } // if (n->getType() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Type:" << std::endl; // n->getType()->accept(this); // } // _level--; } void GenCVisitor::visit(NopExprASTNode *n) { _level++; printTab(_level); std::cout << "NK_NOP_EXPR" << std::endl; _level--; } void GenCVisitor::visit(LShiftExprASTNode *n) { n->getLhs()->accept(this); std::cout << " << "; n->getRhs()->accept(this); } void GenCVisitor::visit(RShiftExprASTNode *n) { n->getLhs()->accept(this); std::cout << " >> "; n->getRhs()->accept(this); } void GenCVisitor::visit(BitIorExprASTNode *n) { n->getLhs()->accept(this); std::cout << " | "; n->getRhs()->accept(this); } void GenCVisitor::visit(BitXorExprASTNode *n) { n->getLhs()->accept(this); std::cout << " ^ "; n->getRhs()->accept(this); } void GenCVisitor::visit(BitAndExprASTNode *n) { n->getLhs()->accept(this); std::cout << " & "; n->getRhs()->accept(this); } void GenCVisitor::visit(LogAndExprASTNode *n) { n->getLhs()->accept(this); std::cout << " && "; n->getRhs()->accept(this); } void GenCVisitor::visit(LogOrExprASTNode *n) { n->getLhs()->accept(this); std::cout << " || "; n->getRhs()->accept(this); } void GenCVisitor::visit(PlusExprASTNode *n) { n->getLhs()->accept(this); std::cout << " + "; n->getRhs()->accept(this); } void GenCVisitor::visit(MinusExprASTNode *n) { n->getLhs()->accept(this); std::cout << " - "; n->getRhs()->accept(this); } void GenCVisitor::visit(MultExprASTNode *n) { n->getLhs()->accept(this); std::cout << " * "; n->getRhs()->accept(this); } void GenCVisitor::visit(TruncDivExprASTNode *n) { n->getLhs()->accept(this); std::cout << " / "; n->getRhs()->accept(this); } void GenCVisitor::visit(TruncModExprASTNode *n) { n->getLhs()->accept(this); std::cout << " % "; n->getRhs()->accept(this); } void GenCVisitor::visit(ArrayRefASTNode *n) { // _level++; // printTab(_level); // std::cout << "ARRAY_REF" << std::endl; // if (n->getExpr() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Expression:" << std::endl; // n->getExpr()->accept(this); // } // if (n->getIndex() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Index:" << std::endl; // n->getIndex()->accept(this); // } // if (n->getType() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Element type:" << std::endl; // n->getType()->accept(this); // } // _level--; if (n->getExpr() != NULL_AST_NODE) n->getExpr()->accept(this); std::cout << "["; if (n->getIndex() != NULL_AST_NODE) n->getIndex()->accept(this); std::cout << "]"; } void GenCVisitor::visit(StructRefASTNode *n) { // _level++; // printTab(_level); // std::cout << "STRUCT_REF" << std::endl; // if (n->getName() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Name:" << std::endl; // n->getName()->accept(this); // } // if (n->getMember() != NULL_AST_NODE) // { // printTab(_level); // std::cout << "Member:" << std::endl; // n->getMember()->accept(this); // } // _level--; if (n->getName() != NULL_AST_NODE) n->getName()->accept(this); std::cout << "."; if (n->getMember() != NULL_AST_NODE) n->getMember()->accept(this); } void GenCVisitor::visit(LtExprASTNode *n) { n->getLhs()->accept(this); std::cout << " < "; n->getRhs()->accept(this); } void GenCVisitor::visit(LeExprASTNode *n) { n->getLhs()->accept(this); std::cout << " <= "; n->getRhs()->accept(this); } void GenCVisitor::visit(GtExprASTNode *n) { n->getLhs()->accept(this); std::cout << " > "; n->getRhs()->accept(this); } void GenCVisitor::visit(GeExprASTNode *n) { n->getLhs()->accept(this); std::cout << " >= "; n->getRhs()->accept(this); } void GenCVisitor::visit(EqExprASTNode *n) { n->getLhs()->accept(this); std::cout << " == "; n->getRhs()->accept(this); } void GenCVisitor::visit(NeExprASTNode *n) { n->getLhs()->accept(this); std::cout << " != "; n->getRhs()->accept(this); } void GenCVisitor::visit(AssignExprASTNode *n) { n->getLhs()->accept(this); std::cout << " = "; n->getRhs()->accept(this); } void GenCVisitor::visit(CondExprASTNode *n) { n->getCondition()->accept(this); std::cout << " ? "; n->getThenClause()->accept(this); std::cout << " : "; n->getElseClause()->accept(this); } void GenCVisitor::visit(CallExprASTNode *n) { n->getExpr()->accept(this); std::cout << "("; _inList++; n->getArgs()->accept(this); _inList--; std::cout << ")"; } void GenCVisitor::visit(VoidTypeASTNode *n) { std::cout << "void"; } void GenCVisitor::visit(IntegralTypeASTNode *n) { if (!n->getIsSigned()) std::cout << "unsigned "; switch (n->getAlignment()) { case 1: std::cout << "char"; break; case 2: std::cout << "short"; break; case 4: std::cout << "int"; break; case 8: std::cout << "long"; break; default: std::cout << "int"; break; } } void GenCVisitor::visit(RealTypeASTNode *n) { if (n->getIsDouble()) std::cout << "double"; else std::cout << "float"; } void GenCVisitor::visit(EnumeralTypeASTNode *n) { std::cout << "enum "; n->getName()->accept(this); printTab(_level); std::cout << std::endl << "{" << std::endl; _level++; _inList++; n->getBody()->accept(this); _inList--; _level--; printTab(_level); std::cout << "}"; } void GenCVisitor::visit(PointerTypeASTNode *n) { // std::cout << "* "; n->getBaseType()->accept(this); std::cout << "*"; } void GenCVisitor::visit(FunctionTypeASTNode *n) { // n->getType()->accept(this); // std::cout << "(*"; // // Name // std::cout << ")"; std::cout << "("; _inList++; n->getPrms()->accept(this); _inList--; std::cout << ")"; } void GenCVisitor::visit(ArrayTypeASTNode *n) { // std::cout << "["; // n->getExpr()->accept(this); // std::cout << "]" << std::endl; n->getElementType()->accept(this); } void GenCVisitor::visit(StructTypeASTNode *n) { std::cout << "struct "; if (n->getName() != NULL_AST_NODE) n->getName()->accept(this); if (n->getBody() != NULL_AST_NODE) { std::cout << std::endl; printTab(_level); std::cout << "{" << std::endl; _level++; n->getBody()->accept(this); _level--; printTab(_level); std::cout << "}"; } } void GenCVisitor::visit(UnionTypeASTNode *n) { // TODO: Implement } void GenCVisitor::visit(NullASTNode *n) { // Print nothing } static bool isNonSemi(ASTNodeKind n) { return n == NK_IF_STMT || n == NK_WHILE_STMT || n == NK_DO_STMT || n == NK_FUNCTION_DECL || n == NK_COMPOUND_STMT || n == NK_INTEGRAL_TYPE; } void GenCVisitor::visit(SequenceASTNode *n) { std::vector<ASTNode *> &elements = n->getElements(); if (elements.size() > 0) { if (!_inList) printTab(_level); elements[0]->accept(this); if (!_inList) { if (!isNonSemi(elements[0]->getKind())) std::cout << ";" << std::endl; } } for (unsigned i = 1; i < elements.size(); i++) { if (elements[i] == NULL_AST_NODE) continue; if (!_inList) printTab(_level); else std::cout << ", "; elements[i]->accept(this); if (!_inList) { if (!isNonSemi(elements[i]->getKind())) std::cout << ";" << std::endl; } } } } // namespace cparser
21.057416
85
0.526869
jkolek
fa67ae37381bdd4e1b94aa38eae0735dbf1edc5c
1,272
cpp
C++
tests/vertex_pruning_test.cpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
null
null
null
tests/vertex_pruning_test.cpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
4
2020-04-18T16:16:05.000Z
2020-04-18T16:17:36.000Z
tests/vertex_pruning_test.cpp
mtao/core
91f9bc6e852417989ed62675e2bb372e6afc7325
[ "MIT" ]
null
null
null
#include <iostream> #include <mtao/geometry/kdtree.hpp> #include <mtao/geometry/prune_vertices.hpp> #include <algorithm> int main(int argc, char* argv[]) { mtao::vector<mtao::Vector<double,1>> p; p.push_back(mtao::Vector<double,1>(0.)); p.push_back(mtao::Vector<double,1>(.5)); p.push_back(mtao::Vector<double,1>(.25)); p.push_back(mtao::Vector<double,1>(.75)); p.push_back(mtao::Vector<double,1>(.125)); p.push_back(mtao::Vector<double,1>(.375)); p.push_back(mtao::Vector<double,1>(.625)); p.push_back(mtao::Vector<double,1>(.875)); p.push_back(mtao::Vector<double,1>(1.)); size_t cursize = p.size(); p.push_back(mtao::Vector<double,1>(.5)); p.push_back(mtao::Vector<double,1>(.25)); p.push_back(mtao::Vector<double,1>(.75)); p.resize(1000); std::generate(p.begin()+cursize,p.end(),[]() { return (mtao::Vector<double,1>::Random().array() /2 + .5).eval(); }); auto [p2,remap] = mtao::geometry::prune(p,.0625); for(auto&& v: p2) { std::cout << v.transpose() << std::endl; } for(auto&& [a,b]: remap) { std::cout << a << "=>" << b << std::endl; } std::cout << "Initial size: " << cursize << std::endl; std::cout << "Final size: " << p2.size() << std::endl; }
33.473684
120
0.58805
mtao
fa6acb14331e9c56515c39ac495c021bfdd368d6
661
cpp
C++
queue/circular.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
queue/circular.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
queue/circular.cpp
sans712/SDE-Interview-Questions
44f5bda60b9ed301b93a944e1c333d833c9b054b
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; #include<bits/stdc++.h> class queues{ int *arr; int f,r,cs,ms; public: queues(int ds=5){ arr=new int [ds]; cs=0; ms=ds; f=0; r=ms-1; } bool full(){ return cs==ms; } bool empty(){ return cs==0; } void push(int x){ if(!full()){ r=(r+1)%ms; arr[r]=x; cs++; } } void pop(){ if(!empty()){ f=(f+1)%ms; cs--; } } int front(){ return arr[f]; } ~queues(){ if(arr!=nullptr){ delete [] arr; arr=nullptr; } } }; int main(){ queues q; for(int i=1;i<=5;i++){ q.push(i); } q.pop(); q.pop(); q.push(11); while(!q.empty()){ cout<<q.front()<<" "; q.pop(); } }
11.596491
23
0.497731
sans712
fa6bc6d07b389ee5b05c8ce9109b5bbbb258565e
969
cpp
C++
codes/UVA/10001-19999/uva11014.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/10001-19999/uva11014.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/10001-19999/uva11014.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long ll; const int maxn = 200000; int np, pri[maxn+5], vis[maxn+5]; void priTable (int n) { np = 0; memset(vis, 0, sizeof(vis)); for (int i = 2; i <= n; i++) { if (vis[i]) continue; pri[np++] = i; for (int j = 2*i; j <= n; j += i) vis[j] = 1; } } ll N; inline ll count (ll n) { return n * n * n - 1; } inline ll fcount (ll n) { int ans = 0; for (int i = 0; i < np && pri[i] <= n; i++) { if (n < maxn && !vis[n]) { ans++; break; } if (n%pri[i] == 0) { ans++; n /= pri[i]; if (n%pri[i] == 0) return 0; } } return ans&1 ? -1 : 1; } ll solve () { ll ans = count(N+1); for (ll i = 2; i <= N; i++) { ll t = fcount(i); ans += count(N/(2*i) * 2 + 1) * t; } return ans; } int main () { int cas = 1; priTable(maxn); while (scanf("%lld", &N) == 1 && N) { printf("Crystal %d: %lld\n", cas++, solve()); } return 0; }
14.907692
47
0.4871
JeraKrs
fa6e6425724669d527e75115990d1f7fe9b20ced
73
hpp
C++
benchmarks/benchmark.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
3
2018-10-23T18:46:39.000Z
2019-06-24T00:46:10.000Z
benchmarks/benchmark.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
27
2018-11-10T14:19:16.000Z
2020-03-08T23:33:01.000Z
benchmarks/benchmark.hpp
stdml/stdnn-ops
0e6132bd65319e318f918094e482482698482e9e
[ "MIT" ]
1
2018-11-05T06:17:12.000Z
2018-11-05T06:17:12.000Z
#pragma once #include <benchmark/benchmark.h> #include "build_info.hpp"
14.6
32
0.767123
stdml
fa75e9117e534ec6e8c6b5dae4c83b9277ed8ae6
338
cpp
C++
Codeforces Online Judge Solve/68A - Irrational problem.cpp
Remonhasan/programming-solve
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
[ "Apache-2.0" ]
null
null
null
Codeforces Online Judge Solve/68A - Irrational problem.cpp
Remonhasan/programming-solve
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
[ "Apache-2.0" ]
null
null
null
Codeforces Online Judge Solve/68A - Irrational problem.cpp
Remonhasan/programming-solve
5a4ac8c738dd361e1c974162e0eaebbaae72fd80
[ "Apache-2.0" ]
null
null
null
// Remon Hasan #include <iostream> #include <algorithm> using namespace std; int main() { int p[4], a, b; cin >> p[0] >> p[1] >> p[2] >> p[3] >> a >> b; int m = *min_element(p, p + 4); if (a < m) { cout << min(b, m - 1) - a + 1 << endl; } else { cout << 0 << endl; } return 0; }
14.695652
50
0.423077
Remonhasan
fa7877aae48974b80d2d09d051de5f5d06ce8bc7
1,761
cpp
C++
src/astro/basic_astro/bodyShapeModel.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
src/astro/basic_astro/bodyShapeModel.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
src/astro/basic_astro/bodyShapeModel.cpp
kimonito98/tudat
c28f2a3e78b8492e2e054ad5e0d1f9ad785cd092
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2010-2019, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. * * References * Montebruck O, Gill E. Satellite Orbits, Springer, 2000. * */ #include "tudat/astro/basic_astro/bodyShapeModel.h" namespace tudat { namespace basic_astrodynamics { //! Function to calculate the altitude of a point over a central body //! from positions of both the point and the body (in any frame) double getAltitudeFromNonBodyFixedPosition( const std::shared_ptr< BodyShapeModel > bodyShapeModel, const Eigen::Vector3d& position, const Eigen::Vector3d& bodyPosition, const Eigen::Quaterniond& toBodyFixedFrame ) { return bodyShapeModel->getAltitude( toBodyFixedFrame * ( position - bodyPosition ) ); } //! Function to calculate the altitude of a point over a central body //! from positions of both the point and the body (in any frame) double getAltitudeFromNonBodyFixedPositionFunctions( const std::shared_ptr< BodyShapeModel > bodyShapeModel, const Eigen::Vector3d& position, const std::function< Eigen::Vector3d( ) > bodyPositionFunction, const std::function< Eigen::Quaterniond( ) > toBodyFixedFrameFunction ) { return getAltitudeFromNonBodyFixedPosition( bodyShapeModel, position, bodyPositionFunction( ), toBodyFixedFrameFunction( ) ); } } // namespace basic_astrodynamics } // namespace tudat
39.133333
99
0.720045
kimonito98
fa7a7614a3e05e1605ac92b79eba0e457cd595d8
7,150
cpp
C++
src/mame/drivers/pimps.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
26
2015-03-31T06:25:51.000Z
2021-12-14T09:29:04.000Z
src/mame/drivers/pimps.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
null
null
null
src/mame/drivers/pimps.cpp
Robbbert/messui
49b756e2140d8831bc81335298ee8c5471045e79
[ "BSD-3-Clause" ]
10
2015-03-27T05:45:51.000Z
2022-02-04T06:57:36.000Z
// license:BSD-3-Clause // copyright-holders:Robbbert /*************************************************************************** P.I.M.P.S. (Personal Interactive MicroProcessor System) 2009-12-06 Skeleton driver. No schematics or hardware info available. http://www.classiccmp.org/dunfield/pimps/index.htm Commands: A xxxx xxxx - Assemble (from editor file): origin destination D xxxx,xxxx - Dump memory to host port E - Enter editor A - Append at end of file C - Clear memory file (reqires ESCAPE to confirm) D xx - Delete line number xx I xx - Insert at line xx L xx xx - List range of lines Q - Query: Display highest used address X - eXit editor (requires ESCAPE to confirm) $ xxxx xxxx - exit directly to assembler F - set for Full-duplex host operation G xxxx - Go (execute) at address H - set for Half-duplex host operation M xxxx,xxxx - Display a range of memory (hex dump) P xx xx-[xx.] - display/Edit I/O Port S xxxx - Substitute data into memory T - Transparent link to host (Ctrl-A exits) U - set host Uart parameters (8251 control registers) V - Virtual memory (Not used on PIMPS board) Notes: The 'D'ump command outputs memory to the host in some form of Intel HEX records, and waits for line-feed from the host before proceeding. The 'V'irtual memory function was to control an EPROM emulator which was part of the original design (see Chucks notes below) and was not used on the PIMPS board. Editor: Operates in HEXIDECIMAL line numbers. Only supports up to 256 lines (01-00). You must enter full two-digit number when prompted. You MUST 'C'lear the memory file before you begin, otherwise you will be editing random memory content. Assembler: Comment is an INSTRUCTION! - this means that you need to put at least one space before and after ';' when entering a line comment. Does not understand DECIMAL numbers. It understands character constants ('c' and 'cc') and hex numbers ($xx or $xxxx). 8-bit values MUST contain two hex digits or one quoted character. 16-bit constants MUST contain four hex digits or two quoted characters. Use 'S' instead of 'SP', eg: LXI S,$1000 Only EQU, DB, DW and END directives are supported. An END statement is REQUIRED (otherwise you get the message '?tab-ful' as it fills the symbol table with garbage occuring in memory after the end of the file). RST instructions are implemented as 8 separate 'RST0'-'RST8' memonics. ****************************************************************************/ #include "emu.h" #include "cpu/i8085/i8085.h" #include "machine/clock.h" #include "machine/i8251.h" #include "bus/rs232/rs232.h" class pimps_state : public driver_device { public: pimps_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag) , m_maincpu(*this, "maincpu") , m_rom(*this, "roms") , m_ram(*this, "mainram") { } void pimps(machine_config &config); private: void io_map(address_map &map); void mem_map(address_map &map); virtual void machine_reset() override; memory_passthrough_handler *m_rom_shadow_tap; required_device<cpu_device> m_maincpu; required_region_ptr<u8> m_rom; required_shared_ptr<u8> m_ram; }; void pimps_state::mem_map(address_map &map) { map(0x0000, 0xefff).ram().share("mainram"); map(0xf000, 0xffff).rom().region("roms", 0); } void pimps_state::io_map(address_map &map) { map.unmap_value_high(); map(0xf0, 0xf1).rw("uart1", FUNC(i8251_device::read), FUNC(i8251_device::write)); map(0xf2, 0xf3).rw("uart2", FUNC(i8251_device::read), FUNC(i8251_device::write)); } /* Input ports */ static INPUT_PORTS_START( pimps ) INPUT_PORTS_END void pimps_state::machine_reset() { address_space &program = m_maincpu->space(AS_PROGRAM); program.install_rom(0x0000, 0x07ff, m_rom); // do it here for F3 m_rom_shadow_tap = program.install_read_tap(0xf000, 0xf7ff, "rom_shadow_r",[this](offs_t offset, u8 &data, u8 mem_mask) { if (!machine().side_effects_disabled()) { // delete this tap m_rom_shadow_tap->remove(); // reinstall ram over the rom shadow m_maincpu->space(AS_PROGRAM).install_ram(0x0000, 0x07ff, m_ram); } // return the original data return data; }); } // baud is not documented, we will use 9600 static DEVICE_INPUT_DEFAULTS_START( terminal ) // set up terminal to default to 9600, 7 bits, even parity DEVICE_INPUT_DEFAULTS( "RS232_RXBAUD", 0xff, RS232_BAUD_9600 ) DEVICE_INPUT_DEFAULTS( "RS232_TXBAUD", 0xff, RS232_BAUD_9600 ) DEVICE_INPUT_DEFAULTS( "RS232_DATABITS", 0xff, RS232_DATABITS_7 ) DEVICE_INPUT_DEFAULTS( "RS232_PARITY", 0xff, RS232_PARITY_EVEN ) DEVICE_INPUT_DEFAULTS( "RS232_STOPBITS", 0xff, RS232_STOPBITS_2 ) DEVICE_INPUT_DEFAULTS_END void pimps_state::pimps(machine_config &config) { I8085A(config, m_maincpu, 2_MHz_XTAL); m_maincpu->set_addrmap(AS_PROGRAM, &pimps_state::mem_map); m_maincpu->set_addrmap(AS_IO, &pimps_state::io_map); clock_device &uart_clock(CLOCK(config, "uart_clock", 153'600)); uart_clock.signal_handler().set("uart1", FUNC(i8251_device::write_txc)); uart_clock.signal_handler().append("uart1", FUNC(i8251_device::write_rxc)); uart_clock.signal_handler().append("uart2", FUNC(i8251_device::write_txc)); uart_clock.signal_handler().append("uart2", FUNC(i8251_device::write_rxc)); i8251_device &uart1(I8251(config, "uart1", 0)); uart1.txd_handler().set("rs232a", FUNC(rs232_port_device::write_txd)); uart1.dtr_handler().set("rs232a", FUNC(rs232_port_device::write_dtr)); uart1.rts_handler().set("rs232a", FUNC(rs232_port_device::write_rts)); rs232_port_device &rs232a(RS232_PORT(config, "rs232a", default_rs232_devices, "terminal")); rs232a.rxd_handler().set("uart1", FUNC(i8251_device::write_rxd)); rs232a.dsr_handler().set("uart1", FUNC(i8251_device::write_dsr)); rs232a.cts_handler().set("uart1", FUNC(i8251_device::write_cts)); rs232a.set_option_device_input_defaults("terminal", DEVICE_INPUT_DEFAULTS_NAME(terminal)); // must be exactly here i8251_device &uart2(I8251(config, "uart2", 0)); uart2.txd_handler().set("rs232b", FUNC(rs232_port_device::write_txd)); uart2.dtr_handler().set("rs232b", FUNC(rs232_port_device::write_dtr)); uart2.rts_handler().set("rs232b", FUNC(rs232_port_device::write_rts)); rs232_port_device &rs232b(RS232_PORT(config, "rs232b", default_rs232_devices, nullptr)); rs232b.rxd_handler().set("uart2", FUNC(i8251_device::write_rxd)); rs232b.dsr_handler().set("uart2", FUNC(i8251_device::write_dsr)); rs232b.cts_handler().set("uart2", FUNC(i8251_device::write_cts)); } /* ROM definition */ ROM_START( pimps ) ROM_REGION( 0x1000, "roms", 0 ) ROM_LOAD( "pimps.bin", 0x0000, 0x1000, CRC(5da1898f) SHA1(d20e31d0981a1f54c83186dbdfcf4280e49970d0)) ROM_END /* Driver */ /* YEAR NAME PARENT COMPAT MACHINE INPUT STATE INIT COMPANY FULLNAME FLAGS */ COMP( 197?, pimps, 0, 0, pimps, pimps, pimps_state, empty_init, "Henry Colford", "P.I.M.P.S.", MACHINE_NO_SOUND_HW | MACHINE_SUPPORTS_SAVE ) // terminal beeps
37.239583
170
0.714406
Robbbert
fa7ba8a28c1e8de79e5ff218c649b797b3e8b818
4,748
cpp
C++
src/zenoh_flow_local_planner.cpp
autocore-ai/zenoh_flow_autoware
8b5320fe95cfeb3d0573d7f520a6bab925ff6208
[ "Apache-2.0" ]
1
2022-03-31T08:53:16.000Z
2022-03-31T08:53:16.000Z
src/zenoh_flow_local_planner.cpp
autocore-ai/zenoh_flow_autoware
8b5320fe95cfeb3d0573d7f520a6bab925ff6208
[ "Apache-2.0" ]
2
2022-01-03T20:36:57.000Z
2022-01-19T03:55:51.000Z
src/zenoh_flow_local_planner.cpp
autocore-ai/zenoh_flow_autoware
8b5320fe95cfeb3d0573d7f520a6bab925ff6208
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The AutoCore.AI. // // 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 <zenoh_flow_local_planner/zenoh_flow_local_planner.hpp> #include <zenoh_flow_msg_convert/zenoh_flow_msg_convert.hpp> #include <iostream> namespace zenoh_flow { namespace autoware_auto { namespace ffi { NativeNode_local_planner::NativeNode_local_planner(const NativeConfig &cfg) { if (!rclcpp::ok()) { rclcpp::init(0, nullptr); } rclcpp::NodeOptions options; std::vector<rclcpp::Parameter> paramters = std::vector<rclcpp::Parameter>(); paramters.push_back(rclcpp::Parameter("enable_object_collision_estimator", cfg.enable_object_collision_estimator)); paramters.push_back(rclcpp::Parameter("heading_weight", cfg.heading_weight)); paramters.push_back(rclcpp::Parameter("goal_distance_thresh", cfg.goal_distance_thresh)); paramters.push_back(rclcpp::Parameter("stop_velocity_thresh", cfg.stop_velocity_thresh)); paramters.push_back(rclcpp::Parameter("subroute_goal_offset_lane2parking", cfg.subroute_goal_offset_lane2parking)); paramters.push_back(rclcpp::Parameter("subroute_goal_offset_parking2lane", cfg.subroute_goal_offset_parking2lane)); paramters.push_back(rclcpp::Parameter("vehicle.cg_to_front_m", cfg.vehicle.cg_to_front_m)); paramters.push_back(rclcpp::Parameter("vehicle.cg_to_rear_m", cfg.vehicle.cg_to_rear_m)); paramters.push_back(rclcpp::Parameter("vehicle.front_overhang_m", cfg.vehicle.front_overhang_m)); paramters.push_back(rclcpp::Parameter("vehicle.rear_overhang_m", cfg.vehicle.rear_overhang_m)); options.parameter_overrides(paramters); std::cout << "BehaviorPlannerNode" << std::endl; ptr = std::make_shared<autoware::behavior_planner_nodes::BehaviorPlannerNode>(options, autocore::NodeType::ZenohFlow); } void NativeNode_local_planner::SetRoute(const AutowareAutoMsgsHadmapRoute &msg) { ptr->SetRoute(Convert(msg)); } void NativeNode_local_planner::SetKinematicState(const AutowareAutoMsgsVehicleKinematicState &msg) { if (rclcpp::ok()) { rclcpp::spin_some(ptr); } ptr->SetKinematicState(Convert(msg)); } void NativeNode_local_planner::SetStateReport(const AutowareAutoMsgsVehicleStateReport &msg) { ptr->SetStateReport(Convert(msg)); } AutowareAutoMsgsTrajectory NativeNode_local_planner::GetTrajectory() { return Convert(ptr->GetTrajectory()); } AutowareAutoMsgsVehicleStateCommand NativeNode_local_planner::GetStateCmd() { return Convert(ptr->GetStateCmd()); } std::unique_ptr<NativeNode_local_planner> init_local_planner(const NativeConfig &cfg) { return std::make_unique<NativeNode_local_planner>(cfg); } AutowareAutoMsgsTrajectory get_trajectory(std::unique_ptr<NativeNode_local_planner> &node) { return node->GetTrajectory(); } AutowareAutoMsgsVehicleStateCommand get_state_cmd(std::unique_ptr<NativeNode_local_planner> &node) { return node->GetStateCmd(); } void set_route(std::unique_ptr<NativeNode_local_planner> &node, const AutowareAutoMsgsHadmapRoute &msg) { node->SetRoute(msg); } void set_kinematic_state( std::unique_ptr<NativeNode_local_planner> &node, const AutowareAutoMsgsVehicleKinematicState &msg) { node->SetKinematicState(msg); } void set_state_report( std::unique_ptr<NativeNode_local_planner> &node, const AutowareAutoMsgsVehicleStateReport &msg) { node->SetStateReport(msg); } } } }
48.948454
134
0.639427
autocore-ai
fa7d3d4044a2f033f206ade8d5558b3ed03c9040
2,098
cpp
C++
classnote/Midexam/DB_Conversion.cpp
Alex-Lin5/cpp_practice
c249362d6bbe932dc1eb4a4b8c51728d58db2aa7
[ "MIT" ]
null
null
null
classnote/Midexam/DB_Conversion.cpp
Alex-Lin5/cpp_practice
c249362d6bbe932dc1eb4a4b8c51728d58db2aa7
[ "MIT" ]
null
null
null
classnote/Midexam/DB_Conversion.cpp
Alex-Lin5/cpp_practice
c249362d6bbe932dc1eb4a4b8c51728d58db2aa7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <list> #include <map> using namespace std; //Implement the following function void DB1_to_DB2(list<vector<list<int>*>* >& DB1, vector<list<list<int*> >*>* pDB2); template <typename T> ostream& operator<<(ostream& str, const vector<T>& V); template <typename T> ostream& operator<<(ostream& str, const vector<T *>& V); template <typename T> ostream& operator<<(ostream& str, const list<T>& L); template <typename T> ostream& operator<<(ostream& str, const list<T*>& L); int main() { list<vector<list<int>*>* > DB1{ new vector<list<int>*> { new list<int> {1,2,3}, new list<int>{4,5,6,7}, new list<int>{8, 9}}, new vector<list<int>*> { new list<int> {11,12,13}, new list<int>{14,15,16,17}, new list<int>{18, 19}}, new vector<list<int>*> { new list<int> {21,22,23}, new list<int>{24,25,26,27}, new list<int>{28, 29}} }; cout << DB1 << endl; vector<list<list<int*> >*>* pDB2{ new vector<list<list<int*> >*> {} }; DB1_to_DB2(DB1, pDB2); cout << *pDB2 << endl; return 0; } void DB1_to_DB2(list<vector<list<int>*>* >& DB1, vector<list<list<int*> >*>* pDB2) { for (auto& i : *pDB2) { for (auto& j : *i) { for (auto& k : j) { delete k; } } delete i; } pDB2->clear(); for (auto& i : DB1) { list<list<int*>>* p1{ new list<list<int*>> }; for (auto& j : *i) { list<int*> L1; for (auto& k : *j) { L1.push_back(new int{ k }); } p1->push_back(L1); } pDB2->push_back(p1); } } template <typename T> ostream& operator<<(ostream& str, const vector<T>& V) { str << "[ "; for (auto& i : V) str << i << " "; str << "]"; return str; } template <typename T> ostream& operator<<(ostream& str, const vector<T *>& V) { str << "[ "; for (auto& i : V) str << *i << " "; str << "]"; return str; } template <typename T> ostream& operator<<(ostream& str, const list<T>& L) { str << "< "; for (auto& i : L) str << i << " "; str << ">"; return str; } template <typename T> ostream& operator<<(ostream& str, const list<T*>& L) { str << "< "; for (auto& i : L) str << *i << " "; str << ">"; return str; }
25.901235
126
0.577216
Alex-Lin5
fa7dba3908b35bf14a87cfe638101b39a1dd2dce
6,743
cpp
C++
src/make_detect.cpp
cschreib/qdeblend
dceee75f3ff475995dbbb8660a6665ece205494f
[ "MIT" ]
null
null
null
src/make_detect.cpp
cschreib/qdeblend
dceee75f3ff475995dbbb8660a6665ece205494f
[ "MIT" ]
null
null
null
src/make_detect.cpp
cschreib/qdeblend
dceee75f3ff475995dbbb8660a6665ece205494f
[ "MIT" ]
null
null
null
#include <vif.hpp> #include <vif/astro/ds9.hpp> using namespace vif; using namespace vif::astro; int vif_main(int argc, char* argv[]) { vec1s files = {"acs-f435w", "acs-f606w", "acs-f775w", "acs-f814w", "acs-f850lp", "wfc3-f105w", "wfc3-f125w", "wfc3-f140w", "wfc3-f160w"}; files += ".fits"; std::string flux_image = "wfc3-f160w.fits"; double deblend_threshold = 0.4; double detect_threshold = 1.0; double conv_fwhm = 0.2; double min_snr = 10.0; uint_t min_area = 10; read_args(argc, argv, arg_list(files, flux_image, deblend_threshold, detect_threshold, conv_fwhm, min_area, min_snr )); vec3f imgs; vec1f rms; double stack_rms = 0; vec2f stack; vec2f wstack; fits::header ghdr; double aspix = 0.06; for (std::string& f : files) { if (!file::exists(f)) continue; vec2d img; fits::header hdr; fits::read(f, img, hdr); astro::wcs w(hdr); if (ghdr.empty()) ghdr = hdr; // From DS9 region files std::string base = file::remove_extension(f); std::string bad_file = base+"-bad.reg"; if (!file::exists(bad_file)) { bad_file = base+"_bad.reg"; } if (!file::exists(bad_file)) { bad_file = ""; } if (!bad_file.empty()) { vec2b bad_mask(img.dims); ds9::mask_regions(bad_file, w, bad_mask); img[where(bad_mask)] = dnan; } if (fraction_of(is_finite(img) || abs(img) > 0) < 0.6) continue; rms.push_back(1.48*mad(img)); vec2d wei = replicate(1.0/sqr(rms.back()), img.dims); vec1u idb = where(!is_finite(img)); img[idb] = 0; wei[idb] = 0; if (stack.empty()) { stack = img*wei; wstack = wei; } else { stack += img*wei; wstack += wei; } stack_rms += sqr(rms.back()/sqr(rms.back())); append<0>(imgs, reform(img/rms.back(), 1, img.dims)); } astro::wcs gw(ghdr); double tw = total(1/sqr(rms)); stack_rms = sqrt(stack_rms)/tw; stack /= wstack; fits::write("det_stack.fits", stack, ghdr); append<0>(imgs, reform(stack/stack_rms, 1, stack.dims)); // Build detection image vec2f det = partial_max(0, imgs); double conv = conv_fwhm/aspix/2.335; { vec1u idb = where(!is_finite(det)); det[idb] = 0; uint_t hpix = 5*conv; vec2d kernel = gaussian_profile({{2*hpix+1, 2*hpix+1}}, conv, hpix, hpix); det = convolve2d(det, kernel); det[idb] = fnan; } fits::write("det_snr.fits", det, ghdr); // Perform segmentation segment_deblend_params sdp; sdp.detect_threshold = detect_threshold + median(det); sdp.deblend_threshold = deblend_threshold/aspix; sdp.min_area = min_area; segment_deblend_output segments; vec2u seg = segment_deblend(det, segments, sdp); // Read fluxes on image vec2d himg; fits::read(flux_image, himg); vec1u idbg = where(seg == 0); himg -= median(himg[idbg]); double hrms = 1.48*mad(himg[idbg]); vec1f hflx(segments.id.size()); vec1f hflx_err(segments.id.size()); foreach_segment(seg, segments.origin, [&](uint_t s, vec1u ids) { hflx[s] = total(himg[ids]); hflx_err[s] = sqrt(ids.size())*hrms; }); // Remove too low S/N objects. vec1u idls = where(hflx/hflx_err < min_snr); foreach_segment(seg, segments.origin[idls], [&](uint_t s, vec1u ids) { seg[ids] = 0; }); inplace_remove(segments.id, idls); inplace_remove(segments.area, idls); inplace_remove(segments.px, idls); inplace_remove(segments.py, idls); inplace_remove(hflx, idls); inplace_remove(hflx_err, idls); // Merge segments (if any). std::string manual_file = "merged_segments.reg"; if (file::exists(manual_file)) { vec<1,ds9::region> reg; ds9::read_regions_physical(manual_file, gw, reg); for (uint_t i : range(reg)) { vec2b mask(seg.dims); ds9::mask_region(reg[i], mask); vec1u idm = where(mask); vec1u idu = unique_values(seg[idm]); idu = idu[where(idu != 0)]; if (idu.size() > 1) { print("merged ", idu.size(), " segments"); for (uint_t u : range(1, idu.size())) { vec1u ids = where(seg == idu[u]); seg[ids] = idu[0]; idu[u] = where_first(segments.id == idu[u]); } uint_t im = where_first(segments.id == idu[0]); idu[0] = im; segments.px[im] = total(segments.px[idu]*segments.area[idu])/total(segments.area[idu]); segments.py[im] = total(segments.py[idu]*segments.area[idu])/total(segments.area[idu]); segments.area[im] = total(segments.area[idu]); hflx[im] = total(hflx[idu]); hflx_err[im] = sqrt(total(sqr(hflx_err[idu]))); idu = idu[1-_]; inplace_remove(segments.id, idu); inplace_remove(segments.px, idu); inplace_remove(segments.py, idu); inplace_remove(segments.area, idu); inplace_remove(hflx, idu); inplace_remove(hflx_err, idu); } } } // Add manual detections (if any). manual_file = "det_manual.reg"; if (file::exists(manual_file)) { vec<1,ds9::region> reg; ds9::read_regions_physical(manual_file, gw, reg); vec1s sid(reg.size()); for (uint_t i : range(reg)) sid[i] = reg[i].text; vec1s uid = unique_values(sid); for (std::string s : uid) { vec1u idl = where(sid == s); vec2b mask(seg.dims); for (uint_t i : idl) { ds9::mask_region(reg[i], mask); } vec1u ids = where(mask); uint_t seg_id = max(segments.id)+1; seg[ids] = seg_id; segments.id.push_back(seg_id); segments.px.push_back(reg[idl[0]].params[0]); segments.py.push_back(reg[idl[0]].params[1]); segments.area.push_back(ids.size()); hflx.push_back(total(himg[ids])); hflx_err.push_back(sqrt(ids.size())*hrms); } } fits::write("det_seg.fits", seg, ghdr); vec1d ra, dec; astro::xy2ad(gw, segments.px+1, segments.py+1, ra, dec); fits::write_table("det_cat.fits", "id", segments.id, "area", segments.area, "x", segments.px, "y", segments.py, "ra", ra, "dec", dec, "flux", hflx, "flux_err", hflx_err ); return 0; }
30.102679
103
0.547976
cschreib
fa7fdf0d58c70195d34d1ca216b0ca4b0fbdec95
2,033
cpp
C++
Competitive Programming/Bit Manipulation/Divide two integers without using multiplication, division and mod operator.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
Competitive Programming/Bit Manipulation/Divide two integers without using multiplication, division and mod operator.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
Competitive Programming/Bit Manipulation/Divide two integers without using multiplication, division and mod operator.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
/* https://www.geeksforgeeks.org/divide-two-integers-without-using-multiplication-division-mod-operator/ Divide two integers without using multiplication, division and mod operator Difficulty Level : Medium Last Updated : 03 Sep, 2021 Geek Week Given a two integers say a and b. Find the quotient after dividing a by b without using multiplication, division and mod operator. Example: Input : a = 10, b = 3 Output : 3 Input : a = 43, b = -8 Output : -5 Recommended: Please try your approach on {IDE} first, before moving on to the solution. Approach : Keep subtracting the dividend from the divisor until dividend becomes less than divisor. The dividend becomes the remainder, and the number of times subtraction is done becomes the quotient. */ // C++ implementation to Divide two // integers without using multiplication, // division and mod operator #include <bits/stdc++.h> using namespace std; // Function to divide a by b and // return floor value it int divide(long long dividend, long long divisor) { // Calculate sign of divisor i.e., // sign will be negative only iff // either one of them is negative // otherwise it will be positive int sign = ((dividend < 0) ^ (divisor < 0)) ? -1 : 1; // remove sign of operands dividend = abs(dividend); divisor = abs(divisor); // Initialize the quotient long long quotient = 0, temp = 0; // test down from the highest bit and // accumulate the tentative value for // valid bit for (int i = 31; i >= 0; --i) { if (temp + (divisor << i) <= dividend) { temp += divisor << i; quotient |= 1LL << i; } } //if the sign value computed earlier is -1 then negate the value of quotient if (sign == -1) quotient = -quotient; return quotient; } // Driver code int main() { int a = 10, b = 3; cout << divide(a, b) << "\n"; a = 43, b = -8; cout << divide(a, b); return 0; }
26.064103
130
0.632071
shreejitverma
fa82b6e764767ec297ffd9060a087f242751acf1
8,957
cpp
C++
src/XspfDateTime.cpp
ezdev128/libxspf
ba71431e24293510c44d6581e2c05b901a372880
[ "BSD-3-Clause" ]
null
null
null
src/XspfDateTime.cpp
ezdev128/libxspf
ba71431e24293510c44d6581e2c05b901a372880
[ "BSD-3-Clause" ]
null
null
null
src/XspfDateTime.cpp
ezdev128/libxspf
ba71431e24293510c44d6581e2c05b901a372880
[ "BSD-3-Clause" ]
null
null
null
/* * libxspf - XSPF playlist handling library * * Copyright (C) 2006-2008, Sebastian Pipping / Xiph.Org Foundation * 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 Xiph.Org Foundation nor the names of * its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Sebastian Pipping, sping@xiph.org */ /** * @file XspfDateTime.cpp * Implementation of XspfDateTime. */ #include <xspf/XspfDateTime.h> #include <cstring> #if defined(sun) || defined(__sun) # include <strings.h> // for strncmp() #endif namespace Xspf { /// @cond DOXYGEN_NON_API /** * D object for XspfDateTime. */ class XspfDateTimePrivate { friend class XspfDateTime; int year; ///< Year [-9999..+9999] but not zero int month; ///< Month [1..12] int day; ///< Day [1..31] int hour; ///< Hour [0..23] int minutes; ///< Minutes [0..59] int seconds; ///< Seconds [0..59] int distHours; ///< Time shift hours [-14..+14] int distMinutes; ///< Time shift minutes [-59..+59] /** * Creates a new D object. * * @param year Year [-9999..+9999] but not zero * @param month Month [1..12] * @param day Day [1..31] * @param hour Hour [0..23] * @param minutes Minutes [0..59] * @param seconds Seconds [0..59] * @param distHours Time shift hours [-14..+14] * @param distMinutes Time shift minutes [-59..+59] */ XspfDateTimePrivate(int year, int month, int day, int hour, int minutes, int seconds, int distHours, int distMinutes) : year(year), month(month), day(day), hour(hour), minutes(minutes), seconds(seconds), distHours(distHours), distMinutes(distMinutes) { } /** * Destroys this D object. */ ~XspfDateTimePrivate() { } }; /// @endcond XspfDateTime::XspfDateTime(int year, int month, int day, int hour, int minutes, int seconds, int distHours, int distMinutes) : d(new XspfDateTimePrivate(year, month, day, hour, minutes, seconds, distHours, distMinutes)) { } XspfDateTime::XspfDateTime() : d(new XspfDateTimePrivate(0, 0, 0, -1, -1, -1, 0, 0)) { } XspfDateTime::XspfDateTime(XspfDateTime const & source) : d(new XspfDateTimePrivate(*(source.d))) { } XspfDateTime & XspfDateTime::operator=(XspfDateTime const & source) { if (this != &source) { *(this->d) = *(source.d); } return *this; } XspfDateTime::~XspfDateTime() { delete this->d; } XspfDateTime * XspfDateTime::clone() const { return new XspfDateTime(this->d->year, this->d->month, this->d->day, this->d->hour, this->d->minutes, this->d->seconds, this->d->distHours, this->d->distMinutes); } int XspfDateTime::getYear() const { return this->d->year; } int XspfDateTime::getMonth() const { return this->d->month; } int XspfDateTime::getDay() const { return this->d->day; } int XspfDateTime::getHour() const { return this->d->hour; } int XspfDateTime::getMinutes() const { return this->d->minutes; } int XspfDateTime::getSeconds() const { return this->d->seconds; } int XspfDateTime::getDistHours() const { return this->d->distHours; } int XspfDateTime::getDistMinutes() const { return this->d->distMinutes; } void XspfDateTime::setYear(int year) { this->d->year = year; } void XspfDateTime::setMonth(int month) { this->d->month = month; } void XspfDateTime::setDay(int day) { this->d->day = day; } void XspfDateTime::setHour(int hour) { this->d->hour = hour; } void XspfDateTime::setMinutes(int minutes) { this->d->minutes = minutes; } void XspfDateTime::setSeconds(int seconds) { this->d->seconds = seconds; } void XspfDateTime::setDistHours(int distHours) { this->d->distHours = distHours; } void XspfDateTime::setDistMinutes(int distMinutes) { this->d->distMinutes = distMinutes; } namespace { /** * Calls atoi() on a limited number of characters. * * @param text Text * @param len Number of characters to read * @return Result of atoi() * @since 1.0.0rc1 */ int PORT_ANTOI(XML_Char const * text, int len) { XML_Char * final = new XML_Char[len + 1]; ::PORT_STRNCPY(final, text, len); final[len] = _PT('\0'); int const res = ::PORT_ATOI(final); delete [] final; return res; } } // anon namespace /*static*/ bool XspfDateTime::extractDateTime(XML_Char const * text, XspfDateTime * output) { // http://www.w3.org/TR/xmlschema-2/#dateTime-lexical-representation // '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)? // '-'? bool const leadingMinus = (*text == _PT('-')); if (leadingMinus) { text++; } // yyyy if ((::PORT_STRNCMP(text, _PT("0001"), 4) < 0) || (::PORT_STRNCMP(_PT("9999"), text, 4) < 0)) { return false; } int const year = PORT_ANTOI(text, 4); output->setYear(year); text += 4; // '-' mm if ((::PORT_STRNCMP(text, _PT("-01"), 3) < 0) || (::PORT_STRNCMP(_PT("-12"), text, 3) < 0)) { return false; } int const month = PORT_ANTOI(text + 1, 2); output->setMonth(month); text += 3; // '-' dd if ((::PORT_STRNCMP(text, _PT("-01"), 3) < 0) || (::PORT_STRNCMP(_PT("-31"), text, 3) < 0)) { return false; } int const day = PORT_ANTOI(text + 1, 2); output->setDay(day); text += 3; // Month specific day check switch (month) { case 2: switch (day) { case 31: case 30: return false; case 29: if (((year % 400) != 0) && (((year % 4) != 0) || ((year % 100) == 0))) { // Not a leap year return false; } break; case 28: break; } break; case 4: case 6: case 9: case 11: if (day > 30) { return false; } break; } // 'T' hh if ((::PORT_STRNCMP(text, _PT("T00"), 3) < 0) || (::PORT_STRNCMP(_PT("T23"), text, 3) < 0)) { return false; } output->setHour(PORT_ANTOI(text + 1, 2)); text += 3; // ':' mm if ((::PORT_STRNCMP(text, _PT(":00"), 3) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 3) < 0)) { return false; } output->setMinutes(PORT_ANTOI(text + 1, 2)); text += 3; // ':' ss if ((::PORT_STRNCMP(text, _PT(":00"), 2) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 2) < 0)) { return false; } output->setSeconds(PORT_ANTOI(text + 1, 2)); text += 3; // ('.' s+)? if (*text == _PT('.')) { text++; int counter = 0; while ((*text >= _PT('0')) && (*text <= _PT('9'))) { text++; counter++; } if (counter == 0) { return false; } else { // The fractional second string, if present, must not end in '0' if (*(text - 1) == _PT('0')) { return false; } } } // (zzzzzz)? := (('+' | '-') hh ':' mm) | 'Z' XML_Char const * const timeZoneStart = text; switch (*text) { case _PT('+'): case _PT('-'): { text++; if ((::PORT_STRNCMP(text, _PT("00"), 2) < 0) || (::PORT_STRNCMP(_PT("14"), text, 2) < 0)) { return false; } int const distHours = PORT_ANTOI(text, 2); output->setDistHours(distHours); text += 2; if ((::PORT_STRNCMP(text, _PT(":00"), 3) < 0) || (::PORT_STRNCMP(_PT(":59"), text, 3) < 0)) { return false; } int const distMinutes = PORT_ANTOI(text + 1, 2); output->setDistMinutes(distMinutes); if ((distHours == 14) && (distMinutes != 0)) { return false; } text += 3; if (*text != _PT('\0')) { return false; } if (*timeZoneStart == _PT('-')) { output->setDistHours(-distHours); output->setDistMinutes(-distMinutes); } } break; case _PT('Z'): text++; if (*text != _PT('\0')) { return false; } // NO BREAK case _PT('\0'): output->setDistHours(0); output->setDistMinutes(0); break; default: return false; } return true; } } // namespace Xspf
21.275534
96
0.620744
ezdev128
fa84c5de496b50b331d7308b8ed59f971edba5be
729
cpp
C++
src/modell/objects/ZRectangle.cpp
hemmerling/cpp-3dogs
0902ea6de8b8f03fa0b8ca7130a04a87ee3e73d7
[ "Apache-2.0" ]
null
null
null
src/modell/objects/ZRectangle.cpp
hemmerling/cpp-3dogs
0902ea6de8b8f03fa0b8ca7130a04a87ee3e73d7
[ "Apache-2.0" ]
null
null
null
src/modell/objects/ZRectangle.cpp
hemmerling/cpp-3dogs
0902ea6de8b8f03fa0b8ca7130a04a87ee3e73d7
[ "Apache-2.0" ]
null
null
null
#include "zrectangle.h" #include "opengl2.h" ZRectangle::ZRectangle(void) { // Basisklassen-Variablen werden vom Basisklassen-Konstruktor initialisiert setLength(1.0); setDefaultLength(1.0); } ZRectangle::~ZRectangle(void){} void ZRectangle::display(OpenGL &aOpenGL){ ZObject::update1(aOpenGL); aOpenGL.display(this); ZObject::update2(aOpenGL); } GLfloat &ZRectangle::getLength(void) { return length; } void ZRectangle::setLength(GLfloat length) { this->length = length; } GLfloat &ZRectangle::getDefaultLength(void) { return defaultLength; } void ZRectangle::setDefaultLength(GLfloat defaultLength) { this->defaultLength = defaultLength; this->length = defaultLength; }
18.692308
79
0.717421
hemmerling
fa8625618391b436b5d3793376c4526443b27842
3,821
cpp
C++
scripts/da_shotgun.cpp
mpforums/RenSharp
5b3fb8bff2a1772a82a4148bcf3e1265a11aa097
[ "Apache-2.0" ]
1
2021-10-04T02:34:33.000Z
2021-10-04T02:34:33.000Z
scripts/da_shotgun.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
9
2019-07-03T19:19:59.000Z
2020-03-02T22:00:21.000Z
scripts/da_shotgun.cpp
TheUnstoppable/RenSharp
2a123c6018c18f3fc73501737d600e291ac3afa7
[ "Apache-2.0" ]
2
2019-08-14T08:37:36.000Z
2020-09-29T06:44:26.000Z
/* Renegade Scripts.dll Dragonade Shotgun Wars Game Mode Copyright 2017 Whitedragon, Tiberian Technologies This file is part of the Renegade scripts.dll The Renegade scripts.dll 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, or (at your option) any later version. See the file COPYING for more details. In addition, an exemption is given to allow Run Time Dynamic Linking of this code with any closed source module that does not contain code covered by this licence. Only the source code to the module(s) containing the licenced code has to be released. */ #include "general.h" #include "scripts.h" #include "engine.h" #include "engine_DA.h" #include "da.h" #include "da_shotgun.h" void DAShotgunGameModeClass::Init() { Register_Event(DAEvent::ADDWEAPONREQUEST,INT_MAX); Register_Object_Event(DAObjectEvent::CREATED,DAObjectEvent::POWERUP | DAObjectEvent::BUILDING | DAObjectEvent::ARMED,INT_MAX); WeaponDefinitionClass *Shotgun = (WeaponDefinitionClass*)Find_Named_Definition("Weapon_Shotgun_Player"); WeaponDefinitionClass *Repair = (WeaponDefinitionClass*)Find_Named_Definition("Weapon_RepairGun_Player"); int ShotgunID = Shotgun->Get_ID(); Shotgun->MaxInventoryRounds = -1; int RepairID = Repair->Get_ID(); ArmorType LightArmor = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight"); for (SoldierGameObjDef *Def = (SoldierGameObjDef*)DefinitionMgrClass::Get_First(CID_Soldier);Def;Def = (SoldierGameObjDef*)DefinitionMgrClass::Get_Next(Def,CID_Soldier)) { Def->WeaponDefID = ShotgunID; Def->SecondaryWeaponDefID = RepairID; Def->WeaponRounds = -1; } for (VehicleGameObjDef *Def = (VehicleGameObjDef*)DefinitionMgrClass::Get_First(CID_Vehicle); Def; Def = (VehicleGameObjDef*)DefinitionMgrClass::Get_Next(Def, CID_Vehicle)) { if (Def->Get_Type() != VehicleType::VEHICLE_TYPE_TURRET) { Def->WeaponDefID = ShotgunID; Def->WeaponRounds = -1; } if (Def->DefenseObjectDef.ShieldType != ArmorType(1)) { Def->DefenseObjectDef.ShieldType = LightArmor; Def->DefenseObjectDef.Skin = LightArmor; } } } bool DAShotgunGameModeClass::Add_Weapon_Request_Event(cPlayer *Player,const WeaponDefinitionClass *Weapon) { if (_stricmp(Weapon->Get_Name(),"Weapon_Shotgun_Player") && _stricmp(Weapon->Get_Name(), "Weapon_RepairGun_Player")) { return false; } return true; } void DAShotgunGameModeClass::Object_Created_Event(GameObject *obj) { if (BuildingGameObj *Building = obj->As_BuildingGameObj()) { Building->Get_Defense_Object()->Set_Skin(ArmorWarheadManager::Get_Armor_Type("CNCVehicleMedium")); Building->Get_Defense_Object()->Set_Shield_Type(ArmorWarheadManager::Get_Armor_Type("CNCVehicleMedium")); const_cast<BuildingGameObjDef&>(Building->Get_Definition()).MCTSkin = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight"); } else if (VehicleGameObj *Vehicle = obj->As_VehicleGameObj()) { if (!_stricmp(Vehicle->Get_Weapon()->Get_Name(),"Weapon_Shotgun_Player")) { Update_Network_Object(Vehicle); Set_Position_Clip_Bullets(Vehicle,1,-1); } if (Vehicle->Get_Defense_Object()->Get_Shield_Type() != ArmorType(1)) { ArmorType LightArmor = ArmorWarheadManager::Get_Armor_Type("CNCVehicleLight"); Vehicle->Get_Defense_Object()->Set_Shield_Type(LightArmor); Vehicle->Get_Defense_Object()->Set_Skin(LightArmor); } } else if (SoldierGameObj *Soldier = obj->As_SoldierGameObj()) { if (Soldier->Get_Player()) { Update_Network_Object(Soldier->Get_Player()); } Update_Network_Object(Soldier); Set_Position_Clip_Bullets(Soldier,1,-1); } else if (((PowerUpGameObj*)obj)->Get_Definition().GrantWeapon) { obj->Set_Delete_Pending(); } } Register_Game_Mode(DAShotgunGameModeClass,"Shotgun","Shotgun Wars",0);
44.430233
175
0.772311
mpforums
fa880fafc7cf99141dacb7894697df7d7d21d0a1
2,546
cpp
C++
src/cpp/sample/Aggregate.cpp
sjoerdvankreel/xt-audio
960d6ed595c872c01af5c321b38b88a6ea07680a
[ "MIT" ]
49
2017-04-01T00:41:14.000Z
2022-03-23T09:03:28.000Z
src/cpp/sample/Aggregate.cpp
sjoerdvankreel/xt-audio
960d6ed595c872c01af5c321b38b88a6ea07680a
[ "MIT" ]
18
2017-04-29T22:46:35.000Z
2022-02-26T18:33:47.000Z
src/cpp/sample/Aggregate.cpp
sjoerdvankreel/xt-audio
960d6ed595c872c01af5c321b38b88a6ea07680a
[ "MIT" ]
14
2017-05-01T12:33:20.000Z
2021-10-01T07:16:26.000Z
#include <xt/XtAudio.hpp> #include <chrono> #include <thread> #include <cstdint> #include <cstring> #include <iostream> // Normally don't do I/O in the callback. static void OnXRun(Xt::Stream const& stream, int32_t index, void* user) { std::cout << "XRun on device " << index << ".\n"; } static void OnRunning(Xt::Stream const& stream, bool running, uint64_t error, void* user) { char const* evt = running? "Started": "Stopped"; std::cout << "Stream event: " << evt << ", new state: " << stream.IsRunning() << ".\n"; if(error != 0) std::cout << Xt::Audio::GetErrorInfo(error) << ".\n"; } static uint32_t OnBuffer(Xt::Stream const& stream, Xt::Buffer const& buffer, void* user) { Xt::Format const& format = stream.GetFormat(); Xt::Attributes attrs = Xt::Audio::GetSampleAttributes(format.mix.sample); int32_t bytes = buffer.frames * format.channels.inputs * attrs.size; std::memcpy(buffer.output, buffer.input, bytes); return 0; } int AggregateMain() { Xt::Mix mix(48000, Xt::Sample::Int16); Xt::Format inputFormat(mix, Xt::Channels(2, 0, 0, 0)); Xt::Format outputFormat(mix, Xt::Channels(0, 0, 2, 0)); std::unique_ptr<Xt::Platform> platform = Xt::Audio::Init("", nullptr); Xt::System system = platform->SetupToSystem(Xt::Setup::SystemAudio); std::unique_ptr<Xt::Service> service = platform->GetService(system); if(!service || (service->GetCapabilities() & Xt::ServiceCapsAggregation) == 0) return 0; std::optional<std::string> defaultInput = service->GetDefaultDeviceId(false); if(!defaultInput.has_value()) return 0; std::unique_ptr<Xt::Device> input = service->OpenDevice(defaultInput.value()); if(!input->SupportsFormat(inputFormat)) return 0; std::optional<std::string> defaultOutput = service->GetDefaultDeviceId(true); if(!defaultOutput.has_value()) return 0; std::unique_ptr<Xt::Device> output = service->OpenDevice(defaultOutput.value()); if(!output->SupportsFormat(outputFormat)) return 0; Xt::AggregateDeviceParams deviceParams[2]; deviceParams[0] = Xt::AggregateDeviceParams(input.get(), inputFormat.channels, 30.0); deviceParams[1] = Xt::AggregateDeviceParams(output.get(), outputFormat.channels, 30.0); Xt::StreamParams streamParams(true, OnBuffer, OnXRun, OnRunning); Xt::AggregateStreamParams aggregateParams(streamParams, deviceParams, 2, mix, output.get()); std::unique_ptr<Xt::Stream> stream = service->AggregateStream(aggregateParams, nullptr); stream->Start(); std::this_thread::sleep_for(std::chrono::seconds(2)); stream->Stop(); return 0; }
39.78125
94
0.706599
sjoerdvankreel
fa89ea2261e78ef1482282bd0f0a714639e05cbd
8,064
cpp
C++
Src/Base/PsuadeSession.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
14
2017-10-31T17:52:38.000Z
2022-03-04T05:16:56.000Z
Src/Base/PsuadeSession.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
3
2021-03-10T22:10:32.000Z
2022-01-14T04:31:05.000Z
Src/Base/PsuadeSession.cpp
lbianchi-lbl/psuade-lite
09d7ca75aba8a9e31e1fb5c3e134af046fca3460
[ "Apache-2.0" ]
12
2017-12-13T01:08:17.000Z
2020-11-26T22:58:08.000Z
// ************************************************************************ // Copyright (c) 2007 Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the PSUADE team. // All rights reserved. // // Please see the COPYRIGHT_and_LICENSE file for the copyright notice, // disclaimer, contact information and the GNU Lesser General Public License. // // PSUADE 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) version 2.1 dated February 1999. // // PSUADE 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 terms and conditions of the GNU General // Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, write to the Free Software Foundation, // Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // ************************************************************************ // Functions for the class PsuadeSession // AUTHOR : CHARLES TONG // DATE : 2014 // ************************************************************************ #include <assert.h> #include <stdlib.h> #include <stdio.h> #include "PsuadeSession.h" #include "PsuadeUtil.h" #include "sysdef.h" #include "PDFBase.h" #include "pData.h" #define PABS(x) (((x) > 0.0) ? (x) : -(x)) // ************************************************************************ // constructor // ------------------------------------------------------------------------ PsuadeSession::PsuadeSession() { owned_ = 0; inputLBounds_ = NULL; inputUBounds_ = NULL; sampleInputs_ = NULL; sampleOutputs_ = NULL; sampleStates_ = NULL; inputPDFs_ = NULL; inputMeans_ = NULL; inputStdevs_ = NULL; inputNames_ = NULL; outputNames_ = NULL; outputLevel_ = 0; nSamples_ = 0; nInputs_ = 0; nOutputs_ = 0; psuadeIO_ = NULL; } // ************************************************************************ // Copy constructor by Bill Oliver // ------------------------------------------------------------------------ PsuadeSession::PsuadeSession(const PsuadeSession &ps) { int ii; outputLevel_ = ps.outputLevel_; nSamples_ = ps.nSamples_; nInputs_ = ps.nInputs_; nOutputs_ = ps.nOutputs_; rsType_ = ps.rsType_; owned_ = 1; if (nInputs_ > 0 && ps.inputLBounds_ != NULL) { inputLBounds_ = new double[nInputs_]; inputUBounds_ = new double[nInputs_]; for (ii = 0; ii < nInputs_; ii++) { inputLBounds_[ii] = ps.inputLBounds_[ii]; inputUBounds_[ii] = ps.inputUBounds_[ii]; } } if (nSamples_ > 0 && nInputs_ > 0) { if (ps.sampleInputs_ != NULL) { sampleInputs_ = new double[nSamples_*nInputs_]; for (ii = 0; ii < nSamples_*nInputs_; ii++) sampleInputs_[ii] = ps.sampleInputs_[ii]; } if (ps.inputNames_ != NULL) { inputNames_ = new char*[nInputs_]; for (ii = 0; ii < nInputs_; ii++) { inputNames_[ii] = new char[1001]; strcpy(inputNames_[ii], ps.inputNames_[ii]); } } if (ps.inputPDFs_ != NULL) { inputPDFs_ = new int[nInputs_]; for (ii = 0; ii < nInputs_; ii++) inputPDFs_[ii] = ps.inputPDFs_[ii]; } if (ps.inputMeans_ != NULL) { inputMeans_ = new double[nInputs_]; for (ii = 0; ii < nInputs_; ii++) inputMeans_[ii] = ps.inputMeans_[ii]; } if (ps.inputStdevs_ != NULL) { inputStdevs_ = new double[nInputs_]; for (ii = 0; ii < nInputs_; ii++) inputStdevs_[ii] = ps.inputStdevs_[ii]; } corMatrix_.load((psMatrix &) ps.corMatrix_); } if (nSamples_ > 0 && nOutputs_ > 0 & ps.sampleOutputs_ != NULL) { sampleOutputs_ = new double[nSamples_*nOutputs_]; for(ii = 0; ii < nSamples_*nOutputs_; ii++) sampleOutputs_[ii] = ps.sampleOutputs_[ii]; if (ps.outputNames_ != NULL) { outputNames_ = new char*[nOutputs_]; for(ii = 0; ii < nOutputs_; ii++) { outputNames_[ii] = new char[1001]; strcpy(outputNames_[ii], ps.outputNames_[ii]); } } } if (nSamples_ > 0 && nOutputs_ > 0 & ps.sampleStates_ != NULL) { sampleStates_ = new int[nSamples_]; for(ii = 0; ii < nSamples_; ii++) sampleStates_[ii] = ps.sampleStates_[ii]; } } // ************************************************************************ // operator= // ------------------------------------------------------------------------ PsuadeSession & PsuadeSession::operator=(const PsuadeSession & ps) { int ii; if(this == &ps) return *this; owned_ = 1; inputLBounds_ = NULL; inputUBounds_ = NULL; sampleInputs_ = NULL; sampleOutputs_ = NULL; sampleStates_ = NULL; inputPDFs_ = NULL; inputMeans_ = NULL; inputStdevs_ = NULL; inputNames_ = NULL; outputNames_ = NULL; psuadeIO_ = NULL; outputLevel_ = ps.outputLevel_; nSamples_ = ps.nSamples_; nInputs_ = ps.nInputs_; nOutputs_ = ps.nOutputs_; rsType_ = ps.rsType_; if (nInputs_ > 0 && ps.inputLBounds_ != NULL) { inputLBounds_ = new double[nInputs_]; inputUBounds_ = new double[nInputs_]; for(int ii = 0; ii < nInputs_; ii++) { inputLBounds_[ii] = ps.inputLBounds_[ii]; inputUBounds_[ii] = ps.inputUBounds_[ii]; } } if (nSamples_ > 0 && nInputs_ > 0) { if (ps.sampleInputs_ != NULL) { sampleInputs_ = new double[nSamples_*nInputs_]; for(ii = 0; ii < nSamples_*nInputs_; ii++) sampleInputs_[ii] = ps.sampleInputs_[ii]; } if (ps.inputNames_ != NULL) { inputNames_ = new char*[nInputs_]; for(ii = 0; ii < nInputs_; ii++) { inputNames_[ii] = new char[1001]; strcpy(inputNames_[ii], ps.inputNames_[ii]); } } } if (nSamples_ > 0 && nOutputs_ > 0 & ps.sampleOutputs_ != NULL) { sampleOutputs_ = new double[nSamples_*nOutputs_]; for(ii = 0; ii < nSamples_*nOutputs_; ii++) sampleOutputs_[ii] = ps.sampleOutputs_[ii]; if (ps.outputNames_ != NULL) { outputNames_ = new char*[nOutputs_]; for(ii = 0; ii < nOutputs_; ii++) { outputNames_[ii] = new char[1001]; strcpy(outputNames_[ii], ps.outputNames_[ii]); } } } if (nSamples_ > 0 && nOutputs_ > 0 & ps.sampleStates_ != NULL) { sampleStates_ = new int[nSamples_]; for(ii = 0; ii < nSamples_; ii++) sampleStates_[ii] = ps.sampleStates_[ii]; } return *this; } // ************************************************************************ // destructor // ------------------------------------------------------------------------ PsuadeSession::~PsuadeSession() { int ii; if (owned_) { if (sampleInputs_ != NULL) delete [] sampleInputs_; if (sampleOutputs_ != NULL) delete [] sampleOutputs_; if (sampleStates_ != NULL) delete [] sampleStates_; if (inputLBounds_ != NULL) delete [] inputLBounds_; if (inputUBounds_ != NULL) delete [] inputUBounds_; if (inputNames_ != NULL) { for(ii = 0; ii < nInputs_; ii++) if (inputNames_[ii] != NULL) delete [] inputNames_[ii]; delete [] inputNames_[ii]; } if (outputNames_ != NULL) { for(ii = 0; ii < nOutputs_; ii++) if (outputNames_[ii] != NULL) delete [] outputNames_[ii]; delete [] outputNames_[ii]; } if (inputPDFs_ != NULL) delete [] inputPDFs_; if (inputMeans_ != NULL) delete [] inputMeans_; if (inputStdevs_ != NULL) delete [] inputStdevs_; } psuadeIO_ = NULL; }
32
78
0.535094
lbianchi-lbl
fa8cab7d2db90b6c1d432127901d174625e5eb3e
362
hh
C++
fields/versionchecker.hh
45G/libsocks6msg
73b778bfe8efb2c311520617debdfbadf10b6d88
[ "MIT" ]
2
2020-08-18T11:20:21.000Z
2022-03-08T23:49:02.000Z
fields/versionchecker.hh
45G/libsocks6msg
73b778bfe8efb2c311520617debdfbadf10b6d88
[ "MIT" ]
null
null
null
fields/versionchecker.hh
45G/libsocks6msg
73b778bfe8efb2c311520617debdfbadf10b6d88
[ "MIT" ]
null
null
null
#ifndef SOCKS6MSG_VERSIONCHECKER_HH #define SOCKS6MSG_VERSIONCHECKER_HH #include "bytebuffer.hh" namespace S6M { template <uint8_t VER> struct VersionChecker { VersionChecker() {} VersionChecker(ByteBuffer *bb) { uint8_t *ver = bb->peek<uint8_t>(); if (*ver != VER) throw BadVersionException(*ver); } }; } #endif // SOCKS6MSG_VERSIONCHECKER_HH
14.48
37
0.732044
45G
fa90467c310331ed5de2fbe188d6fa0e46e86225
9,392
hh
C++
wersja szablonowa/include/macierz.hh
KPO-2020-2021/zad3-AdamStypczyc
68c9b63d1b9b0176536ae46cc6863127d608433c
[ "Unlicense" ]
null
null
null
wersja szablonowa/include/macierz.hh
KPO-2020-2021/zad3-AdamStypczyc
68c9b63d1b9b0176536ae46cc6863127d608433c
[ "Unlicense" ]
null
null
null
wersja szablonowa/include/macierz.hh
KPO-2020-2021/zad3-AdamStypczyc
68c9b63d1b9b0176536ae46cc6863127d608433c
[ "Unlicense" ]
null
null
null
#ifndef MACIERZ_HH #define MACIERZ_HH #include <iostream> #include <cstdlib> #include <cmath> #include "wektor.hh" template <typename Templ_Typ, unsigned int Templ_Rozmiar> class Macierz { private: Templ_Typ value[Templ_Rozmiar][Templ_Rozmiar]; // Wartosci macierzy double kat_stopnie; double kat_radian; double kat_stopnieX; double kat_radianX; double kat_stopnieY; double kat_radianY; double kat_stopnieZ; double kat_radianZ; public: Macierz(Templ_Typ tmp[Templ_Rozmiar][Templ_Rozmiar]); // Konstruktor klasy Macierz(); // Konstruktor klasy // Wektor operator*(Wektor tmp); // Operator mnożenia przez wektor Macierz operator+(Macierz tmp); Macierz operator-(Macierz tmp); Macierz operator*(Macierz tmp); Templ_Typ &operator()(unsigned int row, unsigned int column); const Templ_Typ &operator()(unsigned int row, unsigned int column) const; void StopienNaRadian(); void StopienNaRadianX(); void StopienNaRadianY(); void StopienNaRadianZ(); void Oblicz_Macierz_Obrotu(); void Oblicz_Macierz_ObrotuX(); void Oblicz_Macierz_ObrotuY(); void Oblicz_Macierz_ObrotuZ(); void przypisz_stopnie(double stopnie); void przypisz_stopnieX(double stopnie); void przypisz_stopnieY(double stopnie); void przypisz_stopnieZ(double stopnie); bool operator==(const Macierz tmp) const; }; template <typename Templ_Typ, unsigned int Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::Macierz(Templ_Typ tmp[Templ_Rozmiar][Templ_Rozmiar]) { for (unsigned int index = 0; index < Templ_Rozmiar; ++index) { for (unsigned int j = 0; j < Templ_Rozmiar; ++j) { value[index][j] = tmp[index][j]; } } } template <typename Templ_Typ, unsigned int Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::Macierz() { for (unsigned int i = 0; i < Templ_Rozmiar; ++i) { for (unsigned int j = 0; j < Templ_Rozmiar; ++j) { value[i][j] = 0; } } } // template <typename Templ_Typ, unsigned int Templ_Rozmiar> // Wektor<Templ_Typ, Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::operator*(Wektor<Templ_Typ, Templ_Rozmiar> tmp) // { // Wektor<Templ_Typ, Templ_Rozmiar> result; // for (unsigned int i = 0; i < Templ_Rozmiar; ++i) // { // for (unsigned int j = 0; j < Templ_Rozmiar; ++j) // { // result[i] += value[i][j] * tmp[j]; // } // } // return result; // } template <typename Templ_Typ, unsigned int Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::operator+(Macierz<Templ_Typ, Templ_Rozmiar> tmp) { Macierz result = Macierz(); for (unsigned int i = 0; i < Templ_Rozmiar; ++i) { for (unsigned int j = 0; j < Templ_Rozmiar; ++j) { result(i, j) = this->value[i][j] + tmp(i, j); } } return result; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::operator-(Macierz<Templ_Typ, Templ_Rozmiar> tmp) { Macierz result = Macierz(); for (unsigned int i = 0; i < Templ_Rozmiar; ++i) { for (unsigned int j = 0; j < Templ_Rozmiar; ++j) { result(i, j) = this->value[i][j] - tmp(i, j); } } return result; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar> Macierz<Templ_Typ, Templ_Rozmiar>::operator*(Macierz<Templ_Typ, Templ_Rozmiar> tmp) { Macierz result = Macierz(); for (unsigned int i = 0; i < Templ_Rozmiar; ++i) { for (unsigned int j = 0; j < Templ_Rozmiar; ++j) { for (unsigned int k = 0; k < Templ_Rozmiar; ++k) { result(i, j) += this->value[i][k] * tmp(k, j); } } } return result; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> Templ_Typ &Macierz<Templ_Typ, Templ_Rozmiar>::operator()(unsigned int row, unsigned int column) { if (row >= Templ_Rozmiar) { std::cout << "Error: Macierz jest poza zasiegiem"; exit(0); } if (column >= Templ_Rozmiar) { std::cout << "Error: Macierz jest poza zasiegiem"; exit(0); } return value[row][column]; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> const Templ_Typ &Macierz<Templ_Typ, Templ_Rozmiar>::operator()(unsigned int row, unsigned int column) const { if (row >= Templ_Rozmiar) { std::cout << "Error: Macierz jest poza zasiegiem"; exit(0); // lepiej byłoby rzucić wyjątkiem stdexcept } if (column >= Templ_Rozmiar) { std::cout << "Error: Macierz jest poza zasiegiem"; exit(0); // lepiej byłoby rzucić wyjątkiem stdexcept } return value[row][column]; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::StopienNaRadian() { kat_radian = kat_stopnie * M_PI / 180; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::StopienNaRadianX() { kat_radianX = kat_stopnieX * M_PI / 180; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::StopienNaRadianY() { kat_radianY = kat_stopnieY * M_PI / 180; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::StopienNaRadianZ() { kat_radianZ = kat_stopnieZ * M_PI / 180; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::Oblicz_Macierz_Obrotu() { if (Templ_Rozmiar == 2) { value[0][0] = cos(kat_radian); value[0][1] = -sin(kat_radian); value[1][0] = sin(kat_radian); value[1][1] = cos(kat_radian); } else { std::cerr << "Błąd!!!" << std::endl; } } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::Oblicz_Macierz_ObrotuX() { if (Templ_Rozmiar == 3) { value[0][0] = 1; value[0][1] = 0; value[0][2] = 0; value[1][0] = 0; value[1][1] = cos(kat_radianX); value[1][2] = -sin(kat_radianX); value[2][0] = 0; value[2][1] = sin(kat_radianX); value[2][2] = cos(kat_radianX); } else { std::cerr << "Błąd!!!" << std::endl; } } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::Oblicz_Macierz_ObrotuY() { if (Templ_Rozmiar == 3) { value[0][0] = cos(kat_radianY); value[0][1] = 0; value[0][2] = sin(kat_radianY); value[1][0] = 0; value[1][1] = 1; value[1][2] = 0; value[2][0] = -sin(kat_radianY); value[2][1] = 0; value[2][2] = cos(kat_radianY); } else { std::cerr << "Błąd!!!" << std::endl; } } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::Oblicz_Macierz_ObrotuZ() { if (Templ_Rozmiar == 3) { value[0][0] = cos(kat_radianZ); value[0][1] = -sin(kat_radianZ); value[0][2] = 0; value[1][0] = sin(kat_radianZ); value[1][1] = cos(kat_radianZ); value[1][2] = 0; value[2][0] = 0; value[2][1] = 0; value[2][2] = 1; } else { std::cerr << "Błąd!!!" << std::endl; } } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::przypisz_stopnie(double stopnie) { kat_stopnie = stopnie; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::przypisz_stopnieX(double stopnie) { kat_stopnieX = stopnie; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::przypisz_stopnieY(double stopnie) { kat_stopnieY = stopnie; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> void Macierz<Templ_Typ, Templ_Rozmiar>::przypisz_stopnieZ(double stopnie) { kat_stopnieZ = stopnie; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> bool Macierz<Templ_Typ, Templ_Rozmiar>::operator==(const Macierz<Templ_Typ, Templ_Rozmiar> tmp) const { int liczenie = 0; for (unsigned int i = 0; i < Templ_Rozmiar; ++i) { for (unsigned int j = 0; j < Templ_Rozmiar; ++j) { if (std::abs(value[i][j] - tmp(i, j)) <= MIN_DIFF) { ++liczenie; } } } if (liczenie == pow(Templ_Rozmiar, 2)) { return true; } return false; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> std::istream &operator>>(std::istream &in, Macierz<Templ_Typ, Templ_Rozmiar> &mat) { for (unsigned int i = 0; i < Templ_Rozmiar; ++i) { for (unsigned int j = 0; j < Templ_Rozmiar; ++j) { in >> mat(i, j); } } return in; } template <typename Templ_Typ, unsigned int Templ_Rozmiar> std::ostream &operator<<(std::ostream &out, Macierz<Templ_Typ, Templ_Rozmiar> const &mat) { for (unsigned int i = 0; i < Templ_Rozmiar; ++i) { for (unsigned int j = 0; j < Templ_Rozmiar; ++j) { out << "| " << mat(i, j) << " | "; } std::cout << std::endl; } return out; } #endif
27.144509
118
0.622658
KPO-2020-2021
fa9352f0a3e8c427cda52d7fe8c0521ff69da1b3
2,053
cc
C++
cpp/Codeforces/251-300/300A_Array.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/251-300/300A_Array.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
cpp/Codeforces/251-300/300A_Array.cc
phongvcao/CP_Contests_Solutions
2e76e73ee7e53c798f63e1870be47653c75180a9
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <sstream> #include <vector> #include <unordered_map> #include <stdint.h> #include <cmath> #include <algorithm> using namespace std; typedef int64_t Int; typedef uint64_t UInt; int main(int argc, char **argv) { Int n = 0; // Read the first line string line = ""; if (getline(cin, line)) { stringstream ss(line); ss >> n; } vector<Int> firstSet; vector<Int> secondSet; vector<Int> thirdSet; Int intVectorIdx = 0; // Read the second line if (getline(cin, line)) { stringstream ss(line); while (intVectorIdx < n) { Int curNum = 0; bool isExcluded = false; ss >> curNum; if ((curNum < 0) && (firstSet.empty())) { firstSet.push_back(curNum); isExcluded = true; } if ((curNum > 0) && (secondSet.empty())) { secondSet.push_back(curNum); isExcluded = true; } if (!isExcluded) { thirdSet.push_back(curNum); } ++intVectorIdx; if (intVectorIdx == n) break; } } if (secondSet.empty()) { for (Int i = 0; i < thirdSet.size(); ++i) { if (thirdSet[i] < 0) { secondSet.push_back(thirdSet[i]); thirdSet.erase(thirdSet.begin() + i); --i; } if (secondSet.size() == 2) break; } } cout << firstSet.size() << " " << firstSet[0] << endl; cout << secondSet.size() << " "; for (Int i = 0; i != secondSet.size(); ++i) { cout << secondSet[i]; if (i < secondSet.size() - 1) { cout << " "; } else { cout << endl; } } cout << thirdSet.size() << " "; for (Int i = 0; i != thirdSet.size(); ++i) { cout << thirdSet[i]; if (i < thirdSet.size() - 1) { cout << " "; } } return 0; }
20.94898
58
0.458354
phongvcao
fa94d6f14af96e2f2446dd9d22660d36b62b6b1f
1,149
cpp
C++
BadRobots/src/Controllers/MenuController/MenuFactory/BRMenuFactory.cpp
demensdeum/Bad-Robots
e43f901ae2ead9a2992202a4bfb0e84e0a98fb97
[ "MIT" ]
null
null
null
BadRobots/src/Controllers/MenuController/MenuFactory/BRMenuFactory.cpp
demensdeum/Bad-Robots
e43f901ae2ead9a2992202a4bfb0e84e0a98fb97
[ "MIT" ]
null
null
null
BadRobots/src/Controllers/MenuController/MenuFactory/BRMenuFactory.cpp
demensdeum/Bad-Robots
e43f901ae2ead9a2992202a4bfb0e84e0a98fb97
[ "MIT" ]
null
null
null
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: BRMenuFactory.cpp * Author: demensdeum * * Created on March 23, 2017, 9:10 PM */ #include "BRMenuFactory.h" #include <BadRobots/src/Const/BRConst.h> #include <FlameSteelEngineGameToolkit/Data/Components/FSEGTFactory.h> BRMenuFactory::BRMenuFactory() { } BRMenuFactory::BRMenuFactory(const BRMenuFactory& orig) { } void BRMenuFactory::makeScene(shared_ptr<FSEGTGameData> gameData) { gameData->getGameObjects()->removeAllObjects(); auto menuImageObject = FSEGTFactory::makeOnSceneObject( shared_ptr<string>(new string(BRFilePathBadRobotsImage)), shared_ptr<string>(new string(BRFilePathBadRobotsImage)), shared_ptr<string>(new string(BRFilePathBadRobotsImage)), 360, 405, 0, 720, 405, 0, 0 ); gameData->addGameObject(menuImageObject); } BRMenuFactory::~BRMenuFactory() { }
22.98
79
0.655352
demensdeum
fa94f3a3046e6cbd35b7f1ec92771ba7927d1907
913
hpp
C++
Applications/ZilchShadersTests/Helpers.hpp
jodavis42/ZilchShaders
a161323165c54d2824fe184f5d540e0a008b4d59
[ "MIT" ]
1
2019-08-31T00:45:45.000Z
2019-08-31T00:45:45.000Z
Applications/ZilchShadersTests/Helpers.hpp
jodavis42/ZilchShaders
a161323165c54d2824fe184f5d540e0a008b4d59
[ "MIT" ]
5
2020-04-13T00:17:11.000Z
2021-04-20T23:11:42.000Z
Applications/ZilchShadersTests/Helpers.hpp
jodavis42/ZilchShaders
a161323165c54d2824fe184f5d540e0a008b4d59
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2015, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once void LoadSettingsOrDefault(ZilchShaderSpirVSettings& settings, StringParam defFilePath); void LoadDirectorySettingsOrDefault(ZilchShaderSpirVSettings& settings, StringParam directoryPath); void LoadFragmentCodeDirectory(SimpleZilchShaderIRGenerator& shaderGenerator, StringParam directory); // Simple function to display a diff error in notepad++ (ideally use a better text editor or something later) void DisplayError(StringParam filePath, StringParam lineNumber, StringParam errMsg); void FileToStream(File& file, TextStreamBuffer& stream); void RunProcess(StringParam applicationPath, StringParam args, String* stdOutResult, String* stdErrResult);
50.722222
109
0.684556
jodavis42
fa965d14c8328527988ae1edb2011efab9fa57a5
404
hpp
C++
server/world.hpp
irl-game/irl
ba507a93371ab172b705c1ede8cd062123fc96f5
[ "MIT" ]
null
null
null
server/world.hpp
irl-game/irl
ba507a93371ab172b705c1ede8cd062123fc96f5
[ "MIT" ]
null
null
null
server/world.hpp
irl-game/irl
ba507a93371ab172b705c1ede8cd062123fc96f5
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <unordered_map> #include <unordered_set> class Entity; class Client; class World { public: World(); ~World(); auto tick() noexcept -> void; std::unordered_map<Client *, std::unique_ptr<Client>> clients; private: std::unordered_map<const Entity *, std::unique_ptr<Entity>> entities; std::unordered_map<uint32_t, std::unordered_set<Entity *>> grid; };
20.2
71
0.717822
irl-game
b71232d372e0f2221c02359b6f2eb745778fe0b7
634
cpp
C++
Lista_2/mike_new.cpp
Thulio-Carvalho/Advanced-Algorithms-Problems
724bfb765d056ddab414df7dd640914aa0c665ae
[ "MIT" ]
null
null
null
Lista_2/mike_new.cpp
Thulio-Carvalho/Advanced-Algorithms-Problems
724bfb765d056ddab414df7dd640914aa0c665ae
[ "MIT" ]
null
null
null
Lista_2/mike_new.cpp
Thulio-Carvalho/Advanced-Algorithms-Problems
724bfb765d056ddab414df7dd640914aa0c665ae
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define MAXN 200014 using namespace std; int N, arr[MAXN], l[MAXN], r[MAXN]; stack<int> s; int main(){ cin >> N; for (int i = 0; i < N; i++) { cin >> arr[i]; } fill(l, l + MAXN, -1); fill(r, r + MAXN, N); for (int i = 0; i < N; i++) { while(!s.empty() && arr[s.top()] >= arr[i]) s.pop(); if (!s.empty()) l[i] = s.top(); s.push(i); } for (int i = 0; i < N; i++) { cout << arr[i] << " "; } cout << endl; for (int i = 0; i < N; i++) { cout << l[i] << " "; } cout << endl; return 0; }
17.611111
51
0.388013
Thulio-Carvalho
b71300420aeed2ab23a6a8af5412a20fed020f3c
4,213
cpp
C++
test/lib/Dialect/VectorExt/TestVectorMaskingUtils.cpp
giuseros/iree-llvm-sandbox
d47050d04d299dab799f8a1c6eb7e5d85bda535f
[ "Apache-2.0" ]
null
null
null
test/lib/Dialect/VectorExt/TestVectorMaskingUtils.cpp
giuseros/iree-llvm-sandbox
d47050d04d299dab799f8a1c6eb7e5d85bda535f
[ "Apache-2.0" ]
null
null
null
test/lib/Dialect/VectorExt/TestVectorMaskingUtils.cpp
giuseros/iree-llvm-sandbox
d47050d04d299dab799f8a1c6eb7e5d85bda535f
[ "Apache-2.0" ]
null
null
null
//===- TestMaskingUtils.cpp - Utilities for vector masking ----------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements logic for testing Vector masking utilities. // //===----------------------------------------------------------------------===// #include "Dialects/VectorExt/VectorExtOps.h" #include "Dialects/VectorExt/VectorMaskingUtils.h" #include "mlir/Dialect/Linalg/IR/Linalg.h" #include "mlir/Dialect/Vector/IR/VectorOps.h" #include "mlir/IR/Visitors.h" #include "mlir/Pass/Pass.h" using namespace mlir; using namespace mlir::linalg; using namespace mlir::vector; using namespace mlir::vector_ext; namespace { struct TestVectorMaskingUtils : public PassWrapper<TestVectorMaskingUtils, OperationPass<FuncOp>> { TestVectorMaskingUtils() = default; TestVectorMaskingUtils(const TestVectorMaskingUtils &pass) {} StringRef getArgument() const final { return "test-vector-masking-utils"; } StringRef getDescription() const final { return "Test vector masking utilities"; } void getDependentDialects(DialectRegistry &registry) const override { registry.insert<LinalgDialect, VectorDialect, VectorExtDialect>(); } Option<bool> predicationEnabled{*this, "predication", llvm::cl::desc("Test vector predication"), llvm::cl::init(false)}; Option<bool> maskingEnabled{*this, "masking", llvm::cl::desc("Test vector masking"), llvm::cl::init(false)}; void testPredication() { // Try different testing approaches until one triggers the predication // transformation for that particular function. bool predicationSucceeded = false; // Test tiled loop body predication. if (!predicationSucceeded) { getOperation().walk([&](TiledLoopOp loopOp) { predicationSucceeded = true; OpBuilder builder(loopOp); if (failed(predicateTiledLoop(builder, loopOp, /*incomingMask=*/llvm::None))) loopOp.emitError("Predication of tiled loop failed"); }); } // Test function body predication. if (!predicationSucceeded) { FuncOp funcOp = getOperation(); ValueRange funcArgs = funcOp.body().getArguments(); if (funcArgs.size() >= 3) { predicationSucceeded = true; // Return the mask from the third argument position starting from the // end, if found. Otherwise, return a null value. auto createPredicateMaskForFuncOp = [&](OpBuilder &builder) -> Value { if (funcArgs.size() < 3) return Value(); // Predicate mask is the third argument starting from the end. Value mask = *std::prev(funcArgs.end(), 3); if (auto vecType = mask.getType().dyn_cast<VectorType>()) { Type elemType = vecType.getElementType(); if (elemType.isInteger(1)) return mask; } return Value(); }; OpBuilder builder(funcOp); Value idx = *std::prev(funcArgs.end(), 2); Value incoming = funcArgs.back(); if (!predicateOp(builder, funcOp, &funcOp.body(), createPredicateMaskForFuncOp, idx, incoming)) funcOp.emitRemark("Predication of function failed"); } } } void testMasking() { FuncOp funcOp = getOperation(); OpBuilder builder(funcOp); if (failed(maskVectorPredicateOps(builder, funcOp, maskGenericOpWithSideEffects))) funcOp.emitError("Masking of function failed"); } void runOnOperation() override { if (predicationEnabled) testPredication(); if (maskingEnabled) testMasking(); } }; } // namespace namespace mlir { namespace test_ext { void registerTestVectorMaskingUtils() { PassRegistration<TestVectorMaskingUtils>(); } } // namespace test_ext } // namespace mlir
33.704
80
0.61785
giuseros
b71353bd1158764cddf2d9e45be1599d3d6c7708
12,774
hpp
C++
src/codegen/bytecode.hpp
Zoxc/mirb
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
[ "BSD-3-Clause" ]
10
2016-10-06T06:22:20.000Z
2022-02-28T05:33:09.000Z
src/codegen/bytecode.hpp
Zoxc/mirb
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
[ "BSD-3-Clause" ]
null
null
null
src/codegen/bytecode.hpp
Zoxc/mirb
14c2fe2d2a026fb3bb62c883e8839e1078ebc3b6
[ "BSD-3-Clause" ]
3
2018-01-08T03:34:34.000Z
2021-09-12T12:12:22.000Z
#pragma once #include "../common.hpp" #include "opcodes.hpp" #include "../tree/nodes.hpp" #include "../tree/tree.hpp" #include <Prelude/JoiningBuffer.hpp> namespace Mirb { namespace Tree { class Scope; }; namespace CodeGen { class ByteCodeGenerator; class VariableGroup { private: size_t address; ByteCodeGenerator *bcg; var_t var; public: VariableGroup(ByteCodeGenerator *bcg, size_t size); var_t operator[](size_t index); var_t use(); size_t size; }; class Label { public: #ifdef MIRB_DEBUG_COMPILER size_t id; Label(size_t id) : id(id) {} #endif size_t pos; }; class ByteCodeGenerator { private: void convert_data(Tree::Node *basic_node, var_t var); void convert_heredoc(Tree::Node *basic_node, var_t var); void convert_interpolate(Tree::Node *basic_node, var_t var); void convert_integer(Tree::Node *basic_node, var_t var); void convert_float(Tree::Node *basic_node, var_t var); void convert_variable(Tree::Node *basic_node, var_t var); void convert_cvar(Tree::Node *basic_node, var_t var); void convert_ivar(Tree::Node *basic_node, var_t var); void convert_global(Tree::Node *basic_node, var_t var); void convert_constant(Tree::Node *basic_node, var_t var); void convert_unary_op(Tree::Node *basic_node, var_t var); void convert_boolean_not(Tree::Node *basic_node, var_t var); void convert_binary_op(Tree::Node *basic_node, var_t var); void convert_boolean_op(Tree::Node *basic_node, var_t var); void convert_assignment(Tree::Node *basic_node, var_t var); void convert_self(Tree::Node *basic_node, var_t var); void convert_nil(Tree::Node *basic_node, var_t var); void convert_true(Tree::Node *basic_node, var_t var); void convert_false(Tree::Node *basic_node, var_t var); void convert_symbol(Tree::Node *basic_node, var_t var); void convert_range(Tree::Node *basic_node, var_t var); void convert_array(Tree::Node *basic_node, var_t var); void convert_hash(Tree::Node *basic_node, var_t var); void convert_block(Tree::Node *basic_node, var_t var); void convert_call(Tree::Node *basic_node, var_t var); void convert_super(Tree::Node *basic_node, var_t var); void convert_if(Tree::Node *basic_node, var_t var); void convert_case(Tree::Node *basic_node, var_t var); void convert_loop(Tree::Node *basic_node, var_t var); void convert_group(Tree::Node *basic_node, var_t var); void convert_return(Tree::Node *basic_node, var_t var); void convert_break(Tree::Node *basic_node, var_t var); void convert_next(Tree::Node *basic_node, var_t var); void convert_redo(Tree::Node *basic_node, var_t var); void convert_class(Tree::Node *basic_node, var_t var); void convert_module(Tree::Node *basic_node, var_t var); void convert_method(Tree::Node *basic_node, var_t var); void convert_alias(Tree::Node *basic_node, var_t var); void convert_undef(Tree::Node *basic_node, var_t var); void convert_handler(Tree::Node *basic_node, var_t var); void convert_multiple_expressions(Tree::Node *basic_node, var_t var); static void (ByteCodeGenerator::*jump_table[Tree::SimpleNode::Types])(Tree::Node *basic_node, var_t var); void convert_multiple_assignment(Tree::MultipleExpressionsNode *node, var_t rhs); // Members Label *body; // The point after the prolog of the block. Tree::Scope *const scope; Label *epilog; // The end of the block var_t return_var; Mirb::Block *final; /* * Exception related fields */ ExceptionBlock *current_exception_block; Vector<ExceptionBlock *, MemoryPool> exception_blocks; Vector<const char_t *, MemoryPool> strings; JoiningBuffer<sizeof(MoveOp) * 32, MemoryPool> opcode; typedef std::pair<size_t, Label *> BranchInfo; typedef std::pair<size_t, const SourceLoc *> SourceInfo; Vector<BranchInfo, MemoryPool> branches; Vector<SourceInfo, MemoryPool> source_locs; var_t heap_var; void finalize(); size_t var_count; // The total variable count. #ifdef MIRB_DEBUG_COMPILER size_t label_count; // Nicer label labeling... #endif size_t loc; Mirb::Block *compile(Tree::Scope *scope); Mirb::Block *defer(Tree::Scope *scope); void to_bytecode(Tree::Node *node, var_t var) { mirb_debug_assert(node); mirb_debug_assert(node->type() < Tree::Node::Types); auto func = jump_table[node->type()]; mirb_debug_assert(func); (this->*func)(node, var); } var_t reuse(var_t var) { // TODO: Make sure no code stores results in the returned variable return var == no_var ? create_var() : var; } var_t ref(Tree::Variable *var) { if(var) return var->loc; else return no_var; } void gen_string(var_t var, const DataEntry &data) { auto str = data.copy<Prelude::Allocator::Standard>(); strings.push(str.data); gen<StringOp>(var, str.data, str.length); } void gen_regexp(var_t var, const DataEntry &data, const SourceLoc &range) { auto str = data.copy<Prelude::Allocator::Standard>(); strings.push(str.data); gen<RegexpOp>(var, str.data, str.length); location(&range); } void gen_if(Label *ltrue, var_t var) { branches.push(BranchInfo(gen<BranchIfOp>(var), ltrue)); } void gen_unwind_redo(Label *body) { branches.push(BranchInfo(gen<UnwindRedoOp>(), body)); } void gen_unless(Label *lfalse, var_t var) { branches.push(BranchInfo(gen<BranchUnlessOp>(var), lfalse)); } void location(const SourceLoc *range) { source_locs.push(SourceInfo(opcode.size(), range)); } void gen_branch(Label *block) { branches.push(BranchInfo(gen<BranchOp>(), block)); } void branch(Label *block) { gen_branch(block); //TODO: Eliminate code generation from this point. The block will never be reached gen(create_label()); } template<typename F> var_t write_node(Tree::Node *lhs, F func, var_t temp) { switch(lhs->type()) { case Tree::SimpleNode::MultipleExpressions: { var_t var = reuse(temp); var_t rhs = create_var(); func(var); gen<ArrayOp>(rhs, 0, 0); // TODO: Add an opcode to convert into an array to avoid copying data gen<PushArrayOp>(rhs, var); convert_multiple_assignment((Tree::MultipleExpressionsNode *)lhs, rhs); return var; } case Tree::SimpleNode::Call: { auto node = (Tree::CallNode *)lhs; var_t var = reuse(temp); func(var); size_t argc = node->arguments.size + 1; VariableGroup group(this, argc); size_t param = 0; for(auto arg: node->arguments) to_bytecode(arg, group[param++]); gen<MoveOp>(group[param++], var); var_t obj = create_var(); to_bytecode(node->object, obj); gen<CallOp>(var, obj, node->method, no_var, argc, group.use()); location(node->range); return var; } case Tree::SimpleNode::Variable: { auto variable = (Tree::VariableNode *)lhs; return write_variable(variable->var, func, temp); } case Tree::SimpleNode::CVar: { auto variable = (Tree::CVarNode *)lhs; var_t var = reuse(temp); func(var); gen<SetIVarOp>(variable->name, var); // TODO: Fix cvars return var; } case Tree::SimpleNode::IVar: { auto variable = (Tree::IVarNode *)lhs; var_t var = reuse(temp); func(var); gen<SetIVarOp>(variable->name, var); return var; } case Tree::SimpleNode::Global: { auto variable = (Tree::GlobalNode *)lhs; var_t var = reuse(temp); func(var); gen<SetGlobalOp>(variable->name, var); location(&variable->range); return var; } case Tree::SimpleNode::Constant: { auto variable = (Tree::ConstantNode *)lhs; var_t var = reuse(temp); func(var); var_t obj = no_var; if(variable->obj) { obj = create_var(); to_bytecode(variable->obj, obj); } else if(variable->top_scope) { obj = create_var(); gen<LoadObjectOp>(obj); } if(obj == no_var) gen<SetConstOp>(variable->name, var); else gen<SetScopedConstOp>(obj, variable->name, var); location(variable->range); return var; } default: mirb_debug_abort("Unknown left hand expression"); } } template<typename F> var_t write_variable(Tree::Variable *var, F func, var_t temp) { if(var->heap) { var_t heap; if(var->owner != scope) { heap = create_var(); gen<LookupOp>(heap, scope->referenced_scopes.index_of(var->owner)); } else heap = heap_var; var_t store = reuse(temp); func(store); gen<SetHeapVarOp>(heap, var->loc, store); return store; } else { var_t store = reuse(temp); func(store); gen<MoveOp>(ref(var), store); return store; } } var_t block_arg(Tree::Scope *scope, var_t break_dst); var_t call_args(Tree::InvokeNode *node, Tree::Scope *scope, size_t &argc, var_t &argv, var_t break_dst); void early_finalize(Block *block, Tree::Scope *scope); friend class VariableGroup; friend class ByteCodePrinter; public: ByteCodeGenerator(MemoryPool memory_pool, Tree::Scope *scope); MemoryPool memory_pool; Label *gen(Label *block) { block->pos = opcode.size(); return block; } bool is_var(var_t var) { return var != no_var; } template<class T, typename F> size_t alloc(F func) { size_t result = opcode.size(); func(opcode.allocate(sizeof(T))); return result; } template<class T> size_t gen() { return alloc<T>([&](void *p) { new (p) T(); }); } template<class T, typename Arg1> size_t gen(Arg1 arg1) { return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1)); }); } template<class T, typename Arg1, typename Arg2> size_t gen(Arg1&& arg1, Arg2&& arg2) { return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2)); }); } template<class T, typename Arg1, typename Arg2, typename Arg3> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3) { return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3)); }); } template<class T, typename Arg1, typename Arg2, typename Arg3, typename Arg4> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4) { return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4)); }); } template<class T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4, Arg5&& arg5) { return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4), std::forward<Arg5>(arg5)); }); } template<class T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4, Arg5&& arg5, Arg6&& arg6) { return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4), std::forward<Arg5>(arg5), std::forward<Arg6>(arg6)); }); } template<class T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6, typename Arg7> size_t gen(Arg1&& arg1, Arg2&& arg2, Arg3&& arg3, Arg4&& arg4, Arg5&& arg5, Arg6&& arg6, Arg7&& arg7) { return alloc<T>([&](void *p) { new (p) T(std::forward<Arg1>(arg1), std::forward<Arg2>(arg2), std::forward<Arg3>(arg3), std::forward<Arg4>(arg4), std::forward<Arg5>(arg5), std::forward<Arg6>(arg6), std::forward<Arg7>(arg7)); }); } var_t create_var(); Label *create_label(); var_t read_variable(Tree::Variable *var); void write_variable(Tree::Variable *var, var_t value); Block *generate(); }; }; };
27.95186
232
0.617739
Zoxc
b7176c107b4c4c326de6c7ac47392a995897d323
9,801
hpp
C++
include/mflib/waveformTemplate.hpp
uofuseismo/mflib
14695f62082d28d4cc5603bb6edcaf1efe9dd980
[ "MIT" ]
5
2019-12-06T21:14:17.000Z
2021-09-21T03:36:58.000Z
include/mflib/waveformTemplate.hpp
uofuseismo/mflib
14695f62082d28d4cc5603bb6edcaf1efe9dd980
[ "MIT" ]
5
2019-11-27T19:06:06.000Z
2020-04-24T19:07:44.000Z
include/mflib/waveformTemplate.hpp
uofuseismo/mflib
14695f62082d28d4cc5603bb6edcaf1efe9dd980
[ "MIT" ]
2
2021-09-09T11:15:50.000Z
2021-12-04T00:50:53.000Z
#ifndef MFLIB_WAVEFORMTEMPLATE_HPP #define MFLIB_WAVEFORMTEMPLATE_HPP #include <memory> #include "mflib/enums.hpp" namespace MFLib { class NetworkStationPhase; /*! * @brief Defines a waveform template. * @copyright Ben Baker (University of Utah) distributed under the MIT license. */ class WaveformTemplate { public: /*! @name Constructors * @{ */ /*! * @brief Constructor. */ WaveformTemplate(); /*! * @brief Copy constructor. * @param[in] tplate The template class from which to initialize this * template. */ WaveformTemplate(const WaveformTemplate &tplate); /*! * @brief Move constructor. * @param[in,out] tplate The template class whose memory will be moved * to this. On exit, tplate's behavior is undefined. */ WaveformTemplate(WaveformTemplate &&tplate) noexcept; /*! } */ /*! * @brief Copy assignment operator. * @param[in] tplate The waveform template class to copy. * @result A deep copy of the inupt waveform template. */ WaveformTemplate& operator=(const WaveformTemplate &tplate); /*! * @brief Move assignment operator. * @param[in,out] tplate The waveform template class whose memory will be * moved to this class. On exit, tplate's behavior * is undefined. * @result The memory from tplate moved to this. */ WaveformTemplate& operator=(WaveformTemplate &&tplate) noexcept; /*! @name Destructors * @{ */ /*! * @brief Destructor. */ ~WaveformTemplate(); /*! * @brief Clears and resets the memory of the class. */ void clear() noexcept; /*! @} */ /*! @name Signal (Required) * @{ */ /*! * @brief Sets the template waveform signal. * @param[in] npts The number of samples in the template. * @param[in] x The template waveform signal. This is an array whose * dimension is [npts]. * @throws std::invalid_argument if npts is not positive or x is NULL. * @note This will invalidate the onset time. */ void setSignal(int npts, const double x[]); /*! @coypdoc setSignal */ void setSignal(int npts, const float x[]); /*! * @brief Gets the template waveform signal. * @param[in] maxx The maximum number of samples that x can hold. This * must be at least \c getSignalLength(). * @param[out] x The waveform template. This is an array whose dimension * is [maxx] however only the first \c getSignalLength() * samples are accessed. * @throws std::invalid_argument if x is NULL or maxx is too small. * @throws std::runtime_error if the signal was not set. */ void getSignal(int maxx, double *x[]) const; /*! @copydoc getSignal */ void getSignal(int maxx, float *x[]) const; /*! * @result The length of the template waveform signal. * @throws std::runtime_error if the template waveform was not set. * @sa \c haveSignal() */ int getSignalLength() const; /*! * @brief Determines if the template waveform signal was set. * @result True indicates that the template was set. */ bool haveSignal() const noexcept; /*! @} */ /*! @name Sampling Rate (Required) * @{ */ /*! * @brief Sets the sampling rate. * @param[in] samplingRate The sampling rate in Hz of the template waveform * signal. * @throws std::invalid_argument if this is not positive. * @note This will invalidate the onset time. */ void setSamplingRate(double samplingRate); /*! * @brief Gets the sampling rate. * @result The template's sampling rate. * @throws std::runtime_error if the sampling rate was not set. */ double getSamplingRate() const; /*! * @brief Determines if the sampling rate was set. * @result True indicates that the sampling rate was set. */ bool haveSamplingRate() const noexcept; /*! @} */ /*! @name Shift and Sum Weight * @{ */ /*! * @brief Defines the template's weight in the shift and stack operation. * @param[in] weight The weight of this template during the shift and sum * operation. * @throws std::invalid_argument if weight is not in the range [0,1]. */ void setShiftAndStackWeight(double weight); /*! * @brief Gets the template's weight during the shift and stack operation. * @result The template's weight during the shift and sum operation. * @note If \c setShiftStackAndWeight() was not called then this will * be unity. */ double getShiftAndStackWeight() const noexcept; /*! @} */ /*! @name Onset Time (Required for Shifting) * @{ */ /*! * @brief Sets the time in seconds relative to the trace where the * phase onset occurs. * @param[in] onsetTime The onset time in seconds where the pick occurs. * For example, if the pick is 2 seconds into the * the trace, i.e., there is `noise' 2 seconds prior * to the pick, then this should be 2. * @throws std::runtime_error if the waveform template signal was not set * or the sampling rate was not set. * @throws std::invalid_argument if the onset time is not in the trace. * @sa \c haveSignal(), \c haveSamplingRate(). * @note This is invalidated whenever the sampling period or signal is set. */ void setPhaseOnsetTime(double onsetTime); /*! * @brief Gets the phase onset time. * @result The time, relative to the trace start, where the pick occurs. * For example, if 2, then 2 seconds into the trace is where the * pick was made. * @throws std::runtime_error if the onset time was not set. * @sa \c havePhaseOnsetTime() */ double getPhaseOnsetTime() const; /*! * @brief Determines if the onset time was set. * @result True indicates that the onset time was set. */ bool havePhaseOnsetTime() const noexcept; /*!@ } */ /*! @brief Travel Time (Required for Shifting) * @{ */ /*! * @brief Sets the observed travel time for the pick. * @param[in] travelTime The observed travel time in seconds for the pick. * For example, if this is 7, then it took 7 seconds * for the wave to travel from the source to the * receiver. * @throws std::invalid_argument if travelTime is negative * @note The trace commences travelTime - onsetTime seconds after the origin * time. */ void setTravelTime(double travelTime); /*! * @brief Gets the observed travel time for the pick. * @result The observed travel time for this pick in seconds. * For example, if this is 7, then it took 7 seconds for the * wave to travel from the source to the receiver. * @throws std::runtime_error if the travel time was not set. * @sa \c haveTravelTime() */ double getTravelTime() const; /*! * @brief Determines if the travel time was set set. * @result True indicates that the travel time was set. */ bool haveTravelTime() const noexcept; /*! @} */ /*! @brief Identifier * @{ */ /*! * @brief This is used to give the waveform template an identifier. * The identifier defines the network, station, and phase * as well as the event identifier to which the phase was associated * in the catalog. * @param[in] id The waveform identifier. */ void setIdentifier(const std::pair<NetworkStationPhase, uint64_t> &id) noexcept; /*! * @brief Gets the waveform template identifier. * @result The waveform identifier where result.first is the network, * station, and phase while result.second is the event identifier. * @throws std::runtime_error if the waveform identifier was not set. * @sa \c haveIdentifier() */ std::pair<NetworkStationPhase, uint64_t> getIdentifier() const; /*! * @brief Determines whether or not the waveform identifier was set. * @result True indicates that the waveform identifier was set. */ bool haveIdentifier() const noexcept; /*! @} */ /*! @brief Magnitude * @{ */ /*! * @brief Sets the event magnitude associated with this template. * @param[in] magnitude The magnitude. */ void setMagnitude(double magnitude) noexcept; /*! * @brief Gets the magnitude associated with this template. * @result The magnitude associated with this template. * @throws std::runtime_error if the magnitude was not set. * @sa \c haveMagnitude() */ double getMagnitude() const; /*! * @brief Determines whether or not the magnitude was set. * @result True indicates that the magnitude was set. */ bool haveMagnitude() const noexcept; /*! @} */ /*! @brief Polarity * @{ */ /*! * @brief Sets the onset's polarity. * @param[in] polarity The arrival's polarity. */ void setPolarity(MFLib::Polarity polarity) noexcept; /*! * @brief Gets the onset's polarity. * @result The onset's polarity. By default this is unknown. */ MFLib::Polarity getPolarity() const noexcept; /*! @} */ private: class WaveformTemplateImpl; std::unique_ptr<WaveformTemplateImpl> pImpl; }; } #endif
35.255396
84
0.605755
uofuseismo
b7195e0b4a7870d5eb1e153904e59c4b42652bbe
2,773
cpp
C++
systems/polyvox/PolyVoxShader.cpp
phisko/kengine
c30f98cc8e79cce6574b5f61088b511f29bbe8eb
[ "MIT" ]
259
2018-11-01T05:12:37.000Z
2022-03-28T11:15:27.000Z
systems/polyvox/PolyVoxShader.cpp
raptoravis/kengine
619151c20e9db86584faf04937bed3d084e3bc21
[ "MIT" ]
2
2018-11-30T13:58:44.000Z
2018-12-17T11:58:42.000Z
systems/polyvox/PolyVoxShader.cpp
raptoravis/kengine
619151c20e9db86584faf04937bed3d084e3bc21
[ "MIT" ]
16
2018-12-01T13:38:18.000Z
2021-12-04T21:31:55.000Z
#include "PolyVoxShader.hpp" #include "EntityManager.hpp" #include "data/TransformComponent.hpp" #include "data/PolyVoxComponent.hpp" #include "data/GraphicsComponent.hpp" #include "data/ModelComponent.hpp" #include "data/OpenGLModelComponent.hpp" #include "systems/opengl/shaders/ApplyTransparencySrc.hpp" #include "systems/opengl/ShaderHelper.hpp" static inline const char * vert = R"( #version 330 layout (location = 0) in vec3 position; layout (location = 2) in vec3 color; uniform mat4 proj; uniform mat4 view; uniform mat4 model; uniform vec3 viewPos; out vec4 WorldPosition; out vec3 EyeRelativePos; out vec3 Color; void main() { WorldPosition = model * vec4(position, 1.0); EyeRelativePos = WorldPosition.xyz - viewPos; Color = color; //Color = vec3(1.0); // This is pretty gl_Position = proj * view * WorldPosition; } )"; static inline const char * frag = R"( #version 330 in vec4 WorldPosition; in vec3 EyeRelativePos; in vec3 Color; uniform vec4 color; uniform float entityID; layout (location = 0) out vec4 gposition; layout (location = 1) out vec3 gnormal; layout (location = 2) out vec4 gcolor; layout (location = 3) out float gentityID; void applyTransparency(float a); void main() { applyTransparency(color.a); gposition = WorldPosition; gnormal = -normalize(cross(dFdy(EyeRelativePos), dFdx(EyeRelativePos))); gcolor = vec4(Color * color.rgb, 0.0); gentityID = entityID; } )"; namespace kengine { static glm::vec3 toVec(const putils::Point3f & p) { return { p.x, p.y, p.z }; } PolyVoxShader::PolyVoxShader(EntityManager & em) : Program(false, putils_nameof(PolyVoxShader)), _em(em) {} void PolyVoxShader::init(size_t firstTextureID) { initWithShaders<PolyVoxShader>(putils::make_vector( ShaderDescription{ vert, GL_VERTEX_SHADER }, ShaderDescription{ frag, GL_FRAGMENT_SHADER }, ShaderDescription{ Shaders::src::ApplyTransparency::Frag::glsl, GL_FRAGMENT_SHADER } )); } void PolyVoxShader::run(const Parameters & params) { use(); _view = params.view; _proj = params.proj; _viewPos = params.camPos; for (const auto &[e, poly, graphics, transform] : _em.getEntities<PolyVoxObjectComponent, GraphicsComponent, TransformComponent>()) { if (graphics.model == Entity::INVALID_ID) continue; const auto & modelInfoEntity = _em.getEntity(graphics.model); if (!modelInfoEntity.has<OpenGLModelComponent>() || !modelInfoEntity.has<ModelComponent>()) continue; const auto & modelInfo = modelInfoEntity.get<ModelComponent>(); const auto & openGL = modelInfoEntity.get<OpenGLModelComponent>(); _model = ShaderHelper::getModelMatrix(modelInfo, transform); _entityID = (float)e.id; _color = graphics.color; ShaderHelper::drawModel(openGL); } } }
25.440367
135
0.728814
phisko
b71f730d0ceb1b4f5c53fcc95d266471fccfd42d
1,402
cc
C++
NEST-14.0-FPGA/sli/namedatum.cc
OpenHEC/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
45
2019-12-09T06:45:53.000Z
2022-01-29T12:16:41.000Z
NEST-14.0-FPGA/sli/namedatum.cc
zlchai/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
2
2020-05-23T05:34:21.000Z
2021-09-08T02:33:46.000Z
NEST-14.0-FPGA/sli/namedatum.cc
OpenHEC/SNN-simulator-on-PYNQcluster
14f86a76edf4e8763b58f84960876e95d4efc43a
[ "MIT" ]
10
2019-12-09T06:45:59.000Z
2021-03-25T09:32:56.000Z
/* * namedatum.cc * * This file is part of NEST. * * Copyright (C) 2004 The NEST Initiative * * NEST 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. * * NEST 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 NEST. If not, see <http://www.gnu.org/licenses/>. * */ #include "namedatum.h" // initialization of static members requires template<> // see Stroustrup C.13.1 --- HEP 2001-08-09 template <> sli::pool AggregateDatum< Name, &SLIInterpreter::Nametype >::memory( sizeof( NameDatum ), 10240, 1 ); template <> sli::pool AggregateDatum< Name, &SLIInterpreter::Literaltype >::memory( sizeof( LiteralDatum ), 10240, 1 ); // explicit template instantiation needed // because otherwise methods defined in // numericdatum_impl.h will not be instantiated // Moritz, 2007-04-16 template class AggregateDatum< Name, &SLIInterpreter::Nametype >; template class AggregateDatum< Name, &SLIInterpreter::Literaltype >;
31.155556
72
0.724679
OpenHEC
b7245a4e3e3b4e528c572d69ba7e14ba1b7c4ecf
2,350
cc
C++
chrome/browser/ui/app_list/arc/arc_app_launcher.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/app_list/arc/arc_app_launcher.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/ui/app_list/arc/arc_app_launcher.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/app_list/arc/arc_app_launcher.h" #include <memory> #include "ui/events/event_constants.h" ArcAppLauncher::ArcAppLauncher(content::BrowserContext* context, const std::string& app_id, const base::Optional<std::string>& launch_intent, bool deferred_launch_allowed, int64_t display_id, arc::UserInteractionType interaction) : context_(context), app_id_(app_id), launch_intent_(launch_intent), deferred_launch_allowed_(deferred_launch_allowed), display_id_(display_id), interaction_(interaction) { ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context_); DCHECK(prefs); std::unique_ptr<ArcAppListPrefs::AppInfo> app_info = prefs->GetApp(app_id_); if (!app_info || !MaybeLaunchApp(app_id, *app_info)) prefs->AddObserver(this); } ArcAppLauncher::~ArcAppLauncher() { if (!app_launched_) { ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context_); if (prefs) prefs->RemoveObserver(this); VLOG(2) << "App " << app_id_ << "was not launched."; } } void ArcAppLauncher::OnAppRegistered( const std::string& app_id, const ArcAppListPrefs::AppInfo& app_info) { MaybeLaunchApp(app_id, app_info); } void ArcAppLauncher::OnAppStatesChanged( const std::string& app_id, const ArcAppListPrefs::AppInfo& app_info) { MaybeLaunchApp(app_id, app_info); } bool ArcAppLauncher::MaybeLaunchApp(const std::string& app_id, const ArcAppListPrefs::AppInfo& app_info) { DCHECK(!app_launched_); if (app_id != app_id_ || (!app_info.ready && !deferred_launch_allowed_) || app_info.suspended) { return false; } ArcAppListPrefs* prefs = ArcAppListPrefs::Get(context_); DCHECK(prefs && prefs->GetApp(app_id_)); prefs->RemoveObserver(this); if (!arc::LaunchAppWithIntent(context_, app_id_, launch_intent_, ui::EF_NONE, interaction_, display_id_)) { VLOG(2) << "Failed to launch app: " + app_id_ + "."; } app_launched_ = true; return true; }
32.191781
80
0.655745
sarang-apps
b726b6a2a934148784791d29bdc232ba711d26fe
942
hpp
C++
sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/key_create_options.hpp
sjoubert/azure-sdk-for-cpp
5e2e84cdbcf49497ac67b77f642c2c7d0f2f0278
[ "MIT" ]
null
null
null
sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/key_create_options.hpp
sjoubert/azure-sdk-for-cpp
5e2e84cdbcf49497ac67b77f642c2c7d0f2f0278
[ "MIT" ]
null
null
null
sdk/keyvault/azure-security-keyvault-keys/inc/azure/keyvault/keys/key_create_options.hpp
sjoubert/azure-sdk-for-cpp
5e2e84cdbcf49497ac67b77f642c2c7d0f2f0278
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT /** * @brief Defines the supported options to create a Key Vault Key. * */ #pragma once #include <azure/core/context.hpp> #include <azure/core/datetime.hpp> #include <azure/core/nullable.hpp> #include "azure/keyvault/keys/key_operation.hpp" #include <list> #include <string> #include <unordered_map> namespace Azure { namespace Security { namespace KeyVault { namespace Keys { struct CreateKeyOptions { /** * @brief Context for cancelling long running operations. */ Azure::Core::Context Context; std::list<KeyOperation> KeyOperations; Azure::Core::Nullable<Azure::Core::DateTime> NotBefore; Azure::Core::Nullable<Azure::Core::DateTime> ExpiresOn; Azure::Core::Nullable<bool> Enabled; std::unordered_map<std::string, std::string> Tags; }; }}}} // namespace Azure::Security::KeyVault::Keys
22.428571
76
0.707006
sjoubert
b727edd6f6e528c256e2dc56b9a9c2e0379019bf
1,531
cpp
C++
tests/test_cpu.cpp
Ma-Dan/ncnn
8e94566ffb6b676b05a3d2875eaa9463acc4a176
[ "BSD-3-Clause" ]
59
2020-12-28T02:46:58.000Z
2022-02-10T14:50:48.000Z
tests/test_cpu.cpp
Ma-Dan/ncnn
8e94566ffb6b676b05a3d2875eaa9463acc4a176
[ "BSD-3-Clause" ]
2
2020-11-05T05:39:31.000Z
2020-11-27T06:08:23.000Z
tests/test_cpu.cpp
Ma-Dan/ncnn
8e94566ffb6b676b05a3d2875eaa9463acc4a176
[ "BSD-3-Clause" ]
13
2020-12-28T02:49:01.000Z
2022-03-12T11:58:33.000Z
#include <stdio.h> #include "cpu.h" #if defined __ANDROID__ || defined __linux__ static int test_cpu_set() { ncnn::CpuSet set; if (set.num_enabled() != 0) { fprintf(stderr, "By default all cpus should be disabled\n"); return 1; } set.enable(0); if (!set.is_enabled(0)) { fprintf(stderr, "CpuSet enable doesn't work\n"); return 1; } if (set.num_enabled() != 1) { fprintf(stderr, "Only one cpu should be enabled\n"); return 1; } set.disable(0); if (set.is_enabled(0)) { fprintf(stderr, "CpuSet disable doesn't work\n"); return 1; } return 0; } static int test_cpu_info() { if (ncnn::get_cpu_count() >= 0 && ncnn::get_little_cpu_count() >= 0 && ncnn::get_big_cpu_count() >= 0) { return 0; } else { fprintf(stderr, "The system cannot have a negative number of processors\n"); return 1; } } static int test_cpu_omp() { if (ncnn::get_omp_num_threads() >= 0 && ncnn::get_omp_thread_num() >= 0 && ncnn::get_omp_dynamic() >= 0) { return 0; } else { fprintf(stderr, "The OMP cannot have a negative number of processors\n"); return 1; } } #else static int test_cpu_set() { return 0; } static int test_cpu_info() { return 0; } static int test_cpu_omp() { return 0; } #endif int main() { return 0 || test_cpu_set() || test_cpu_info() || test_cpu_omp(); }
16.641304
108
0.555846
Ma-Dan
b728245881598bd173e019180fb2863faf68151d
1,845
cpp
C++
1135/main.cpp
Heliovic/PAT_Solutions
7c5dd554654045308f2341713c3e52cc790beb59
[ "MIT" ]
2
2019-03-18T12:55:38.000Z
2019-09-07T10:11:26.000Z
1135/main.cpp
Heliovic/My_PAT_Answer
7c5dd554654045308f2341713c3e52cc790beb59
[ "MIT" ]
null
null
null
1135/main.cpp
Heliovic/My_PAT_Answer
7c5dd554654045308f2341713c3e52cc790beb59
[ "MIT" ]
null
null
null
#include <cstdio> //#include <cstdlib> #define MAX_N 64 #define RED -1 #define BLACK 1 using namespace std; struct node { int type, data; node* lc; node* rc; node() {lc = rc = NULL;} }; int K, N; node* root = NULL; int black_cnt = -1; bool is_rbtree = true; void insert_bst(int data, node* & r, int type) { if (r == NULL) { r = new node; r->data = data; r->type = type; return; } if (data < r->data) insert_bst(data, r->lc, type); else insert_bst(data, r->rc, type); } int dfs(node* r) { if (!is_rbtree) return -1; if (r == NULL) { return 1; } /*system("pause"); printf("%d\n", r->data);*/ if (r->type == RED) { if ((r->lc != NULL && r->lc->type == RED) || (r->rc != NULL && r->rc->type == RED)) { is_rbtree = false; return -1; } } int lcnt = dfs(r->lc); int rcnt = dfs(r->rc); if (lcnt != rcnt) is_rbtree = false; return r->type == BLACK ? lcnt + 1 : lcnt; } void pre(node* r) { if (r == NULL) return; printf("%d ", r->data); pre(r->lc); pre(r->rc); } int main() { scanf("%d", &K); while (K--) { root = NULL; black_cnt = -1; is_rbtree = true; scanf("%d", &N); for (int i = 0; i < N; i++) { int t; scanf("%d", &t); if (t < 0) insert_bst(-t, root, RED); else insert_bst(t, root, BLACK); } if (root->type == RED) { printf("No\n"); continue; } //pre(root); dfs(root); if (is_rbtree) printf("Yes\n"); else printf("No\n"); } return 0; }
15.769231
91
0.416802
Heliovic
b72addd0b84922e8ce3620fd8c1a1584a73f03d6
2,562
cpp
C++
Samples/RadialController/cpp/RadialController.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/RadialController/cpp/RadialController.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/RadialController/cpp/RadialController.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
1
2020-01-18T09:12:02.000Z
2020-01-18T09:12:02.000Z
#include "stdafx.h" #include <tchar.h> #include <StrSafe.h> #include <wrl\implements.h> #include <wrl\module.h> #include <wrl\event.h> #include <roapi.h> #include <wrl.h> #include "DeviceListener.h" #include <ShellScalingApi.h> #define CLASSNAME L"Radial Device Controller" #define BUFFER_SIZE 2000 LRESULT CALLBACK WindowProc( __in HWND hWindow, __in UINT uMsg, __in WPARAM wParam, __in LPARAM lParam); HANDLE console; WCHAR windowClass[MAX_PATH]; void PrintMsg(WCHAR *msg) { size_t textLength; DWORD charsWritten; StringCchLength(msg, BUFFER_SIZE, &textLength); WriteConsole(console, msg, (DWORD)textLength, &charsWritten, NULL); } void PrintStartupMessage() { wchar_t message[2000]; swprintf_s(message, 2000, L"Press F10 to begin...\n"); PrintMsg(message); } int _cdecl _tmain( int argc, TCHAR *argv[]) { // Register Window Class WNDCLASS wndClass = { CS_DBLCLKS, (WNDPROC)WindowProc, 0,0,0,0,0,0,0, CLASSNAME }; RegisterClass(&wndClass); HWND hwnd = CreateWindow( CLASSNAME, L"Message Listener Window", WS_OVERLAPPEDWINDOW | WS_VISIBLE | WS_VSCROLL, CW_USEDEFAULT, // default horizontal position CW_USEDEFAULT, // default vertical position CW_USEDEFAULT, // default width CW_USEDEFAULT, // default height NULL, NULL, NULL, NULL); console = GetStdHandle(STD_OUTPUT_HANDLE); PrintStartupMessage(); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); // Dispatch message to WindowProc if (msg.message == WM_QUIT) { Windows::Foundation::Uninitialize(); break; } } SetConsoleTextAttribute(console, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED); } DeviceListener *listener = nullptr; LRESULT CALLBACK WindowProc( __in HWND hWindow, __in UINT uMsg, __in WPARAM wParam, __in LPARAM lParam) { switch (uMsg) { case WM_CLOSE: DestroyWindow(hWindow); break; case WM_DESTROY: PostQuitMessage(0); break; case WM_SYSKEYUP: //Press F10 if (!listener) { listener = new DeviceListener(console); listener->Init(hWindow); } default: return DefWindowProc(hWindow, uMsg, wParam, lParam); } return 0; }
23.943925
91
0.607728
windows-development
b72bcdc1cba305dc1b857157a455e1a46417bce8
2,902
hpp
C++
src/xalanc/XPath/XNumber.hpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
null
null
null
src/xalanc/XPath/XNumber.hpp
kidaa/xalan-c
bb666d0ab3d0a192410823e6857c203d83c27b16
[ "Apache-2.0" ]
1
2021-08-18T12:32:31.000Z
2021-08-18T12:32:31.000Z
src/xalanc/XPath/XNumber.hpp
AaronNGray/xalan
6741bbdcb64a9d33df8bd7e21b558d66bb4292ec
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(XNUMBER_HEADER_GUARD_1357924680) #define XNUMBER_HEADER_GUARD_1357924680 // Base header file. Must be first. #include <xalanc/XPath/XPathDefinitions.hpp> #include <xalanc/XalanDOM/XalanDOMString.hpp> // Base class header file. #include <xalanc/XPath/XNumberBase.hpp> XALAN_CPP_NAMESPACE_BEGIN class XALAN_XPATH_EXPORT XNumber : public XNumberBase { public: /** * Create an XNumber from a number. * * @param val numeric value to use */ XNumber( double val, MemoryManager& theMemoryManager); XNumber( const XNumber& source, MemoryManager& theMemoryManager); virtual ~XNumber(); // These methods are inherited from XObject ... virtual double num(XPathExecutionContext& executionContext) const; virtual double num() const; virtual const XalanDOMString& str(XPathExecutionContext& executionContext) const; virtual const XalanDOMString& str() const; virtual void str( XPathExecutionContext& executionContext, FormatterListener& formatterListener, MemberFunctionPtr function) const; virtual void str( FormatterListener& formatterListener, MemberFunctionPtr function) const; virtual void str( XPathExecutionContext& executionContext, XalanDOMString& theBuffer) const; virtual void str(XalanDOMString& theBuffer) const; virtual double stringLength(XPathExecutionContext& executionContext) const; // These methods are new to XNumber... /** * Change the value of an XNumber * * @param theValue The new value. */ void set(double theValue); private: // not implemented XNumber(); XNumber(const XNumber&); // Value of the number being represented. double m_value; mutable XalanDOMString m_cachedStringValue; }; XALAN_CPP_NAMESPACE_END #endif // XNUMBER_HEADER_GUARD_1357924680
23.216
75
0.677119
kidaa
b72cbe0cdb20542c671e93d4b43a752a288deb49
22,060
cpp
C++
ScannerBit/src/scanners/polychord/polychord.cpp
sebhoof/gambit_1.5
f9a3f788e3331067c555ae1a030420e903c6fdcd
[ "Unlicense" ]
2
2020-09-08T20:05:27.000Z
2021-04-26T07:57:56.000Z
ScannerBit/src/scanners/polychord/polychord.cpp
sebhoof/gambit_1.5
f9a3f788e3331067c555ae1a030420e903c6fdcd
[ "Unlicense" ]
9
2020-10-19T09:56:17.000Z
2021-05-28T06:12:03.000Z
ScannerBit/src/scanners/polychord/polychord.cpp
sebhoof/gambit_1.5
f9a3f788e3331067c555ae1a030420e903c6fdcd
[ "Unlicense" ]
5
2020-09-08T02:23:34.000Z
2021-03-23T08:48:04.000Z
// GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// ScannerBit interface to PolyChord 1.17.1 /// /// ********************************************* /// /// Authors (add name and date if you modify): // /// \author Ben Farmer /// (ben.farmer@gmail.com) /// \date October 2013 - Aug 2016 /// /// \author Will Handley /// (wh260@cam.ac.uk) /// \date May 2018 /// /// \author Patrick Stoecker /// (stoecker@physik.rwth-aachen.de) /// \date May 2020 /// /// ********************************************* #include <vector> #include <string> #include <cmath> #include <iostream> #include <fstream> #include <map> #include <sstream> #include <iomanip> // For debugging only #include <algorithm> #include <numeric> #include "gambit/ScannerBit/scanner_plugin.hpp" #include "gambit/ScannerBit/scanners/polychord/polychord.hpp" #include "gambit/Utils/yaml_options.hpp" #include "gambit/Utils/util_functions.hpp" namespace Gambit { namespace PolyChord { /// Global pointer to loglikelihood wrapper object, for use in the PolyChord callback functions LogLikeWrapper *global_loglike_object; } } /// Typedef for the ScannerBit pointer to the external loglikelihood function typedef Gambit::Scanner::like_ptr scanPtr; /// ================================================= /// Interface to ScannerBit /// ================================================= scanner_plugin(polychord, version(1, 17, 1)) { // An error is thrown if any of the following entries are not present in the inifile (none absolutely required for PolyChord). reqd_inifile_entries(); // Tell cmake system to search known paths for these libraries; any not found must be specified in config/scanner_locations.yaml. reqd_libraries("chord"); // Pointer to the (log)likelihood function scanPtr LogLike; /// The constructor to run when the PolyChord plugin is loaded. plugin_constructor { // Retrieve the external likelihood calculator LogLike = get_purpose(get_inifile_value<std::string>("like")); if (LogLike->getRank() == 0) std::cout << "Loading PolyChord nested sampling plugin for ScannerBit." << std::endl; } /// The main routine to run for the PolyChord scanner. int plugin_main (void) { /// ************ /// TODO: Replace with some wrapper? Maybe not, this is already pretty straightforward, /// though perhaps a little counterintuitive that the printer is the place to get this /// information. bool resume_mode = get_printer().resume_mode(); /// ************ // Retrieve the dimensionality of the scan. int ma = get_dimension(); // Retrieve the global option specifying the minimum interesting likelihood double gl0 = get_inifile_value<double>("likelihood: model_invalid_for_lnlike_below"); // Retrieve the global option specifying the likelihood offset to use double offset = get_inifile_value<double>("likelihood: lnlike_offset", 0.); // Make sure the likleihood functor knows to apply the offset internally in ScannerBit LogLike->setPurposeOffset(offset); // Offset the minimum interesting likelihood by the offset gl0 = gl0 + offset; // Retrieve whether the scanned parameters should be added to the native output and determine nderived int nderived = 2; if (get_inifile_value<bool>("print_parameters_in_native_output", false)) nderived += ma; // Initialise polychord settings Settings settings(ma, nderived); // Create the object that interfaces to the PolyChord LogLike callback function Gambit::PolyChord::LogLikeWrapper loglwrapper(LogLike, get_printer()); Gambit::PolyChord::global_loglike_object = &loglwrapper; // ---------- Compute an ordering for fast and slow parameters // Read list of fast parameters from file std::vector<std::string> fast_params = get_inifile_value<std::vector<std::string>>("fast_params", {}); // Get list of parameters used from loglikelihood std::vector<std::string> varied_params = LogLike->getShownParameters(); std::vector<std::string> all_params = LogLike->getParameters(); // Compute the set difference between fast_params and all_params to check if there are any fast_params not included in all_params std::set<std::string> set_fast_params(fast_params.begin(), fast_params.end()), set_params(all_params.begin(), all_params.end()), diff; std::set_difference(set_fast_params.begin(), set_fast_params.end(), set_params.begin(), set_params.end(),std::inserter(diff,diff.begin())); if (diff.size()) { // Raise an error if any specified fast_params are not actually being sampled over. std::string error_message = "You have specified:\n"; for (auto param : diff) error_message += param + "\n" ; error_message += "as fast param(s), but the list of params is:\n"; for (auto param : all_params) error_message += param + "\n"; scan_error().raise(LOCAL_INFO,error_message); } // Compute the locations in PolyChord's unit hypercube, ordering from slow to fast // This defaults to nDims if there are no fast parameters, or if all parameters are fast. // grade_dims is a vector of integers that indicates the number of slow and fast parameters settings.grade_dims.clear(); int i = 0; // Run through all the parameters, and if they're slow parameters // give them an index i, then increment i for (auto param : varied_params) if (std::find(fast_params.begin(), fast_params.end(),param) == fast_params.end()) Gambit::PolyChord::global_loglike_object->index_map[param] = (i++); int nslow = i; if(nslow!=0) settings.grade_dims.push_back(nslow); // Do the same for the fast parameters for (auto param : varied_params) if (std::find(fast_params.begin(), fast_params.end(),param) != fast_params.end()) Gambit::PolyChord::global_loglike_object->index_map[param] = (i++); int nfast = i-nslow; if (nfast>0) settings.grade_dims.push_back(nfast); if (nslow>0 and nfast>0) { // Specify the fraction of time to spend in the slow parameters. double frac_slow = get_inifile_value<double>("frac_slow",0.75); settings.grade_frac = std::vector<double>({frac_slow, 1-frac_slow}); } else if (nslow==0) // In the unusual case of all fast parameters, there's only one grade. nslow = nfast; // ---------- End computation of ordering for fast and slow parameters // PolyChord algorithm options. settings.nlive = get_inifile_value<int>("nlive", settings.nDims*25); // number of live points settings.num_repeats = get_inifile_value<int>("num_repeats", nslow*2); // length of slice sampling chain settings.nprior = get_inifile_value<int>("nprior", settings.nlive*10); // number of prior samples to begin algorithm with settings.do_clustering = get_inifile_value<bool>("do_clustering", true); // Whether or not to perform clustering settings.feedback = get_inifile_value<int>("fb", 1); // Feedback level settings.precision_criterion = get_inifile_value<double>("tol", 0.5); // Stopping criterion (consistent with multinest) settings.logzero = get_inifile_value<double>("logzero",gl0); settings.max_ndead = get_inifile_value<double>("maxiter", -1); // Max no. of iterations, a negative value means infinity (different in comparison with multinest). settings.maximise = get_inifile_value<bool>("maximise", false); // Whether to run a maximisation algorithm once the run is finished settings.boost_posterior = 0; // Increase the number of posterior samples produced bool outfile (get_inifile_value<bool>("outfile", true)); // write output files? settings.posteriors = outfile; settings.equals = outfile; settings.cluster_posteriors = outfile; settings.write_paramnames = outfile; settings.write_stats = outfile; settings.write_live = outfile; settings.write_dead = outfile; settings.write_prior = outfile; settings.write_resume = outfile; settings.read_resume = resume_mode; settings.compression_factor = get_inifile_value<double>("compression_factor",0.36787944117144233); settings.base_dir = get_inifile_value<std::string>("default_output_path")+"PolyChord"; settings.file_root = get_inifile_value<std::string>("root", "native"); settings.seed = get_inifile_value<int>("seed",-1); Gambit::Utils::ensure_path_exists(settings.base_dir); Gambit::Utils::ensure_path_exists(settings.base_dir + "/clusters/"); // Point the boundSettings to the settings in use Gambit::PolyChord::global_loglike_object->boundSettings = settings; // Set the speed threshold for the printer. // Evaluations of speeds >= threshold are not printed // Speeds start at 0 Gambit::PolyChord::global_loglike_object->printer_speed_threshold = get_inifile_value<int>("printer_speed_threshold",settings.grade_dims.size()); if(resume_mode==1 and outfile==0) { // It is stupid to be in resume mode while not writing output files. // Means subsequent resumes will be impossible. Throw an error. scan_error().raise(LOCAL_INFO,"Error from PolyChord ScannerBit plugin! Resume mode is activated, however " "PolyChord native output files are set to not be written. These are needed " "for resuming; please change this setting in your yaml file (set option \"outfile: 1\")"); } // Setup auxilliary streams. These are only needed by the master process, // so let's create them only for that process int myrank = get_printer().get_stream()->getRank(); // MPI rank of this process if(myrank==0) { // Get inifile options for each print stream Gambit::Options txt_options = get_inifile_node("aux_printer_txt_options"); //Gambit::Options stats_options = get_inifile_node("aux_printer_stats_options"); //FIXME Gambit::Options live_options = get_inifile_node("aux_printer_live_options"); // Options to desynchronise print streams from the main Gambit iterations. This allows for random access writing, or writing of global scan data. //stats_options.setValue("synchronised",false); //FIXME txt_options.setValue("synchronised",false); live_options.setValue("synchronised",false); // Initialise auxiliary print streams get_printer().new_stream("txt",txt_options); //get_printer().new_stream("stats",stats_options); //FIXME get_printer().new_stream("live",live_options); } // Ensure that MPI processes have the same IDs for auxiliary print streams; Gambit::Scanner::assign_aux_numbers("Posterior","LastLive"); //Run PolyChord, passing callback functions for the loglike and dumper. if(myrank == 0) std::cout << "Starting PolyChord run..." << std::endl; run_polychord(Gambit::PolyChord::callback_loglike, Gambit::PolyChord::callback_dumper, settings); if(myrank == 0) std::cout << "PolyChord run finished!" << std::endl; return 0; } } /// ================================================= /// Function definitions /// ================================================= namespace Gambit { namespace PolyChord { ///@{ Plain-vanilla functions to pass to PolyChord for the callback // Note: we are using the c interface from cwrapper.f90, so the function // signature is a little different than in the polychord examples. double callback_loglike(double *Cube, int ndim, double* phi, int nderived) { // Call global interface to ScannerBit loglikelihood function // Could also pass this object in via context pointer, but that // involves some casting and could risk a segfault. return global_loglike_object->LogLike(Cube, ndim, phi, nderived); } void callback_dumper(int ndead, int nlive, int npars, double *live, double *dead, double* logweights, double logZ, double logZerr) { global_loglike_object-> dumper(ndead, nlive, npars, live, dead, logweights, logZ, logZerr); } ///@} /// LogLikeWrapper Constructor LogLikeWrapper::LogLikeWrapper(scanPtr loglike, printer_interface& printer) : boundLogLike(loglike), boundPrinter(printer) { } /// Main interface function from PolyChord to ScannerBit-supplied loglikelihood function /// This is the function that will be passed to PolyChord as the /// loglike callback routine /// /// Input arguments /// ndim = dimensionality (total number of free parameters) of the problem /// nderived = total number of derived parameters /// Cube[ndim] = ndim parameters /// /// Output arguments /// phi[nderived] = nderived devired parameters /// lnew = loglikelihood /// double LogLikeWrapper::LogLike(double *Cube, int ndim, double* phi, int nderived) { // Cached "below threshold" unitcube parameters of the previous point. static int ndim_threshold = std::accumulate( boundSettings.grade_dims.begin(), boundSettings.grade_dims.begin() + printer_speed_threshold, 0); static std::vector<double> prev_slow_unit(ndim_threshold); //convert C style array to C++ vector class, reordering parameters slow->fast std::vector<std::string> params = boundLogLike->getShownParameters(); std::vector<double> unitpars(ndim); for (auto i=0; i<ndim; i++) unitpars[i] = Cube[index_map[params[i]]]; std::vector<double> derived(phi, phi + nderived); // Disable the printer when the unitcube parameters with speeds below // the threshold have not changed and enable it otherwise // (It might be probably already enabled again at that point) if ( ndim_threshold < ndim && std::equal(prev_slow_unit.begin(),prev_slow_unit.end(),Cube) ) { boundLogLike->getPrinter().disable(); } else { boundLogLike->getPrinter().enable(); } prev_slow_unit = std::vector<double>(Cube,Cube+ndim_threshold); double lnew = boundLogLike(unitpars); // Done! (lnew will be used by PolyChord to guide the search) // Get the transformed parameters and add them as derived parameters if (nderived > 2) { std::unordered_map<std::string,double> param_map; boundLogLike->getPrior().transform(unitpars, param_map); for (auto& param: param_map) { // param_map contains ALL parameters. // We just need the ones which are varied (i.e. the keys of index_map) if (index_map.find(param.first) != index_map.end()) phi[index_map[param.first]] = param.second; } } // Get, set and ouptut the process rank and this point's ID int myrank = boundLogLike->getRank(); // MPI rank of this process int pointID = boundLogLike->getPtID(); // point ID number phi[nderived - 2] = myrank; phi[nderived - 1] = pointID; return lnew; } /// Main interface to PolyChord dumper routine /// The dumper routine will be called every time the live points compress by a factor compression_factor /// PolyChord does not need to the user to do anything. User can use the arguments in whichever way they want /// /// Arguments: /// /// ndead = total number of discarded points for posterior usage /// nlive = total number of live points /// nPar = total number of parameters + 2 (free + derived + 2) /// live[nlive*npars] = 2D array containing the last set of live points /// (physical parameters plus derived parameters + birth contour + death contour) /// dead[ndead*npars] = posterior distribution containing nSamples points. /// Each sample has nPar parameters (physical + derived) /// along with the their loglike value & posterior probability /// logweights[ndead] = log of posterior weighting of dead points. Use this to turn them into posterior weighted samples /// logZ = log evidence value /// logZerr = error on log evidence value void LogLikeWrapper::dumper(int ndead, int nlive, int npars, double *live, double *dead, double* logweights, double /*logZ*/, double /*logZerr*/) { int thisrank = boundPrinter.get_stream()->getRank(); // MPI rank of this process if(thisrank!=0) { scan_err <<"Error! ScannerBit PolyChord plugin attempted to run 'dumper' function on a worker process " <<"(thisrank=="<<thisrank<<")! PolyChord should only try to run this function on the master " <<"process. Most likely this means that your PolyChord installation is not running in MPI mode " <<"correctly, and is actually running independent scans on each process. Alternatively, the " <<"version of PolyChord you are using may be too far ahead of what this plugin can handle, " <<"if e.g. the described behaviour has changed since this plugin was written." << scan_end; } // Write a file at first run of dumper to specify the index of a given dataset. static bool first = true; if (first) { int ndim = boundSettings.nDims; int nderived = boundSettings.nDerived; // Construct the inversed index map // map[polychord_hypercube] = {name, gambit_hypercube} std::vector<std::string> params = boundLogLike->getShownParameters(); std::map<int,std::pair<std::string,int>> inversed_map; for (int i=0; i<ndim; ++i) inversed_map[index_map[params[i]]] = {params[i],i}; std::ostringstream fname; fname << boundSettings.base_dir << "/" <<boundSettings.file_root << ".indices"; std::ofstream ofs(fname.str()); int index = 0; ofs << index++ << "\t" << "Posterior" << std::endl; ofs << index++ << "\t" << "-2*(" << boundLogLike->getPurpose() << ")" << std::endl; for (int i=0; i<ndim; ++i) ofs << index++ << "\t" << "unitCubeParameters[" << inversed_map[i].second <<"]" << std::endl; for (int i=0; i<nderived -2; ++i) ofs << index++ << "\t" << inversed_map[i].first << std::endl; ofs << index++ << "\t" << "MPIrank" << std::endl; ofs << index++ << "\t" << "pointID" << std::endl; ofs.close(); } first = false; // Get printers for each auxiliary stream printer* txt_stream( boundPrinter.get_stream("txt") ); printer* live_stream( boundPrinter.get_stream("live") ); // Reset the print streams. WARNING! This potentially deletes the old data (here we overwrite it on purpose) txt_stream->reset(); live_stream->reset(); // Ensure the "quantity" IDcode is UNIQUE across all printers! This way fancy printers // have the option of ignoring duplicate writes and doing things like combine all the // auxiliary streams into a single database. But must be able to assume IDcodes are // unique for a given quanity to do this. // Negative numbers not used by functors, so those are 'safe' to use here // The discarded live points (and rejected candidate live points if IS = 1) for( int i_dead = 0; i_dead < ndead; i_dead++ ) { int myrank = dead[npars*i_dead + npars-4]; //MPI rank stored in fourth last column int pointID = dead[npars*i_dead + npars-3]; //pointID stored in third last column double logw = logweights[i_dead]; //posterior weight stored in logweights double birth = dead[npars*i_dead + npars-2]; // birth contours double death = dead[npars*i_dead + npars-1]; // death contours txt_stream->print( std::exp(logw), "Posterior", myrank, pointID); txt_stream->print( birth, "LogLike_birth", myrank, pointID); txt_stream->print( death, "LogLike_death", myrank, pointID); } // The last set of live points for( int i_live = 0; i_live < nlive; i_live++ ) { int myrank = live[npars*i_live + npars-4]; //MPI rank stored in fourth last column int pointID = live[npars*i_live + npars-3]; //pointID stored in third last column live_stream->print( true, "LastLive", myrank, pointID); // Flag which points were the last live set } } } }
48.271335
182
0.614098
sebhoof
b72faa3af2987906a98316a5bd7213df17989063
2,109
cpp
C++
ModelItems/VarPathModelItem.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
ModelItems/VarPathModelItem.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
ModelItems/VarPathModelItem.cpp
yoann01/FabricUI
d4d24f25245b8ccd2d206aded2b6c5f2aca09155
[ "BSD-3-Clause" ]
null
null
null
// // Copyright (c) 2010-2017 Fabric Software Inc. All rights reserved. // #include <assert.h> #include <FabricUI/DFG/DFGUICmdHandler.h> #include <FabricUI/ModelItems/VarPathModelItem.h> #include <FabricUI/ModelItems/VarPathItemMetadata.h> #include <QStringList> namespace FabricUI { namespace ModelItems { ////////////////////////////////////////////////////////////////////////// VarPathModelItem::VarPathModelItem( DFG::DFGUICmdHandler *dfgUICmdHandler, FabricCore::DFGBinding binding, FTL::StrRef execPath, FabricCore::DFGExec exec, FTL::StrRef refName ) : m_dfgUICmdHandler( dfgUICmdHandler ) , m_binding( binding ) , m_execPath( execPath ) , m_exec( exec ) , m_refName( refName ) , m_metadata( 0 ) { } VarPathModelItem::~VarPathModelItem() { delete m_metadata; } FTL::CStrRef VarPathModelItem::getName() { return FTL_STR("varPath"); } bool VarPathModelItem::canRename() { return false; } void VarPathModelItem::rename( FTL::CStrRef newName ) { assert( false ); } void VarPathModelItem::onRenamed( FTL::CStrRef oldName, FTL::CStrRef newName ) { assert( false ); } QVariant VarPathModelItem::getValue() { FTL::CStrRef varPath = m_exec.getRefVarPath( m_refName.c_str() ); if ( !varPath.empty() ) return QVariant( QString::fromUtf8( varPath.data(), varPath.size() ) ); else return QVariant( QString() ); } void VarPathModelItem::setValue( QVariant value, bool commit, QVariant valueAtInteractionBegin ) { if(commit) m_dfgUICmdHandler->dfgDoSetRefVarPath( m_binding, m_execPath.c_str(), m_exec, m_refName.c_str(), value.toString()); } bool VarPathModelItem::hasDefault() { return false; } void VarPathModelItem::resetToDefault() { assert( false ); } FabricUI::ValueEditor::ItemMetadata *VarPathModelItem::getMetadata() { if ( !m_metadata ) m_metadata = new VarPathItemMetadata( this ); return m_metadata; } void VarPathModelItem::setMetadataImp( const char* key, const char* value, bool canUndo ) /**/ { assert( false ); } } // namespace ModelItems } // namespace FabricUI
19
75
0.682314
yoann01
b734f0cd3f3cc7fa7d4671f172f94cf7d4a471b7
2,361
cpp
C++
Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2022-03-16T14:31:36.000Z
2022-03-16T14:31:36.000Z
Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
null
null
null
Examples/CPP/WorkingWithResourceAssignments/GetResourceAssignmentOvertimes.cpp
aspose-tasks/Aspose.Tasks-for-C
acb3e2b75685f65cbe34dd739c7eae0dfc285aa1
[ "MIT" ]
1
2020-07-01T01:26:17.000Z
2020-07-01T01:26:17.000Z
#include "GetResourceAssignmentOvertimes.h" #include <system/type_info.h> #include <system/string.h> #include <system/shared_ptr.h> #include <system/reflection/method_base.h> #include <system/object_ext.h> #include <system/object.h> #include <system/decimal.h> #include <system/console.h> #include <system/collections/ienumerator.h> #include <ResourceAssignmentCollection.h> #include <ResourceAssignment.h> #include <Project.h> #include <Key.h> #include <enums/AsnKey.h> #include <Duration.h> #include <Asn.h> #include "RunExamples.h" namespace Aspose { namespace Tasks { namespace Examples { namespace CPP { namespace WorkingWithResourceAssignments { RTTI_INFO_IMPL_HASH(3423715729u, ::Aspose::Tasks::Examples::CPP::WorkingWithResourceAssignments::GetResourceAssignmentOvertimes, ThisTypeBaseTypesInfo); void GetResourceAssignmentOvertimes::Run() { // The path to the documents directory. System::String dataDir = RunExamples::GetDataDir(System::Reflection::MethodBase::GetCurrentMethod(ASPOSE_CURRENT_FUNCTION)->get_DeclaringType().get_FullName()); // ExStart:GetResourceAssignmentOvertimes // Create project instance System::SharedPtr<Project> project1 = System::MakeObject<Project>(dataDir + u"ResourceAssignmentOvertimes.mpp"); // Print assignment overtimes { auto ra_enumerator = (project1->get_ResourceAssignments())->GetEnumerator(); decltype(ra_enumerator->get_Current()) ra; while (ra_enumerator->MoveNext() && (ra = ra_enumerator->get_Current(), true)) { System::Console::WriteLine(ra->Get<System::Decimal>(Asn::OvertimeCost())); System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::OvertimeWork()))); System::Console::WriteLine(ra->Get<System::Decimal>(Asn::RemainingCost())); System::Console::WriteLine(ra->Get<System::Decimal>(Asn::RemainingOvertimeCost())); System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::RemainingOvertimeWork()))); System::Console::WriteLine(System::ObjectExt::ToString(ra->Get<Duration>(Asn::RemainingOvertimeWork()))); } } // ExEnd:GetResourceAssignmentOvertimes } } // namespace WorkingWithResourceAssignments } // namespace CPP } // namespace Examples } // namespace Tasks } // namespace Aspose
35.772727
164
0.725964
aspose-tasks
b73b91877c6c37a97da62a77dd2023b25fd36147
1,310
cpp
C++
week 4/Linked List/10. Minimum Platforms .cpp
arpit456jain/gfg-11-Weeks-Workshop-on-DSA-in-CPP
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
[ "MIT" ]
6
2021-08-06T14:36:41.000Z
2022-03-22T11:22:07.000Z
week 4/Linked List/10. Minimum Platforms .cpp
arpit456jain/11-Weeks-Workshop-on-DSA-in-CPP
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
[ "MIT" ]
1
2021-08-09T05:09:48.000Z
2021-08-09T05:09:48.000Z
week 4/Linked List/10. Minimum Platforms .cpp
arpit456jain/11-Weeks-Workshop-on-DSA-in-CPP
ed7fd8bc0a581f54ba3a3588dd01013776c4ece6
[ "MIT" ]
1
2021-08-09T14:25:17.000Z
2021-08-09T14:25:17.000Z
// { Driver Code Starts // Program to find minimum number of platforms // required on a railway station #include <bits/stdc++.h> using namespace std; // } Driver Code Ends class Solution{ public: //Function to find the minimum number of platforms required at the //railway station such that no train waits. int findPlatform(int arr[], int dep[], int n) { // Your code here sort(arr,arr+n); sort(dep,dep+n); int i=1; // we are considring the 1 train is arived int j=0; // its not dept int max_plat = 1; int plat = 1; while(i<n && j<n) { if(arr[i]<=dep[j]) { plat++; i++; } else if(arr[i]>dep[j]) { plat--; j++; } max_plat = max(max_plat,plat); } return max_plat; } }; // { Driver Code Starts. // Driver code int main() { int t; cin>>t; while(t--) { int n; cin>>n; int arr[n]; int dep[n]; for(int i=0;i<n;i++) cin>>arr[i]; for(int j=0;j<n;j++){ cin>>dep[j]; } Solution ob; cout <<ob.findPlatform(arr, dep, n)<<endl; } return 0; } // } Driver Code Ends
19.264706
70
0.468702
arpit456jain
b73fb29122ad1d5fb7d2b4bfdd756a4d1bbf966e
9,819
cc
C++
content/browser/renderer_host/async_resource_handler.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
content/browser/renderer_host/async_resource_handler.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
content/browser/renderer_host/async_resource_handler.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2012 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 "content/browser/renderer_host/async_resource_handler.h" #include <algorithm> #include <vector> #include "base/debug/alias.h" #include "base/hash_tables.h" #include "base/logging.h" #include "base/shared_memory.h" #include "content/browser/debugger/devtools_netlog_observer.h" #include "content/browser/host_zoom_map_impl.h" #include "content/browser/renderer_host/resource_dispatcher_host_impl.h" #include "content/browser/renderer_host/resource_message_filter.h" #include "content/browser/resource_context_impl.h" #include "content/common/resource_messages.h" #include "content/common/view_messages.h" #include "content/public/browser/global_request_id.h" #include "content/public/browser/resource_dispatcher_host_delegate.h" #include "content/public/browser/resource_request_info.h" #include "content/public/common/resource_response.h" #include "net/base/io_buffer.h" #include "net/base/load_flags.h" #include "net/base/net_log.h" #include "webkit/glue/resource_loader_bridge.h" using base::TimeTicks; namespace content { namespace { // When reading, we don't know if we are going to get EOF (0 bytes read), so // we typically have a buffer that we allocated but did not use. We keep // this buffer around for the next read as a small optimization. SharedIOBuffer* g_spare_read_buffer = NULL; // The initial size of the shared memory buffer. (32 kilobytes). const int kInitialReadBufSize = 32768; // The maximum size of the shared memory buffer. (512 kilobytes). const int kMaxReadBufSize = 524288; } // namespace // Our version of IOBuffer that uses shared memory. class SharedIOBuffer : public net::IOBuffer { public: explicit SharedIOBuffer(int buffer_size) : net::IOBuffer(), ok_(false), buffer_size_(buffer_size) {} bool Init() { if (shared_memory_.CreateAndMapAnonymous(buffer_size_)) { data_ = reinterpret_cast<char*>(shared_memory_.memory()); DCHECK(data_); ok_ = true; } return ok_; } base::SharedMemory* shared_memory() { return &shared_memory_; } bool ok() { return ok_; } int buffer_size() { return buffer_size_; } private: ~SharedIOBuffer() { DCHECK(g_spare_read_buffer != this); data_ = NULL; } base::SharedMemory shared_memory_; bool ok_; int buffer_size_; }; AsyncResourceHandler::AsyncResourceHandler( ResourceMessageFilter* filter, int routing_id, const GURL& url, ResourceDispatcherHostImpl* rdh) : filter_(filter), routing_id_(routing_id), rdh_(rdh), next_buffer_size_(kInitialReadBufSize), url_(url) { } AsyncResourceHandler::~AsyncResourceHandler() { } bool AsyncResourceHandler::OnUploadProgress(int request_id, uint64 position, uint64 size) { return filter_->Send(new ResourceMsg_UploadProgress(routing_id_, request_id, position, size)); } bool AsyncResourceHandler::OnRequestRedirected( int request_id, const GURL& new_url, content::ResourceResponse* response, bool* defer) { *defer = true; net::URLRequest* request = rdh_->GetURLRequest( GlobalRequestID(filter_->child_id(), request_id)); if (rdh_->delegate()) rdh_->delegate()->OnRequestRedirected(request, response); DevToolsNetLogObserver::PopulateResponseInfo(request, response); response->request_start = request->creation_time(); response->response_start = TimeTicks::Now(); return filter_->Send(new ResourceMsg_ReceivedRedirect( routing_id_, request_id, new_url, *response)); } bool AsyncResourceHandler::OnResponseStarted( int request_id, content::ResourceResponse* response) { // For changes to the main frame, inform the renderer of the new URL's // per-host settings before the request actually commits. This way the // renderer will be able to set these precisely at the time the // request commits, avoiding the possibility of e.g. zooming the old content // or of having to layout the new content twice. net::URLRequest* request = rdh_->GetURLRequest( GlobalRequestID(filter_->child_id(), request_id)); if (rdh_->delegate()) rdh_->delegate()->OnResponseStarted(request, response, filter_); DevToolsNetLogObserver::PopulateResponseInfo(request, response); content::ResourceContext* resource_context = filter_->resource_context(); content::HostZoomMap* host_zoom_map = content::GetHostZoomMapForResourceContext(resource_context); const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request); if (info->GetResourceType() == ResourceType::MAIN_FRAME && host_zoom_map) { GURL request_url(request->url()); filter_->Send(new ViewMsg_SetZoomLevelForLoadingURL( info->GetRouteID(), request_url, host_zoom_map->GetZoomLevel(net::GetHostOrSpecFromURL( request_url)))); } response->request_start = request->creation_time(); response->response_start = TimeTicks::Now(); filter_->Send(new ResourceMsg_ReceivedResponse( routing_id_, request_id, *response)); if (request->response_info().metadata) { std::vector<char> copy(request->response_info().metadata->data(), request->response_info().metadata->data() + request->response_info().metadata->size()); filter_->Send(new ResourceMsg_ReceivedCachedMetadata( routing_id_, request_id, copy)); } return true; } bool AsyncResourceHandler::OnWillStart(int request_id, const GURL& url, bool* defer) { return true; } bool AsyncResourceHandler::OnWillRead(int request_id, net::IOBuffer** buf, int* buf_size, int min_size) { DCHECK_EQ(-1, min_size); if (g_spare_read_buffer) { DCHECK(!read_buffer_); read_buffer_.swap(&g_spare_read_buffer); DCHECK(read_buffer_->data()); *buf = read_buffer_.get(); *buf_size = read_buffer_->buffer_size(); } else { read_buffer_ = new SharedIOBuffer(next_buffer_size_); if (!read_buffer_->Init()) { DLOG(ERROR) << "Couldn't allocate shared io buffer"; read_buffer_ = NULL; return false; } DCHECK(read_buffer_->data()); *buf = read_buffer_.get(); *buf_size = next_buffer_size_; } return true; } bool AsyncResourceHandler::OnReadCompleted(int request_id, int* bytes_read) { if (!*bytes_read) return true; DCHECK(read_buffer_.get()); if (read_buffer_->buffer_size() == *bytes_read) { // The network layer has saturated our buffer. Next time, we should give it // a bigger buffer for it to fill, to minimize the number of round trips we // do with the renderer process. next_buffer_size_ = std::min(next_buffer_size_ * 2, kMaxReadBufSize); } if (!rdh_->WillSendData(filter_->child_id(), request_id)) { // We should not send this data now, we have too many pending requests. return true; } base::SharedMemoryHandle handle; if (!read_buffer_->shared_memory()->GiveToProcess( filter_->peer_handle(), &handle)) { // We wrongfully incremented the pending data count. Fake an ACK message // to fix this. We can't move this call above the WillSendData because // it's killing our read_buffer_, and we don't want that when we pause // the request. rdh_->DataReceivedACK(filter_->child_id(), request_id); // We just unmapped the memory. read_buffer_ = NULL; return false; } // We just unmapped the memory. read_buffer_ = NULL; net::URLRequest* request = rdh_->GetURLRequest( GlobalRequestID(filter_->child_id(), request_id)); int encoded_data_length = DevToolsNetLogObserver::GetAndResetEncodedDataLength(request); filter_->Send(new ResourceMsg_DataReceived( routing_id_, request_id, handle, *bytes_read, encoded_data_length)); return true; } void AsyncResourceHandler::OnDataDownloaded( int request_id, int bytes_downloaded) { filter_->Send(new ResourceMsg_DataDownloaded( routing_id_, request_id, bytes_downloaded)); } bool AsyncResourceHandler::OnResponseCompleted( int request_id, const net::URLRequestStatus& status, const std::string& security_info) { // If we crash here, figure out what URL the renderer was requesting. // http://crbug.com/107692 char url_buf[128]; base::strlcpy(url_buf, url_.spec().c_str(), arraysize(url_buf)); base::debug::Alias(url_buf); TimeTicks completion_time = TimeTicks::Now(); filter_->Send(new ResourceMsg_RequestComplete(routing_id_, request_id, status, security_info, completion_time)); // If we still have a read buffer, then see about caching it for later... // Note that we have to make sure the buffer is not still being used, so we // have to perform an explicit check on the status code. if (g_spare_read_buffer || net::URLRequestStatus::SUCCESS != status.status()) { read_buffer_ = NULL; } else if (read_buffer_.get()) { DCHECK(read_buffer_->data()); read_buffer_.swap(&g_spare_read_buffer); } return true; } void AsyncResourceHandler::OnRequestClosed() { } // static void AsyncResourceHandler::GlobalCleanup() { if (g_spare_read_buffer) { // Avoid the CHECK in SharedIOBuffer::~SharedIOBuffer(). SharedIOBuffer* tmp = g_spare_read_buffer; g_spare_read_buffer = NULL; tmp->Release(); } } } // namespace content
33.858621
79
0.690702
Scopetta197
b73fce49595bcb5c50d37701f3db5ffd4bff29e6
2,052
cpp
C++
src/VisumScriptMain.cpp
Mokon/visum
53f602fcf22eadd60f446d04a26b4a6e7217c052
[ "RSA-MD" ]
null
null
null
src/VisumScriptMain.cpp
Mokon/visum
53f602fcf22eadd60f446d04a26b4a6e7217c052
[ "RSA-MD" ]
null
null
null
src/VisumScriptMain.cpp
Mokon/visum
53f602fcf22eadd60f446d04a26b4a6e7217c052
[ "RSA-MD" ]
null
null
null
/* Copyright (C) 2013-2016 David 'Mokon' Bond, All Rights Reserved */ #include <config.h> #include <glog/logging.h> #include <visum/entities/common/Bank.hpp> #include <visum/entities/common/CreditCard.hpp> #include <visum/entities/common/Person.hpp> #include <visum/entities/Entity.hpp> #include <visum/entities/EntityGraph.hpp> #include <visum/events/actions/BankDepositFunds.hpp> #include <visum/events/Event.hpp> #include <visum/events/repeats/Once.hpp> #include <visum/types/positions/Account.hpp> namespace visum { // TODO (005) remove this exe once we load from a text script inline void printStaticGraph() { auto eg = std::make_shared<EntityGraph>(localTime()); auto person = std::make_shared<Person>("person"); auto bank = std::make_shared<Bank>("bank"); auto creditcard = std::make_shared<CreditCard>("creditcard"); eg->graph::Graph::add(person); eg->graph::Graph::add(bank); eg->graph::Graph::add(creditcard); auto checking = bank->createAccount(person); auto cc = creditcard->createAccount(person); auto once = std::make_shared<Once>(eg->getSimulationTime()); auto event = std::make_shared<BankDepositFunds>(checking, bank, person, Currency(100, Currency::Code::USD)); auto initialBalance = std::make_shared<Event>("initial balance", once, event); eg->add(initialBalance); cereal::JSONOutputArchive ar(std::cout); ar(cereal::make_nvp("entityGraph", eg)); } } int main(int argc, char* argv[]) { int ret = EXIT_SUCCESS; try { assert(argc); google::InitGoogleLogging(argv[0]); google::InstallFailureSignalHandler(); google::SetStderrLogging(google::INFO); visum::printStaticGraph(); } catch(const std::exception& ex) { LOG(ERROR) << ex.what() << std::endl; ret = EXIT_FAILURE; } catch (...) { LOG(ERROR) << "Caught thrown" << std::endl; ret = EXIT_FAILURE; } return ret; }
30.626866
96
0.640838
Mokon
b74115f46e59ed50c0fc8073187eebec5c4d43a4
10,906
cc
C++
internal/platform/implementation/g3/wifi_hotspot.cc
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
69
2021-10-18T00:37:29.000Z
2022-03-20T19:53:38.000Z
internal/platform/implementation/g3/wifi_hotspot.cc
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
14
2021-10-13T19:49:27.000Z
2022-03-31T22:19:13.000Z
internal/platform/implementation/g3/wifi_hotspot.cc
google/nearby
1aeb1093a9864c73394d27598684f2e9287d6e4e
[ "Apache-2.0" ]
22
2021-10-20T12:36:47.000Z
2022-03-31T18:39:46.000Z
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "internal/platform/implementation/g3/wifi_hotspot.h" #include <functional> #include <iostream> #include <memory> #include <optional> #include <string> #include <utility> #include "absl/strings/str_format.h" #include "absl/synchronization/mutex.h" #include "internal/platform/implementation/wifi_hotspot.h" #include "internal/platform/cancellation_flag_listener.h" #include "internal/platform/logging.h" #include "internal/platform/medium_environment.h" namespace location { namespace nearby { namespace g3 { // Code for WifiHotspotSocket WifiHotspotSocket::~WifiHotspotSocket() { absl::MutexLock lock(&mutex_); DoClose(); } void WifiHotspotSocket::Connect(WifiHotspotSocket& other) { absl::MutexLock lock(&mutex_); remote_socket_ = &other; input_ = other.output_; } InputStream& WifiHotspotSocket::GetInputStream() { auto* remote_socket = GetRemoteSocket(); CHECK(remote_socket != nullptr); return remote_socket->GetLocalInputStream(); } OutputStream& WifiHotspotSocket::GetOutputStream() { return GetLocalOutputStream(); } WifiHotspotSocket* WifiHotspotSocket::GetRemoteSocket() { absl::MutexLock lock(&mutex_); return remote_socket_; } bool WifiHotspotSocket::IsConnected() const { absl::MutexLock lock(&mutex_); return IsConnectedLocked(); } bool WifiHotspotSocket::IsClosed() const { absl::MutexLock lock(&mutex_); return closed_; } Exception WifiHotspotSocket::Close() { absl::MutexLock lock(&mutex_); DoClose(); return {Exception::kSuccess}; } void WifiHotspotSocket::DoClose() { if (!closed_) { remote_socket_ = nullptr; output_->GetOutputStream().Close(); output_->GetInputStream().Close(); input_->GetOutputStream().Close(); input_->GetInputStream().Close(); closed_ = true; } } bool WifiHotspotSocket::IsConnectedLocked() const { return input_ != nullptr; } InputStream& WifiHotspotSocket::GetLocalInputStream() { absl::MutexLock lock(&mutex_); return output_->GetInputStream(); } OutputStream& WifiHotspotSocket::GetLocalOutputStream() { absl::MutexLock lock(&mutex_); return output_->GetOutputStream(); } // Code for WifiHotspotServerSocket std::string WifiHotspotServerSocket::GetName(absl::string_view ip_address, int port) { return absl::StrCat(ip_address, ":", port); } std::unique_ptr<api::WifiHotspotSocket> WifiHotspotServerSocket::Accept() { absl::MutexLock lock(&mutex_); while (!closed_ && pending_sockets_.empty()) { cond_.Wait(&mutex_); } // whether or not we were running in the wait loop, return early if closed. if (closed_) return {}; auto* remote_socket = pending_sockets_.extract(pending_sockets_.begin()).value(); CHECK(remote_socket); auto local_socket = std::make_unique<WifiHotspotSocket>(); local_socket->Connect(*remote_socket); remote_socket->Connect(*local_socket); cond_.SignalAll(); return local_socket; } bool WifiHotspotServerSocket::Connect(WifiHotspotSocket& socket) { absl::MutexLock lock(&mutex_); if (closed_) return false; if (socket.IsConnected()) { NEARBY_LOGS(ERROR) << "Failed to connect to WifiHotspot server socket: already connected"; return true; // already connected. } // add client socket to the pending list pending_sockets_.insert(&socket); cond_.SignalAll(); while (!socket.IsConnected()) { cond_.Wait(&mutex_); if (closed_) return false; } return true; } void WifiHotspotServerSocket::SetCloseNotifier(std::function<void()> notifier) { absl::MutexLock lock(&mutex_); close_notifier_ = std::move(notifier); } WifiHotspotServerSocket::~WifiHotspotServerSocket() { absl::MutexLock lock(&mutex_); DoClose(); } Exception WifiHotspotServerSocket::Close() { absl::MutexLock lock(&mutex_); return DoClose(); } Exception WifiHotspotServerSocket::DoClose() { bool should_notify = !closed_; closed_ = true; if (should_notify) { cond_.SignalAll(); if (close_notifier_) { auto notifier = std::move(close_notifier_); mutex_.Unlock(); // Notifier may contain calls to public API, and may cause deadlock, if // mutex_ is held during the call. notifier(); mutex_.Lock(); } } return {Exception::kSuccess}; } // Code for WifiHotspotMedium WifiHotspotMedium::WifiHotspotMedium() { auto& env = MediumEnvironment::Instance(); env.RegisterWifiHotspotMedium(*this); } WifiHotspotMedium::~WifiHotspotMedium() { auto& env = MediumEnvironment::Instance(); env.UnregisterWifiHotspotMedium(*this); } bool WifiHotspotMedium::StartWifiHotspot( HotspotCredentials* hotspot_credentials) { absl::MutexLock lock(&mutex_); if (!IsInterfaceValid()) return false; std::string ssid = absl::StrCat("DIRECT-", Prng().NextUint32()); hotspot_credentials->SetSSID(ssid); std::string password = absl::StrFormat("%08x", Prng().NextUint32()); hotspot_credentials->SetPassword(password); NEARBY_LOGS(INFO) << "G3 StartWifiHotspot: ssid=" << ssid << ", password:" << password; auto& env = MediumEnvironment::Instance(); env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials, /*is_ap=*/true, /*enabled=*/true); return true; } bool WifiHotspotMedium::StopWifiHotspot() { absl::MutexLock lock(&mutex_); NEARBY_LOGS(INFO) << "G3 StopWifiHotspot"; if (!IsInterfaceValid()) return false; auto& env = MediumEnvironment::Instance(); env.UpdateWifiHotspotMediumForStartOrConnect(*this, /*credentials*/nullptr, /*is_ap=*/true, /*enabled=*/false); return true; } bool WifiHotspotMedium::ConnectWifiHotspot( HotspotCredentials* hotspot_credentials) { absl::MutexLock lock(&mutex_); NEARBY_LOGS(INFO) << "G3 ConnectWifiHotspot: ssid=" << hotspot_credentials->GetSSID() << ", password:" << hotspot_credentials->GetPassword(); auto& env = MediumEnvironment::Instance(); auto* remote_medium = static_cast<WifiHotspotMedium*>( env.GetWifiHotspotMedium(hotspot_credentials->GetSSID(), {})); if (!remote_medium) { env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials, /*is_ap=*/false, /*enabled=*/false); return false; } env.UpdateWifiHotspotMediumForStartOrConnect(*this, hotspot_credentials, /*is_ap=*/false, /*enabled=*/true); return true; } bool WifiHotspotMedium::DisconnectWifiHotspot() { absl::MutexLock lock(&mutex_); NEARBY_LOGS(INFO) << "G3 DisconnectWifiHotspot"; auto& env = MediumEnvironment::Instance(); env.UpdateWifiHotspotMediumForStartOrConnect(*this, /*credentials*/nullptr, /*is_ap=*/false, /*enabled=*/false); return true; } std::unique_ptr<api::WifiHotspotSocket> WifiHotspotMedium::ConnectToService( absl::string_view ip_address, int port, CancellationFlag* cancellation_flag) { std::string socket_name = WifiHotspotServerSocket::GetName(ip_address, port); NEARBY_LOGS(INFO) << "G3 WifiHotspot ConnectToService [self]: medium=" << this << ", ip address + port=" << socket_name; // First, find an instance of remote medium, that exposed this service. auto& env = MediumEnvironment::Instance(); auto* remote_medium = static_cast<WifiHotspotMedium*>( env.GetWifiHotspotMedium({}, ip_address)); if (remote_medium == nullptr) { return {}; } WifiHotspotServerSocket* server_socket = nullptr; NEARBY_LOGS(INFO) << "G3 WifiHotspot ConnectToService [peer]: medium=" << remote_medium << ", remote ip address + port=" << socket_name; // Then, find our server socket context in this medium. { absl::MutexLock medium_lock(&remote_medium->mutex_); auto item = remote_medium->server_sockets_.find(socket_name); server_socket = item != server_sockets_.end() ? item->second : nullptr; if (server_socket == nullptr) { NEARBY_LOGS(ERROR) << "G3 WifiHotspot Failed to find WifiHotspot Server " "socket: socket_name=" << socket_name; return {}; } } if (cancellation_flag->Cancelled()) { NEARBY_LOGS(ERROR) << "G3 WifiHotspot Connect: Has been cancelled: socket_name=" << socket_name; return {}; } CancellationFlagListener listener(cancellation_flag, [&server_socket]() { NEARBY_LOGS(INFO) << "G3 WifiHotspot Cancel Connect."; if (server_socket != nullptr) { server_socket->Close(); } }); auto socket = std::make_unique<WifiHotspotSocket>(); // Finally, Request to connect to this socket. if (!server_socket->Connect(*socket)) { NEARBY_LOGS(ERROR) << "G3 WifiHotspot Failed to connect to existing WifiHotspot " "Server socket: name=" << socket_name; return {}; } NEARBY_LOGS(INFO) << "G3 WifiHotspot ConnectToService: connected: socket=" << socket.get(); return socket; } std::unique_ptr<api::WifiHotspotServerSocket> WifiHotspotMedium::ListenForService(int port) { auto& env = MediumEnvironment::Instance(); auto server_socket = std::make_unique<WifiHotspotServerSocket>(); std::string dot_decimal_ip; std::string ip_address = env.GetFakeIPAddress(); if (ip_address.empty()) return nullptr; for (auto byte : ip_address) { absl::StrAppend(&dot_decimal_ip, absl::StrFormat("%d", byte), "."); } dot_decimal_ip.pop_back(); server_socket->SetIPAddress(dot_decimal_ip); server_socket->SetPort(port == 0 ? env.GetFakePort() : port); std::string socket_name = WifiHotspotServerSocket::GetName( server_socket->GetIPAddress(), server_socket->GetPort()); server_socket->SetCloseNotifier([this, socket_name]() { absl::MutexLock lock(&mutex_); server_sockets_.erase(socket_name); }); NEARBY_LOGS(INFO) << "G3 WifiHotspot Adding server socket: medium=" << this << ", socket_name=" << socket_name; absl::MutexLock lock(&mutex_); server_sockets_.insert({socket_name, server_socket.get()}); return server_socket; } } // namespace g3 } // namespace nearby } // namespace location
31.429395
80
0.685953
google
b7415fabb9cac20eba8cc19edb1a7fa026a177f7
1,139
cpp
C++
gpu_lib/external_gpu_algorithm.cpp
ARGO-group/Argo_CUDA
7a15252906860f4a725e37b6add211f625b91869
[ "MIT" ]
null
null
null
gpu_lib/external_gpu_algorithm.cpp
ARGO-group/Argo_CUDA
7a15252906860f4a725e37b6add211f625b91869
[ "MIT" ]
null
null
null
gpu_lib/external_gpu_algorithm.cpp
ARGO-group/Argo_CUDA
7a15252906860f4a725e37b6add211f625b91869
[ "MIT" ]
1
2021-07-10T09:59:52.000Z
2021-07-10T09:59:52.000Z
#include "external_gpu_algorithm.h" #include <thread> #include <config.h> #include <hash_conversions.h> #include <run_parallel.h> #include <safe_counter.h> #include <gpu_info.h> #include "finder_kernel.cuh" void external_gpu_algorithm(const std::vector<uint32_t> &motif_hashes, const SequenceHashes &sequence_hashes, std::vector<uint16_t> &out_motif_weights, const GpuCudaParams &params) { out_motif_weights.resize(motif_hashes.size(), 0); uint32_t threads = (params.gpu_count > 0) ? params.gpu_count : 1; SafeCounter motifs_counter(motif_hashes.size()); run_parallel(threads, [&](uint32_t thread_id) { GpuExternalMemory gpu_memory(params, sequence_hashes); while (true) { const auto range = motifs_counter.get_and_increment_range_info(params.motif_range_size); if (range.count() == 0) { break; } motif_finder_gpu_external( motif_hashes, gpu_memory, params, out_motif_weights, range.start, range.count(), thread_id); } }); }
32.542857
108
0.639157
ARGO-group
b74bf15f46745c90202343ea77a3026b857f93c9
784
cpp
C++
Software/app/nixie_state.cpp
gotlaufs/rtu-nixie-clock
7fe43f13deb8f5314ce19d00fe6623337c0d0df7
[ "MIT" ]
null
null
null
Software/app/nixie_state.cpp
gotlaufs/rtu-nixie-clock
7fe43f13deb8f5314ce19d00fe6623337c0d0df7
[ "MIT" ]
5
2019-02-19T22:23:19.000Z
2019-02-19T22:27:27.000Z
Software/app/nixie_state.cpp
gotlaufs/rtu-nixie-clock
7fe43f13deb8f5314ce19d00fe6623337c0d0df7
[ "MIT" ]
null
null
null
// Nixie state class implementation #include "nixie_state.h" NixieState::NixieState(NixieClock & app_) : app(app_) { memset(&nixie_data, 0, sizeof(nixie_data_type)); } void NixieState::writeTimeToNixie() { if (sec > 99) { // Blank tubes if too big digit nixie_data.N6 = 10; nixie_data.N5 = 10; } else { nixie_data.N6 = sec % 10; nixie_data.N5 = sec / 10; } if (min > 99) { nixie_data.N4 = 10; nixie_data.N3 = 10; } else { nixie_data.N4 = min % 10; nixie_data.N3 = min / 10; } if (hour > 99) { nixie_data.N2 = 10; nixie_data.N1 = 10; } else { nixie_data.N2 = hour % 10; nixie_data.N1 = hour / 10; } }
17.422222
53
0.512755
gotlaufs
b74c2f463fe2ec1f3eab79af4dbebde53df4d597
90
cpp
C++
core/src/backend/task/FunctionDataTemplate.cpp
ExaBerries/spruce
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
[ "MIT" ]
null
null
null
core/src/backend/task/FunctionDataTemplate.cpp
ExaBerries/spruce
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
[ "MIT" ]
null
null
null
core/src/backend/task/FunctionDataTemplate.cpp
ExaBerries/spruce
85845244f7d6cd5a662f0dbc9b4079a1230d9a4b
[ "MIT" ]
null
null
null
#include <backend/task/FunctionDataTemplate.h> namespace spruce { namespace task { } }
12.857143
46
0.744444
ExaBerries
b753e58ff00bc994c8dc9e157fe23b35e3166aa9
8,811
hpp
C++
include/mockturtle/algorithms/aqfp/detail/dag_util.hpp
shi27feng/mockturtle
032dcd590b57040c5ff10d80b515353ffe822671
[ "MIT" ]
null
null
null
include/mockturtle/algorithms/aqfp/detail/dag_util.hpp
shi27feng/mockturtle
032dcd590b57040c5ff10d80b515353ffe822671
[ "MIT" ]
null
null
null
include/mockturtle/algorithms/aqfp/detail/dag_util.hpp
shi27feng/mockturtle
032dcd590b57040c5ff10d80b515353ffe822671
[ "MIT" ]
null
null
null
/* mockturtle: C++ logic network library * Copyright (C) 2018-2021 EPFL * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /*! \file dag_util.hpp \brief Utilities for DAG generation \author Dewmini Marakkalage */ #pragma once #include <map> #include <set> #include <unordered_map> #include <vector> #include <mockturtle/utils/hash_functions.hpp> namespace mockturtle { namespace detail { /*! \brief Computes and returns the frequency map for a given collection of elements. * Use std::map instead of std::unordered_map because we use it as a key in a hash-table so the order is important to compute the hash */ template<typename ElemT> inline std::map<ElemT, uint32_t> get_frequencies( const std::vector<ElemT>& elems ) { std::map<ElemT, uint32_t> elem_counts; std::for_each( elems.begin(), elems.end(), [&elem_counts]( auto e ) { elem_counts[e]++; } ); return elem_counts; } template<typename ElemT> class partition_generator { using part = std::multiset<ElemT>; using partition = std::multiset<part>; using partition_set = std::set<partition>; using inner_cache_key_t = std::vector<ElemT>; using inner_cache_t = std::unordered_map<inner_cache_key_t, partition_set, hash<inner_cache_key_t>>; using outer_cache_key_t = std::tuple<std::vector<uint32_t>, uint32_t, uint32_t>; using outer_cache_t = std::unordered_map<outer_cache_key_t, inner_cache_t, hash<outer_cache_key_t>>; public: /*! \brief Computes and returns a set of partitions for a given list of elements * such that no part contains any element `e` more than `max_counts[e]` times. */ partition_set operator()( std::vector<int> elems, const std::vector<uint32_t>& max_counts = {}, uint32_t max_parts = 0, uint32_t max_part_size = 0 ) { _elems = elems; _max_counts = max_counts; _max_parts = max_parts; _max_part_size = max_part_size; const outer_cache_key_t key = { _max_counts, _max_parts, _max_part_size }; partition_cache = outer_cache.insert( { key, inner_cache_t() } ).first; return get_all_partitions(); } private: outer_cache_t outer_cache; typename outer_cache_t::iterator partition_cache; std::vector<ElemT> _elems; std::vector<uint32_t> _max_counts; uint32_t _max_parts; uint32_t _max_part_size; partition_set get_all_partitions() { if ( _elems.size() == 0 ) { return { {} }; // return the empty partition. } inner_cache_key_t key = _elems; if ( partition_cache->second.count( key ) ) { return partition_cache->second.at( key ); } partition_set result; auto last = _elems.back(); _elems.pop_back(); auto temp = get_all_partitions(); for ( auto&& t : temp ) { partition cpy; // take 'last' in its own partition cpy = t; if ( _max_parts == 0u || _max_parts > cpy.size() ) { cpy.insert( { last } ); result.insert( cpy ); } // add 'last' to one of the existing partitions for ( auto it = t.begin(); it != t.end(); ) { if ( _max_counts.empty() || it->count( last ) < _max_counts[last] ) { if ( _max_part_size == 0 || _max_part_size > it->size() ) { cpy = t; auto elem_it = cpy.find( *it ); auto cpy_elem = *elem_it; cpy_elem.insert( last ); cpy.erase( elem_it ); cpy.insert( cpy_elem ); result.insert( cpy ); } } std::advance( it, t.count( *it ) ); } } return ( partition_cache->second[key] = result ); } }; template<typename ElemT> class partition_extender { using part = std::multiset<ElemT>; using partition = std::multiset<part>; using partition_set = std::set<partition>; using inner_cache_key_t = std::vector<ElemT>; using inner_cache_t = std::unordered_map<inner_cache_key_t, partition_set, hash<inner_cache_key_t>>; using outer_cache_key_t = std::tuple<partition, std::vector<uint32_t>, uint32_t>; using outer_cache_t = std::map<outer_cache_key_t, inner_cache_t>; public: /*! \brief Compute a list of different partitions that can be obtained by adding elements * in `elems` to the parts of `base` such that no part contains any element `e` more than * `max_counts[e]` times */ partition_set operator()( std::vector<ElemT> elems, partition base, const std::vector<uint32_t>& max_counts, uint32_t max_part_size = 0 ) { _elems = elems; _base = base; _max_counts = max_counts; _max_part_size = max_part_size; const outer_cache_key_t key = { _base, _max_counts, _max_part_size }; partition_cache = outer_cache.insert( { key, inner_cache_t() } ).first; return extend_partitions(); } private: outer_cache_t outer_cache; typename outer_cache_t::iterator partition_cache; std::vector<ElemT> _elems; partition _base; std::vector<uint32_t> _max_counts; uint32_t _max_part_size; partition_set extend_partitions() { if ( _elems.size() == 0 ) { return { _base }; } inner_cache_key_t key = _elems; if ( partition_cache->second.count( key ) ) { return partition_cache->second.at( key ); } partition_set result; auto last = _elems.back(); _elems.pop_back(); auto temp = extend_partitions(); for ( auto&& t : temp ) { partition cpy; for ( auto it = t.begin(); it != t.end(); ) { if ( it->count( last ) < _max_counts.at( last ) ) { if ( _max_part_size == 0 || _max_part_size > it->size() ) { cpy = t; auto elem_it = cpy.find( *it ); auto cpy_elem = *elem_it; cpy_elem.insert( last ); cpy.erase( elem_it ); cpy.insert( cpy_elem ); result.insert( cpy ); } } std::advance( it, t.count( *it ) ); } } return ( partition_cache->second[key] = result ); } }; template<typename ElemT> struct sublist_generator { using sub_list_cache_key_t = std::map<ElemT, uint32_t>; public: /** * \brief Given a list of elements `elems`, generate all sub lists of those elements. * Ex: if `elems` = [1, 2, 2, 3], this will generate the following lists: * [0], [1], [1, 2], [1, 2, 2], [1, 2, 2, 3], [1, 2, 3], [1, 3], [2], [2, 2], [2, 2, 3], [2, 3], and [3]. */ std::set<std::vector<ElemT>> operator()( std::vector<ElemT> elems ) { elem_counts = get_frequencies( elems ); return get_sub_lists_recur(); } private: std::unordered_map<sub_list_cache_key_t, std::set<std::vector<ElemT>>, hash<sub_list_cache_key_t>> sub_list_cache; std::map<ElemT, uint32_t> elem_counts; std::set<std::vector<ElemT>> get_sub_lists_recur() { if ( elem_counts.size() == 0u ) { return { {} }; } sub_list_cache_key_t key = elem_counts; if ( !sub_list_cache.count( key ) ) { auto last = std::prev( elem_counts.end() ); auto last_elem = last->first; auto last_count = last->second; elem_counts.erase( last ); std::set<std::vector<int>> result; std::vector<int> t; for ( auto i = last_count; i > 0; --i ) { t.push_back( last_elem ); result.insert( t ); // insert a copy of t, and note that t is already sorted. } auto temp = get_sub_lists_recur(); for ( std::vector<int> t : temp ) { result.insert( t ); for ( auto i = last_count; i > 0; --i ) { t.push_back( last_elem ); std::sort( t.begin(), t.end() ); result.insert( t ); } } sub_list_cache[key] = result; } return sub_list_cache[key]; } }; } // namespace detail } // namespace mockturtle
27.794953
139
0.637726
shi27feng
b75582d23033bd9636bd190462cb22da89e5bd0b
61,137
cpp
C++
vphysics_bullet/Physics_Environment.cpp
SwagSoftware/Kisak-Strike
7498c886b5199b37cbd156ceac9377ecac73b982
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
vphysics_bullet/Physics_Environment.cpp
SwagSoftware/Kisak-Strike
7498c886b5199b37cbd156ceac9377ecac73b982
[ "Unlicense" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
vphysics_bullet/Physics_Environment.cpp
SwagSoftware/Kisak-Strike
7498c886b5199b37cbd156ceac9377ecac73b982
[ "Unlicense" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
#include "StdAfx.h" #include <cmodel.h> #include <cstring> #include "Physics_Environment.h" #include "Physics.h" #include "Physics_Object.h" #include "Physics_ShadowController.h" #include "Physics_PlayerController.h" #include "Physics_FluidController.h" #include "Physics_DragController.h" #include "Physics_MotionController.h" #include "Physics_Constraint.h" #include "Physics_Collision.h" #include "Physics_VehicleController.h" #include "miscmath.h" #include "convert.h" #if DEBUG_DRAW #include "DebugDrawer.h" #endif #include "BulletCollision/CollisionDispatch/btDefaultCollisionConfiguration.h" #include "BulletDynamics/MLCPSolvers/btMLCPSolver.h" #include "BulletDynamics/MLCPSolvers/btLemkeSolver.h" #include "BulletDynamics/MLCPSolvers/btDantzigSolver.h" #include "BulletDynamics/MLCPSolvers/btSolveProjectedGaussSeidel.h" #include "BulletDynamics/ConstraintSolver/btNNCGConstraintSolver.h" #include "BulletDynamics/ConstraintSolver/btSequentialImpulseConstraintSolverMt.h" #include "BulletDynamics/Dynamics/btDiscreteDynamicsWorldMt.h" #include "BulletCollision/CollisionDispatch/btCollisionDispatcherMt.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" /***************************** * MISC. CLASSES *****************************/ class IDeleteQueueItem { public: virtual void Delete() = 0; }; template <typename T> class CDeleteProxy : public IDeleteQueueItem { public: CDeleteProxy(T *pItem) : m_pItem(pItem) {} virtual void Delete() override { delete m_pItem; } private: T *m_pItem; }; class CDeleteQueue { public: void Add(IDeleteQueueItem *pItem) { m_list.AddToTail(pItem); } template <typename T> void QueueForDelete(T *pItem) { Add(new CDeleteProxy<T>(pItem)); } void DeleteAll() { for (int i = m_list.Count()-1; i >= 0; --i) { m_list[i]->Delete(); delete m_list[i]; } m_list.RemoveAll(); } private: CUtlVector<IDeleteQueueItem *> m_list; }; bool CCollisionSolver::needBroadphaseCollision(btBroadphaseProxy *proxy0, btBroadphaseProxy *proxy1) const { btRigidBody *body0 = btRigidBody::upcast(static_cast<btCollisionObject*>(proxy0->m_clientObject)); btRigidBody *body1 = btRigidBody::upcast(static_cast<btCollisionObject*>(proxy1->m_clientObject)); if(!body0 || !body1) { // Check if one of them is a soft body // btCollisionObject *colObj0 = static_cast<btCollisionObject*>(proxy0->m_clientObject); // btCollisionObject *colObj1 = static_cast<btCollisionObject*>(proxy1->m_clientObject); // if (colObj0->getInternalType() & btCollisionObject::CO_SOFT_BODY || colObj1->getInternalType() & btCollisionObject::CO_SOFT_BODY) { // return true; // } return (body0 != nullptr && !body0->isStaticObject()) || (body1 != nullptr && !body1->isStaticObject()); } CPhysicsObject *pObject0 = static_cast<CPhysicsObject*>(body0->getUserPointer()); CPhysicsObject *pObject1 = static_cast<CPhysicsObject*>(body1->getUserPointer()); bool collides = NeedsCollision(pObject0, pObject1) && (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask); if (!collides) { // Clean this pair from the cache m_pEnv->GetBulletEnvironment()->getBroadphase()->getOverlappingPairCache()->removeOverlappingPair(proxy0, proxy1, m_pEnv->GetBulletEnvironment()->getDispatcher()); } return collides; } bool CCollisionSolver::NeedsCollision(CPhysicsObject *pObject0, CPhysicsObject *pObject1) const { if (pObject0 && pObject1) { // No static->static collisions if (pObject0->IsStatic() && pObject1->IsStatic()) { return false; } // No shadow->shadow collisions if (pObject0->GetShadowController() && pObject1->GetShadowController()) { return false; } if (!pObject0->IsCollisionEnabled() || !pObject1->IsCollisionEnabled()) { return false; } if ((pObject0->GetCallbackFlags() & CALLBACK_ENABLING_COLLISION) || (pObject1->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE)) { return false; } // No kinematic->static collisions if ((pObject0->GetObject()->getCollisionFlags() & btCollisionObject::CF_KINEMATIC_OBJECT && pObject1->IsStatic()) || (pObject1->GetObject()->getCollisionFlags() & btCollisionObject::CF_KINEMATIC_OBJECT && pObject0->IsStatic())) { return false; } if ((pObject1->GetCallbackFlags() & CALLBACK_ENABLING_COLLISION) || (pObject0->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE)) { return false; } // Most expensive call, do this check last if (m_pSolver && !m_pSolver->ShouldCollide(pObject0, pObject1, pObject0->GetGameData(), pObject1->GetGameData())) { return false; } } else { // One of the objects has no phys object... if (pObject0 && !pObject0->IsCollisionEnabled()) return false; if (pObject1 && !pObject1->IsCollisionEnabled()) return false; } return true; } void SerializeWorld_f(const CCommand &args) { if (args.ArgC() != 3) { Msg("Usage: bt_serialize <index> <name>\n"); return; } CPhysicsEnvironment *pEnv = (CPhysicsEnvironment *)g_Physics.GetActiveEnvironmentByIndex(atoi(args.Arg(2))); if (pEnv) { btDiscreteDynamicsWorld *pWorld = static_cast<btDiscreteDynamicsWorld*>(pEnv->GetBulletEnvironment()); Assert(pWorld); btSerializer *pSerializer = new btDefaultSerializer; pWorld->serialize(pSerializer); // FIXME: We shouldn't be using this. Find the appropiate method from valve interfaces. const char *pName = args.Arg(2); FILE *pFile = fopen(pName, "wb"); if (pFile) { fwrite(pSerializer->getBufferPointer(), pSerializer->getCurrentBufferSize(), 1, pFile); fclose(pFile); } else { Warning("Couldn't open \"%s\" for writing!\n", pName); } } else { Warning("Invalid environment index supplied!\n"); } } static ConCommand cmd_serializeworld("bt_serialize", SerializeWorld_f, "Serialize environment by index (usually 0=server, 1=client)\n\tDumps the file out to the exe directory."); /******************************* * CLASS CObjectTracker *******************************/ class CObjectTracker { public: CObjectTracker(CPhysicsEnvironment *pEnv, IPhysicsObjectEvent *pObjectEvents) { m_pEnv = pEnv; m_pObjEvents = pObjectEvents; } int GetActiveObjectCount() const { return m_activeObjects.Count(); } void GetActiveObjects(IPhysicsObject **pOutputObjectList) const { if (!pOutputObjectList) return; const int size = m_activeObjects.Count(); for (int i = 0; i < size; i++) { pOutputObjectList[i] = m_activeObjects[i]; } } void SetObjectEventHandler(IPhysicsObjectEvent *pEvents) { m_pObjEvents = pEvents; } void ObjectRemoved(CPhysicsObject *pObject) { m_activeObjects.FindAndRemove(pObject); } void Tick() { btDiscreteDynamicsWorld *pBulletEnv = m_pEnv->GetBulletEnvironment(); btCollisionObjectArray &colObjArray = pBulletEnv->getCollisionObjectArray(); for (int i = 0; i < colObjArray.size(); i++) { CPhysicsObject *pObj = static_cast<CPhysicsObject*>(colObjArray[i]->getUserPointer()); if (!pObj) continue; // Internal object that the game doesn't need to know about Assert(*(char *)pObj != 0xDD); // Make sure the object isn't deleted (only works in debug builds) TODO: This can be removed, result is always true // Don't add objects marked for delete if (pObj->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) { continue; } if (colObjArray[i]->getActivationState() != pObj->GetLastActivationState()) { const int newState = colObjArray[i]->getActivationState(); // Not a state we want to track. if (newState == WANTS_DEACTIVATION) continue; if (m_pObjEvents) { switch (newState) { // FIXME: Objects may call objectwake twice if they go from disable_deactivation -> active_tag case DISABLE_DEACTIVATION: case ACTIVE_TAG: m_pObjEvents->ObjectWake(pObj); break; case ISLAND_SLEEPING: m_pObjEvents->ObjectSleep(pObj); break; case DISABLE_SIMULATION: // Don't call ObjectSleep on DISABLE_SIMULATION on purpose. break; default: NOT_IMPLEMENTED; assert(false); } } switch (newState) { case DISABLE_DEACTIVATION: case ACTIVE_TAG: // Don't add the object twice! if (m_activeObjects.Find(pObj) == -1) m_activeObjects.AddToTail(pObj); break; case DISABLE_SIMULATION: case ISLAND_SLEEPING: m_activeObjects.FindAndRemove(pObj); break; default: NOT_IMPLEMENTED; assert(false); } pObj->SetLastActivationState(newState); } } } private: CPhysicsEnvironment *m_pEnv; IPhysicsObjectEvent *m_pObjEvents; CUtlVector<IPhysicsObject *> m_activeObjects; }; /******************************* * CLASS CPhysicsCollisionData *******************************/ class CPhysicsCollisionData : public IPhysicsCollisionData { public: CPhysicsCollisionData(btManifoldPoint *manPoint) { ConvertDirectionToHL(manPoint->m_normalWorldOnB, m_surfaceNormal); ConvertPosToHL(manPoint->getPositionWorldOnA(), m_contactPoint); ConvertPosToHL(manPoint->m_lateralFrictionDir1, m_contactSpeed); // FIXME: Need the correct variable from the manifold point } // normal points toward second object (object index 1) void GetSurfaceNormal(Vector &out) override { out = m_surfaceNormal; } // contact point of collision (in world space) void GetContactPoint(Vector &out) override { out = m_contactPoint; } // speed of surface 1 relative to surface 0 (in world space) void GetContactSpeed(Vector &out) override { out = m_contactSpeed; } private: Vector m_surfaceNormal; Vector m_contactPoint; Vector m_contactSpeed; }; /********************************* * CLASS CCollisionEventListener *********************************/ class CCollisionEventListener : public btSolveCallback { public: CCollisionEventListener(CPhysicsEnvironment *pEnv) { m_pEnv = pEnv; m_pCallback = NULL; } // TODO: Optimize this, heavily! void preSolveContact(btSolverBody *body0, btSolverBody *body1, btManifoldPoint *cp) override { CPhysicsObject *pObj0 = static_cast<CPhysicsObject*>(body0->m_originalColObj->getUserPointer()); CPhysicsObject *pObj1 = static_cast<CPhysicsObject*>(body1->m_originalColObj->getUserPointer()); if (pObj0->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE || pObj1->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return; const unsigned int flags0 = pObj0->GetCallbackFlags(); const unsigned int flags1 = pObj1->GetCallbackFlags(); // Clear it memset(&m_tmpEvent, 0, sizeof(m_tmpEvent)); m_tmpEvent.collisionSpeed = 0.f; // Invalid pre-collision m_tmpEvent.deltaCollisionTime = 10.f; // FIXME: Find a way to track the real delta time m_tmpEvent.isCollision = (flags0 & flags1 & CALLBACK_GLOBAL_COLLISION); // False when either one of the objects don't have CALLBACK_GLOBAL_COLLISION m_tmpEvent.isShadowCollision = ((flags0 ^ flags1) & CALLBACK_SHADOW_COLLISION) != 0; // True when only one of the objects is a shadow (if both are shadow, it's handled by the game) m_tmpEvent.pObjects[0] = pObj0; m_tmpEvent.pObjects[1] = pObj1; m_tmpEvent.surfaceProps[0] = pObj0->GetMaterialIndex(); m_tmpEvent.surfaceProps[1] = pObj1->GetMaterialIndex(); if ((pObj0->IsStatic() && !(flags1 & CALLBACK_GLOBAL_COLLIDE_STATIC)) || (pObj1->IsStatic() && !(flags0 & CALLBACK_GLOBAL_COLLIDE_STATIC))) { m_tmpEvent.isCollision = false; } if (!m_tmpEvent.isCollision && !m_tmpEvent.isShadowCollision) return; CPhysicsCollisionData data(cp); m_tmpEvent.pInternalData = &data; // Give the game its stupid velocities if (body0->m_originalBody) { m_tmpVelocities[0] = body0->m_originalBody->getLinearVelocity(); m_tmpAngVelocities[0] = body0->m_originalBody->getAngularVelocity(); body0->m_originalBody->setLinearVelocity(m_tmpVelocities[0] + body0->internalGetDeltaLinearVelocity()); body0->m_originalBody->setAngularVelocity(m_tmpAngVelocities[0] + body0->internalGetDeltaAngularVelocity()); } if (body1->m_originalBody) { m_tmpVelocities[1] = body1->m_originalBody->getLinearVelocity(); m_tmpAngVelocities[1] = body1->m_originalBody->getAngularVelocity(); body1->m_originalBody->setLinearVelocity(m_tmpVelocities[1] + body1->internalGetDeltaLinearVelocity()); body1->m_originalBody->setAngularVelocity(m_tmpAngVelocities[1] + body1->internalGetDeltaAngularVelocity()); } if (m_pCallback) m_pCallback->PreCollision(&m_tmpEvent); // Restore the velocities // UNDONE: No need, postSolveContact will do this. /* if (body0->m_originalBody) { body0->m_originalBody->setLinearVelocity(m_tmpVelocities[0]); body0->m_originalBody->setAngularVelocity(m_tmpAngVelocities[0]); } if (body1->m_originalBody) { body1->m_originalBody->setLinearVelocity(m_tmpVelocities[1]); body1->m_originalBody->setAngularVelocity(m_tmpAngVelocities[1]); } */ } // TODO: Optimize this, heavily! void postSolveContact(btSolverBody *body0, btSolverBody *body1, btManifoldPoint *cp) override { btRigidBody *rb0 = btRigidBody::upcast(body0->m_originalColObj); btRigidBody *rb1 = btRigidBody::upcast(body1->m_originalColObj); // FIXME: Problem with bullet code, only one solver body created for static objects! // There could be more than one static object created by us! CPhysicsObject *pObj0 = static_cast<CPhysicsObject*>(body0->m_originalColObj->getUserPointer()); CPhysicsObject *pObj1 = static_cast<CPhysicsObject*>(body1->m_originalColObj->getUserPointer()); if (pObj0->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE || pObj1->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return; //unsigned int flags0 = pObj0->GetCallbackFlags(); //unsigned int flags1 = pObj1->GetCallbackFlags(); const btScalar combinedInvMass = rb0->getInvMass() + rb1->getInvMass(); m_tmpEvent.collisionSpeed = BULL2HL(cp->m_appliedImpulse * combinedInvMass); // Speed of body 1 rel to body 2 on axis of constraint normal // FIXME: Find a way to track the real delta time // IVP tracks this delta time between object pairs // lwss: I had a method in here to track the delta times between the pairs. // I wondered what it was for, turns out it's all 95% for a sound hack // in which they don't play sounds too often on 2 colliding objects. // so for now, I'll just leave this as is and play all physics sounds m_tmpEvent.deltaCollisionTime = 10.f; //lwss hack - ragdoll sounds are a bit too loud if( pObj0->GetCollisionHints() & COLLISION_HINT_RAGDOLL || pObj1->GetCollisionHints() & COLLISION_HINT_RAGDOLL ) { // value determined from testing :)) m_tmpEvent.collisionSpeed *= 0.4f; } //lwss end /* m_tmpEvent.isCollision = (flags0 & flags1 & CALLBACK_GLOBAL_COLLISION); // False when either one of the objects don't have CALLBACK_GLOBAL_COLLISION m_tmpEvent.isShadowCollision = (flags0 ^ flags1) & CALLBACK_SHADOW_COLLISION; // True when only one of the objects is a shadow m_tmpEvent.pObjects[0] = pObj0; m_tmpEvent.pObjects[1] = pObj1; m_tmpEvent.surfaceProps[0] = pObj0 ? pObj0->GetMaterialIndex() : 0; m_tmpEvent.surfaceProps[1] = pObj1 ? pObj1->GetMaterialIndex() : 0; */ if (!m_tmpEvent.isCollision && !m_tmpEvent.isShadowCollision) return; CPhysicsCollisionData data(cp); m_tmpEvent.pInternalData = &data; // Give the game its stupid velocities if (body0->m_originalBody) { body0->m_originalBody->setLinearVelocity(m_tmpVelocities[0] + body0->internalGetDeltaLinearVelocity()); body0->m_originalBody->setAngularVelocity(m_tmpAngVelocities[0] + body0->internalGetDeltaAngularVelocity()); } if (body1->m_originalBody) { body1->m_originalBody->setLinearVelocity(m_tmpVelocities[1] + body1->internalGetDeltaLinearVelocity()); body1->m_originalBody->setAngularVelocity(m_tmpAngVelocities[1] + body1->internalGetDeltaAngularVelocity()); } if (m_pCallback) m_pCallback->PostCollision(&m_tmpEvent); // Restore the velocities if (body0->m_originalBody) { body0->m_originalBody->setLinearVelocity(m_tmpVelocities[0]); body0->m_originalBody->setAngularVelocity(m_tmpAngVelocities[0]); } if (body1->m_originalBody) { body1->m_originalBody->setLinearVelocity(m_tmpVelocities[1]); body1->m_originalBody->setAngularVelocity(m_tmpAngVelocities[1]); } } void friction(btSolverBody *body0, btSolverBody *body1, btSolverConstraint *constraint) override { /* btRigidBody *rb0 = btRigidBody::upcast(body0->m_originalColObj); btRigidBody *rb1 = btRigidBody::upcast(body1->m_originalColObj); // FIXME: Problem with bullet code, only one solver body created for static objects! // There could be more than one static object created by us! CPhysicsObject *pObj0 = (CPhysicsObject *)body0->m_originalColObj->getUserPointer(); CPhysicsObject *pObj1 = (CPhysicsObject *)body1->m_originalColObj->getUserPointer(); unsigned int flags0 = pObj0->GetCallbackFlags(); unsigned int flags1 = pObj1->GetCallbackFlags(); // Don't do the callback if it's disabled on either object if (!(flags0 & flags1 & CALLBACK_GLOBAL_FRICTION)) return; // If the solver uses 2 friction directions btSolverConstraint *constraint2 = NULL; if (m_pEnv->GetBulletEnvironment()->getSolverInfo().m_solverMode & SOLVER_USE_2_FRICTION_DIRECTIONS) { constraint2 = constraint + 1; // Always stored after the first one } // Calculate the energy consumed float totalImpulse = constraint->m_appliedImpulse + (constraint2 ? constraint2->m_appliedImpulse : 0); totalImpulse *= rb0->getInvMass(); // Get just the velocity totalImpulse *= totalImpulse; // Square it totalImpulse *= SAFE_DIVIDE(.5, rb0->getInvMass()); // Add back the mass (1/2*mv^2) if (m_pCallback) m_pCallback->Friction(pObj0) */ } void SetCollisionEventCallback(IPhysicsCollisionEvent *pCallback) { m_pCallback = pCallback; } private: CPhysicsEnvironment *m_pEnv; IPhysicsCollisionEvent *m_pCallback; // Temp. variables saved between Pre/PostCollision btVector3 m_tmpVelocities[2]; btVector3 m_tmpAngVelocities[2]; vcollisionevent_t m_tmpEvent{}; }; /******************************* * Bullet Dynamics World Static References *******************************/ // TODO: See if this dynamics world pointer is right, it's assigned twice static bool gBulletDynamicsWorldGuard = false; static btDynamicsWorld* gBulletDynamicsWorld = NULL; #ifdef BT_THREADSAFE static bool gMultithreadedWorld = true; static SolverType gSolverType = SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT; #else static bool gMultithreadedWorld = false; static SolverType gSolverType = SOLVER_TYPE_SEQUENTIAL_IMPULSE; #endif static int gSolverMode = SOLVER_SIMD | SOLVER_USE_WARMSTARTING | /* SOLVER_RANDMIZE_ORDER | SOLVER_INTERLEAVE_CONTACT_AND_FRICTION_CONSTRAINTS | SOLVER_USE_2_FRICTION_DIRECTIONS |*/ 0; /******************************* * Bullet Dynamics World ConVars *******************************/ // bt_solveriterations static void cvar_solver_iterations_Change(IConVar *var, const char *pOldValue, float flOldValue); static ConVar cvar_solver_iterations("bt_solver_iterations", "4", FCVAR_REPLICATED, "Number of collision solver iterations", true, 1, true, 32, cvar_solver_iterations_Change); static void cvar_solver_iterations_Change(IConVar *var, const char *pOldValue, float flOldValue) { if(gBulletDynamicsWorld) { gBulletDynamicsWorld->getSolverInfo().m_numIterations = cvar_solver_iterations.GetInt(); Msg("Solver iteration count is changed from %i to %i\n", static_cast<int>(flOldValue), cvar_solver_iterations.GetInt()); } } // bt_solver_residualthreshold static void cvar_solver_residualthreshold_Change(IConVar *var, const char *pOldValue, float flOldValue); static ConVar cvar_solver_residualthreshold("bt_solver_residualthreshold", "0.0", FCVAR_REPLICATED, "Solver leastSquaresResidualThreshold (used to run fewer solver iterations when convergence is good)", true, 0.0f, true, 0.25f, cvar_solver_residualthreshold_Change); static void cvar_solver_residualthreshold_Change(IConVar *var, const char *pOldValue, float flOldValue) { if (gBulletDynamicsWorld) { gBulletDynamicsWorld->getSolverInfo().m_leastSquaresResidualThreshold = cvar_solver_residualthreshold.GetFloat(); Msg("Solver residual threshold is changed from %f to %f\n", flOldValue, cvar_solver_residualthreshold.GetFloat()); } } // bt_substeps static ConVar bt_max_world_substeps("bt_max_world_substeps", "5", FCVAR_REPLICATED, "Maximum amount of catchup simulation-steps BulletPhysics is allowed to do per Simulation()", true, 1, true, 12); // Threadsafe specific console variables #ifdef BT_THREADSAFE // bt_threadcount static void cvar_threadcount_Change(IConVar *var, const char *pOldValue, float flOldValue); static ConVar cvar_threadcount("bt_threadcount", "1", FCVAR_REPLICATED, "Number of cores utilized by bullet task scheduler. By default, TBB sets this to optimal value", true, 1, true, static_cast<float>(BT_MAX_THREAD_COUNT), cvar_threadcount_Change); static void cvar_threadcount_Change(IConVar *var, const char *pOldValue, float flOldValue) { const int newNumThreads = MIN(cvar_threadcount.GetInt(), int(BT_MAX_THREAD_COUNT)); const int oldNumThreads = btGetTaskScheduler()->getNumThreads(); // only call when the thread count is different if (newNumThreads != oldNumThreads) { btGetTaskScheduler()->setNumThreads(newNumThreads); Msg("Changed %s task scheduler thread count from %i to %i\n", btGetTaskScheduler()->getName(), oldNumThreads, newNumThreads); } } // bt_island_batchingthreshold static void cvar_island_batchingthreshold_Change(IConVar *var, const char *pOldValue, float flOldValue); static ConVar cvar_island_batchingthreshold("bt_solver_islandbatchingthreshold", std::to_string(btSequentialImpulseConstraintSolverMt::s_minimumContactManifoldsForBatching).c_str(), FCVAR_REPLICATED, "If the number of manifolds that an island have reaches to that value, they will get batched", true, 1, true, 2000, cvar_island_batchingthreshold_Change); static void cvar_island_batchingthreshold_Change(IConVar *var, const char *pOldValue, float flOldValue) { btSequentialImpulseConstraintSolverMt::s_minimumContactManifoldsForBatching = cvar_island_batchingthreshold.GetInt(); Msg("Island batching threshold is changed from %i to %i\n", static_cast<int>(flOldValue), cvar_island_batchingthreshold.GetInt()); } // bt_solver_minbatchsize static void cvar_solver_minbatchsize_Change(IConVar *var, const char *pOldValue, float flOldValue); static ConVar cvar_solver_minbatchsize("bt_solver_minbatchsize", std::to_string(btSequentialImpulseConstraintSolverMt::s_minBatchSize).c_str(), FCVAR_REPLICATED, "Minimum size of batches for solver", true, 1, true, 1000, cvar_solver_minbatchsize_Change); // bt_solver_maxbatchsize static void cvar_solver_maxbatchsize_Change(IConVar *var, const char *pOldValue, float flOldValue); static ConVar cvar_solver_maxbatchsize("bt_solver_maxbatchsize", std::to_string(btSequentialImpulseConstraintSolverMt::s_maxBatchSize).c_str(), FCVAR_REPLICATED, "Maximum size of batches for solver", true, 1, true, 1000, cvar_solver_maxbatchsize_Change); static void cvar_solver_minbatchsize_Change(IConVar *var, const char *pOldValue, float flOldValue) { cvar_solver_maxbatchsize.SetValue(MAX(cvar_solver_maxbatchsize.GetInt(), cvar_solver_minbatchsize.GetInt())); btSequentialImpulseConstraintSolverMt::s_minBatchSize = cvar_solver_minbatchsize.GetInt(); btSequentialImpulseConstraintSolverMt::s_maxBatchSize = cvar_solver_maxbatchsize.GetInt(); Msg("Min batch size for solver is changed from %i to %i\n", flOldValue, cvar_solver_minbatchsize.GetFloat()); } static void cvar_solver_maxbatchsize_Change(IConVar *var, const char *pOldValue, float flOldValue) { cvar_solver_minbatchsize.SetValue(MIN(cvar_solver_maxbatchsize.GetInt(), cvar_solver_minbatchsize.GetInt())); btSequentialImpulseConstraintSolverMt::s_minBatchSize = cvar_solver_minbatchsize.GetInt(); btSequentialImpulseConstraintSolverMt::s_maxBatchSize = cvar_solver_maxbatchsize.GetInt(); Msg("Max batch size for solver is changed from %i to %i\n", flOldValue, cvar_solver_maxbatchsize.GetFloat()); } #endif /******************************* * CLASS CPhysicsEnvironment *******************************/ CPhysicsEnvironment::CPhysicsEnvironment() { m_multithreadedWorld = false; m_multithreadCapable = false; m_deleteQuick = false; m_bUseDeleteQueue = false; m_inSimulation = false; m_bConstraintNotify = false; m_pDebugOverlay = NULL; m_pConstraintEvent = NULL; m_pObjectEvent = NULL; m_pObjectTracker = NULL; m_pCollisionEvent = NULL; m_pThreadManager = NULL; m_pBulletBroadphase = NULL; m_pBulletConfiguration = NULL; m_pBulletDispatcher = NULL; m_pBulletDynamicsWorld = NULL; m_pBulletGhostCallback = NULL; m_pBulletSolver = NULL; m_timestep = 0.f; m_invPSIScale = 0.f; m_simPSICurrent = 0; m_simPSI = 0; m_simTime = 0.0f; #ifdef BT_THREADSAFE // Initilize task scheduler, we will be using TBB // btSetTaskScheduler(btGetSequentialTaskScheduler()); // Can be used for debugging purposes //btSetTaskScheduler(btGetTBBTaskScheduler()); //const int maxNumThreads = btGetTBBTaskScheduler()->getMaxNumThreads(); //btGetTBBTaskScheduler()->setNumThreads(maxNumThreads); btSetTaskScheduler(btGetOpenMPTaskScheduler()); //lwss: this is silly to use all cpu threads, how about just 2 btGetOpenMPTaskScheduler()->setNumThreads(2); cvar_threadcount.SetValue(2); #endif // Create a fresh new dynamics world CreateEmptyDynamicsWorld(); } CPhysicsEnvironment::~CPhysicsEnvironment() { #if DEBUG_DRAW delete m_debugdraw; #endif CPhysicsEnvironment::SetQuickDelete(true); for (int i = m_objects.Count() - 1; i >= 0; --i) { delete m_objects[i]; } m_objects.RemoveAll(); CPhysicsEnvironment::CleanupDeleteList(); delete m_pDeleteQueue; delete m_pPhysicsDragController; delete m_pBulletDynamicsWorld; delete m_pBulletSolver; delete m_pBulletBroadphase; delete m_pBulletDispatcher; delete m_pBulletConfiguration; delete m_pBulletGhostCallback; // delete m_pCollisionListener; delete m_pCollisionSolver; delete m_pObjectTracker; } btConstraintSolver* createSolverByType(SolverType t) { btMLCPSolverInterface* mlcpSolver = NULL; switch (t) { case SOLVER_TYPE_SEQUENTIAL_IMPULSE: return new btSequentialImpulseConstraintSolver(); case SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT: return new btSequentialImpulseConstraintSolverMt(); case SOLVER_TYPE_NNCG: return new btNNCGConstraintSolver(); case SOLVER_TYPE_MLCP_PGS: mlcpSolver = new btSolveProjectedGaussSeidel(); break; case SOLVER_TYPE_MLCP_DANTZIG: mlcpSolver = new btDantzigSolver(); break; case SOLVER_TYPE_MLCP_LEMKE: mlcpSolver = new btLemkeSolver(); break; default: assert(false); break; } if (mlcpSolver) { return new btMLCPSolver(mlcpSolver); } return NULL; } IVPhysicsDebugOverlay *g_pDebugOverlay = NULL; void CPhysicsEnvironment::CreateEmptyDynamicsWorld() { if(gBulletDynamicsWorldGuard) { gBulletDynamicsWorld = m_pBulletDynamicsWorld; } else { gBulletDynamicsWorldGuard = true; } m_pCollisionListener = new CCollisionEventListener(this); m_solverType = gSolverType; #ifdef BT_THREADSAFE btAssert(btGetTaskScheduler() != NULL); if (btGetTaskScheduler() != NULL && btGetTaskScheduler()->getNumThreads() > 1) { m_multithreadCapable = true; } #endif if (gMultithreadedWorld) { #ifdef BT_THREADSAFE btAssert(btGetTaskScheduler() != NULL); m_pBulletDispatcher = NULL; btDefaultCollisionConstructionInfo cci; cci.m_defaultMaxPersistentManifoldPoolSize = 80000; cci.m_defaultMaxCollisionAlgorithmPoolSize = 80000; m_pBulletConfiguration = new btDefaultCollisionConfiguration(cci); // Dispatcher generates around 360 pair objects on average. Maximize thread usage by using this value m_pBulletDispatcher = new btCollisionDispatcherMt(m_pBulletConfiguration, 360 / cvar_threadcount.GetInt() + 1); m_pBulletBroadphase = new btDbvtBroadphase(); // Enable deferred collide, increases performance with many collisions calculations going on at the same time static_cast<btDbvtBroadphase*>(m_pBulletBroadphase)->m_deferedcollide = true; btConstraintSolverPoolMt* solverPool; { SolverType poolSolverType = m_solverType; if (poolSolverType == SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT) { // pool solvers shouldn't be parallel solvers, we don't allow that kind of // nested parallelism because of performance issues poolSolverType = SOLVER_TYPE_SEQUENTIAL_IMPULSE; } CUtlVector<btConstraintSolver*> solvers; const int threadCount = cvar_threadcount.GetInt(); for (int i = 0; i < threadCount; ++i) { auto solver = createSolverByType(poolSolverType); solver->setSolveCallback(m_pCollisionListener); solvers.AddToTail(solver); } solverPool = new btConstraintSolverPoolMt(solvers.Base(), threadCount); m_pBulletSolver = solverPool; m_pBulletSolver->setSolveCallback(m_pCollisionListener); } btSequentialImpulseConstraintSolverMt* solverMt = NULL; if (m_solverType == SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT) { solverMt = new btSequentialImpulseConstraintSolverMt(); } btDiscreteDynamicsWorld* world = new btDiscreteDynamicsWorldMt(m_pBulletDispatcher, m_pBulletBroadphase, solverPool, solverMt, m_pBulletConfiguration); m_pBulletDynamicsWorld = world; m_pBulletDynamicsWorld->setForceUpdateAllAabbs(false); gBulletDynamicsWorld = world; // Also keep a static ref for ConVar callbacks m_multithreadedWorld = true; #endif // #if BT_THREADSAFE } else { // single threaded world m_multithreadedWorld = false; ///collision configuration contains default setup for memory, collision setup m_pBulletConfiguration = new btDefaultCollisionConfiguration(); // Use the default collision dispatcher. For parallel processing you can use a different dispatcher (see Extras/BulletMultiThreaded) m_pBulletDispatcher = new btCollisionDispatcher(m_pBulletConfiguration); m_pBulletBroadphase = new btDbvtBroadphase(); SolverType solverType = m_solverType; if (solverType == SOLVER_TYPE_SEQUENTIAL_IMPULSE_MT) { // using the parallel solver with the single-threaded world works, but is // disabled here to avoid confusion solverType = SOLVER_TYPE_SEQUENTIAL_IMPULSE; } m_pBulletSolver = createSolverByType(solverType); m_pBulletSolver->setSolveCallback(m_pCollisionListener); m_pBulletDynamicsWorld = new btDiscreteDynamicsWorld(m_pBulletDispatcher, m_pBulletBroadphase, m_pBulletSolver, m_pBulletConfiguration); } m_pBulletDynamicsWorld->getSolverInfo().m_solverMode = gSolverMode; m_pBulletDynamicsWorld->getSolverInfo().m_numIterations = cvar_solver_iterations.GetInt(); m_pBulletGhostCallback = new btGhostPairCallback; m_pCollisionSolver = new CCollisionSolver(this); m_pBulletDynamicsWorld->getPairCache()->setOverlapFilterCallback(m_pCollisionSolver); m_pBulletBroadphase->getOverlappingPairCache()->setInternalGhostPairCallback(m_pBulletGhostCallback); m_pDeleteQueue = new CDeleteQueue; m_pPhysicsDragController = new CPhysicsDragController; m_pObjectTracker = new CObjectTracker(this, NULL); m_perfparams.Defaults(); memset(&m_stats, 0, sizeof(m_stats)); // TODO: Threads solve any oversized batches (>32?), otherwise solving done on main thread. m_pBulletDynamicsWorld->getSolverInfo().m_minimumSolverBatchSize = 128; // Combine islands up to this many constraints m_pBulletDynamicsWorld->getDispatchInfo().m_allowedCcdPenetration = 0.0001f; m_pBulletDynamicsWorld->setApplySpeculativeContactRestitution(true); m_pBulletDynamicsWorld->setInternalTickCallback(TickCallback, (void *)this); // HACK: Get ourselves a debug overlay on the client // CreateInterfaceFn engine = Sys_GetFactory("engine"); // CPhysicsEnvironment::SetDebugOverlay(engine); m_pDebugOverlay = g_Physics.GetPhysicsDebugOverlay(); g_pDebugOverlay = m_pDebugOverlay; #if DEBUG_DRAW m_debugdraw = new CDebugDrawer(m_pBulletDynamicsWorld); m_debugdraw->SetDebugOverlay( m_pDebugOverlay ); #endif } // Don't call this directly void CPhysicsEnvironment::TickCallback(btDynamicsWorld *world, btScalar timeStep) { if (!world) return; CPhysicsEnvironment *pEnv = static_cast<CPhysicsEnvironment*>(world->getWorldUserInfo()); if (pEnv) pEnv->BulletTick(timeStep); } //void CPhysicsEnvironment::SetDebugOverlay(CreateInterfaceFn debugOverlayFactory) { // if (debugOverlayFactory && !g_pDebugOverlay) // g_pDebugOverlay = static_cast<IVPhysicsDebugOverlay*>(debugOverlayFactory(VPHYSICS_DEBUG_OVERLAY_INTERFACE_VERSION, NULL)); // //#if DEBUG_DRAW // if (g_pDebugOverlay) // m_debugdraw->SetDebugOverlay(g_pDebugOverlay); //#endif //} IVPhysicsDebugOverlay *CPhysicsEnvironment::GetDebugOverlay() { return g_pDebugOverlay; } btIDebugDraw *CPhysicsEnvironment::GetDebugDrawer() const { return reinterpret_cast<btIDebugDraw*>(m_debugdraw); } void CPhysicsEnvironment::SetGravity(const Vector &gravityVector) { btVector3 temp; ConvertPosToBull(gravityVector, temp); m_pBulletDynamicsWorld->setGravity(temp); } void CPhysicsEnvironment::GetGravity(Vector *pGravityVector) const { if (!pGravityVector) return; const btVector3 temp = m_pBulletDynamicsWorld->getGravity(); ConvertPosToHL(temp, *pGravityVector); } void CPhysicsEnvironment::SetAirDensity(float density) { m_pPhysicsDragController->SetAirDensity(density); } float CPhysicsEnvironment::GetAirDensity() const { return m_pPhysicsDragController->GetAirDensity(); } IPhysicsObject *CPhysicsEnvironment::CreatePolyObject(const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams) { IPhysicsObject *pObject = CreatePhysicsObject(this, pCollisionModel, materialIndex, position, angles, pParams, false); m_objects.AddToTail(pObject); return pObject; } IPhysicsObject *CPhysicsEnvironment::CreatePolyObjectStatic(const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams) { IPhysicsObject *pObject = CreatePhysicsObject(this, pCollisionModel, materialIndex, position, angles, pParams, true); m_objects.AddToTail(pObject); return pObject; } // Deprecated. Create a sphere model using collision interface. IPhysicsObject *CPhysicsEnvironment::CreateSphereObject(float radius, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams, bool isStatic) { IPhysicsObject *pObject = CreatePhysicsSphere(this, radius, materialIndex, position, angles, pParams, isStatic); m_objects.AddToTail(pObject); return pObject; } void CPhysicsEnvironment::DestroyObject(IPhysicsObject *pObject) { if (!pObject) return; Assert(m_deadObjects.Find(pObject) == -1); // If you hit this assert, the object is already on the list! m_objects.FindAndRemove(pObject); m_pObjectTracker->ObjectRemoved(dynamic_cast<CPhysicsObject*>(pObject)); if (m_inSimulation || m_bUseDeleteQueue) { // We're still in the simulation, so deleting an object would be disastrous here. Queue it! dynamic_cast<CPhysicsObject*>(pObject)->AddCallbackFlags(CALLBACK_MARKED_FOR_DELETE); m_deadObjects.AddToTail(pObject); } else { delete pObject; } } IPhysicsFluidController *CPhysicsEnvironment::CreateFluidController(IPhysicsObject *pFluidObject, fluidparams_t *pParams) { CPhysicsFluidController *pFluid = ::CreateFluidController(this, static_cast<CPhysicsObject*>(pFluidObject), pParams); if (pFluid) m_fluids.AddToTail(pFluid); return pFluid; } void CPhysicsEnvironment::DestroyFluidController(IPhysicsFluidController *pController) { m_fluids.FindAndRemove(dynamic_cast<CPhysicsFluidController*>(pController)); delete pController; } IPhysicsSpring *CPhysicsEnvironment::CreateSpring(IPhysicsObject *pObjectStart, IPhysicsObject *pObjectEnd, springparams_t *pParams) { return ::CreateSpringConstraint(this, pObjectStart, pObjectEnd, pParams); } void CPhysicsEnvironment::DestroySpring(IPhysicsSpring *pSpring) { if (!pSpring) return; CPhysicsConstraint* pConstraint = reinterpret_cast<CPhysicsConstraint*>(pSpring); if (m_deleteQuick) { IPhysicsObject *pObj0 = pConstraint->GetReferenceObject(); if (pObj0 && !pObj0->IsStatic()) pObj0->Wake(); IPhysicsObject *pObj1 = pConstraint->GetAttachedObject(); if (pObj1 && !pObj0->IsStatic()) pObj1->Wake(); } if (m_inSimulation) { pConstraint->Deactivate(); m_pDeleteQueue->QueueForDelete(pSpring); } else { delete pSpring; } } IPhysicsConstraint *CPhysicsEnvironment::CreateRagdollConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ragdollparams_t &ragdoll) { return ::CreateRagdollConstraint(this, pReferenceObject, pAttachedObject, pGroup, ragdoll); } IPhysicsConstraint *CPhysicsEnvironment::CreateHingeConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_hingeparams_t &hinge) { return ::CreateHingeConstraint(this, pReferenceObject, pAttachedObject, pGroup, hinge); } IPhysicsConstraint *CPhysicsEnvironment::CreateFixedConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_fixedparams_t &fixed) { return ::CreateFixedConstraint(this, pReferenceObject, pAttachedObject, pGroup, fixed); } IPhysicsConstraint *CPhysicsEnvironment::CreateSlidingConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_slidingparams_t &sliding) { return ::CreateSlidingConstraint(this, pReferenceObject, pAttachedObject, pGroup, sliding); } IPhysicsConstraint *CPhysicsEnvironment::CreateBallsocketConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ballsocketparams_t &ballsocket) { return ::CreateBallsocketConstraint(this, pReferenceObject, pAttachedObject, pGroup, ballsocket); } IPhysicsConstraint *CPhysicsEnvironment::CreatePulleyConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_pulleyparams_t &pulley) { return ::CreatePulleyConstraint(this, pReferenceObject, pAttachedObject, pGroup, pulley); } IPhysicsConstraint *CPhysicsEnvironment::CreateLengthConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_lengthparams_t &length) { return ::CreateLengthConstraint(this, pReferenceObject, pAttachedObject, pGroup, length); } IPhysicsConstraint *CPhysicsEnvironment::CreateGearConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_gearparams_t &gear) { return ::CreateGearConstraint(this, pReferenceObject, pAttachedObject, pGroup, gear); } IPhysicsConstraint *CPhysicsEnvironment::CreateUserConstraint(IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, IPhysicsUserConstraint *pConstraint) { return ::CreateUserConstraint(this, pReferenceObject, pAttachedObject, pGroup, pConstraint); } void CPhysicsEnvironment::DestroyConstraint(IPhysicsConstraint *pConstraint) { if (!pConstraint) return; if (m_deleteQuick) { IPhysicsObject *pObj0 = pConstraint->GetReferenceObject(); if (pObj0 && !pObj0->IsStatic()) pObj0->Wake(); IPhysicsObject *pObj1 = pConstraint->GetAttachedObject(); if (pObj1 && !pObj1->IsStatic()) pObj1->Wake(); } if (m_inSimulation) { pConstraint->Deactivate(); m_pDeleteQueue->QueueForDelete(pConstraint); } else { delete pConstraint; } } IPhysicsConstraintGroup *CPhysicsEnvironment::CreateConstraintGroup(const constraint_groupparams_t &groupParams) { return ::CreateConstraintGroup(this, groupParams); } void CPhysicsEnvironment::DestroyConstraintGroup(IPhysicsConstraintGroup *pGroup) { delete pGroup; } IPhysicsShadowController *CPhysicsEnvironment::CreateShadowController(IPhysicsObject *pObject, bool allowTranslation, bool allowRotation) { CShadowController *pController = ::CreateShadowController(pObject, allowTranslation, allowRotation); if (pController) m_controllers.AddToTail(pController); return pController; } void CPhysicsEnvironment::DestroyShadowController(IPhysicsShadowController *pController) { if (!pController) return; m_controllers.FindAndRemove(static_cast<CShadowController*>(pController)); delete pController; } IPhysicsPlayerController *CPhysicsEnvironment::CreatePlayerController(IPhysicsObject *pObject) { CPlayerController *pController = ::CreatePlayerController(this, pObject); if (pController) m_controllers.AddToTail(pController); return pController; } void CPhysicsEnvironment::DestroyPlayerController(IPhysicsPlayerController *pController) { if (!pController) return; m_controllers.FindAndRemove(dynamic_cast<CPlayerController*>(pController)); delete pController; } IPhysicsMotionController *CPhysicsEnvironment::CreateMotionController(IMotionEvent *pHandler) { CPhysicsMotionController *pController = dynamic_cast<CPhysicsMotionController*>(::CreateMotionController(this, pHandler)); if (pController) m_controllers.AddToTail(pController); return pController; } void CPhysicsEnvironment::DestroyMotionController(IPhysicsMotionController *pController) { if (!pController) return; m_controllers.FindAndRemove(static_cast<CPhysicsMotionController*>(pController)); delete pController; } IPhysicsVehicleController *CPhysicsEnvironment::CreateVehicleController(IPhysicsObject *pVehicleBodyObject, const vehicleparams_t &params, unsigned int nVehicleType, IPhysicsGameTrace *pGameTrace) { return ::CreateVehicleController(this, static_cast<CPhysicsObject*>(pVehicleBodyObject), params, nVehicleType, pGameTrace); } void CPhysicsEnvironment::DestroyVehicleController(IPhysicsVehicleController *pController) { delete pController; } void CPhysicsEnvironment::SetCollisionSolver(IPhysicsCollisionSolver *pSolver) { m_pCollisionSolver->SetHandler(pSolver); } void CPhysicsEnvironment::Simulate(float deltaTime) { Assert(m_pBulletDynamicsWorld); // Input deltaTime is how many seconds have elapsed since the previous frame // phys_timescale can scale this parameter however... // Can cause physics to slow down on the client environment when the game's window is not in focus // Also is affected by the tickrate as well if (deltaTime > 1.0 || deltaTime < 0.0) { deltaTime = 0; } else if (deltaTime > 0.1) { deltaTime = 0.1f; } // sim PSI: How many substeps are done in a single simulation step m_simPSI = bt_max_world_substeps.GetInt() != 0 ? bt_max_world_substeps.GetInt() : 1; m_simPSICurrent = m_simPSI; // Substeps left in this step m_numSubSteps = m_simPSI; m_curSubStep = 0; // Simulate no less than 1 ms if (deltaTime > 0.001) { // Now mark us as being in simulation. This is used for callbacks from bullet mid-simulation // so we don't end up doing stupid things like deleting objects still in use m_inSimulation = true; m_subStepTime = m_timestep; // Okay, how this fixed timestep shit works: // The game sends in deltaTime which is the amount of time that has passed since the last frame // Bullet will add the deltaTime to its internal counter // When this internal counter exceeds m_timestep (param 3 to the below), the simulation will run for fixedTimeStep seconds // If the internal counter does not exceed fixedTimeStep, bullet will just interpolate objects so the game can render them nice and happy //if( deltaTime > (bt_max_world_substeps.GetInt() * m_timestep) ) //{ // Msg("Warning! We are losing physics-time! - deltaTime(%f) - maxTime(%f)\n", deltaTime, (bt_max_world_substeps.GetInt() * m_timestep)); //} int stepsTaken = m_pBulletDynamicsWorld->stepSimulation(deltaTime, bt_max_world_substeps.GetInt(), m_timestep, m_simPSICurrent); //lwss: stepSimulation returns the number of steps taken in the simulation this go-around. // We can simply multiply this by the timestep(60hz client - 64hz server) to get the time simulated. // and add it to our simtime. m_simTime += ( stepsTaken * m_timestep ); // No longer in simulation! m_inSimulation = false; } #if DEBUG_DRAW m_debugdraw->DrawWorld(); #endif } bool CPhysicsEnvironment::IsInSimulation() const { return m_inSimulation; } float CPhysicsEnvironment::GetSimulationTimestep() const { return m_timestep; } void CPhysicsEnvironment::SetSimulationTimestep(float timestep) { m_timestep = timestep; } float CPhysicsEnvironment::GetSimulationTime() const { //lwss - add simulation time. (mainly used for forced ragdoll sleeping hack in csgo) return m_simTime; } void CPhysicsEnvironment::ResetSimulationClock() { m_simTime = 0.0f; } float CPhysicsEnvironment::GetNextFrameTime() const { NOT_IMPLEMENTED return 0; } void CPhysicsEnvironment::SetCollisionEventHandler(IPhysicsCollisionEvent *pCollisionEvents) { //lwss: This enables the CCollisionEvent::PreCollision() and CCollisionEvent::PostCollision() // in client/physics.cpp and server/physics.cpp // Used for: Physics hit sounds, dust particles, and screen shake(unused?) // The accuracy of the physics highly depends on the stepSimulation() maxSteps and resolution. // // There is another section that calls m_pCollisionEvent->Friction(). // That section is somewhat similar, But deals with friction Scrapes instead of impacts. // It is ran on the server, which sends the particle/sound commands to the client // TODO m_pCollisionListener->SetCollisionEventCallback(pCollisionEvents); m_pCollisionEvent = pCollisionEvents; } void CPhysicsEnvironment::SetObjectEventHandler(IPhysicsObjectEvent *pObjectEvents) { m_pObjectEvent = pObjectEvents; m_pObjectTracker->SetObjectEventHandler(pObjectEvents); } void CPhysicsEnvironment::SetConstraintEventHandler(IPhysicsConstraintEvent *pConstraintEvents) { m_pConstraintEvent = pConstraintEvents; } void CPhysicsEnvironment::SetQuickDelete(bool bQuick) { m_deleteQuick = bQuick; } int CPhysicsEnvironment::GetActiveObjectCount() const { return m_pObjectTracker->GetActiveObjectCount(); } void CPhysicsEnvironment::GetActiveObjects(IPhysicsObject **pOutputObjectList) const { return m_pObjectTracker->GetActiveObjects(pOutputObjectList); } int CPhysicsEnvironment::GetObjectCount() const { return m_objects.Count(); } const IPhysicsObject **CPhysicsEnvironment::GetObjectList(int *pOutputObjectCount) const { if (pOutputObjectCount) { *pOutputObjectCount = m_objects.Count(); } return const_cast<const IPhysicsObject**>(m_objects.Base()); } bool CPhysicsEnvironment::TransferObject(IPhysicsObject *pObject, IPhysicsEnvironment *pDestinationEnvironment) { if (!pObject || !pDestinationEnvironment) return false; if (pDestinationEnvironment == this) { dynamic_cast<CPhysicsObject*>(pObject)->TransferToEnvironment(this); m_objects.AddToTail(pObject); if (pObject->IsFluid()) m_fluids.AddToTail(dynamic_cast<CPhysicsObject*>(pObject)->GetFluidController()); return true; } else { m_objects.FindAndRemove(pObject); if (pObject->IsFluid()) m_fluids.FindAndRemove(dynamic_cast<CPhysicsObject*>(pObject)->GetFluidController()); return pDestinationEnvironment->TransferObject(pObject, pDestinationEnvironment); } } void CPhysicsEnvironment::CleanupDeleteList() { for (int i = 0; i < m_deadObjects.Count(); i++) { delete m_deadObjects.Element(i); } m_deadObjects.Purge(); m_pDeleteQueue->DeleteAll(); } void CPhysicsEnvironment::EnableDeleteQueue(bool enable) { m_bUseDeleteQueue = enable; } bool CPhysicsEnvironment::Save(const physsaveparams_t &params) { NOT_IMPLEMENTED return false; } void CPhysicsEnvironment::PreRestore(const physprerestoreparams_t &params) { NOT_IMPLEMENTED } bool CPhysicsEnvironment::Restore(const physrestoreparams_t &params) { NOT_IMPLEMENTED return false; } void CPhysicsEnvironment::PostRestore() { NOT_IMPLEMENTED } //lwss add void CPhysicsEnvironment::SetAlternateGravity(const Vector &gravityVector) { ConvertPosToBull(gravityVector, m_vecRagdollGravity); } void CPhysicsEnvironment::GetAlternateGravity(Vector *pGravityVector) const { ConvertPosToHL( m_vecRagdollGravity, *pGravityVector ); } float CPhysicsEnvironment::GetDeltaFrameTime(int maxTicks) const { //TODO - implement this for bullet // this is fully accurate, the IDA king has spoken. //double timeDiff = m_pPhysEnv->time_of_next_psi.get_time() - m_pPhysEnv->current_time.get_time(); //return float( (float(maxTicks) * m_pPhysEnv->delta_PSI_time) + timeDiff ); // HACK ALERT!! return 1.0f; } void CPhysicsEnvironment::ForceObjectsToSleep(IPhysicsObject **pList, int listCount) { //lwss: Technically this does not force the objects to sleep, but works OK. for( int i = 0; i < listCount; i++ ) { pList[i]->Sleep(); } } void CPhysicsEnvironment::SetPredicted(bool bPredicted) { // This check is a little different from retail if( m_objects.Count() > 0 || m_deadObjects.Count() > 0 ) { Error( "Predicted physics are not designed to change once objects have been made.\n"); /* Exit */ } if( bPredicted ) Warning("WARNING: Kisak physics does NOT have prediction!\n"); //m_predictionEnabled = bPredicted; } bool CPhysicsEnvironment::IsPredicted() { //lwss hack - I didn't redo the whole physics prediction. // return false so it doesn't try to use it. return false; //return m_predictionEnabled; } void CPhysicsEnvironment::SetPredictionCommandNum(int iCommandNum) { if( !m_predictionEnabled ) return; //lwss hack - didn't reimplement the entire physics prediction system. m_predictionCmdNum = iCommandNum; Warning("LWSS didn't implement SetPredictionCommandNum\n"); } int CPhysicsEnvironment::GetPredictionCommandNum() { return m_predictionCmdNum; } void CPhysicsEnvironment::DoneReferencingPreviousCommands(int iCommandNum) { //lwss hack //Warning("LWSS didn't implement DoneReferencingPreviousCommands\n"); } void CPhysicsEnvironment::RestorePredictedSimulation() { //lwss hack Warning("LWSS didn't implement RestorePredictedSimulation\n"); } void CPhysicsEnvironment::DestroyCollideOnDeadObjectFlush(CPhysCollide *) { //lwss hack Warning("LWSS didn't implement DestroyCollideOnDeadObjectFlush\n"); // m_lastObjectThisTick // +20 bytes } //lwss end bool CPhysicsEnvironment::IsCollisionModelUsed(CPhysCollide *pCollide) const { for (int i = 0; i < m_objects.Count(); i++) { if (dynamic_cast<CPhysicsObject*>(m_objects[i])->GetObject()->getCollisionShape() == pCollide->GetCollisionShape()) return true; } // Also scan the to-be-deleted objects list for (int i = 0; i < m_deadObjects.Count(); i++) { if (dynamic_cast<CPhysicsObject*>(m_deadObjects[i])->GetObject()->getCollisionShape() == pCollide->GetCollisionShape()) return true; } return false; } void CPhysicsEnvironment::TraceRay(const Ray_t &ray, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace) { if (!ray.m_IsRay || !pTrace) return; btVector3 vecStart, vecEnd; ConvertPosToBull(ray.m_Start + ray.m_StartOffset, vecStart); ConvertPosToBull(ray.m_Start + ray.m_StartOffset + ray.m_Delta, vecEnd); // TODO: Override this class to use the mask and trace filter. btCollisionWorld::ClosestRayResultCallback cb(vecStart, vecEnd); m_pBulletDynamicsWorld->rayTest(vecStart, vecEnd, cb); pTrace->fraction = cb.m_closestHitFraction; ConvertPosToHL(cb.m_hitPointWorld, pTrace->endpos); ConvertDirectionToHL(cb.m_hitNormalWorld, pTrace->plane.normal); } // Is this function ever called? // TODO: This is a bit more complex, bullet doesn't support compound sweep tests. void CPhysicsEnvironment::SweepCollideable(const CPhysCollide *pCollide, const Vector &vecAbsStart, const Vector &vecAbsEnd, const QAngle &vecAngles, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace) { NOT_IMPLEMENTED } class CFilteredConvexResultCallback : public btCollisionWorld::ClosestConvexResultCallback { public: CFilteredConvexResultCallback(IPhysicsTraceFilter *pFilter, unsigned int mask, const btVector3 &convexFromWorld, const btVector3 &convexToWorld): btCollisionWorld::ClosestConvexResultCallback(convexFromWorld, convexToWorld) { m_pTraceFilter = pFilter; m_mask = mask; } virtual bool needsCollision(btBroadphaseProxy *proxy0) const { btCollisionObject *pColObj = (btCollisionObject *)proxy0->m_clientObject; CPhysicsObject *pObj = (CPhysicsObject *)pColObj->getUserPointer(); if (pObj && !m_pTraceFilter->ShouldHitObject(pObj, m_mask)) { return false; } bool collides = (proxy0->m_collisionFilterGroup & m_collisionFilterMask) != 0; collides = collides && (m_collisionFilterGroup & proxy0->m_collisionFilterMask); return collides; } private: IPhysicsTraceFilter *m_pTraceFilter; unsigned int m_mask; }; void CPhysicsEnvironment::SweepConvex(const CPhysConvex *pConvex, const Vector &vecAbsStart, const Vector &vecAbsEnd, const QAngle &vecAngles, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace) { if (!pConvex || !pTrace) return; btVector3 vecStart, vecEnd; ConvertPosToBull(vecAbsStart, vecStart); ConvertPosToBull(vecAbsEnd, vecEnd); btMatrix3x3 matAng; ConvertRotationToBull(vecAngles, matAng); btTransform transStart, transEnd; transStart.setOrigin(vecStart); transStart.setBasis(matAng); transEnd.setOrigin(vecEnd); transEnd.setBasis(matAng); btConvexShape *pShape = (btConvexShape *)pConvex; CFilteredConvexResultCallback cb(pTraceFilter, fMask, vecStart, vecEnd); m_pBulletDynamicsWorld->convexSweepTest(pShape, transStart, transEnd, cb, 0.0001f); pTrace->fraction = cb.m_closestHitFraction; ConvertPosToHL(cb.m_hitPointWorld, pTrace->endpos); ConvertDirectionToHL(cb.m_hitNormalWorld, pTrace->plane.normal); } void CPhysicsEnvironment::GetPerformanceSettings(physics_performanceparams_t *pOutput) const { if (!pOutput) return; *pOutput = m_perfparams; } void CPhysicsEnvironment::SetPerformanceSettings(const physics_performanceparams_t *pSettings) { if (!pSettings) return; m_perfparams = *pSettings; } void CPhysicsEnvironment::ReadStats(physics_stats_t *pOutput) { if (!pOutput) return; *pOutput = m_stats; } void CPhysicsEnvironment::ClearStats() { memset(&m_stats, 0, sizeof(m_stats)); } unsigned int CPhysicsEnvironment::GetObjectSerializeSize(IPhysicsObject *pObject) const { NOT_IMPLEMENTED return 0; } void CPhysicsEnvironment::SerializeObjectToBuffer(IPhysicsObject *pObject, unsigned char *pBuffer, unsigned int bufferSize) { NOT_IMPLEMENTED } IPhysicsObject *CPhysicsEnvironment::UnserializeObjectFromBuffer(void *pGameData, unsigned char *pBuffer, unsigned int bufferSize, bool enableCollisions) { NOT_IMPLEMENTED return NULL; } void CPhysicsEnvironment::EnableConstraintNotify(bool bEnable) { // Notify game about broken constraints? m_bConstraintNotify = bEnable; } // FIXME: What do? Source SDK mods call this every frame in debug builds. void CPhysicsEnvironment::DebugCheckContacts() { } // UNEXPOSED btDiscreteDynamicsWorld *CPhysicsEnvironment::GetBulletEnvironment() const { return m_pBulletDynamicsWorld; } // UNEXPOSED float CPhysicsEnvironment::GetInvPSIScale() const { return m_invPSIScale; } // UNEXPOSED void CPhysicsEnvironment::BulletTick(btScalar dt) { // Dirty hack to spread the controllers throughout the current simulation step if (m_simPSICurrent) { m_invPSIScale = 1.0f / static_cast<float>(m_simPSICurrent); m_simPSICurrent--; } else { m_invPSIScale = 0; } m_pPhysicsDragController->Tick(dt); for (int i = 0; i < m_controllers.Count(); i++) m_controllers[i]->Tick(dt); for (int i = 0; i < m_fluids.Count(); i++) m_fluids[i]->Tick(dt); m_inSimulation = false; // Update object sleep states m_pObjectTracker->Tick(); if (!m_bUseDeleteQueue) { CleanupDeleteList(); } //lwss: This part of the code is used by the server to send FRICTION sounds/dust // these are separate from collisions. DoCollisionEvents(dt); //lwss end. if (m_pCollisionEvent) m_pCollisionEvent->PostSimulationFrame(); m_inSimulation = true; m_curSubStep++; } // UNEXPOSED CPhysicsDragController *CPhysicsEnvironment::GetDragController() const { return m_pPhysicsDragController; } CCollisionSolver *CPhysicsEnvironment::GetCollisionSolver() const { return m_pCollisionSolver; } btVector3 CPhysicsEnvironment::GetMaxLinearVelocity() const { return btVector3(HL2BULL(m_perfparams.maxVelocity), HL2BULL(m_perfparams.maxVelocity), HL2BULL(m_perfparams.maxVelocity)); } btVector3 CPhysicsEnvironment::GetMaxAngularVelocity() const { return btVector3(HL2BULL(m_perfparams.maxAngularVelocity), HL2BULL(m_perfparams.maxAngularVelocity), HL2BULL(m_perfparams.maxAngularVelocity)); } // UNEXPOSED // Purpose: To be the biggest eyesore ever // Bullet doesn't provide many callbacks such as the ones we're looking for, so // we have to iterate through all the contact manifolds and generate the callbacks ourselves. // FIXME: Remove this function and implement callbacks in bullet code void CPhysicsEnvironment::DoCollisionEvents(float dt) { if (m_pCollisionEvent) { const int numManifolds = m_pBulletDynamicsWorld->getDispatcher()->getNumManifolds(); for (int i = 0; i < numManifolds; i++) { btPersistentManifold *contactManifold = m_pBulletDynamicsWorld->getDispatcher()->getManifoldByIndexInternal(i); if (contactManifold->getNumContacts() <= 0) continue; const btCollisionObject *obA = contactManifold->getBody0(); const btCollisionObject *obB = contactManifold->getBody1(); if (!obA || !obB) continue; CPhysicsObject *physObA = static_cast<CPhysicsObject*>(obA->getUserPointer()); CPhysicsObject *physObB = static_cast<CPhysicsObject*>(obB->getUserPointer()); // These are our own internal objects, don't do callbacks on them. if (obA->getInternalType() == btCollisionObject::CO_GHOST_OBJECT || obB->getInternalType() == btCollisionObject::CO_GHOST_OBJECT) continue; if (!(physObA->GetCallbackFlags() & CALLBACK_GLOBAL_FRICTION) || !(physObB->GetCallbackFlags() & CALLBACK_GLOBAL_FRICTION)) continue; for (int j = 0; j < contactManifold->getNumContacts(); j++) { btManifoldPoint manPoint = contactManifold->getContactPoint(j); // FRICTION CALLBACK // FIXME: We need to find the energy used by the friction! Bullet doesn't provide this in the manifold point. // This may not be the proper variable but whatever, as of now it works. const float energy = abs(manPoint.m_appliedImpulseLateral1); if (energy > 0.05f) { CPhysicsCollisionData data(&manPoint); m_pCollisionEvent->Friction(static_cast<CPhysicsObject*>(obA->getUserPointer()), ConvertEnergyToHL(energy), static_cast<CPhysicsObject*>(obA->getUserPointer())->GetMaterialIndex(), static_cast<CPhysicsObject*>(obB->getUserPointer())->GetMaterialIndex(), &data); } // TODO: Collision callback // Source wants precollision and postcollision callbacks (pre velocity and post velocity, etc.) // How do we generate a callback before the collision happens? } } } } // ================== // EVENTS // ================== // UNEXPOSED void CPhysicsEnvironment::HandleConstraintBroken(CPhysicsConstraint *pConstraint) const { if (m_bConstraintNotify && m_pConstraintEvent) m_pConstraintEvent->ConstraintBroken(pConstraint); } // UNEXPOSED void CPhysicsEnvironment::HandleFluidStartTouch(CPhysicsFluidController *pController, CPhysicsObject *pObject) const { if (pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return; if (m_pCollisionEvent) m_pCollisionEvent->FluidStartTouch(pObject, pController); } // UNEXPOSED void CPhysicsEnvironment::HandleFluidEndTouch(CPhysicsFluidController *pController, CPhysicsObject *pObject) const { if (pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return; if (m_pCollisionEvent) m_pCollisionEvent->FluidEndTouch(pObject, pController); } // UNEXPOSED void CPhysicsEnvironment::HandleObjectEnteredTrigger(CPhysicsObject *pTrigger, CPhysicsObject *pObject) const { if (pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return; if (m_pCollisionEvent) m_pCollisionEvent->ObjectEnterTrigger(pTrigger, pObject); } // UNEXPOSED void CPhysicsEnvironment::HandleObjectExitedTrigger(CPhysicsObject *pTrigger, CPhysicsObject *pObject) const { if (pObject->GetCallbackFlags() & CALLBACK_MARKED_FOR_DELETE) return; if (m_pCollisionEvent) m_pCollisionEvent->ObjectLeaveTrigger(pTrigger, pObject); }
36.0053
354
0.762828
SwagSoftware
b755fae74c436939a563f178a7d1bb9e6675d203
1,106
cpp
C++
Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp
codenameone-akshat/LittleJsonReader
2a28219ef494d4d3a02961d74fb90fa4829a14c5
[ "MIT" ]
null
null
null
Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp
codenameone-akshat/LittleJsonReader
2a28219ef494d4d3a02961d74fb90fa4829a14c5
[ "MIT" ]
null
null
null
Source/src/Json Parser/DataTypeHandlers/JsonObject.cpp
codenameone-akshat/LittleJsonReader
2a28219ef494d4d3a02961d74fb90fa4829a14c5
[ "MIT" ]
null
null
null
#include "JsonObjectItem.h" JsonReader::JsonItem * JsonReader::JsonObjectItem::GetValue() { return this; } JsonReader::JsonItem * JsonReader::JsonObjectItem::GetFirstChild() { it = m_value.begin(); return *it; } JsonReader::JsonItem * JsonReader::JsonObjectItem::GetNextChild() { std::vector<JsonItem*>::iterator end = m_value.end()-1; if (it != end) { ++it; return *it; } else return *it; } JsonReader::JsonItem * JsonReader::JsonObjectItem::AddChild(JsonItem* jsonItem) { m_value.push_back(jsonItem); return jsonItem; } JsonReader::JsonItem * JsonReader::JsonObjectItem::GetChildAt(int index) { if (index <= m_value.size() - 1) { return m_value.at(index); } else return nullptr; } int JsonReader::JsonObjectItem::asInt() { return 0; } double JsonReader::JsonObjectItem::asDouble() { return 0.0; } bool JsonReader::JsonObjectItem::asBool() { return false; } std::string JsonReader::JsonObjectItem::asString() { return std::string(); } int JsonReader::JsonObjectItem::size() { return m_value.size(); }
16.757576
80
0.664557
codenameone-akshat
b758578b94442795754abc3bccdd5a85647c9325
677
cpp
C++
sources codes/tute30b.cpp
darkrabel/c-personal-reference-code-
0ea62666a6f8b7ea876e96498e3c0b6b4e773a7f
[ "MIT" ]
2
2021-06-17T11:05:01.000Z
2021-11-15T11:39:46.000Z
sources codes/tute30b.cpp
darkrabel/c-personal-reference-code-
0ea62666a6f8b7ea876e96498e3c0b6b4e773a7f
[ "MIT" ]
null
null
null
sources codes/tute30b.cpp
darkrabel/c-personal-reference-code-
0ea62666a6f8b7ea876e96498e3c0b6b4e773a7f
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; class Point{ int x, y; public: Point(int a, int b){ x = a; y = b; } void displayPoint(){ cout<<"The point is ("<<x<<", "<<y<<")"<<endl; } }; // Create a function (Hint: Make it a friend function) which takes 2 point objects and computes the distance between those 2 points // Use these examples to check your code: // Distance between (1, 1) and (1, 1) is 0 // Distance between (0, 1) and (0, 6) is 5 // Distance between (1, 0) and (70, 0) is 69 int main(){ Point p(1, 1); p.displayPoint(); Point q(4, 6); q.displayPoint(); return 0; }
21.83871
131
0.552437
darkrabel
b758a6cf9bbdefdea70c38d7834f979c448873cb
2,396
cpp
C++
third_party/WebKit/Source/core/dom/DOMMatrixReadOnly.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
third_party/WebKit/Source/core/dom/DOMMatrixReadOnly.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/dom/DOMMatrixReadOnly.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2014 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 "core/dom/DOMMatrix.h" namespace blink { DOMMatrixReadOnly::~DOMMatrixReadOnly() { } bool DOMMatrixReadOnly::is2D() const { return m_is2D; } bool DOMMatrixReadOnly::isIdentity() const { return m_matrix->isIdentity(); } DOMMatrix* DOMMatrixReadOnly::multiply(DOMMatrix* other) { return DOMMatrix::create(this)->multiplySelf(other); } DOMMatrix* DOMMatrixReadOnly::translate(double tx, double ty, double tz) { return DOMMatrix::create(this)->translateSelf(tx, ty, tz); } DOMMatrix* DOMMatrixReadOnly::scale(double scale, double ox, double oy) { return DOMMatrix::create(this)->scaleSelf(scale, ox, oy); } DOMMatrix* DOMMatrixReadOnly::scale3d(double scale, double ox, double oy, double oz) { return DOMMatrix::create(this)->scale3dSelf(scale, ox, oy, oz); } DOMMatrix* DOMMatrixReadOnly::scaleNonUniform(double sx, double sy, double sz, double ox, double oy, double oz) { return DOMMatrix::create(this)->scaleNonUniformSelf(sx, sy, sz, ox, oy, oz); } DOMFloat32Array* DOMMatrixReadOnly::toFloat32Array() const { float array[] = { static_cast<float>(m_matrix->m11()), static_cast<float>(m_matrix->m12()), static_cast<float>(m_matrix->m13()), static_cast<float>(m_matrix->m14()), static_cast<float>(m_matrix->m21()), static_cast<float>(m_matrix->m22()), static_cast<float>(m_matrix->m23()), static_cast<float>(m_matrix->m24()), static_cast<float>(m_matrix->m31()), static_cast<float>(m_matrix->m32()), static_cast<float>(m_matrix->m33()), static_cast<float>(m_matrix->m34()), static_cast<float>(m_matrix->m41()), static_cast<float>(m_matrix->m42()), static_cast<float>(m_matrix->m43()), static_cast<float>(m_matrix->m44()) }; return DOMFloat32Array::create(array, 16); } DOMFloat64Array* DOMMatrixReadOnly::toFloat64Array() const { double array[] = { m_matrix->m11(), m_matrix->m12(), m_matrix->m13(), m_matrix->m14(), m_matrix->m21(), m_matrix->m22(), m_matrix->m23(), m_matrix->m24(), m_matrix->m31(), m_matrix->m32(), m_matrix->m33(), m_matrix->m34(), m_matrix->m41(), m_matrix->m42(), m_matrix->m43(), m_matrix->m44() }; return DOMFloat64Array::create(array, 16); } } // namespace blink
32.378378
155
0.695326
Wzzzx
b75b6cd1faa782a6f70b5eddbb1aacaba1f7d65b
860
hpp
C++
src/Camera.hpp
Philipp-M/CG_Project1
19e6b96c8c6d6fe4323af50f247ed07120c74f9c
[ "MIT" ]
null
null
null
src/Camera.hpp
Philipp-M/CG_Project1
19e6b96c8c6d6fe4323af50f247ed07120c74f9c
[ "MIT" ]
null
null
null
src/Camera.hpp
Philipp-M/CG_Project1
19e6b96c8c6d6fe4323af50f247ed07120c74f9c
[ "MIT" ]
null
null
null
#pragma once #include <GL/gl.h> #include <glm/glm.hpp> #include <glm/gtc/constants.hpp> const GLfloat PI_4 = 0.78539816339744830962; class Camera { private: GLfloat fieldOfView; GLfloat width; GLfloat height; GLfloat nearPlane; GLfloat farPlane; glm::mat4 viewMat; public: Camera(GLfloat width = 1920, GLfloat height = 1080, GLfloat nearPlane = 1, GLfloat farPlane = 50, GLfloat fieldOfView = PI_4); GLfloat getWidth() const; void setWidth(GLfloat width); GLfloat getHeight() const; void setHeight(GLfloat height); /*** implemented from the interface Entity ***/ void move(glm::vec3 delta); void rotate(glm::vec3 delta); void rotateAroundAxis(glm::vec3 a, float w); void scale(glm::vec3 factor); void scale(GLfloat factor); void resetViewMatrix(); glm::mat4 getViewMatrix() const; glm::mat4 getProjectionMatrix() const; };
17.916667
127
0.727907
Philipp-M
b75cfe6dbda9e66acdf42f4480e39184ba41ea21
449
cpp
C++
code/data-structures/segment_tree_node.cpp
viswamy/CompetitiveProgramming
497d58adce25cfe4fc327301d977da275ad80201
[ "MIT" ]
null
null
null
code/data-structures/segment_tree_node.cpp
viswamy/CompetitiveProgramming
497d58adce25cfe4fc327301d977da275ad80201
[ "MIT" ]
null
null
null
code/data-structures/segment_tree_node.cpp
viswamy/CompetitiveProgramming
497d58adce25cfe4fc327301d977da275ad80201
[ "MIT" ]
1
2019-07-28T03:12:29.000Z
2019-07-28T03:12:29.000Z
#ifndef STNODE #define STNODE struct node { int l, r; ll x, lazy; node() {} node(int _l, int _r) : l(_l), r(_r), x(0), lazy(0) { } node(int _l, int _r, ll _x) : node(_l,_r) { x = _x; } node(node a, node b) : node(a.l,b.r) { x = a.x + b.x; } void update(ll v) { x = v; } void range_update(ll v) { lazy = v; } void apply() { x += lazy * (r - l + 1); lazy = 0; } void push(node &u) { u.lazy += lazy; } }; #endif
29.933333
59
0.492205
viswamy
b75d44febf8380f8be76304cc07dfba54fa17725
1,197
cc
C++
chrome/browser/android/blimp/blimp_contents_profile_attachment.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
chrome/browser/android/blimp/blimp_contents_profile_attachment.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/android/blimp/blimp_contents_profile_attachment.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/android/blimp/blimp_contents_profile_attachment.h" #include "base/logging.h" #include "base/supports_user_data.h" #include "blimp/client/public/contents/blimp_contents.h" namespace { const char kBlimpContentsProfileAttachment[] = "blimp_contents_profile_attachment"; // A holder struct for a Profile that can be used as data. struct Attachment : public base::SupportsUserData::Data { Profile* profile; }; } // namespace void AttachProfileToBlimpContents(blimp::client::BlimpContents* blimp_contents, Profile* profile) { DCHECK(profile); Attachment* attachment = new Attachment; attachment->profile = profile; blimp_contents->SetUserData(kBlimpContentsProfileAttachment, attachment); } Profile* GetProfileFromBlimpContents( blimp::client::BlimpContents* blimp_contents) { Attachment* attachment = static_cast<Attachment*>( blimp_contents->GetUserData(kBlimpContentsProfileAttachment)); DCHECK(attachment); return attachment->profile; }
32.351351
79
0.759398
xzhan96
b75d4cd4fa9ad3ad38b152ff060b557b21d0287d
575
cpp
C++
Redo.cpp
albcristi/MoviesApp
aeb390e13fd3130474e12ddb55ba7ada3fcd898d
[ "MIT" ]
null
null
null
Redo.cpp
albcristi/MoviesApp
aeb390e13fd3130474e12ddb55ba7ada3fcd898d
[ "MIT" ]
null
null
null
Redo.cpp
albcristi/MoviesApp
aeb390e13fd3130474e12ddb55ba7ada3fcd898d
[ "MIT" ]
null
null
null
#include "Redo.h" Redo::Redo() { } Redo::~Redo() { } RedoAdd::RedoAdd(Movie mov, Repository& rep) :addedMovie{ mov },repo{rep} { } void RedoAdd::redoAction() { repo.addElement(addedMovie); } RedoAdd::~RedoAdd() { } RedoDelete::RedoDelete(Movie mo, Repository& re) : deletedMovie{ mo }, repo{ re } { } void RedoDelete::redoAction() { repo.remove(deletedMovie); } RedoDelete::~RedoDelete() { } RedoUpdate::RedoUpdate(Movie tod, Movie toa, Repository& re) :toDel{ tod }, toAdd{ toa }, repo{ re } { } void RedoUpdate::redoAction() { repo.update(toDel, toAdd); }
11.734694
81
0.662609
albcristi
b75e80dfc6b4645d842b4b4bce139b667dddd272
1,416
cpp
C++
VIIL/src/renderer/interface/Shader.cpp
Vixnil/VIIL
0057464a1bc6e938825cfdf59a977cbe53c03a00
[ "Apache-2.0" ]
null
null
null
VIIL/src/renderer/interface/Shader.cpp
Vixnil/VIIL
0057464a1bc6e938825cfdf59a977cbe53c03a00
[ "Apache-2.0" ]
null
null
null
VIIL/src/renderer/interface/Shader.cpp
Vixnil/VIIL
0057464a1bc6e938825cfdf59a977cbe53c03a00
[ "Apache-2.0" ]
null
null
null
#include "core/standardUse.h" #include "renderer/interface/Shader.h" #include "renderer//interface/RendererLibrary.h" #include "renderer/OpenGL/OpenGLShader.h" namespace VIIL { std::shared_ptr<Shader> Shader::Create(const std::shared_ptr<File>& shaderSrc) { switch (RendererLibrary::getType()) { case RendererLibrary::Type::OpenGL: return std::shared_ptr<Shader>(new OpenGLShader(shaderSrc)); break; default: VL_ENGINE_FATAL("Unimplemented renderer type selected. Shader creation failed."); } return nullptr; } std::shared_ptr<Shader> Shader::Create(const std::string& name, const std::shared_ptr<File>& vertexFile, const std::shared_ptr<File>& fragmentFile) { switch (RendererLibrary::getType()) { case RendererLibrary::Type::OpenGL: return std::shared_ptr<Shader>(new OpenGLShader(name, vertexFile, fragmentFile)); break; default: VL_ENGINE_FATAL("Unimplemented renderer type selected. Shader creation failed."); } return nullptr; } std::shared_ptr<Shader> Shader::Create(const std::string& name, const std::string& vertexSrc, const std::string& fragmentSrc) { switch (RendererLibrary::getType()) { case RendererLibrary::Type::OpenGL: return std::shared_ptr<Shader>(new OpenGLShader(name, vertexSrc, fragmentSrc)); break; default: VL_ENGINE_FATAL("Unimplemented renderer type selected. Shader creation failed."); } return nullptr; } }
27.764706
148
0.737288
Vixnil
b767de3fcf18ad1ff838a3b3ee458af38573a642
5,173
cpp
C++
test/System/Session.cpp
ntoskrnl7/win32api-ex
e91521b53745655fd8fb7d6532770f4888420814
[ "MIT" ]
18
2022-01-12T23:01:55.000Z
2022-03-28T01:50:56.000Z
test/System/Session.cpp
ntoskrnl7/win32api-ex
e91521b53745655fd8fb7d6532770f4888420814
[ "MIT" ]
null
null
null
test/System/Session.cpp
ntoskrnl7/win32api-ex
e91521b53745655fd8fb7d6532770f4888420814
[ "MIT" ]
3
2022-02-25T10:55:41.000Z
2022-02-25T13:06:21.000Z
#include <Win32Ex/System/Session.hpp> #include <gtest/gtest.h> TEST(SessionTest, ThisSession) { EXPECT_EQ(Win32Ex::ThisSession::Id(), WTSGetActiveConsoleSessionId()); EXPECT_STREQ(Win32Ex::ThisSession::Name().c_str(), Win32Ex::System::Session(Win32Ex::ThisSession::Id()).Name().c_str()); EXPECT_STREQ(Win32Ex::ThisSession::UserName().c_str(), Win32Ex::System::Session(Win32Ex::ThisSession::Id()).UserName().c_str()); } TEST(SessionTest, ThisSessionNewProcessT) { #if defined(WIN32EX_USE_TEMPLATE_FUNCTION_DEFAULT_ARGUMENT_STRING_T) auto process = Win32Ex::ThisSession::NewProcessT(Win32Ex::System::UserAccount, TEXT("notepad")); #else Win32Ex::Result<Win32Ex::System::SessionT<>::RunnableProcessPtr> process = Win32Ex::ThisSession::NewProcessT<Win32Ex::StringT>(Win32Ex::System::UserAccount, TEXT("notepad")); #endif if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } process = Win32Ex::ThisSession::NewProcessT<Win32Ex::StringT>(Win32Ex::System::SystemAccount, TEXT("notepad")); if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } } TEST(SessionTest, ThisSessionNewProcess) { #if defined(WIN32EX_USE_TEMPLATE_FUNCTION_DEFAULT_ARGUMENT_STRING_T) auto process = Win32Ex::ThisSession::NewProcess(Win32Ex::System::UserAccount, "notepad"); #else Win32Ex::Result<Win32Ex::System::Session::RunnableProcessPtr> process = Win32Ex::ThisSession::NewProcess(Win32Ex::System::UserAccount, "notepad"); #endif if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } process = Win32Ex::ThisSession::NewProcess(Win32Ex::System::SystemAccount, "notepad"); if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } } TEST(SessionTest, ThisSessionNewProcessW) { #if defined(WIN32EX_USE_TEMPLATE_FUNCTION_DEFAULT_ARGUMENT_STRING_T) auto process = Win32Ex::ThisSession::NewProcessW(Win32Ex::System::UserAccount, L"notepad"); #else Win32Ex::Result<Win32Ex::System::SessionW::RunnableProcessPtr> process = Win32Ex::ThisSession::NewProcessW(Win32Ex::System::UserAccount, L"notepad"); #endif if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } process = Win32Ex::ThisSession::NewProcessW(Win32Ex::System::SystemAccount, L"notepad"); if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } } TEST(SessionTest, SessionNewProcess) { #if defined(__cpp_range_based_for) for (auto session : Win32Ex::System::Session::All()) { auto process = session.NewProcess(Win32Ex::System::UserAccount, "notepad"); #else // clang-format off for each (Win32Ex::System::Session session in Win32Ex::System::Session::All()) { Win32Ex::Result<Win32Ex::System::Session::RunnableProcessPtr> process = session.NewProcess(Win32Ex::System::UserAccount, "notepad"); // clang-format on #endif if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } process = session.NewProcess(Win32Ex::System::SystemAccount, "notepad"); if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } } } TEST(SessionTest, SessionWNewProcess) { #if defined(__cpp_range_based_for) for (auto session : Win32Ex::System::SessionW::All()) { auto process = session.NewProcess(Win32Ex::System::UserAccount, L"notepad"); #else // clang-format off for each (Win32Ex::System::SessionW session in Win32Ex::System::SessionW::All()) { Win32Ex::Result<Win32Ex::System::SessionW::RunnableProcessPtr> process = session.NewProcess(Win32Ex::System::UserAccount, L"notepad"); // clang-format on #endif if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } process = session.NewProcess(Win32Ex::System::SystemAccount, L"notepad"); if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } } } TEST(SessionTest, SessionTNewProcess) { #if defined(__cpp_range_based_for) for (auto session : Win32Ex::System::SessionT<>::All()) { auto process = session.NewProcess(Win32Ex::System::UserAccount, TEXT("notepad")); #else // clang-format off for each (Win32Ex::System::SessionT<> session in Win32Ex::System::SessionT<>::All()) { Win32Ex::Result<Win32Ex::System::SessionT<>::RunnableProcessPtr> process = session.NewProcess(Win32Ex::System::UserAccount, TEXT("notepad")); // clang-format on #endif if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } process = session.NewProcess(Win32Ex::System::SystemAccount, TEXT("notepad")); if (process.IsOk()) { process->RunAsync().Wait(500); process->Exit(); } } }
32.534591
115
0.635028
ntoskrnl7
b76996137e2d4537aa8e1c0517082983ffb95e8b
11,242
cpp
C++
bob/io/audio/writer.cpp
bioidiap/bob.io.audio
8b46b15b3a4cdfa9d20c31560781541a3012fed3
[ "BSD-3-Clause" ]
4
2016-02-11T10:12:29.000Z
2018-06-28T13:08:27.000Z
bob/io/audio/writer.cpp
bioidiap/bob.io.audio
8b46b15b3a4cdfa9d20c31560781541a3012fed3
[ "BSD-3-Clause" ]
3
2016-01-21T19:48:58.000Z
2016-03-07T11:10:44.000Z
bob/io/audio/writer.cpp
bioidiap/bob.io.audio
8b46b15b3a4cdfa9d20c31560781541a3012fed3
[ "BSD-3-Clause" ]
1
2016-03-08T11:14:17.000Z
2016-03-08T11:14:17.000Z
/** * @author Andre Anjos <andre.anjos@idiap.ch> * @date Wed 20 Jan 2016 15:38:07 CET * * @brief Bindings to bob::io::audio::Writer */ #include "main.h" static auto s_writer = bob::extension::ClassDoc( "writer", "Use this object to write samples to audio files", "Audio writer objects can write data to audio files. " "The current implementation uses `SoX <http://sox.sourceforge.net/>`_.\n\n" "Audio files are objects composed potentially multiple channels. " "The numerical representation are 2-D arrays where the first dimension corresponds to the channels of the audio stream and the second dimension represents the samples through time." ) .add_constructor( bob::extension::FunctionDoc( "reader", "Opens an audio file for writing", "Opens the audio file with the given filename for writing, i.e., using the :py:meth:`append` function", true ) .add_prototype("filename, [rate], [encoding], [bits_per_sample]", "") .add_parameter("filename", "str", "The file path to the file you want to write data to") .add_parameter("rate", "float", "[Default: ``8000.``] The number of samples per second") .add_parameter("encoding", "str", "[Default: ``'UNKNOWN'``] The encoding to use") .add_parameter("bits_per_sample", "int", "[Default: ``16``] The number of bits per sample to be recorded") ); /* The __init__(self) method */ static int PyBobIoAudioWriter_Init(PyBobIoAudioWriterObject* self, PyObject *args, PyObject* kwds) { BOB_TRY char** kwlist = s_writer.kwlist(); char* filename = 0; double rate = 8000.; const char* encoding = "UNKNOWN"; Py_ssize_t bits_per_sample = 16; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|dsn", kwlist, &filename, &rate, &encoding, &bits_per_sample)) return -1; sox_encoding_t sox_encoding = bob::io::audio::string2encoding(encoding); self->v = boost::make_shared<bob::io::audio::Writer>(filename, rate, sox_encoding, bits_per_sample); return 0; BOB_CATCH_MEMBER("constructor", -1) } static void PyBobIoAudioWriter_Delete (PyBobIoAudioWriterObject* o) { o->v.reset(); Py_TYPE(o)->tp_free((PyObject*)o); } static auto s_filename = bob::extension::VariableDoc( "filename", "str", "The full path to the file that will be decoded by this object" ); PyObject* PyBobIoAudioWriter_Filename(PyBobIoAudioWriterObject* self) { return Py_BuildValue("s", self->v->filename()); } static auto s_rate = bob::extension::VariableDoc( "rate", "float", "The sampling rate of the audio stream" ); PyObject* PyBobIoAudioWriter_Rate(PyBobIoAudioWriterObject* self) { return Py_BuildValue("d", self->v->rate()); } static auto s_number_of_channels = bob::extension::VariableDoc( "number_of_channels", "int", "The number of channels on the audio stream" ); PyObject* PyBobIoAudioWriter_NumberOfChannels(PyBobIoAudioWriterObject* self) { return Py_BuildValue("n", self->v->numberOfChannels()); } static auto s_bits_per_sample = bob::extension::VariableDoc( "bits_per_sample", "int", "The number of bits per sample in this audio stream" ); PyObject* PyBobIoAudioWriter_BitsPerSample(PyBobIoAudioWriterObject* self) { return Py_BuildValue("n", self->v->bitsPerSample()); } static auto s_number_of_samples = bob::extension::VariableDoc( "number_of_samples", "int", "The number of samples in this audio stream" ); PyObject* PyBobIoAudioWriter_NumberOfSamples(PyBobIoAudioWriterObject* self) { return Py_BuildValue("n", self->v->numberOfSamples()); } static auto s_duration = bob::extension::VariableDoc( "duration", "float", "Total duration of this audio file in seconds" ); PyObject* PyBobIoAudioWriter_Duration(PyBobIoAudioWriterObject* self) { return Py_BuildValue("d", self->v->duration()); } static auto s_compression_factor = bob::extension::VariableDoc( "compression_factor", "float", "Compression factor on the audio stream" ); PyObject* PyBobIoAudioWriter_CompressionFactor(PyBobIoAudioWriterObject* self) { return Py_BuildValue("d", self->v->compressionFactor()); } static auto s_encoding = bob::extension::VariableDoc( "encoding", "str", "Name of the encoding in which this audio file will be written" ); PyObject* PyBobIoAudioWriter_EncodingName(PyBobIoAudioWriterObject* self) { return Py_BuildValue("s", bob::io::audio::encoding2string(self->v->encoding())); } static auto s_type = bob::extension::VariableDoc( "type", "tuple", "Typing information to load all of the file at once" ); PyObject* PyBobIoAudioWriter_TypeInfo(PyBobIoAudioWriterObject* self) { return PyBobIo_TypeInfoAsTuple(self->v->type()); } static auto s_is_opened = bob::extension::VariableDoc( "is_opened", "bool", "A flag indicating if the audio is still opened for writing, or has already been closed by the user using :py:meth:`close`" ); static PyObject* PyBobIoAudioWriter_IsOpened(PyBobIoAudioWriterObject* self) { if (self->v->is_opened()) Py_RETURN_TRUE; Py_RETURN_FALSE; } static PyGetSetDef PyBobIoAudioWriter_getseters[] = { { s_filename.name(), (getter)PyBobIoAudioWriter_Filename, 0, s_filename.doc(), 0, }, { s_rate.name(), (getter)PyBobIoAudioWriter_Rate, 0, s_rate.doc(), 0, }, { s_number_of_channels.name(), (getter)PyBobIoAudioWriter_NumberOfChannels, 0, s_number_of_channels.doc(), 0, }, { s_bits_per_sample.name(), (getter)PyBobIoAudioWriter_BitsPerSample, 0, s_bits_per_sample.doc(), 0, }, { s_number_of_samples.name(), (getter)PyBobIoAudioWriter_NumberOfSamples, 0, s_number_of_samples.doc(), 0, }, { s_duration.name(), (getter)PyBobIoAudioWriter_Duration, 0, s_duration.doc(), 0, }, { s_encoding.name(), (getter)PyBobIoAudioWriter_EncodingName, 0, s_encoding.doc(), 0, }, { s_compression_factor.name(), (getter)PyBobIoAudioWriter_CompressionFactor, 0, s_compression_factor.doc(), 0, }, { s_type.name(), (getter)PyBobIoAudioWriter_TypeInfo, 0, s_type.doc(), 0, }, { s_is_opened.name(), (getter)PyBobIoAudioWriter_IsOpened, 0, s_is_opened.doc(), 0, }, {0} /* Sentinel */ }; static PyObject* PyBobIoAudioWriter_Repr(PyBobIoAudioWriterObject* self) { if (!self->v->is_opened()) { PyErr_Format(PyExc_RuntimeError, "`%s' for `%s' is closed", Py_TYPE(self)->tp_name, self->v->filename()); return 0; } return # if PY_VERSION_HEX >= 0x03000000 PyUnicode_FromFormat # else PyString_FromFormat # endif ("%s(filename='%s', rate=%g, encoding=%s, bits_per_sample=%" PY_FORMAT_SIZE_T "d)", Py_TYPE(self)->tp_name, self->v->filename(), self->v->rate(), bob::io::audio::encoding2string(self->v->encoding()), self->v->bitsPerSample()); } static auto s_append = bob::extension::FunctionDoc( "append", "Writes a new sample or set of samples to the file", "The frame should be setup as a array with 1 dimension where each entry corresponds to one stream channel. " "Sets of samples should be setup as a 2D array in this way: (channels, samples). " "Arrays should contain only 64-bit float numbers.\n\n" ".. note::\n" " At present time we only support arrays that have C-style storages (if you pass reversed arrays or arrays with Fortran-style storage, the result is undefined)", true ) .add_prototype("sample") .add_parameter("sample", "array-like (1D or 2D, float)", "The sample(s) that should be appended to the file") ; static PyObject* PyBobIoAudioWriter_Append(PyBobIoAudioWriterObject* self, PyObject *args, PyObject* kwds) { BOB_TRY if (!self->v->is_opened()) { PyErr_Format(PyExc_RuntimeError, "`%s' for `%s' is closed", Py_TYPE(self)->tp_name, self->v->filename()); return 0; } char** kwlist = s_append.kwlist(); PyBlitzArrayObject* sample = 0; if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&", kwlist, &PyBlitzArray_BehavedConverter, &sample)) return 0; auto sample_ = make_safe(sample); if (sample->ndim != 1 && sample->ndim != 2) { PyErr_Format(PyExc_ValueError, "input array should have 1 or 2 dimensions, but you passed an array with %" PY_FORMAT_SIZE_T "d dimensions", sample->ndim); return 0; } if (sample->type_num != NPY_FLOAT64) { PyErr_Format(PyExc_TypeError, "input array should have dtype `float64', but you passed an array with dtype == `%s'", PyBlitzArray_TypenumAsString(sample->type_num)); return 0; } if (sample->ndim == 1) { self->v->append(*PyBlitzArrayCxx_AsBlitz<double,1>(sample)); } else { self->v->append(*PyBlitzArrayCxx_AsBlitz<double,2>(sample)); } Py_RETURN_NONE; BOB_CATCH_MEMBER("append", 0) } static auto s_close = bob::extension::FunctionDoc( "close", "Closes the current audio stream and forces writing the trailer", "After this point the audio is finalized and cannot be written to anymore.", true ) .add_prototype("") ; static PyObject* PyBobIoAudioWriter_Close(PyBobIoAudioWriterObject* self) { BOB_TRY self->v->close(); Py_RETURN_NONE; BOB_CATCH_MEMBER("close", 0) } static PyMethodDef PyBobIoAudioWriter_Methods[] = { { s_append.name(), (PyCFunction)PyBobIoAudioWriter_Append, METH_VARARGS|METH_KEYWORDS, s_append.doc(), }, { s_close.name(), (PyCFunction)PyBobIoAudioWriter_Close, METH_NOARGS, s_close.doc(), }, {0} /* Sentinel */ }; Py_ssize_t PyBobIoAudioWriter_Len(PyBobIoAudioWriterObject* self) { return self->v->numberOfSamples(); } static PyMappingMethods PyBobIoAudioWriter_Mapping = { (lenfunc)PyBobIoAudioWriter_Len, //mp_length 0, /* (binaryfunc)PyBobIoAudioWriter_GetItem, //mp_subscript */ 0 /* (objobjargproc)PyBobIoAudioWriter_SetItem //mp_ass_subscript */ }; PyTypeObject PyBobIoAudioWriter_Type = { PyVarObject_HEAD_INIT(0, 0) 0 }; bool init_BobIoAudioWriter(PyObject* module){ // initialize the File PyBobIoAudioWriter_Type.tp_name = s_writer.name(); PyBobIoAudioWriter_Type.tp_basicsize = sizeof(PyBobIoAudioWriterObject); PyBobIoAudioWriter_Type.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE; PyBobIoAudioWriter_Type.tp_doc = s_writer.doc(); // set the functions PyBobIoAudioWriter_Type.tp_new = PyType_GenericNew; PyBobIoAudioWriter_Type.tp_init = reinterpret_cast<initproc>(PyBobIoAudioWriter_Init); PyBobIoAudioWriter_Type.tp_dealloc = reinterpret_cast<destructor>(PyBobIoAudioWriter_Delete); PyBobIoAudioWriter_Type.tp_methods = PyBobIoAudioWriter_Methods; PyBobIoAudioWriter_Type.tp_getset = PyBobIoAudioWriter_getseters; PyBobIoAudioWriter_Type.tp_str = reinterpret_cast<reprfunc>(PyBobIoAudioWriter_Repr); PyBobIoAudioWriter_Type.tp_repr = reinterpret_cast<reprfunc>(PyBobIoAudioWriter_Repr); PyBobIoAudioWriter_Type.tp_as_mapping = &PyBobIoAudioWriter_Mapping; // check that everything is fine if (PyType_Ready(&PyBobIoAudioWriter_Type) < 0) return false; // add the type to the module Py_INCREF(&PyBobIoAudioWriter_Type); return PyModule_AddObject(module, "writer", (PyObject*)&PyBobIoAudioWriter_Type) >= 0; }
29.898936
228
0.70797
bioidiap
b76d9160b34a21db97aa8eac8705d37d6e0abf72
13,690
cpp
C++
cppLib/code/dep/G3D/source/ConvexPolyhedron.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
3
2019-05-14T07:19:59.000Z
2019-05-14T08:08:25.000Z
cppLib/code/dep/G3D/source/ConvexPolyhedron.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
null
null
null
cppLib/code/dep/G3D/source/ConvexPolyhedron.cpp
DrYaling/ProcedureContentGenerationForUnity
3c4f1e70b01e4fe2b9f847324b60b15016b9a740
[ "MIT" ]
1
2018-08-08T07:39:16.000Z
2018-08-08T07:39:16.000Z
/** @file ConvexPolyhedron.cpp @author Morgan McGuire, http://graphics.cs.williams.edu @created 2001-11-11 @edited 2009-08-10 Copyright 2000-2009, Morgan McGuire. All rights reserved. */ #include "G3D/platform.h" #include "G3D/ConvexPolyhedron.h" #include "G3D/debug.h" namespace G3D { ConvexPolygon::ConvexPolygon(const Array<Vector3>& __vertex) : _vertex(__vertex) { // Intentionally empty } ConvexPolygon::ConvexPolygon(const Vector3& v0, const Vector3& v1, const Vector3& v2) { _vertex.append(v0, v1, v2); } bool ConvexPolygon::isEmpty() const { return (_vertex.length() == 0) || (getArea() <= fuzzyEpsilon32); } float ConvexPolygon::getArea() const { if (_vertex.length() < 3) { return 0; } float sum = 0; int length = _vertex.length(); // Split into triangle fan, compute individual area for (int v = 2; v < length; ++v) { int i0 = 0; int i1 = v - 1; int i2 = v; sum += (_vertex[i1] - _vertex[i0]).cross(_vertex[i2] - _vertex[i0]).magnitude() / 2; } return sum; } void ConvexPolygon::cut(const Plane& plane, ConvexPolygon &above, ConvexPolygon &below) { DirectedEdge edge; cut(plane, above, below, edge); } void ConvexPolygon::cut(const Plane& plane, ConvexPolygon &above, ConvexPolygon &below, DirectedEdge &newEdge) { above._vertex.resize(0); below._vertex.resize(0); if (isEmpty()) { //debugPrintf("Empty\n"); return; } int v = 0; int length = _vertex.length(); Vector3 polyNormal = normal(); Vector3 planeNormal= plane.normal(); // See if the polygon is *in* the plane. if (planeNormal.fuzzyEq(polyNormal) || planeNormal.fuzzyEq(-polyNormal)) { // Polygon is parallel to the plane. It must be either above, // below, or in the plane. double a, b, c, d; Vector3 pt = _vertex[0]; plane.getEquation(a,b,c,d); float r = (float)(a * pt.x + b * pt.y + c * pt.z + d); if (fuzzyGe(r, 0)) { // The polygon is entirely in the plane. //debugPrintf("Entirely above\n"); above = *this; return; } else { //debugPrintf("Entirely below (1)\n"); below = *this; return; } } // Number of edges crossing the plane. Used for // debug assertions. int count = 0; // True when the last _vertex we looked at was above the plane bool lastAbove = plane.halfSpaceContains(_vertex[v]); if (lastAbove) { above._vertex.append(_vertex[v]); } else { below._vertex.append(_vertex[v]); } for (v = 1; v < length; ++v) { bool isAbove = plane.halfSpaceContains(_vertex[v]); if (lastAbove ^ isAbove) { // Switched sides. // Create an interpolated point that lies // in the plane, between the two points. Line line = Line::fromTwoPoints(_vertex[v - 1], _vertex[v]); Vector3 interp = line.intersection(plane); if (! interp.isFinite()) { // Since the polygon is not in the plane (we checked above), // it must be the case that this edge (and only this edge) // is in the plane. This only happens when the polygon is // entirely below the plane except for one edge. This edge // forms a degenerate polygon, so just treat the whole polygon // as below the plane. below = *this; above._vertex.resize(0); //debugPrintf("Entirely below\n"); return; } above._vertex.append(interp); below._vertex.append(interp); if (lastAbove) { newEdge.stop = interp; } else { newEdge.start = interp; } ++count; } lastAbove = isAbove; if (lastAbove) { above._vertex.append(_vertex[v]); } else { below._vertex.append(_vertex[v]); } } // Loop back to the first point, seeing if an interpolated point is // needed. bool isAbove = plane.halfSpaceContains(_vertex[0]); if (lastAbove ^ isAbove) { Line line = Line::fromTwoPoints(_vertex[length - 1], _vertex[0]); Vector3 interp = line.intersection(plane); if (! interp.isFinite()) { // Since the polygon is not in the plane (we checked above), // it must be the case that this edge (and only this edge) // is in the plane. This only happens when the polygon is // entirely below the plane except for one edge. This edge // forms a degenerate polygon, so just treat the whole polygon // as below the plane. below = *this; above._vertex.resize(0); //debugPrintf("Entirely below\n"); return; } above._vertex.append(interp); below._vertex.append(interp); debugAssertM(count < 2, "Convex polygons may only intersect planes at two edges."); if (lastAbove) { newEdge.stop = interp; } else { newEdge.start = interp; } ++count; } debugAssertM((count == 2) || (count == 0), "Convex polygons may only intersect planes at two edges."); } ConvexPolygon ConvexPolygon::inverse() const { ConvexPolygon result; int length = _vertex.length(); result._vertex.resize(length); for (int v = 0; v < length; ++v) { result._vertex[v] = _vertex[length - v - 1]; } return result; } void ConvexPolygon::removeDuplicateVertices(){ // Any valid polygon should have 3 or more vertices, but why take chances? if (_vertex.size() >= 2){ // Remove duplicate vertices. for (int i=0;i<_vertex.size()-1;++i){ if (_vertex[i].fuzzyEq(_vertex[i+1])){ _vertex.remove(i+1); --i; // Don't move forward. } } // Check the last vertex against the first. if (_vertex[_vertex.size()-1].fuzzyEq(_vertex[0])){ _vertex.pop(); } } } ////////////////////////////////////////////////////////////////////////////// ConvexPolyhedron::ConvexPolyhedron(const Array<ConvexPolygon>& _face) : face(_face) { // Intentionally empty } float ConvexPolyhedron::getVolume() const { if (face.length() < 4) { return 0; } // The volume of any pyramid is 1/3 * h * base area. // Discussion at: http://nrich.maths.org/mathsf/journalf/oct01/art1/ float sum = 0; // Choose the first _vertex of the first face as the origin. // This lets us skip one face, too, and avoids negative heights. Vector3 v0 = face[0]._vertex[0]; for (int f = 1; f < face.length(); ++f) { const ConvexPolygon& poly = face[f]; float height = (poly._vertex[0] - v0).dot(poly.normal()); float base = poly.getArea(); sum += height * base; } return sum / 3; } bool ConvexPolyhedron::isEmpty() const { return (face.length() == 0) || (getVolume() <= fuzzyEpsilon32); } void ConvexPolyhedron::cut(const Plane& plane, ConvexPolyhedron &above, ConvexPolyhedron &below) { above.face.resize(0); below.face.resize(0); Array<DirectedEdge> edge; int f; // See if the plane cuts this polyhedron at all. Detect when // the polyhedron is entirely to one side or the other. //{ int numAbove = 0, numIn = 0, numBelow = 0; bool ruledOut = false; double d; Vector3 abc; plane.getEquation(abc, d); // This number has to be fairly large to prevent precision problems down // the road. const float eps = 0.005f; for (f = face.length() - 1; (f >= 0) && (!ruledOut); f--) { const ConvexPolygon& poly = face[f]; for (int v = poly._vertex.length() - 1; (v >= 0) && (!ruledOut); v--) { double r = abc.dot(poly._vertex[v]) + d; if (r > eps) { ++numAbove; } else if (r < -eps) { ++numBelow; } else { ++numIn; } ruledOut = (numAbove != 0) && (numBelow !=0); } } if (numBelow == 0) { above = *this; return; } else if (numAbove == 0) { below = *this; return; } //} // Clip each polygon, collecting split edges. for (f = face.length() - 1; f >= 0; f--) { ConvexPolygon a, b; DirectedEdge e; face[f].cut(plane, a, b, e); bool aEmpty = a.isEmpty(); bool bEmpty = b.isEmpty(); //debugPrintf("\n"); if (! aEmpty) { //debugPrintf(" Above %f\n", a.getArea()); above.face.append(a); } if (! bEmpty) { //debugPrintf(" Below %f\n", b.getArea()); below.face.append(b); } if (! aEmpty && ! bEmpty) { //debugPrintf(" == Split\n"); edge.append(e); } else { // Might be the case that the polygon is entirely on // one side of the plane yet there is an edge we need // because it touches the plane. // // Extract the non-empty _vertex list and examine it. // If we find exactly one edge in the plane, add that edge. const Array<Vector3>& _vertex = (aEmpty ? b._vertex : a._vertex); int L = _vertex.length(); int count = 0; for (int v = 0; v < L; ++v) { if (plane.fuzzyContains(_vertex[v]) && plane.fuzzyContains(_vertex[(v + 1) % L])) { e.start = _vertex[v]; e.stop = _vertex[(v + 1) % L]; ++count; } } if (count == 1) { edge.append(e); } } } if (above.face.length() == 1) { // Only one face above means that this entire // polyhedron is below the plane. Move that face over. below.face.append(above.face[0]); above.face.resize(0); } else if (below.face.length() == 1) { // This shouldn't happen, but it arises in practice // from numerical imprecision. above.face.append(below.face[0]); below.face.resize(0); } if ((above.face.length() > 0) && (below.face.length() > 0)) { // The polyhedron was actually cut; create a cap polygon ConvexPolygon cap; // Collect the final polgyon by sorting the edges int numVertices = edge.length(); /*debugPrintf("\n"); for (int xx=0; xx < numVertices; ++xx) { std::string s1 = edge[xx].start.toString(); std::string s2 = edge[xx].stop.toString(); debugPrintf("%s -> %s\n", s1.c_str(), s2.c_str()); } */ // Need at least three points to make a polygon debugAssert(numVertices >= 3); Vector3 last_vertex = edge.last().stop; cap._vertex.append(last_vertex); // Search for the next _vertex. Because of accumulating // numerical error, we have to find the closest match, not // just the one we expect. for (int v = numVertices - 1; v >= 0; v--) { // matching edge index int index = 0; int num = edge.length(); double distance = (edge[index].start - last_vertex).squaredMagnitude(); for (int e = 1; e < num; ++e) { double d = (edge[e].start - last_vertex).squaredMagnitude(); if (d < distance) { // This is the new closest one index = e; distance = d; } } // Don't tolerate ridiculous error. debugAssertM(distance < 0.02, "Edge missing while closing polygon."); last_vertex = edge[index].stop; cap._vertex.append(last_vertex); } //debugPrintf("\n"); //debugPrintf("Cap (both) %f\n", cap.getArea()); above.face.append(cap); below.face.append(cap.inverse()); } // Make sure we put enough faces on each polyhedra debugAssert((above.face.length() == 0) || (above.face.length() >= 4)); debugAssert((below.face.length() == 0) || (below.face.length() >= 4)); } /////////////////////////////////////////////// ConvexPolygon2D::ConvexPolygon2D(const Array<Vector2>& pts, bool reverse) : m_vertex(pts) { if (reverse) { m_vertex.reverse(); } } bool ConvexPolygon2D::contains(const Vector2& p, bool reverse) const { // Compute the signed area of each polygon from p to an edge. // If the area is non-negative for all polygons then p is inside // the polygon. (To adapt this algorithm for a concave polygon, // the *sum* of the areas must be non-negative). float r = reverse ? -1.0f : 1.0f; for (int i0 = 0; i0 < m_vertex.size(); ++i0) { int i1 = (i0 + 1) % m_vertex.size(); const Vector2& v0 = m_vertex[i0]; const Vector2& v1 = m_vertex[i1]; Vector2 e0 = v0 - p; Vector2 e1 = v1 - p; // Area = (1/2) cross product, negated to be ccw in // a 2D space; we neglect the 1/2 float area = -(e0.x * e1.y - e0.y * e1.x); if (area * r < 0) { return false; } } return true; } }
29.89083
112
0.530533
DrYaling
b76eb4286d77bfd240be40bfb88e07e96323c37b
277
cpp
C++
Cplusplus/FuncaoEspecial-INLINE.cpp
carlosvilela/Testes-C-
b6be1d94569027d0b5d6e8aa227e279a7cb16937
[ "MIT" ]
null
null
null
Cplusplus/FuncaoEspecial-INLINE.cpp
carlosvilela/Testes-C-
b6be1d94569027d0b5d6e8aa227e279a7cb16937
[ "MIT" ]
null
null
null
Cplusplus/FuncaoEspecial-INLINE.cpp
carlosvilela/Testes-C-
b6be1d94569027d0b5d6e8aa227e279a7cb16937
[ "MIT" ]
null
null
null
inline int soma (int a, int b){ int r; r = a + b; return r; } main (){ int resultado; resultado = soma (1,5); printf("Resultado = %d", resultado); resultado = soma (8,3); printf("\nResultado = %d", resultado); }
13.190476
42
0.476534
carlosvilela
b7726f6aa53071e6a333dd5784e55ebad81a0659
2,367
cpp
C++
src/red4ext.dll/Utils.cpp
gammaparticle/RED4ext
1d5ad2745cc806acf1111cde7e46d3f250d42474
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/red4ext.dll/Utils.cpp
gammaparticle/RED4ext
1d5ad2745cc806acf1111cde7e46d3f250d42474
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/red4ext.dll/Utils.cpp
gammaparticle/RED4ext
1d5ad2745cc806acf1111cde7e46d3f250d42474
[ "MIT", "BSD-3-Clause" ]
null
null
null
#include "stdafx.hpp" #include "Utils.hpp" #include "App.hpp" std::wstring Utils::FormatErrorMessage(uint32_t aErrorCode) { wchar_t* buffer = nullptr; auto errorCode = GetLastError(); FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorCode, LANG_USER_DEFAULT, reinterpret_cast<LPWSTR>(&buffer), 0, nullptr); std::wstring result = buffer; LocalFree(buffer); buffer = nullptr; return result; } const RED4ext::VersionInfo Utils::GetRuntimeVersion() { auto app = App::Get(); auto filename = app->GetExecutablePath(); auto size = GetFileVersionInfoSize(filename.c_str(), nullptr); if (!size) { auto err = GetLastError(); auto errMsg = Utils::FormatErrorMessage(err); spdlog::error(L"Could not retrive game's version size, error: 0x{:X}, description: {}", err, errMsg); return RED4EXT_SEMVER(0, 0, 0); } auto data = new char[size]; if (!data) { spdlog::error(L"Could not allocate {} bytes on stack or heap", size); return RED4EXT_SEMVER(0, 0, 0); } if (!GetFileVersionInfo(filename.c_str(), 0, size, data)) { auto err = GetLastError(); auto errMsg = Utils::FormatErrorMessage(err); spdlog::error(L"Could not retrive game's version info, error: 0x{:X}, description: {}", err, errMsg); delete[] data; return RED4EXT_SEMVER(0, 0, 0); } VS_FIXEDFILEINFO* buffer = nullptr; uint32_t length = 0; if (!VerQueryValue(data, L"\\", reinterpret_cast<LPVOID*>(&buffer), &length) || !length) { auto err = GetLastError(); auto errMsg = Utils::FormatErrorMessage(err); spdlog::error(L"Could not query version info, error: 0x{:X}, description: {}", err, errMsg); delete[] data; return RED4EXT_SEMVER(0, 0, 0); } if (buffer->dwSignature != 0xFEEF04BD) { spdlog::error(L"Retrived version signature does not match"); delete[] data; return RED4EXT_SEMVER(0, 0, 0); } uint8_t major = (buffer->dwProductVersionMS >> 16) & 0xFF; uint16_t minor = buffer->dwProductVersionMS & 0xFFFF; uint32_t patch = (buffer->dwProductVersionLS >> 16) & 0xFFFF; delete[] data; return RED4EXT_SEMVER(major, minor, patch); }
29.222222
119
0.635403
gammaparticle
b772ee97ebe4f0d16c6334320ad604ce1763ddff
5,375
hxx
C++
main/linguistic/workben/sprophelp.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/linguistic/workben/sprophelp.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/linguistic/workben/sprophelp.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef _LINGU2_PROPHELP_HXX_ #define _LINGU2_PROPHELP_HXX_ #include <tools/solar.h> #include <uno/lbnames.h> // CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type #include <cppuhelper/implbase2.hxx> // helper for implementations #include <cppuhelper/interfacecontainer.h> #include <com/sun/star/beans/XPropertyChangeListener.hpp> #include <com/sun/star/beans/PropertyValues.hpp> #include <com/sun/star/linguistic2/XLinguServiceEventBroadcaster.hpp> namespace com { namespace sun { namespace star { namespace beans { class XPropertySet; }}}}; namespace com { namespace sun { namespace star { namespace linguistic2 { struct LinguServiceEvent; }}}}; using namespace ::rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::linguistic2; /////////////////////////////////////////////////////////////////////////// // PropertyChgHelper // virtual base class for all XPropertyChangeListener members of the // various lingu services. // Only propertyChange needs to be implemented. class PropertyChgHelper : public cppu::WeakImplHelper2 < XPropertyChangeListener, XLinguServiceEventBroadcaster > { Sequence< OUString > aPropNames; Reference< XInterface > xMyEvtObj; ::cppu::OInterfaceContainerHelper aLngSvcEvtListeners; Reference< XPropertySet > xPropSet; // disallow use of copy-constructor and assignment-operator PropertyChgHelper( const PropertyChgHelper & ); PropertyChgHelper & operator = ( const PropertyChgHelper & ); public: PropertyChgHelper( const Reference< XInterface > &rxSource, Reference< XPropertySet > &rxPropSet, const char *pPropNames[], USHORT nPropCount ); virtual ~PropertyChgHelper(); // XEventListener virtual void SAL_CALL disposing( const EventObject& rSource ) throw(RuntimeException); // XPropertyChangeListener virtual void SAL_CALL propertyChange( const PropertyChangeEvent& rEvt ) throw(RuntimeException) = 0; // XLinguServiceEventBroadcaster virtual sal_Bool SAL_CALL addLinguServiceEventListener( const Reference< XLinguServiceEventListener >& rxListener ) throw(RuntimeException); virtual sal_Bool SAL_CALL removeLinguServiceEventListener( const Reference< XLinguServiceEventListener >& rxListener ) throw(RuntimeException); // non UNO functions void AddAsPropListener(); void RemoveAsPropListener(); void LaunchEvent( const LinguServiceEvent& rEvt ); const Sequence< OUString > & GetPropNames() const { return aPropNames; } const Reference< XPropertySet > & GetPropSet() const { return xPropSet; } const Reference< XInterface > & GetEvtObj() const { return xMyEvtObj; } }; /////////////////////////////////////////////////////////////////////////// class PropertyHelper_Spell : public PropertyChgHelper { // default values BOOL bIsGermanPreReform; BOOL bIsIgnoreControlCharacters; BOOL bIsUseDictionaryList; BOOL bIsSpellUpperCase; BOOL bIsSpellWithDigits; BOOL bIsSpellCapitalization; // return values, will be set to default value or current temporary value BOOL bResIsGermanPreReform; BOOL bResIsIgnoreControlCharacters; BOOL bResIsUseDictionaryList; BOOL bResIsSpellUpperCase; BOOL bResIsSpellWithDigits; BOOL bResIsSpellCapitalization; // disallow use of copy-constructor and assignment-operator PropertyHelper_Spell( const PropertyHelper_Spell & ); PropertyHelper_Spell & operator = ( const PropertyHelper_Spell & ); void SetDefault(); public: PropertyHelper_Spell( const Reference< XInterface > &rxSource, Reference< XPropertySet > &rxPropSet ); virtual ~PropertyHelper_Spell(); // XPropertyChangeListener virtual void SAL_CALL propertyChange( const PropertyChangeEvent& rEvt ) throw(RuntimeException); void SetTmpPropVals( const PropertyValues &rPropVals ); BOOL IsGermanPreReform() const { return bResIsGermanPreReform; } BOOL IsIgnoreControlCharacters() const { return bResIsIgnoreControlCharacters; } BOOL IsUseDictionaryList() const { return bResIsUseDictionaryList; } BOOL IsSpellUpperCase() const { return bResIsSpellUpperCase; } BOOL IsSpellWithDigits() const { return bResIsSpellWithDigits; } BOOL IsSpellCapitalization() const { return bResIsSpellCapitalization; } }; /////////////////////////////////////////////////////////////////////////// #endif
31.804734
106
0.718326
Grosskopf
b7754f8a24f2eec03b0a4eb5550898756d22483f
2,368
cc
C++
Alignment/ReferenceTrajectories/src/DualBzeroReferenceTrajectory.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-08-09T08:42:11.000Z
2019-08-09T08:42:11.000Z
Alignment/ReferenceTrajectories/src/DualBzeroReferenceTrajectory.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
null
null
null
Alignment/ReferenceTrajectories/src/DualBzeroReferenceTrajectory.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
1
2019-04-03T19:23:27.000Z
2019-04-03T19:23:27.000Z
#include "Alignment/ReferenceTrajectories/interface/DualBzeroReferenceTrajectory.h" #include "TrackingTools/TrajectoryState/interface/TrajectoryStateOnSurface.h" #include "DataFormats/CLHEP/interface/AlgebraicObjects.h" #include "DataFormats/TrajectoryState/interface/LocalTrajectoryParameters.h" #include "Alignment/ReferenceTrajectories/interface/BzeroReferenceTrajectory.h" DualBzeroReferenceTrajectory::DualBzeroReferenceTrajectory(const TrajectoryStateOnSurface& tsos, const ConstRecHitContainer& forwardRecHits, const ConstRecHitContainer& backwardRecHits, const MagneticField* magField, const reco::BeamSpot& beamSpot, const ReferenceTrajectoryBase::Config& config) : DualReferenceTrajectory(tsos.localParameters().mixedFormatVector().kSize - 1, numberOfUsedRecHits(forwardRecHits) + numberOfUsedRecHits(backwardRecHits) - 1, config), theMomentumEstimate(config.momentumEstimate) { theValidityFlag = construct(tsos, forwardRecHits, backwardRecHits, magField, beamSpot); } ReferenceTrajectory* DualBzeroReferenceTrajectory::construct(const TrajectoryStateOnSurface &referenceTsos, const ConstRecHitContainer &recHits, double mass, MaterialEffects materialEffects, const PropagationDirection propDir, const MagneticField *magField, bool useBeamSpot, const reco::BeamSpot &beamSpot) const { if (materialEffects >= breakPoints) throw cms::Exception("BadConfig") << "[DualBzeroReferenceTrajectory::construct] Wrong MaterialEffects: " << materialEffects; ReferenceTrajectoryBase::Config config(materialEffects, propDir, mass, theMomentumEstimate); config.useBeamSpot = useBeamSpot; config.hitsAreReverse = false; return new BzeroReferenceTrajectory(referenceTsos, recHits, magField, beamSpot, config); } AlgebraicVector DualBzeroReferenceTrajectory::extractParameters(const TrajectoryStateOnSurface &referenceTsos) const { AlgebraicVector param = asHepVector<5>( referenceTsos.localParameters().mixedFormatVector() ); return param.sub( 2, 5 ); }
43.851852
107
0.697213
nistefan
b77ce2e5d8a48c5d3c80b162ff0c92de63ce96f0
1,590
cpp
C++
src/UNIT_4RELAY.cpp
m5stack/UNIT_4RELAY
f7586379b2dfd079527a990f740f98ca97206820
[ "MIT" ]
null
null
null
src/UNIT_4RELAY.cpp
m5stack/UNIT_4RELAY
f7586379b2dfd079527a990f740f98ca97206820
[ "MIT" ]
null
null
null
src/UNIT_4RELAY.cpp
m5stack/UNIT_4RELAY
f7586379b2dfd079527a990f740f98ca97206820
[ "MIT" ]
1
2022-02-10T18:18:56.000Z
2022-02-10T18:18:56.000Z
#include "UNIT_4RELAY.h" void UNIT_4RELAY::write1Byte(uint8_t address, uint8_t Register_address, uint8_t data) { Wire.beginTransmission(address); Wire.write(Register_address); Wire.write(data); Wire.endTransmission(); } uint8_t UNIT_4RELAY::read1Byte(uint8_t address, uint8_t Register_address) { Wire.beginTransmission(address); // Initialize the Tx buffer Wire.write(Register_address); // Put slave register address in Tx buffer Wire.endTransmission(); Wire.requestFrom(address, 1); uint8_t data = Wire.read(); return data; } void UNIT_4RELAY::relayALL(bool state) { write1Byte(addr,relay_Reg,state*(0x0f)); } void UNIT_4RELAY::LED_ALL(bool state) { write1Byte(addr,relay_Reg,state*(0xf0)); } void UNIT_4RELAY::relayWrite( uint8_t number, bool state ) { uint8_t StateFromDevice = read1Byte(addr, relay_Reg); if( state == 0 ) { StateFromDevice &= ~( 0x01 << number ); } else { StateFromDevice |= ( 0x01 << number ); } write1Byte(addr,relay_Reg,StateFromDevice); } void UNIT_4RELAY::LEDWrite( uint8_t number, bool state ) { uint8_t StateFromDevice = read1Byte(addr, relay_Reg); if( state == 0 ) { StateFromDevice &= ~( 0x10 << number ); } else { StateFromDevice |= ( 0x10 << number ); } write1Byte(addr,0x11,StateFromDevice); } void UNIT_4RELAY::switchMode( bool mode ) { write1Byte(addr, 0x10 ,mode); } void UNIT_4RELAY::Init(bool mode) { write1Byte(addr,mode_Reg,mode); write1Byte(addr,relay_Reg,0); }
21.2
87
0.662264
m5stack
b77cfa1b68cff6fbd2eca0a1d11220cf9d3b33ec
1,158
cpp
C++
common/gui/win32/WinFileUtil.cpp
lesit/NeuroStudio
f505065d694a8614587e7cc243ede72c141bd80b
[ "W3C" ]
21
2018-11-15T08:23:14.000Z
2022-03-30T15:44:59.000Z
common/gui/win32/WinFileUtil.cpp
lesit/NeuroStudio
f505065d694a8614587e7cc243ede72c141bd80b
[ "W3C" ]
null
null
null
common/gui/win32/WinFileUtil.cpp
lesit/NeuroStudio
f505065d694a8614587e7cc243ede72c141bd80b
[ "W3C" ]
1
2021-12-08T01:17:27.000Z
2021-12-08T01:17:27.000Z
#include "stdafx.h" #include "WinFileUtil.h" using namespace np::gui::win32; bool WinFileUtil::IsDirectory(const wchar_t* strFilePath) { DWORD dwAttr = GetFileAttributes(strFilePath); if (dwAttr == INVALID_FILE_ATTRIBUTES) return false; return (dwAttr & FILE_ATTRIBUTE_DIRECTORY)>0; } bool WinFileUtil::GetNormalFileType(const wchar_t* strFilePath, bool& bDirectory) { DWORD dwAttr = GetFileAttributes(strFilePath); if (dwAttr == INVALID_FILE_ATTRIBUTES) return false; if (dwAttr & (FILE_ATTRIBUTE_TEMPORARY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN)) return false; bDirectory = (dwAttr & FILE_ATTRIBUTE_DIRECTORY)>0; return true; } void WinFileUtil::GetSubFiles(const wchar_t* dir_path, std_wstring_vector& path_vector) { WIN32_FIND_DATA findFileData; HANDLE hFind = FindFirstFile(dir_path, &findFileData); if (hFind == INVALID_HANDLE_VALUE) { DEBUG_OUTPUT(L"FindFirstFile failed (%d)", GetLastError()); return; } do { if (findFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) continue; path_vector.push_back(findFileData.cFileName); } while (FindNextFile(hFind, &findFileData)); FindClose(hFind); }
22.705882
89
0.765976
lesit
b77e355a449d985fa8a1ac1c11900ec489b00fa8
3,114
cpp
C++
UVa 12833 - Daily Potato/sample/12833 - Daily Potato.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 12833 - Daily Potato/sample/12833 - Daily Potato.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 12833 - Daily Potato/sample/12833 - Daily Potato.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> #include <string.h> #include <algorithm> #include <vector> using namespace std; #define MAXL 262144 char S[MAXL], C[MAXL], T[MAXL]; int dp[MAXL], n, m; int A[MAXL][26], SUM[MAXL][26]; void exbuild(char S[]) { // manacher's algorithm n = strlen(S), m = 2 * n + 1; int mx = 0, idx = 0; int ans = 0; T[0] = '$', T[m] = '#', T[m + 1] = '\0'; for (int i = 0; i < n; i++) T[i * 2 + 1] = '#', T[i * 2 + 2] = S[i]; // memset(SUM[0], 0, sizeof(SUM[0])); for (int i = 1; i < m; i++) { memcpy(SUM[i], SUM[i-1], sizeof(SUM[0])); if ('a' <= T[i] && T[i] <= 'z') SUM[i][T[i] - 'a']++; } // for (int i = 1; i < m; i++) { if (mx > i) { memcpy(A[i], A[2 * idx - i], sizeof(A[2 * idx - i])); dp[i] = min(dp[2 * idx - i], mx - i); if (dp[2 * idx - i] >= mx - i) { int r = idx - (mx - idx), l = 2 * idx - i - dp[2 * idx - i]; for (int j = 0; j < 26; j++) { A[i][j] -= (SUM[r][j] - SUM[l][j]) * 2; } } } else { for (int j = 0; j < 26; j++) A[i][j] = SUM[i][j] - SUM[i-1][j]; dp[i] = 1; } for(; T[i-dp[i]] == T[i+dp[i]]; dp[i]++) if ('a' <= T[i+dp[i]] && T[i+dp[i]] <= 'z') A[i][T[i-dp[i]] - 'a'] += 2; if(dp[i] + i > mx) mx = dp[i] + i, idx = i; } // for (int i = 1, j = 0; i < m; i ++, j++) // printf("[%02d] %c %d\n", i, T[i], dp[i]); } vector<int> pos[128]; vector<int> M[2][26]; void prepare() { for (int i = 0; i < 26; i++) M[0][i].clear(), M[1][i].clear(); // for (int i = 0; i < 128; i++) // pos[i].clear(); // for (int i = 1; i < m; i++) { // pos[T[i]].push_back(i); // } for (int i = 1; i < m; i++) { // printf("%c ", T[i]); for (int j = 0; j < 26; j++) { M[A[i][j]&1][j].push_back(A[i][j]); // printf("%d ", A[i][j]); } // puts(""); } for (int i = 0; i < 26; i++) { sort(M[0][i].begin(), M[0][i].end()); sort(M[1][i].begin(), M[1][i].end()); } } void query(int x, char c) { if (x == 0) {puts("0"); return;} // int sum = 0, front = 0, rear = 0; // int ret = 0, mid; // for (int i = x - 1, j = 0; i < pos[c].size(); i++, j++) { // front = pos[c][j], rear = pos[c][i]; // mid = (front + rear)/2; // if (mid + dp[mid] - 1 >= rear) // ret++; // } // printf("%d\n", ret); int p = (int) (lower_bound(M[x&1][c - 'a'].begin(), M[x&1][c - 'a'].end(), x) - M[x&1][c - 'a'].begin()); printf("%d\n", int(M[x&1][c - 'a'].size() - p)); } int main() { freopen("in.txt", "r+t", stdin); freopen("out2.txt", "w+t", stdout); int testcase, N, Q, cases = 0; int x; scanf("%d", &testcase); while(testcase--) { scanf("%d %s", &N, S); scanf("%d %s", &Q, C); exbuild(S); prepare(); printf("Case %d:\n", ++cases); for (int i = 0; i < Q; i++) { scanf("%d", &x); query(x, C[i]); } } return 0; } /* 1 8 abccbaab 6 abcabc 2 2 2 1 1 3 1000 6 abaaba 7 aaaaaab 5 4 3 2 1 0 2 123 10 ccecabebcb 10 ebddcdacad 5 6 2 5 5 5 5 1 9 9 10 abbbbeaaba 10 cbabcabcec 2 0 1 8 5 6 2 4 8 1 10 baddaeaecb 10 bbdebdbedd 1 5 5 6 2 9 9 1 5 0 */
22.729927
106
0.423892
tadvi
b77eb22e05e8b69ed2c7767aa7a8eab4bed43f85
10,700
cpp
C++
src/openpose/utilities/fileSystem.cpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
null
null
null
src/openpose/utilities/fileSystem.cpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
null
null
null
src/openpose/utilities/fileSystem.cpp
meiwanlanjun/openpose
71078eb1b7571789c7589cf6c8de1786c3227a90
[ "DOC", "MIT-CMU" ]
null
null
null
#include <cstdio> // fopen #ifdef _WIN32 #include <direct.h> // _mkdir #include <windows.h> // DWORD, GetFileAttributesA #elif defined __unix__ #include <dirent.h> // opendir #include <sys/stat.h> // mkdir #else #error Unknown environment! #endif #include <openpose/utilities/string.hpp> #include <openpose/utilities/fileSystem.hpp> namespace op { void makeDirectory(const std::string& directoryPath) { try { if (!directoryPath.empty()) { // Format the path first const auto formatedPath = formatAsDirectory(directoryPath); // Create dir if it doesn't exist yet if (!existDirectory(formatedPath)) { #ifdef _WIN32 const auto status = _mkdir(formatedPath.c_str()); #elif defined __unix__ // Create folder // Access permission - 775 (7, 7, 4+1) // https://www.gnu.org/software/libc/manual/html_node/Permission-Bits.html const auto status = mkdir(formatedPath.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH); #endif // Error if folder cannot be created if (status != 0) error("Could not create directory: " + formatedPath + ". Status error = " + std::to_string(status) + ". Does the parent folder exist and/or do you have writting" " access to that path?", __LINE__, __FUNCTION__, __FILE__); } } } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); } } bool existDirectory(const std::string& directoryPath) { try { // Format the path first const auto formatedPath = formatAsDirectory(directoryPath); #ifdef _WIN32 DWORD status = GetFileAttributesA(formatedPath.c_str()); // It is not a directory if (status == INVALID_FILE_ATTRIBUTES) return false; // It is a directory else if (status & FILE_ATTRIBUTE_DIRECTORY) return true; // It is not a directory return false; // this is not a directory! #elif defined __unix__ // It is a directory if (auto* directory = opendir(formatedPath.c_str())) { closedir(directory); return true; } // It is not a directory else return false; #else #error Unknown environment! #endif } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return false; } } bool existFile(const std::string& filePath) { try { if (auto* file = fopen(filePath.c_str(), "r")) { fclose(file); return true; } else return false; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return false; } } std::string formatAsDirectory(const std::string& directoryPathString) { try { std::string directoryPath = directoryPathString; if (!directoryPath.empty()) { // Replace all '\\' to '/' std::replace(directoryPath.begin(), directoryPath.end(), '\\', '/'); if (directoryPath.back() != '/') directoryPath = directoryPath + "/"; // Windows - Replace all '/' to '\\' #ifdef _WIN32 std::replace(directoryPath.begin(), directoryPath.end(), '/', '\\'); #endif } return directoryPath; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return ""; } } std::string getFileNameAndExtension(const std::string& fullPath) { try { size_t lastSlashPos = fullPath.find_last_of("\\/"); if (lastSlashPos != std::string::npos) return fullPath.substr(lastSlashPos+1, fullPath.size() - lastSlashPos - 1); else return fullPath; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return ""; } } std::string getFileNameNoExtension(const std::string& fullPath) { try { // Name + extension std::string nameExt = getFileNameAndExtension(fullPath); // Name size_t dotPos = nameExt.find_last_of("."); if (dotPos != std::string::npos) return nameExt.substr(0, dotPos); else return nameExt; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return ""; } } std::string getFileExtension(const std::string& fullPath) { try { // Name + extension std::string nameExt = getFileNameAndExtension(fullPath); // Extension size_t dotPos = nameExt.find_last_of("."); if (dotPos != std::string::npos) return nameExt.substr(dotPos + 1, nameExt.size() - dotPos - 1); else return ""; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return ""; } } // This function just removes the initial '.' in the std::string (if any) // To avoid errors for not finding extensions because of comparing ".jpg" vs "jpg" std::string removeExtensionDot(const std::string& extension) { try { // Extension is empty if (extension.empty()) return ""; // Return string without initial character else if (*extension.cbegin() == '.') return extension.substr(1, extension.size() - 1); // Return string itself else return extension; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return ""; } } bool extensionIsDesired(const std::string& extension, const std::vector<std::string>& extensions) { try { const auto cleanedExtension = toLower(removeExtensionDot(extension)); for (auto& extensionI : extensions) if (cleanedExtension == toLower(removeExtensionDot(extensionI))) return true; return false; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return false; } } std::vector<std::string> getFilesOnDirectory(const std::string& directoryPath, const std::vector<std::string>& extensions) { try { // Format the path first const auto formatedPath = formatAsDirectory(directoryPath); // Check folder exits if (!existDirectory(formatedPath)) error("Folder " + formatedPath + " does not exist.", __LINE__, __FUNCTION__, __FILE__); // Read all files in folder std::vector<std::string> filePaths; #ifdef _WIN32 auto formatedPathWindows = formatedPath; formatedPathWindows.append("\\*"); WIN32_FIND_DATA data; HANDLE hFind; if ((hFind = FindFirstFile(formatedPathWindows.c_str(), &data)) != INVALID_HANDLE_VALUE) { do filePaths.emplace_back(formatedPath + data.cFileName); while (FindNextFile(hFind, &data) != 0); FindClose(hFind); } #elif defined __unix__ std::shared_ptr<DIR> directoryPtr( opendir(formatedPath.c_str()), [](DIR* formatedPath){ formatedPath && closedir(formatedPath); } ); struct dirent* direntPtr; while ((direntPtr = readdir(directoryPtr.get())) != nullptr) { std::string currentPath = formatedPath + direntPtr->d_name; if ((strncmp(direntPtr->d_name, ".", 1) == 0) || existDirectory(currentPath)) continue; filePaths.emplace_back(currentPath); } #else #error Unknown environment! #endif // Check #files > 0 if (filePaths.empty()) error("No files were found on " + formatedPath, __LINE__, __FUNCTION__, __FILE__); // If specific extensions specified if (!extensions.empty()) { // Read images std::vector<std::string> specificExtensionPaths; specificExtensionPaths.reserve(filePaths.size()); for (const auto& filePath : filePaths) if (extensionIsDesired(getFileExtension(filePath), extensions)) specificExtensionPaths.emplace_back(filePath); std::swap(filePaths, specificExtensionPaths); } // Sort alphabetically std::sort(filePaths.begin(), filePaths.end()); // Return result return filePaths; } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return {}; } } std::vector<std::string> getFilesOnDirectory(const std::string& directoryPath, const std::string& extension) { try { return getFilesOnDirectory(directoryPath, std::vector<std::string>{extension}); } catch (const std::exception& e) { error(e.what(), __LINE__, __FUNCTION__, __FILE__); return {}; } } }
34.96732
117
0.497383
meiwanlanjun
b77f8a98b9d4e8eff3e6110f4bfe69457782718d
2,746
cc
C++
kernel/futex.cc
mit-pdos/ward
91b598932d161f907590b9ad21d7df395e5d6712
[ "MIT-0" ]
29
2019-12-12T02:30:35.000Z
2022-01-06T17:13:09.000Z
kernel/futex.cc
mit-pdos/ward
91b598932d161f907590b9ad21d7df395e5d6712
[ "MIT-0" ]
47
2019-12-11T02:34:13.000Z
2020-06-08T19:26:59.000Z
kernel/futex.cc
mit-pdos/ward
91b598932d161f907590b9ad21d7df395e5d6712
[ "MIT-0" ]
4
2020-12-08T13:46:55.000Z
2022-01-04T20:25:10.000Z
#include "types.h" #include "kernel.hh" #include "spinlock.hh" #include "cpputil.hh" #include "ns.hh" #include "errno.h" #include "condvar.hh" #include "proc.hh" #include "cpu.hh" #include "spercpu.hh" #include "vm.hh" #include "hash.hh" #define FUTEX_HASH_BUCKETS 257 struct futex_list_bucket { ilist<proc, &proc::futex_link> items; spinlock lock; }; struct futex_list { futex_list_bucket buckets[FUTEX_HASH_BUCKETS]; }; futex_list futex_waiters __attribute__((section (".qdata"))); futexkey::futexkey(uintptr_t useraddr, const sref<class vmap>& vmap_, bool priv) : ptr(nullptr) { if ((useraddr & 0x3) != 0) panic("misaligned futex address"); u64 pageidx; if (!priv && (pageable = vmap_->lookup_pageable(useraddr, &pageidx))) { shared = true; address = pageidx * PGSIZE + useraddr % PGSIZE; } else { shared = false; vmap = vmap_.get(); address = useraddr; } } futexkey::futexkey(futexkey&& other) : futexkey() { *this = std::move(other); } futexkey& futexkey::operator=(futexkey&& other) noexcept { shared = other.shared; address = other.address; ptr = other.ptr; other.ptr = nullptr; return *this; } futexkey::~futexkey() { if (shared) pageable.reset(); } bool futexkey::operator==(const futexkey& other) { return address == other.address && ptr == other.ptr && shared == other.shared; } u64 futex_bucket(futexkey* key) { return (hash(key->address) ^ hash(key->ptr)) % FUTEX_HASH_BUCKETS; } u32 futexval(futexkey* key) { if (key->shared) { auto p = key->pageable->get_page_info(PGROUNDDOWN(key->address)); return *(u32*)((char*)p->va() + (key->address % PGSIZE)); } u32 val; if (key->vmap == myproc()->vmap.get() && !fetchmem_ncli(&val, (const void*)(key->address), 4)) return val; u32* kva = (u32*)key->vmap->pagelookup(key->address); return kva ? *kva : 0; } long futexwait(futexkey&& key, u32 val, u64 timer) { futex_list_bucket* bucket = &futex_waiters.buckets[futex_bucket(&key)]; scoped_acquire l(&bucket->lock); if (futexval(&key) != val) return -EWOULDBLOCK; myproc()->futex_key = std::move(key); bucket->items.push_back(myproc()); u64 nsecto = timer == 0 ? 0 : timer+nsectime(); myproc()->cv->sleep_to(&bucket->lock, nsecto); bucket->items.erase(iiterator<proc, &proc::futex_link>(myproc())); return 0; } long futexwake(futexkey&& key, u64 nwake) { if (nwake == 0) { return -EINVAL; } futex_list_bucket* bucket = &futex_waiters.buckets[futex_bucket(&key)]; scoped_acquire l(&bucket->lock); u64 nwoke = 0; for(auto i = bucket->items.begin(); i != bucket->items.end() && nwoke < nwake; i++) { if (i->futex_key == key) { i->cv->wake_all(); nwoke++; } } return nwoke; }
23.470085
97
0.651493
mit-pdos
b781cdda745f6b32584197979582e87bc6178dd9
23,899
cpp
C++
groups/bsl/bslma/bslma_stdtestallocator.t.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
1
2021-11-10T16:53:42.000Z
2021-11-10T16:53:42.000Z
groups/bsl/bslma/bslma_stdtestallocator.t.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
2
2020-11-05T15:20:55.000Z
2021-01-05T19:38:43.000Z
groups/bsl/bslma/bslma_stdtestallocator.t.cpp
seanbaxter/bde-1
149176ebc2ae49c3b563895a7332fe638a760782
[ "Apache-2.0" ]
2
2020-01-16T17:58:12.000Z
2020-08-11T20:59:30.000Z
// bslma_stdtestallocator.t.cpp -*-C++-*- #include <bslma_stdtestallocator.h> #include <bslma_allocator.h> #include <bslma_default.h> #include <bslma_defaultallocatorguard.h> #include <bslma_testallocator.h> #include <bsls_bsltestutil.h> #include <limits> #include <new> #include <stdio.h> #include <stdlib.h> using namespace BloombergLP; // TBD: fix this up //============================================================================= // TEST PLAN //----------------------------------------------------------------------------- // Overview // -------- // An allocator is a value-semantic type whose value consists of a single // pointer to a 'bslma::Allocator' object (its underlying "mechanism"). This // pointer can be set at construction (and if 0 is passed, then it uses // 'bslma_default' to substitute a pointer to the currently installed default // allocator), and it can be accessed through the 'mechanism' accessor. It // cannot be reset, however, since normally an allocator does not change during // the lifetime of an object. A 'bsl::allocator' is parameterized by the type // that it allocates, and that influences the behavior of several manipulators // and accessors, mainly depending on the size of that type. The same // 'bsl::allocator" can be re-parameterized for another type ("rebound") using // the 'rebind' nested template. // // Although 'bsl::allocator' is a value-semantic type, the fact that its value // is fixed at construction and not permitted to change let us relax the usual // concerns of a typical value-semantic type. Our specific concerns are that // an allocator constructed with a certain underlying mechanism actually uses // that mechanism to allocate memory, and that its rebound versions also do. // Another concern is that the 'max_size' is the maximum possible size for that // type (i.e., it is impossible to meaningfully pass in a larger size), and // that the 'size_type' is unsigned, the 'difference_type' is signed, and // generally all the requirements of C++ standard allocators are met (20.1.2 // [allocator.requirements]). //----------------------------------------------------------------------------- // [ 3] StdTestAllocator(); // [ 3] StdTestAllocator(bslma::Allocator *); // [ 3] StdTestAllocator(const StdTestAllocator&); // [ 3] StdTestAllocator(const StdTestAllocator<U>&); // [ ] ~StdTestAllocator(); // // Modifiers // [ ] StdTestAllocator& operator=(const allocator& rhs); // [ ] pointer allocate(size_type n, const void *hint = 0); // [ ] void deallocate(pointer p, size_type n = 1); // [ ] void construct(pointer p, const TYPE& val); // [ ] void destroy(pointer p); // // Accessors // [ ] pointer address(reference x) const; // [ ] const_pointer address(const_reference x) const; // [ 4] bslma::Allocator *mechanism() const; // [ 4] size_type max_size() const; // // Nested types // [ 5] StdTestAllocator::size_type // [ 5] StdTestAllocator::difference_type // [ 5] StdTestAllocator::pointer; // [ 5] StdTestAllocator::const_pointer; // [ 5] StdTestAllocator::reference; // [ 5] StdTestAllocator::const_reference; // [ 5] StdTestAllocator::value_type; // [ 5] template rebind<U>::other // // Free functions (operators) // [ 4] bool operator==(StdTestAllocator<T>, StdTestAllocator<T>); // [ ] bool operator==(StdTestAllocator<T1>, StdTestAllocator<T2>); // [ 4] bool operator==(bslma::Allocator *, StdTestAllocator<T>); // [ 4] bool operator==(StdTestAllocator<T>, bslma::Allocator*); // [ ] bool operator!=(StdTestAllocator<T1>, StdTestAllocator<T2>); // [ ] bool operator!=(bslma::Allocator *, StdTestAllocator<T>); // [ ] bool operator!=(StdTestAllocator<T>, bslma::Allocator*); //----------------------------------------------------------------------------- // [ 1] BREATHING TEST // [ 6] USAGE EXAMPLE // [ 2] bsl::is_trivially_copyable<StdTestAllocator> // [ 2] bslmf::IsBitwiseEqualityComparable<sl::allocator> // [ 2] bslmf::IsBitwiseMoveable<StdTestAllocator> // ============================================================================ // STANDARD BDE ASSERT TEST MACROS // ---------------------------------------------------------------------------- // NOTE: THIS IS A LOW-LEVEL COMPONENT AND MAY NOT USE ANY C++ LIBRARY // FUNCTIONS, INCLUDING IOSTREAMS. namespace { int testStatus = 0; void aSsErT(bool b, const char *s, int i) { if (b) { printf("Error " __FILE__ "(%d): %s (failed)\n", i, s); if (testStatus >= 0 && testStatus <= 100) ++testStatus; } } } // close unnamed namespace //============================================================================= // STANDARD BDE TEST DRIVER MACROS //----------------------------------------------------------------------------- #define ASSERT BSLS_BSLTESTUTIL_ASSERT #define LOOP_ASSERT BSLS_BSLTESTUTIL_LOOP_ASSERT #define LOOP0_ASSERT BSLS_BSLTESTUTIL_LOOP0_ASSERT #define LOOP1_ASSERT BSLS_BSLTESTUTIL_LOOP1_ASSERT #define LOOP2_ASSERT BSLS_BSLTESTUTIL_LOOP2_ASSERT #define LOOP3_ASSERT BSLS_BSLTESTUTIL_LOOP3_ASSERT #define LOOP4_ASSERT BSLS_BSLTESTUTIL_LOOP4_ASSERT #define LOOP5_ASSERT BSLS_BSLTESTUTIL_LOOP5_ASSERT #define LOOP6_ASSERT BSLS_BSLTESTUTIL_LOOP6_ASSERT #define ASSERTV BSLS_BSLTESTUTIL_ASSERTV #define Q BSLS_BSLTESTUTIL_Q // Quote identifier literally. #define P BSLS_BSLTESTUTIL_P // Print identifier and value. #define P_ BSLS_BSLTESTUTIL_P_ // P(X) without '\n'. #define T_ BSLS_BSLTESTUTIL_T_ // Print a tab (w/o newline). #define L_ BSLS_BSLTESTUTIL_L_ // current Line number // ============================================================================ // NEGATIVE-TEST MACRO ABBREVIATIONS // ---------------------------------------------------------------------------- #define ASSERT_SAFE_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS(EXPR) #define ASSERT_SAFE_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL(EXPR) #define ASSERT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_PASS(EXPR) #define ASSERT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL(EXPR) #define ASSERT_OPT_PASS(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS(EXPR) #define ASSERT_OPT_FAIL(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL(EXPR) #define ASSERT_SAFE_PASS_RAW(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_PASS_RAW(EXPR) #define ASSERT_SAFE_FAIL_RAW(EXPR) BSLS_ASSERTTEST_ASSERT_SAFE_FAIL_RAW(EXPR) #define ASSERT_PASS_RAW(EXPR) BSLS_ASSERTTEST_ASSERT_PASS_RAW(EXPR) #define ASSERT_FAIL_RAW(EXPR) BSLS_ASSERTTEST_ASSERT_FAIL_RAW(EXPR) #define ASSERT_OPT_PASS_RAW(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_PASS_RAW(EXPR) #define ASSERT_OPT_FAIL_RAW(EXPR) BSLS_ASSERTTEST_ASSERT_OPT_FAIL_RAW(EXPR) // ============================================================================ // PRINTF FORMAT MACROS // ---------------------------------------------------------------------------- #define ZU BSLS_BSLTESTUTIL_FORMAT_ZU //============================================================================= // GLOBAL TYPEDEFS/CONSTANTS FOR TESTING //----------------------------------------------------------------------------- enum { VERBOSE_ARG_NUM = 2, VERY_VERBOSE_ARG_NUM, VERY_VERY_VERBOSE_ARG_NUM }; //============================================================================= // GLOBAL HELPER FUNCTIONS FOR TESTING //----------------------------------------------------------------------------- //============================================================================= // USAGE EXAMPLE //----------------------------------------------------------------------------- // =============== // struct MyObject // =============== struct MyObject { // A non-trivial-sized object. // DATA int d_i; char d_s[10]; }; //============================================================================= // MAIN PROGRAM //----------------------------------------------------------------------------- int main(int argc, char *argv[]) { int test = argc > 1 ? atoi(argv[1]) : 0; bool verbose = argc > 2; bool veryVerbose = argc > 3; bool veryVeryVerbose = argc > 4; bool veryVeryVeryVerbose = argc > 5; (void) veryVerbose; (void) veryVeryVerbose; bslma::TestAllocator globalAllocator("global", veryVeryVeryVerbose); bslma::Default::setGlobalAllocator(&globalAllocator); bslma::TestAllocator defaultAllocator("default", veryVeryVeryVerbose); ASSERT(0 == bslma::Default::setDefaultAllocator(&defaultAllocator)); setbuf(stdout, NULL); // Use unbuffered output printf("TEST " __FILE__ " CASE %d\n", test); switch (test) { case 0: // Zero is always the leading case. case 6: { // -------------------------------------------------------------------- // USAGE EXAMPLE // // Concerns: The usage example must compile end execute without // errors. // // Plan: Copy-paste the usage example and replace 'assert' by // 'ASSERT'. // // Testing: // USAGE EXAMPLE // -------------------------------------------------------------------- bslma::TestAllocator ta("default for usage", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard allocGuard(&ta); if (verbose) printf("\nUSAGE EXAMPLE" "\n=============\n"); if (verbose) { printf("This test has not yet been implemented.\n"); } } break; case 5: { // -------------------------------------------------------------------- // TESTING NESTED TYPES // // Concerns: // o that 'size_type' is unsigned while 'difference_type' is signed. // o that size_type and difference_type are the right size (i.e., // they can represent any difference of pointers in the memory // model) // o that all other types exist and are as specified by the C++ // standard // o that if Y is X::rebind<U>::other, then Y::rebind<T>::other is // the same type as X // // Plan: The testing is straightforward and follows the concerns. // // Testing: // bslma::StdTestAllocator::size_type // bslma::StdTestAllocator::difference_type // bslma::StdTestAllocator::pointer; // bslma::StdTestAllocator::const_pointer; // bslma::StdTestAllocator::reference; // bslma::StdTestAllocator::const_reference; // bslma::StdTestAllocator::value_type; // template rebind<U>::other // -------------------------------------------------------------------- if (verbose) printf("\nTESTING NESTED TYPES" "\n====================\n"); typedef bslma::StdTestAllocator<int> AI; typedef bslma::StdTestAllocator<float> AF; if (verbose) printf("\tTesting 'size_type'.\n"); { ASSERT(sizeof(AI::size_type) == sizeof(int*)); ASSERT(0 < ~(AI::size_type)0); } if (verbose) printf("\tTesting 'difference_type'.\n"); { ASSERT(sizeof(AI::difference_type) == sizeof(int*)); ASSERT(0 > ~(AI::difference_type)0); } if (verbose) printf("\tTesting 'pointer'.\n"); { ASSERT((bsl::is_same<AI::pointer, int*>::value)); ASSERT((bsl::is_same<AF::pointer, float*>::value)); } if (verbose) printf("\tTesting 'const_pointer'.\n"); { ASSERT((bsl::is_same<AI::const_pointer, const int*>::value)); ASSERT((bsl::is_same<AF::const_pointer, const float*>::value)); } if (verbose) printf("\tTesting 'reference'.\n"); { ASSERT((bsl::is_same<AI::reference, int&>::value)); ASSERT((bsl::is_same<AF::reference, float&>::value)); } if (verbose) printf("\tTesting 'const_reference'.\n"); { ASSERT((bsl::is_same<AI::const_reference, const int&>::value)); ASSERT((bsl::is_same<AF::const_reference, const float&>::value)); } if (verbose) printf("\tTesting 'value_type'.\n"); { ASSERT((bsl::is_same<AI::value_type, int>::value)); ASSERT((bsl::is_same<AF::value_type, float>::value)); } if (verbose) printf("\tTesting 'rebind'.\n"); { ASSERT((bsl::is_same<AI::rebind<int >::other, AI>::value)); ASSERT((bsl::is_same<AI::rebind<float>::other, AF>::value)); ASSERT((bsl::is_same<AF::rebind<int >::other, AI>::value)); ASSERT((bsl::is_same<AF::rebind<float>::other, AF>::value)); } } break; case 4: { // -------------------------------------------------------------------- // TESTING ACCESSORS // // Concerns: // o that the correct 'bslma::Allocator*' is returned by 'mechanism'. // o that the result of 'max_size' fits and represents the maximum // possible number of bytes in a 'bslma::Allocator::size_type'. // o that all comparisons exist and resolve to comparing the // mechanisms. // // Plan: The concerns are straightforward to test. // // Testing: // bslma::Allocator *mechanism() const; // size_type max_size() const; // bool operator==(StdTestAllocator<T>, StdTestAllocator<T>); // bool operator==(bslma::Allocator *, StdTestAllocator<T>); // bool operator==(StdTestAllocator<T>, bslma::Allocator*); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING ACCESSORS" "\n=================\n"); bslma::TestAllocator da("default"); bslma::DefaultAllocatorGuard dag(&da); if (verbose) printf("\tTesting 'mechanism()'.\n"); { bslma::TestAllocator ta(veryVeryVeryVerbose); bslma::StdTestAllocator<int> ai1; ASSERT(&da == ai1.mechanism()); bslma::StdTestAllocator<int> ai2(&ta); ASSERT(&ta == ai2.mechanism()); bslma::StdTestAllocator<int> ai4(0); ASSERT(&da == ai4.mechanism()); bslma::StdTestAllocator<double> ad1; ASSERT(&da == ai1.mechanism()); bslma::StdTestAllocator<double> ad2(&ta); ASSERT(&ta == ai2.mechanism()); bslma::StdTestAllocator<double> ad4(0); ASSERT(&da == ai4.mechanism()); bslma::StdTestAllocator<int> ai5(ad2); ASSERT(&ta == ai5.mechanism()); bslma::StdTestAllocator<double> ad5(ai2); ASSERT(&ta == ad5.mechanism()); } if (verbose) printf("\tTesting 'max_size()'.\n"); { typedef bslma::Allocator::size_type bsize; bslma::StdTestAllocator<char> charAlloc; bsize cas = charAlloc.max_size(); // verify that max_size() is the largest positive integer of type // size_type LOOP_ASSERT(cas, cas > 0); LOOP_ASSERT(cas, cas == std::numeric_limits<bsize>::max()); if (verbose) { printf("cas = " ZU "\n", cas); } bslma::StdTestAllocator<MyObject> objAlloc; // Detect problem with MSVC in 64-bit mode, which can't do 64-bit // int arithmetic correctly for enums. ASSERT(objAlloc.max_size() < charAlloc.max_size()); bsize oas = objAlloc.max_size(); bsize oass = oas * sizeof(MyObject); bsize oassplus = oass + sizeof(MyObject); LOOP_ASSERT(oas, oas > 0); LOOP_ASSERT(oass, oass < cas); LOOP_ASSERT(oass, oass > oas); // no overflow LOOP_ASSERT(oassplus, oassplus < oas); // overflow if (verbose) { printf("\tAs unsigned long: oas = " ZU ", oass = " ZU ", " "oassplus = " ZU ".\n", oas, oass, oassplus); } } if (verbose) printf("\tTesting 'operator=='.\n"); { bslma::TestAllocator ta1(veryVeryVeryVerbose); bslma::TestAllocator ta2(veryVeryVeryVerbose); bslma::StdTestAllocator<int> ai1(&ta1); bslma::StdTestAllocator<int> ai2(&ta2); bslma::StdTestAllocator<double> ad1(&ta1); bslma::StdTestAllocator<double> ad2(&ta2); // One of lhs or rhs is 'bslma::Allocator *'. ASSERT(&ta1 == ai1); ASSERT(ai1 == &ta1); ASSERT(&ta2 != ai1); ASSERT(ai1 != &ta2); ASSERT(&ta1 == ai1); ASSERT(ai1 == &ta1); ASSERT(&ta2 != ai1); ASSERT(ai1 != &ta2); ASSERT(&ta1 == ad1); ASSERT(ad1 == &ta1); ASSERT(&ta2 != ad1); ASSERT(ad1 != &ta2); ASSERT(&ta1 == ad1); ASSERT(ad1 == &ta1); ASSERT(&ta2 != ad1); ASSERT(ad1 != &ta2); // Both lhs and rhs are 'bslma::StdTestAllocator'. ASSERT(ai1 == ai1); ASSERT(ai1 != ai2); ASSERT(ai1 == ad1); ASSERT(ai1 != ad2); ASSERT(ad1 == ai1); ASSERT(ad1 != ai2); ASSERT(ad1 == ad1); ASSERT(ad1 != ad2); ASSERT(ai2 != ai1); ASSERT(ai2 == ai2); ASSERT(ai2 != ad1); ASSERT(ai2 == ad2); ASSERT(ad2 != ai1); ASSERT(ad2 == ai2); ASSERT(ad2 != ad1); ASSERT(ad2 == ad2); } } break; case 3: { // -------------------------------------------------------------------- // TESTING CONSTRUCTORS // // Concerns: // o that an allocator can be constructed from the various // constructors and that it uses the correct mechanism object. // o that an allocator can be constructed from an allocator to a // different type // // Plan: We construct a number of allocators from various mechanisms, // and test that they do compare equal to the selected mechanism. // Copy constructed allocators have to compare equal to their // original values. // // Testing: // StdTestAllocator(); // StdTestAllocator(bslma::Allocator *); // StdTestAllocator(const StdTestAllocator&); // StdTestAllocator(const StdTestAllocator<U>&); // -------------------------------------------------------------------- if (verbose) printf("\nTESTING CONSTRUCTORS" "\n====================\n"); bslma::TestAllocator da("default", veryVeryVeryVerbose); bslma::DefaultAllocatorGuard dag(&da); bslma::TestAllocator ta("test case 3", veryVeryVeryVerbose); bslma::StdTestAllocator<int> ai1; ASSERT(&da == ai1); bslma::StdTestAllocator<int> ai2(&ta); ASSERT(&ta == ai2); bslma::StdTestAllocator<int> ai3(ai2); ASSERT(&ta == ai3); bslma::StdTestAllocator<int> ai4(0); ASSERT(&da == ai4); bslma::StdTestAllocator<double> ad1; ASSERT(&da == ad1); bslma::StdTestAllocator<double> ad2(&ta); ASSERT(&ta == ad2); bslma::StdTestAllocator<double> ad3(ad2); ASSERT(&ta == ad3); bslma::StdTestAllocator<double> ad4(0); ASSERT(&da == ad4); bslma::StdTestAllocator<int> ai5(ad2); ASSERT(ad2 == ai5); bslma::StdTestAllocator<double> ad5(ai2); ASSERT(ai2 == ad5); } break; case 2: { // -------------------------------------------------------------------- // TESTING TRAITS // // Concerns: // That an allocator has the proper traits defined. // // Plan: Since it does not matter what type 'StdTestAllocator' is // instantiated with, use 'int' and test for each expected trait. // Note that 'void' also needs to be tested since it is a // specialization. // // Testing: // bsl::is_trivially_copyable<StdTestAllocator> // bslmf::IsBitwiseEqualityComparable<StdTestAllocator> // bslmf::IsBitwiseMoveable<StdTestAllocator> // -------------------------------------------------------------------- if (verbose) printf("\nTESTING TRAITS" "\n==============\n"); ASSERT((bslmf::IsBitwiseMoveable<bslma::StdTestAllocator<int> >::value)); ASSERT((bsl::is_trivially_copyable< bslma::StdTestAllocator<int> >::value)); ASSERT((bslmf::IsBitwiseEqualityComparable< bslma::StdTestAllocator<int> >::value)); } break; case 1: { // -------------------------------------------------------------------- // BREATHING TEST // This test case exercises the component but *tests* nothing. // // Concerns: // // Plan: // // Testing: // BREATHING TEST // -------------------------------------------------------------------- if (verbose) printf("\nBREATHING TEST" "\n==============\n"); bslma::TestAllocator ta("breathing test", veryVeryVeryVerbose); #if 0 my_FixedSizeArray<int, bslma::StdTestAllocator<int> > a1(5, &ta); ASSERT(5 == a1.length()); // ASSERT(bslma::Default::defaultAllocator() == a1.allocator()); ASSERT(&ta == a1.allocator()); for (int i = 0; i < a1.length(); ++i) { a1[i] = i + 1; } my_CountingAllocator countingAlloc; my_FixedSizeArray<int, bslma::StdTestAllocator<int> > a2(a1, &countingAlloc); ASSERT(a1 == a2); ASSERT(a1.allocator() != a2.allocator()); ASSERT(&countingAlloc == a2.allocator()); ASSERT(1 == countingAlloc.blocksOutstanding()); // Test that this will compile: bslma::StdTestAllocator<void> voidAlloc(&countingAlloc); #endif } break; default: { fprintf(stderr, "WARNING: CASE `%d' NOT FOUND.\n", test); testStatus = -1; } } // CONCERN: In no case does memory come from the default allocator. ASSERTV(defaultAllocator.numBlocksTotal(), 0 == defaultAllocator.numBlocksTotal()); // CONCERN: In no case does memory come from the global allocator. ASSERTV(globalAllocator.numBlocksTotal(), 0 == globalAllocator.numBlocksTotal()); if (testStatus > 0) { fprintf(stderr, "Error, non-zero test status = %d.\n", testStatus); } return testStatus; } // ---------------------------------------------------------------------------- // Copyright 2018 Bloomberg Finance L.P. // // 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. // ----------------------------- END-OF-FILE ----------------------------------
39.898164
81
0.525378
seanbaxter
b7828e490770598d7cbe06bfad2e50233ce92d64
1,838
hpp
C++
src/backnocles/utils/disablewarnings.hpp
dsiroky/backnocles
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
[ "MIT" ]
3
2017-10-22T17:57:10.000Z
2017-11-06T12:33:31.000Z
src/backnocles/utils/disablewarnings.hpp
dsiroky/backnocles
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
[ "MIT" ]
null
null
null
src/backnocles/utils/disablewarnings.hpp
dsiroky/backnocles
889ab5f65fc1beb27f6dfff36d5fcda8544a9be2
[ "MIT" ]
null
null
null
/// Place this include above thirdparty includes. Pair with enablewarnings.hpp. /// /// Project has very restrictive warnings and lots of libraries does not /// conform to that. MSVC++ does not have "-isystem" equivalent. /// /// @file #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable: 4244) #pragma warning(disable: 4245) #pragma warning(disable: 4251) #pragma warning(disable: 4290) #pragma warning(disable: 4913) #else #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" #pragma GCC diagnostic ignored "-Wconversion" #pragma GCC diagnostic ignored "-Wdelete-non-virtual-dtor" #pragma GCC diagnostic ignored "-Wdeprecated" #pragma GCC diagnostic ignored "-Wfloat-equal" #pragma GCC diagnostic ignored "-Wnon-virtual-dtor" #pragma GCC diagnostic ignored "-Wold-style-cast" #pragma GCC diagnostic ignored "-Woverloaded-virtual" #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wsign-conversion" #pragma GCC diagnostic ignored "-Wsign-promo" #pragma GCC diagnostic ignored "-Wswitch-default" #pragma GCC diagnostic ignored "-Wunused-parameter" #ifndef __APPLE__ #pragma GCC diagnostic ignored "-Wunused-local-typedefs" #endif #ifdef __clang__ #ifndef __APPLE__ #pragma GCC diagnostic ignored "-Winconsistent-missing-override" #endif #pragma GCC diagnostic ignored "-Wfloat-conversion" #pragma GCC diagnostic ignored "-Wgnu-zero-variadic-macro-arguments" #pragma GCC diagnostic ignored "-Wparentheses-equality" #if __clang_major__ * 100 + __clang_minor__ >= 309 #ifndef __APPLE__ #pragma GCC diagnostic ignored "-Wexpansion-to-defined" #endif #pragma GCC diagnostic ignored "-Wnull-dereference" #endif #endif #endif
37.510204
79
0.73667
dsiroky
b782ae90c712d56dc5301eed9c6d2457122afd3f
999
cpp
C++
Common01/Source/Common/Log/LogConsumerConsole.cpp
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
Common01/Source/Common/Log/LogConsumerConsole.cpp
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
Common01/Source/Common/Log/LogConsumerConsole.cpp
DavidCoenFish/game02
3011cf2fe069b579759aa95333cb406a8ff52d53
[ "Unlicense" ]
null
null
null
#include "CommonPCH.h" #include "Common/Log/LogConsumerConsole.h" #include "Common/Log/Log.h" #include "Common/Util/Utf8.h" LogConsumerConsole::LogConsumerConsole(const std::vector<bool>& topicFilterArrayOrEmpty) : m_topicFilterArrayOrEmpty(topicFilterArrayOrEmpty) { if (TRUE == AttachConsole(ATTACH_PARENT_PROCESS)) { FILE* pFileOut = nullptr; freopen_s(&pFileOut, "conout$","w",stdout); LOG_MESSAGE("AttachConsole"); } } LogConsumerConsole::~LogConsumerConsole() { //nop } void LogConsumerConsole::AddMessage(const LogTopic topic, const std::string& message ) { std::string text = std::to_string((int)topic) + std::string(":") + message + "\n"; OutputDebugStringW(Utf8::Utf8ToUtf16(text).c_str()); printf(text.c_str()); } const bool LogConsumerConsole::AcceptsTopic(const LogTopic topic) { if ((0 <= (int)topic) && ((int)topic < m_topicFilterArrayOrEmpty.size())) { return m_topicFilterArrayOrEmpty[(int)topic]; } return true; }
24.975
88
0.703704
DavidCoenFish
b783c70fbc58bdd7d14e497c5f0d07c4cb71122b
320
cpp
C++
DwarfDash/src/Geometry.cpp
Zai-shen/DwarfDash
2a991a33dc4550bdf89a665a092b0b8db6a03724
[ "MIT" ]
null
null
null
DwarfDash/src/Geometry.cpp
Zai-shen/DwarfDash
2a991a33dc4550bdf89a665a092b0b8db6a03724
[ "MIT" ]
null
null
null
DwarfDash/src/Geometry.cpp
Zai-shen/DwarfDash
2a991a33dc4550bdf89a665a092b0b8db6a03724
[ "MIT" ]
null
null
null
#include "Geometry.h" glm::mat4 Geometry::getModelMatrix() { return _modelMatrix; } void Geometry::setTransformMatrix(glm::mat4 transformationMatrix) { _transformMatrix = transformationMatrix; } //void Geometry::transform(glm::mat4 transformationMatrix) { // _modelMatrix = _modelMatrix * transformationMatrix; //}
22.857143
67
0.775
Zai-shen
b785a7ba88c2fcb13ae1a182ee56c29a5e6721f2
8,966
cpp
C++
game/graphics/texture/jak1_tpage_dir.cpp
Hat-Kid/jak-project
0e2320ca9584118316313e41e646b179a1083feb
[ "ISC" ]
54
2022-02-08T13:07:50.000Z
2022-03-31T14:18:42.000Z
game/graphics/texture/jak1_tpage_dir.cpp
Hat-Kid/jak-project
0e2320ca9584118316313e41e646b179a1083feb
[ "ISC" ]
120
2022-02-08T05:19:11.000Z
2022-03-30T22:26:52.000Z
game/graphics/texture/jak1_tpage_dir.cpp
Hat-Kid/jak-project
0e2320ca9584118316313e41e646b179a1083feb
[ "ISC" ]
8
2022-02-13T22:39:55.000Z
2022-03-30T02:17:57.000Z
#include <vector> #include "common/common_types.h" #include "jak1_tpage_dir.h" namespace { std::vector<u32> tpage_dir = { 0x0, 0x2, 0x37, 0x1, 0x1, 0x10, 0x2, 0x4, 0x3, 0x2, 0x1, 0x5, 0x7, 0x8, 0x1, 0x1, 0x1, 0xb, 0xe, 0x8, 0x1, 0x6, 0x4, 0x6, 0x3, 0x3, 0x6, 0x6, 0x4, 0x4, 0x4, 0xd, 0x1, 0x4, 0x9, 0xc, 0x1, 0x1, 0x6, 0x3, 0x2, 0x14, 0x1, 0x1, 0x2, 0x2, 0x34, 0x34, 0x4, 0x15, 0x1, 0x1, 0x1, 0x8, 0x6, 0xb, 0xb, 0x7, 0x17, 0x1, 0x7, 0x20, 0xd, 0xa, 0x1, 0x1, 0xb, 0x11, 0x2, 0x9, 0xb, 0xa, 0xe, 0x1, 0x6, 0x6, 0x1, 0x2, 0x2, 0x33, 0x33, 0xd, 0x2, 0x9, 0x4, 0x68, 0x1, 0x9, 0x1, 0x2, 0x1, 0x5, 0x9, 0x7, 0x14, 0xa, 0x1, 0x1, 0x1, 0x2, 0x10, 0x4, 0x2, 0x17, 0x2, 0x1, 0x13, 0x6, 0x1, 0x1, 0x1, 0x2, 0x1, 0x16, 0x1, 0x5, 0x1, 0xe, 0x3, 0x2, 0x1, 0x9, 0x15, 0x3, 0x1, 0x2, 0x40, 0x6, 0xb, 0x9, 0x2, 0x8, 0xf, 0x2, 0x2, 0x7, 0x11, 0x5, 0x7, 0x13, 0x9, 0x1, 0x1, 0x1, 0x8, 0x1, 0x1, 0x1, 0x1, 0x1, 0x2, 0x2, 0x9, 0x2, 0xb, 0x5, 0x1, 0xa, 0x15, 0x2e, 0x4, 0x22, 0xb, 0x2e, 0x1e, 0x6, 0x4, 0x6, 0x3, 0x3, 0x6, 0x6, 0x2, 0x19, 0x5, 0x5, 0x8, 0x37, 0x15, 0x2, 0x1, 0x1, 0x4, 0x4, 0x8, 0x9, 0x9, 0x9, 0x9, 0x8, 0x6, 0x1e, 0x7, 0x1, 0x5, 0x9, 0x72, 0xc, 0x5, 0x16, 0x5, 0x4, 0x1, 0x6, 0x3, 0x3, 0x3, 0x3, 0x1, 0x1, 0x1c, 0xa3, 0x47, 0x1b, 0xc9, 0xa, 0x1, 0x16, 0x1, 0x4, 0x4, 0x4, 0x4, 0x4, 0xd, 0x4, 0xc, 0x2d, 0x4, 0x1, 0x1, 0xf, 0x2, 0x2, 0x10, 0x3, 0x3, 0x1, 0x1, 0x1, 0x1, 0x1, 0x4, 0x4, 0x9, 0x9, 0x5, 0x6, 0xa, 0x4, 0x1, 0x5, 0x4, 0x9, 0x2, 0x1, 0x4, 0x2, 0x2, 0x3, 0x12, 0xa, 0x8, 0x4, 0x5, 0x1, 0x1, 0x6, 0x6, 0x7, 0xf, 0x1d, 0x4, 0x4, 0x93, 0x1, 0x2, 0x15, 0x1, 0xc, 0x1, 0xb, 0x1, 0x5, 0x1e, 0x1, 0x3c, 0x10, 0x5, 0x4, 0x5, 0x3, 0xb, 0x4, 0x8, 0x4, 0x4, 0x9, 0x6, 0x3, 0x1d, 0x2e, 0x1, 0x3, 0x15, 0xb, 0x1, 0x1, 0x1, 0x2, 0x1, 0x1, 0x1, 0x1, 0x9, 0x8, 0x1a, 0x5, 0xe, 0x1, 0x1e, 0xc, 0x57, 0x71, 0x1, 0x4, 0x8, 0x5, 0x15, 0x7, 0xa, 0x1f, 0xc, 0x6, 0x12, 0x1, 0x2, 0x9, 0x4c, 0xa, 0xc9, 0x1, 0x8, 0x8, 0x1b, 0x8, 0x1d, 0x15, 0x1, 0x19, 0x97, 0x6c, 0xd, 0x3, 0x4, 0x4, 0x2, 0x2, 0x3d, 0xa, 0x36, 0x4, 0x8, 0x21, 0x15, 0x1, 0x1, 0x2, 0x6, 0x2, 0xb, 0x6, 0xb, 0xc, 0x5, 0x4, 0x15, 0x14, 0x1, 0x21, 0x5, 0x6, 0xb, 0x1, 0x1b, 0x57, 0x1e, 0x2, 0xc, 0x16, 0x9, 0x5, 0x9, 0x1, 0x1, 0x2f, 0x1a, 0x9, 0x80, 0x19, 0x97, 0xd, 0x26, 0x8, 0xb, 0x8, 0x1, 0x6, 0x4, 0x1, 0x2, 0x1c, 0x9, 0x13, 0xe, 0x8, 0x1, 0x1, 0x8, 0x4, 0x6, 0x1, 0xd, 0x6, 0x1c, 0x8, 0x1, 0x1d, 0x1, 0x3, 0x4, 0x2, 0x2, 0x1, 0x1, 0x12, 0x3d, 0x13, 0x5, 0x1, 0x25, 0x1, 0x1, 0xb, 0xa, 0x1, 0xe, 0x1, 0xb, 0xa, 0xb, 0x1, 0x38, 0x5, 0x8, 0x1, 0x2, 0x51, 0xc, 0x2, 0x1, 0x5, 0x2, 0x7a, 0x5, 0x5, 0x1, 0x1, 0x2, 0x1, 0x1, 0x7, 0xe, 0xd, 0x2, 0x4, 0x1, 0x1, 0xc, 0x5, 0x3, 0x1, 0x2, 0x24, 0x15, 0x24, 0x8, 0x11, 0x1, 0x1, 0x1, 0x5, 0x1, 0x1, 0x8, 0x2, 0x2, 0x1, 0x1, 0xb, 0xa, 0xa, 0x5, 0x1, 0x1d, 0x4, 0x6, 0x2, 0x4, 0x9, 0x15, 0x4, 0x4, 0x1, 0x6, 0x2, 0x5c, 0x70, 0x9, 0x1, 0xc, 0x74, 0x5, 0x2, 0x7, 0x2, 0x4, 0x2, 0x5, 0x19, 0x1, 0x71, 0x4, 0x8, 0x6, 0x2, 0x2, 0x2, 0x11, 0x11, 0x2, 0x6, 0x5, 0xa, 0x2, 0x1, 0x2, 0x4, 0xf, 0x3b, 0x2, 0x5, 0x5, 0x4, 0x5, 0x4, 0xf, 0xd, 0x2, 0x2, 0x2, 0x7, 0x3f, 0xc, 0x9, 0x3a, 0xa, 0x15, 0x14, 0x4, 0x4, 0x1, 0xa, 0x9, 0x8, 0x1, 0x7, 0x5b, 0x9, 0x13, 0x1c, 0x18, 0x5, 0x5, 0x6, 0x18, 0x4, 0x8, 0x14, 0x3a, 0x13, 0x1, 0x43, 0x4, 0x3, 0x17, 0x1, 0x16, 0x15, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x8a, 0x1, 0x4, 0x1, 0x1, 0x8, 0x1, 0x1, 0x1, 0x1, 0x9, 0x6, 0x6, 0x1, 0x13, 0xa, 0x10, 0x5, 0x3, 0x6, 0x6, 0x3, 0x3, 0x4, 0xf, 0x13, 0xb, 0x3, 0x1, 0x1, 0x3, 0x3, 0x3, 0x14, 0x13, 0x6, 0x15, 0xa, 0x1, 0x5, 0x4, 0x1, 0x2, 0x5, 0x2, 0xd, 0x9, 0xf, 0x5d, 0x9, 0x47, 0xd, 0x6, 0x5, 0x5d, 0xa, 0x47, 0x15, 0x42, 0x9, 0x6, 0x3, 0x5, 0x2, 0xe, 0xd, 0x11, 0x4, 0x5, 0x2, 0x1, 0x15, 0x1, 0x1, 0x4, 0x2, 0x13, 0xf, 0x11, 0x11, 0x2, 0xa, 0x9, 0x5, 0x5, 0x7, 0x5, 0x4, 0x3, 0x4, 0x13, 0x5, 0xb, 0x1, 0x12, 0x12, 0x4, 0x13, 0x1, 0x1, 0x1, 0x1, 0xc, 0x11, 0x9, 0x5b, 0xa, 0x13, 0xd, 0xa, 0x8, 0x1, 0x1, 0x2, 0x9, 0x6, 0x1, 0x1, 0x1, 0x2, 0x1, 0x1, 0xa, 0x9, 0x2, 0xf, 0x1, 0x8, 0x3, 0x9, 0x3, 0x1, 0x9, 0x6, 0x6, 0x5, 0x2, 0x5, 0x2, 0x5, 0x3, 0x1, 0x57, 0x3, 0x1, 0x1, 0x7, 0x3, 0x1, 0x9, 0x7, 0x3, 0x3, 0x3, 0xb1, 0x2, 0x1, 0x12, 0x2b, 0x3, 0x1, 0x3, 0x2, 0x4, 0x1, 0x2, 0x5, 0x6, 0xd, 0x1, 0x1, 0x1, 0x2, 0x2, 0x6, 0x5, 0x2, 0x2, 0x2, 0x10, 0x1, 0x1, 0x24, 0x1, 0x1, 0x1, 0x1, 0x6, 0x4, 0x7, 0x21, 0x2, 0x9, 0xa, 0xa, 0x16, 0xb, 0x34, 0x5, 0x3, 0x10, 0x1, 0x1, 0x2e, 0x13, 0x2, 0x13, 0x1, 0x1, 0x1, 0x25, 0x13, 0x4, 0x47, 0x8, 0x7, 0x4, 0x35, 0x1, 0xb, 0x19, 0x2, 0x2, 0x8, 0x8, 0x7, 0x10, 0xd, 0x6, 0x6, 0xa, 0x3, 0x6a, 0x13, 0x18, 0x12, 0x3, 0x57, 0x1d, 0x1, 0xb, 0x5, 0x4, 0x7, 0x1, 0x1, 0x2, 0x2, 0x2, 0x7, 0x15, 0x2f, 0x1, 0x2, 0xb, 0x4, 0x4, 0x3, 0x5, 0xb, 0xa, 0x9, 0x1, 0x4, 0x5, 0x3, 0x3, 0x3, 0xb, 0x1b, 0x32, 0x9, 0x4, 0x4, 0x1, 0x1, 0x15, 0x1d, 0x13, 0x12, 0x6, 0xe, 0x4, 0x2, 0x7, 0x2, 0xc, 0x6, 0x2, 0x5, 0x3, 0x3, 0x9, 0x7, 0xe, 0x9, 0x2, 0x1, 0x3, 0x5, 0x3, 0x3, 0x4, 0x4, 0x3, 0x6, 0x5, 0x5, 0x19, 0x6, 0x3, 0x1, 0x11, 0x12, 0x84, 0x1c, 0x19, 0xa3, 0x2e, 0xe, 0x13, 0x47, 0x1, 0x1, 0xc, 0x2, 0x1, 0x5, 0x4, 0x5, 0x4, 0x8, 0x7, 0x7, 0x5, 0x5, 0x3, 0xa, 0x5, 0x3, 0x5, 0x4, 0x1, 0x6, 0x4, 0x4, 0x1, 0xe, 0x7, 0x2, 0x15, 0x2, 0x2, 0x14, 0x1, 0xc, 0xa, 0x5d, 0x4, 0x3, 0x2, 0xa, 0x5d, 0x19, 0x1, 0x2, 0x1, 0x1, 0xa, 0x14, 0x1, 0x12, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x17, 0x1, 0x1, 0x13, 0x2, 0x2, 0x1, 0x3, 0x1a, 0x5, 0x15, 0x1, 0x5, 0x1, 0x1a, 0x2, 0x1, 0xc, 0x6, 0x1, 0x1, 0x1, 0x1, 0x7, 0x7, 0x7, 0xc, 0xd, 0xd, 0x10, 0x1b, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x5, 0x2, 0x4d, 0x2b, 0x8, 0x1, 0x2, 0x1, 0x1, 0x1, 0x1, 0x1, 0x9, 0xe, 0xb, 0xa, 0x1, 0xb, 0x1, 0xb, 0xa, 0x1, 0x2, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x9, 0x1, 0x1, 0x15, 0x11, 0x1, 0x8, 0x1, 0x5, 0x1, 0x1, 0x5, 0x4, 0x4, 0x5, 0xb, 0x6, 0x7, 0x2, 0x1, 0x1, 0x2, 0x1, 0x19, 0x19, 0x2, 0x2, 0x2, 0x6, 0x8, 0x3, 0x3, 0x4, 0x8, 0x8, 0x3, 0x1, 0x1a, 0xe, 0x3, 0x1, 0xf, 0x1, 0x9, 0x4, 0xc, 0x5, 0x5, 0x6, 0x1, 0x3b, 0x16, 0x8, 0x7, 0x2, 0x5, 0x32, 0xd, 0x2, 0x55, 0xe, 0x3, 0x14, 0x3, 0x9, 0x9, 0x3, 0x2, 0x12, 0x12, 0x8, 0x14, 0x13, 0x12, 0x12, 0x9, 0xa, 0x39, 0xf, 0x7, 0x6, 0x2, 0x1, 0x5, 0x9, 0x9, 0x9, 0x1, 0x9, 0xe, 0x18, 0x1, 0x3, 0x9, 0x3, 0x9, 0x1, 0x4, 0x2, 0x4, 0x4, 0x2, 0x9, 0x9, 0x9, 0x3, 0x1, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x3, 0x16, 0x5, 0x2, 0x2, 0x3, 0x1, 0x9, 0x3, 0x3f, 0x28, 0x9, 0x26, 0x9, 0xa, 0x65, 0x39, 0xc, 0x15, 0x9, 0x1, 0x2, 0x7, 0xb, 0xc, 0xb, 0xb, 0x2e, 0x4, 0x1e, 0x15, 0x1, 0x2, 0x1, 0x1, 0x2, 0x3, 0x2, 0x2, 0xb, 0x9, 0x1, 0x4, 0x4, 0x65, 0x16, 0x8f, 0x1, 0x10, 0xf, 0xf, 0x7, 0x9, 0x41, 0x9, 0xb, 0xb, 0xe, 0x12, 0x20, 0x2, 0x2, 0x2, 0x2, 0x2, 0x9, 0x15, 0x2, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0xa, 0xd, 0xd, 0x9, 0x1, 0x1, 0xd, 0x68, 0x17, 0x94, 0x1, 0xf, 0x1, 0x1, 0x1, 0xd, 0x79, 0x17, 0x94, 0xd, 0xf, 0x10, 0x16, 0xf, 0x13, 0xd, 0xc, 0x10, 0xb, 0x8, 0x4, 0x2, 0x2, 0x1, 0xb, 0x4, 0x9, 0x61, 0x1, 0x2, 0x7, 0xb, 0xb, 0xf, 0xa, 0x1d, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x2, 0x10, 0x4, 0x5, 0x1, 0x9, 0x9, 0x1, 0x9, 0x3, 0x3f, 0x13, 0x9, 0x41, 0xa, 0x20, 0x9, 0x3f, 0xc, 0x3a, 0x9, 0xa, 0x63, 0x39, 0x1, 0xb, 0xb, 0x1, 0xa, 0x6, 0x1, 0x4, 0x4, 0x4, 0x18, 0xa, 0x39, 0x10, 0x19, 0x7, 0x8, 0x9, 0x53, 0x6, 0x2b, 0x1, 0x2, 0x1, 0x2, 0x5, 0x3, 0x1, 0x1, 0x2, 0xd, 0x9, 0x2, 0x1, 0x17, 0x3, 0x1, 0xc, 0xf, 0x10, 0x16, 0x1, 0xd, 0x9, 0x4, 0x7, 0xd, 0xb, 0xd, 0xc, 0xc, 0x1a, 0x2, 0xc, 0x15, 0x2, 0x2, 0xd, 0x1, 0x1, 0xa, 0x8, 0x8, 0xa, 0xa, 0xa, 0x8, 0x7, 0xd, 0x9, 0x2, 0x3, 0xf, 0xb, 0xf, 0xf, 0x1, 0xd, 0xa, 0x14, 0x11, 0x16, 0x12, 0x1, 0x7, 0x1, 0x2, 0x2, 0x1, 0x9, 0x9, 0x2, 0x2, 0x3, 0x9, 0x61, 0x5, 0xb1, 0x12, 0x2a, 0x4a, 0x6, 0x2, 0x6, 0x13, 0x13, 0x1, 0x2f, 0xb, 0x12, 0x9, 0x3e, 0x4, 0x28, 0x2, 0x1, 0x4, 0x5, 0x3, 0x3, 0x4, 0x1, 0xf, 0x19, 0x10, 0x1, 0x1, 0x1, 0x1, 0x1, 0x9, 0x17, 0x27, 0x3, 0x9, 0x7, 0x3, 0x27, 0x2, 0x1, 0x5, 0x6, 0xe, 0x8, 0x8, 0x1, 0x8, 0x9, 0x3, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1, 0x1a, 0x1, 0x10, 0x3, 0x9, 0x1, 0x9, 0x9, 0x9, 0x9, 0x3, 0x3, 0x3, 0x19, 0x9, 0x3a, 0x3, 0x1, 0x5, 0x11, 0xa, 0xa, 0x1, 0x11, 0x1, 0x1, 0x1, 0x4, 0x4, 0x4, 0x6, 0x9, 0x9, 0x2, 0x3, 0xa, 0xf, 0x8, 0x6, 0x7, 0xb, 0x9, 0xa, 0x5, 0xa, 0x5, 0x9, 0x6, 0x9, 0x4, 0x1, 0x3, 0x3, 0x4, 0x4, 0x3, 0x3, 0xa, 0x11, 0x9, 0xe, 0x11, 0xe, 0x8, 0x7, 0x8, 0x7, 0x8, 0x4, 0x5, 0x6, 0x5, 0xa, 0x5, 0xe, 0xd, 0x5, 0xe, 0xd, 0x5, 0x5, 0x5, 0x6, 0x5, 0x6, 0xf, 0x8, 0x8, 0x7, 0x6, 0x8, 0x3, 0x1, 0x5, 0x1, 0x1, 0x4, 0x4, 0x1, 0x1, 0x9, 0x2, 0xd, 0x7, 0xc, 0xc, 0xa, 0x6, 0x4, 0x1, 0x1, 0x3, 0x2, 0x9, 0x4, 0x2, 0x2, 0x4, 0x4, 0x1, 0x4, 0x2, 0x21, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x2, 0x3, // Pc port texture page: EXTRA_PC_PORT_TEXTURE_COUNT}; } const std::vector<u32> get_jak1_tpage_dir() { return tpage_dir; }
87.901961
100
0.593241
Hat-Kid
b787c07c5eb0a779989ae7c92a2f257eb336b46e
1,574
cc
C++
TopQuarkAnalysis/TopJetCombination/src/TtSemiSimpleBestJetComb.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
TopQuarkAnalysis/TopJetCombination/src/TtSemiSimpleBestJetComb.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
TopQuarkAnalysis/TopJetCombination/src/TtSemiSimpleBestJetComb.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
// // #include "TopQuarkAnalysis/TopJetCombination/interface/TtSemiSimpleBestJetComb.h" TtSemiSimpleBestJetComb::TtSemiSimpleBestJetComb() {} TtSemiSimpleBestJetComb::~TtSemiSimpleBestJetComb() {} int TtSemiSimpleBestJetComb::operator()(std::vector<TtSemiEvtSolution>& sols) { // search the highest probChi^2 value in the among the different jet combination solutions double maxProbChi2 = 0; for (unsigned int s = 0; s < sols.size(); s++) maxProbChi2 = std::max(maxProbChi2, sols[s].getProbChi2()); //search indices of original solutions with highest probChi2 value std::vector<unsigned int> indices; indices.clear(); for (unsigned int s = 0; s < sols.size(); s++) { if (fabs(sols[s].getProbChi2() - maxProbChi2) < 0.0001) indices.push_back(s); } int bestSol = -999; if (maxProbChi2 > 0.) { if (indices.size() == 1) bestSol = indices[0]; if (indices.size() == 2) { //typically only light jets constraints applied, so still b-jet ambiguity to resolve // -> look at DPhi(Whadr,bhadr) and choose smallest value double DPhi_Wb0 = fabs(sols[indices[0]].getFitHadW().phi() - sols[indices[0]].getFitHadb().phi()); double DPhi_Wb1 = fabs(sols[indices[1]].getFitHadW().phi() - sols[indices[1]].getFitHadb().phi()); if (DPhi_Wb0 > 3.1415) DPhi_Wb0 = 2. * 3.1415 - DPhi_Wb0; if (DPhi_Wb1 > 3.1415) DPhi_Wb1 = 2. * 3.1415 - DPhi_Wb1; if (DPhi_Wb0 < DPhi_Wb1) { bestSol = indices[0]; } else { bestSol = indices[1]; } } } return bestSol; }
34.217391
104
0.649936
ckamtsikis
b7919637242c503f2e2d26342b5b56d84824bc24
14,642
cpp
C++
depricated/acyclic_graph_nodes.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
13
2019-03-14T09:54:02.000Z
2021-09-26T14:01:30.000Z
depricated/acyclic_graph_nodes.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
35
2019-08-29T19:12:05.000Z
2021-07-15T22:17:53.000Z
depricated/acyclic_graph_nodes.cpp
imikejackson/bingocpp
6ba00a490c8cb46edebfd78f56b1604a76d668e9
[ "Apache-2.0" ]
9
2018-10-18T02:43:03.000Z
2021-09-02T22:08:39.000Z
/*! * \file acyclic_graph_nodes.cc * * \author Ethan Adams * \date 2/6/2018 * * This file contains the functions associated with each class * implementation of Operation. */ #include "BingoCpp/acyclic_graph_nodes.h" namespace agraphnodes{ namespace { void x_load_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = x.col(stack(result_location, 1)); } void x_load_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { } void c_load_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { if (stack(result_location, 1) != -1) { buffer[result_location] = Eigen::ArrayXXd::Constant(x.rows(), 1, constants[stack(result_location, 1)]); } else { buffer[result_location] = Eigen::ArrayXXd::Zero(x.rows(), 1); } } void c_load_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { } void addition_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)] + buffer[stack(result_location, 2)]; } void addition_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency]; } } void subtraction_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)] - buffer[stack(result_location, 2)]; } void subtraction_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] -= reverse_buffer[dependency]; } } void multiplication_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)] * buffer[stack(result_location, 2)]; } void multiplication_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[stack(dependency, 2)]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[stack(dependency, 1)]; } } void division_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)] / buffer[stack(result_location, 2)]; } void division_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency] / forward_buffer[stack(dependency, 2)]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] += reverse_buffer[dependency] * (-forward_buffer[dependency] / forward_buffer[stack(dependency, 2)]); } } void sin_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)].sin(); } void sin_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[stack(dependency, 1)].cos(); } void cos_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)].cos(); } void cos_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] -= reverse_buffer[dependency] * forward_buffer[stack(dependency, 1)].sin(); } void exp_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)].exp(); } void exp_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[dependency]; } void log_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = (buffer[stack(result_location, 1)].abs()).log(); } void log_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += reverse_buffer[dependency] / forward_buffer[stack(dependency, 1)]; } void power_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = (buffer[stack(result_location, 1)].abs()).pow( buffer[stack(result_location, 2)]); } void power_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { if (stack(dependency, 1) == command_index) { reverse_buffer[command_index] += forward_buffer[dependency] * reverse_buffer[dependency] * forward_buffer[stack(dependency, 2)] / forward_buffer[stack(dependency, 1)]; } if (stack(dependency, 2) == command_index) { reverse_buffer[command_index] += forward_buffer[dependency] * reverse_buffer[dependency] * (forward_buffer[stack(dependency, 1)].abs()).log(); } } void absolute_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = buffer[stack(result_location, 1)].abs(); } void absolute_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += reverse_buffer[dependency] * forward_buffer[stack(dependency, 1)].sign(); } void sqrt_evaluate(const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { buffer[result_location] = (buffer[stack(result_location, 1)].abs()).sqrt(); } void sqrt_deriv_evaluate(const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { reverse_buffer[command_index] += 0.5 * reverse_buffer[dependency] / forward_buffer[dependency] * forward_buffer[stack(dependency, 1)].sign(); } } //namespace const std::vector<forward_operator_function> forward_eval_map { x_load_evaluate, c_load_evaluate, addition_evaluate, subtraction_evaluate, multiplication_evaluate, division_evaluate, sin_evaluate, cos_evaluate, exp_evaluate, log_evaluate, power_evaluate, absolute_evaluate, sqrt_evaluate }; const std::vector<derivative_operator_function> derivative_eval_map { x_load_deriv_evaluate, c_load_deriv_evaluate, addition_deriv_evaluate, subtraction_deriv_evaluate, multiplication_deriv_evaluate, division_deriv_evaluate, sin_deriv_evaluate, cos_deriv_evaluate, exp_deriv_evaluate, log_deriv_evaluate, power_deriv_evaluate, absolute_deriv_evaluate, sqrt_deriv_evaluate }; void forward_eval_function(int node, const Eigen::ArrayX3i &stack, const Eigen::ArrayXXd &x, const Eigen::VectorXd &constants, std::vector<Eigen::ArrayXXd> &buffer, std::size_t result_location) { forward_eval_map.at(node)(stack, x, constants, buffer, result_location); } void derivative_eval_function(int node, const Eigen::ArrayX3i &stack, const int command_index, const std::vector<Eigen::ArrayXXd> &forward_buffer, std::vector<Eigen::ArrayXXd> &reverse_buffer, int dependency) { derivative_eval_map.at(node)(stack, command_index, forward_buffer, reverse_buffer, dependency); } }
46.044025
99
0.523562
imikejackson
b7962ad897f8c79a4958223474666710ab234556
3,059
cpp
C++
GP/FrmProj.cpp
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
4
2020-06-22T16:59:51.000Z
2020-06-28T19:35:23.000Z
GP/FrmProj.cpp
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
59
2020-09-12T23:54:16.000Z
2022-03-24T18:51:43.000Z
GP/FrmProj.cpp
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
4
2020-06-22T13:37:40.000Z
2021-01-29T12:42:54.000Z
// FrmProg.cpp // // Copyright (c) 1994-2020 By Dale L. Larson, All Rights Reserved. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #include "stdafx.h" #include "Gp.h" #include "GamDoc.h" #include "FrmProj.h" #include "VwPrjgsn.h" #include "VwPrjgam.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CProjFrame IMPLEMENT_DYNCREATE(CProjFrame, CMDIChildWndEx) CProjFrame::CProjFrame() { } CProjFrame::~CProjFrame() { } BEGIN_MESSAGE_MAP(CProjFrame, CMDIChildWndEx) //{{AFX_MSG_MAP(CProjFrame) ON_WM_SYSCOMMAND() //}}AFX_MSG_MAP ON_WM_CLOSE() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CProjFrame message handlers BOOL CProjFrame::PreCreateWindow(CREATESTRUCT& cs) { if (!CMDIChildWndEx::PreCreateWindow(cs)) return FALSE; cs.style |= WS_CLIPCHILDREN; cs.style &= ~(DWORD)FWS_ADDTOTITLE; return TRUE; } void CProjFrame::OnUpdateFrameTitle(BOOL bAddToTitle) { CGamDoc* pDoc = (CGamDoc*)GetActiveDocument(); CString str = pDoc->GetTitle(); str += " - "; CString strType; if (pDoc->IsScenario()) strType.LoadString(IDS_PROJTYPE_SCENARIO); else strType.LoadString(IDS_PROJTYPE_GAME); str += strType; SetWindowText(str); } void CProjFrame::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == SC_CLOSE) { CView *pView = GetActiveView(); if (pView) { if (pView->IsKindOf(RUNTIME_CLASS(CGsnProjView)) || pView->IsKindOf(RUNTIME_CLASS(CGamProjView))) { ((CGamDoc*)GetActiveDocument())->OnFileClose(); return; } } } CMDIChildWndEx::OnSysCommand(nID, lParam); } void CProjFrame::OnClose() { // Close the document when the main document window is closed. ((CGamDoc*)GetActiveDocument())->OnFileClose(); }
28.324074
77
0.652501
wsu-cb
b7979d4151b9fc7fe8cc8bc8d2db246cdb4860fc
2,018
hh
C++
include/Apertures/StandardAperturePolygon.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
6
2016-09-28T18:26:42.000Z
2021-04-10T13:19:05.000Z
include/Apertures/StandardAperturePolygon.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
1
2021-02-09T00:24:04.000Z
2021-02-27T22:08:05.000Z
include/Apertures/StandardAperturePolygon.hh
aaronbamberger/gerber_rs274x_parser
d2bbd6c66d322ab47715771642255f8302521300
[ "BSD-2-Clause" ]
5
2017-09-14T09:48:17.000Z
2021-07-19T07:58:34.000Z
/* * Copyright 2021 Aaron Bamberger * Licensed under BSD 2-clause license * See LICENSE file at root of source tree, * or https://opensource.org/licenses/BSD-2-Clause */ #ifndef _STANDARD_APERTURE_POLYGON_H #define _STANDARD_APERTURE_POLYGON_H #include "Apertures/StandardAperture.hh" #include "GlobalDefs.hh" #include "SemanticIssueList.hh" #include "location.hh" #include <iostream> #include <memory> class StandardAperturePolygon : public StandardAperture { public: StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle, double hole_diameter); StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle); StandardAperturePolygon(double diameter, double num_vertices); StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle, double hole_diameter, yy::location diameter_location, yy::location num_vertices_location, yy::location rotation_angle_location, yy::location hole_diameter_location, yy::location location); StandardAperturePolygon(double diameter, double num_vertices, double rotation_angle, yy::location diameter_location, yy::location num_vertices_location, yy::location rotation_angle_location, yy::location location); StandardAperturePolygon(double diameter, double num_vertices, yy::location diameter_location, yy::location num_vertices_location, yy::location location); virtual ~StandardAperturePolygon(); private: Gerber::SemanticValidity do_check_semantic_validity(SemanticIssueList& issue_list); std::ostream& do_print(std::ostream& os) const; std::shared_ptr<StandardAperture> do_clone(); double m_diameter; double m_num_vertices; double m_rotation_angle; double m_hole_diameter; bool m_has_rotation; bool m_has_hole; yy::location m_diameter_location; yy::location m_num_vertices_location; yy::location m_rotation_angle_location; yy::location m_hole_diameter_location; yy::location m_location; }; #endif // _STANDARD_APERTURE_POLYGON_H
38.075472
113
0.806739
aaronbamberger
b79d98c9ccf6ae2243b193a04a675881028db9e4
12,562
cpp
C++
core/RTAudio.cpp
amilo/soundcoreA
30b14ce3d34f74c2385126fc244a0c252c3aa4c4
[ "MIT" ]
null
null
null
core/RTAudio.cpp
amilo/soundcoreA
30b14ce3d34f74c2385126fc244a0c252c3aa4c4
[ "MIT" ]
null
null
null
core/RTAudio.cpp
amilo/soundcoreA
30b14ce3d34f74c2385126fc244a0c252c3aa4c4
[ "MIT" ]
null
null
null
/* * RTAudio.cpp * * Central control code for hard real-time audio on BeagleBone Black * using PRU and Xenomai Linux extensions. This code began as part * of the Hackable Instruments project (EPSRC) at Queen Mary University * of London, 2013-14. * * (c) 2014 Victor Zappi and Andrew McPherson * Queen Mary University of London */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <math.h> #include <iostream> #include <assert.h> #include <vector> // Xenomai-specific includes #include <sys/mman.h> #include <native/task.h> #include <native/timer.h> #include <rtdk.h> #include "../include/RTAudio.h" #include "../include/PRU.h" #include "../include/I2c_Codec.h" #include "../include/render.h" #include "../include/GPIOcontrol.h" using namespace std; // Data structure to keep track of auxiliary tasks we // can schedule typedef struct { RT_TASK task; void (*function)(void); char *name; int priority; } InternalAuxiliaryTask; const char gRTAudioThreadName[] = "beaglert-audio"; // Real-time tasks and objects RT_TASK gRTAudioThread; PRU *gPRU = 0; I2c_Codec *gAudioCodec = 0; vector<InternalAuxiliaryTask*> gAuxTasks; // Flag which tells the audio task to stop bool gShouldStop = false; // general settings int gRTAudioVerbose = 0; // Verbosity level for debugging int gAmplifierMutePin = -1; int gAmplifierShouldBeginMuted = 0; // Number of audio and matrix channels, globally accessible // At least gNumMatrixChannels needs to be global to be used // by the analogRead() and analogWrite() macros without creating // extra confusion in their use cases by passing this argument int gNumAudioChannels = 0; int gNumMatrixChannels = 0; // initAudio() prepares the infrastructure for running PRU-based real-time // audio, but does not actually start the calculations. // periodSize indicates the number of _sensor_ frames per period: the audio period size // is twice this value. In total, the audio latency in frames will be 4*periodSize, // plus any latency inherent in the ADCs and DACs themselves. // useMatrix indicates whether to enable the ADC and DAC or just use the audio codec. // numMatrixChannels indicates how many ADC and DAC channels to use. // userData is an opaque pointer which will be passed through to the initialise_render() // function for application-specific use // // Returns 0 on success. int BeagleRT_initAudio(RTAudioSettings *settings, void *userData) { rt_print_auto_init(1); setVerboseLevel(settings->verbose); if(gRTAudioVerbose == 1) rt_printf("Running with Xenomai\n"); if(gRTAudioVerbose) { cout << "Starting with period size " << settings->periodSize << "; "; if(settings->useMatrix) cout << "matrix enabled\n"; else cout << "matrix disabled\n"; cout << "DAC level " << settings->dacLevel << "dB; ADC level " << settings->adcLevel; cout << "dB; headphone level " << settings->headphoneLevel << "dB\n"; if(settings->beginMuted) cout << "Beginning with speaker muted\n"; } // Prepare GPIO pins for amplifier mute and status LED if(settings->ampMutePin >= 0) { gAmplifierMutePin = settings->ampMutePin; gAmplifierShouldBeginMuted = settings->beginMuted; if(gpio_export(settings->ampMutePin)) { if(gRTAudioVerbose) cout << "Warning: couldn't export amplifier mute pin\n"; } if(gpio_set_dir(settings->ampMutePin, OUTPUT_PIN)) { if(gRTAudioVerbose) cout << "Couldn't set direction on amplifier mute pin\n"; return -1; } if(gpio_set_value(settings->ampMutePin, LOW)) { if(gRTAudioVerbose) cout << "Couldn't set value on amplifier mute pin\n"; return -1; } } // Limit the matrix channels to sane values if(settings->numMatrixChannels >= 8) settings->numMatrixChannels = 8; else if(settings->numMatrixChannels >= 4) settings->numMatrixChannels = 4; else settings->numMatrixChannels = 2; // Sanity check the combination of channels and period size if(settings->numMatrixChannels <= 4 && settings->periodSize < 2) { cout << "Error: " << settings->numMatrixChannels << " channels and period size of " << settings->periodSize << " not supported.\n"; return 1; } if(settings->numMatrixChannels <= 2 && settings->periodSize < 4) { cout << "Error: " << settings->numMatrixChannels << " channels and period size of " << settings->periodSize << " not supported.\n"; return 1; } // Use PRU for audio gPRU = new PRU(); gAudioCodec = new I2c_Codec(); if(gPRU->prepareGPIO(settings->useMatrix, 1, 1)) { cout << "Error: unable to prepare GPIO for PRU audio\n"; return 1; } if(gPRU->initialise(0, settings->periodSize, settings->numMatrixChannels, true)) { cout << "Error: unable to initialise PRU\n"; return 1; } if(gAudioCodec->initI2C_RW(2, settings->codecI2CAddress, -1)) { cout << "Unable to open codec I2C\n"; return 1; } if(gAudioCodec->initCodec()) { cout << "Error: unable to initialise audio codec\n"; return 1; } // Set default volume levels BeagleRT_setDACLevel(settings->dacLevel); BeagleRT_setADCLevel(settings->adcLevel); BeagleRT_setHeadphoneLevel(settings->headphoneLevel); // Initialise the rendering environment: pass the number of audio and matrix // channels, the period size for matrix and audio, and the sample rates int audioPeriodSize = settings->periodSize * 2; float audioSampleRate = 44100.0; float matrixSampleRate = 22050.0; if(settings->useMatrix) { audioPeriodSize = settings->periodSize * settings->numMatrixChannels / 4; matrixSampleRate = audioSampleRate * 4.0 / (float)settings->numMatrixChannels; } gNumAudioChannels = 2; gNumMatrixChannels = settings->useMatrix ? settings->numMatrixChannels : 0; if(!initialise_render(gNumMatrixChannels, gNumAudioChannels, settings->useMatrix ? settings->periodSize : 0, /* matrix period size */ audioPeriodSize, matrixSampleRate, audioSampleRate, userData)) { cout << "Couldn't initialise audio rendering\n"; return 1; } return 0; } // audioLoop() is the main function which starts the PRU audio code // and then transfers control to the PRU object. The PRU object in // turn will call the audio render() callback function every time // there is new data to process. void audioLoop(void *) { if(gRTAudioVerbose==1) rt_printf("_________________Audio Thread!\n"); // PRU audio assert(gAudioCodec != 0 && gPRU != 0); if(gAudioCodec->startAudio(0)) { rt_printf("Error: unable to start I2C audio codec\n"); gShouldStop = 1; } else { if(gPRU->start()) { rt_printf("Error: unable to start PRU\n"); gShouldStop = 1; } else { // All systems go. Run the loop; it will end when gShouldStop is set to 1 if(!gAmplifierShouldBeginMuted) { // First unmute the amplifier if(BeagleRT_muteSpeakers(0)) { if(gRTAudioVerbose) rt_printf("Warning: couldn't set value (high) on amplifier mute pin\n"); } } gPRU->loop(); // Now clean up // gPRU->waitForFinish(); gPRU->disable(); gAudioCodec->stopAudio(); gPRU->cleanupGPIO(); } } if(gRTAudioVerbose == 1) rt_printf("audio thread ended\n"); } // Create a calculation loop which can run independently of the audio, at a different // (equal or lower) priority. Audio priority is 99; priority should be generally be less than this. // Returns an (opaque) pointer to the created task on success; 0 on failure AuxiliaryTask createAuxiliaryTaskLoop(void (*functionToCall)(void), int priority, const char *name) { InternalAuxiliaryTask *newTask = (InternalAuxiliaryTask*)malloc(sizeof(InternalAuxiliaryTask)); // Attempt to create the task if(rt_task_create(&(newTask->task), name, 0, priority, T_JOINABLE | T_FPU)) { cout << "Error: unable to create auxiliary task " << name << endl; free(newTask); return 0; } // Populate the rest of the data structure and store it in the vector newTask->function = functionToCall; newTask->name = strdup(name); newTask->priority = priority; gAuxTasks.push_back(newTask); return (AuxiliaryTask)newTask; } // Schedule a previously created auxiliary task. It will run when the priority rules next // allow it to be scheduled. void scheduleAuxiliaryTask(AuxiliaryTask task) { InternalAuxiliaryTask *taskToSchedule = (InternalAuxiliaryTask *)task; rt_task_resume(&taskToSchedule->task); } // Calculation loop that can be used for other tasks running at a lower // priority than the audio thread. Simple wrapper for Xenomai calls. // Treat the argument as containing the task structure void auxiliaryTaskLoop(void *taskStruct) { // Get function to call from the argument void (*auxiliary_function)(void) = ((InternalAuxiliaryTask *)taskStruct)->function; const char *name = ((InternalAuxiliaryTask *)taskStruct)->name; // Wait for a notification rt_task_suspend(NULL); while(!gShouldStop) { // Then run the calculations auxiliary_function(); // Wait for a notification rt_task_suspend(NULL); } if(gRTAudioVerbose == 1) rt_printf("auxiliary task %s ended\n", name); } // startAudio() should be called only after initAudio() successfully completes. // It launches the real-time Xenomai task which runs the audio loop. Returns 0 // on success. int BeagleRT_startAudio() { // Create audio thread with the highest priority if(rt_task_create(&gRTAudioThread, gRTAudioThreadName, 0, 99, T_JOINABLE | T_FPU)) { cout << "Error: unable to create Xenomai audio thread" << endl; return -1; } // Start all RT threads if(rt_task_start(&gRTAudioThread, &audioLoop, 0)) { cout << "Error: unable to start Xenomai audio thread" << endl; return -1; } // The user may have created other tasks. Start those also. vector<InternalAuxiliaryTask*>::iterator it; for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) { InternalAuxiliaryTask *taskStruct = *it; if(rt_task_start(&(taskStruct->task), &auxiliaryTaskLoop, taskStruct)) { cerr << "Error: unable to start Xenomai task " << taskStruct->name << endl; return -1; } } return 0; } // Stop the PRU-based audio from running and wait // for the tasks to complete before returning. void BeagleRT_stopAudio() { // Tell audio thread to stop (if this hasn't been done already) gShouldStop = true; if(gRTAudioVerbose) cout << "Stopping audio...\n"; // Now wait for threads to respond and actually stop... rt_task_join(&gRTAudioThread); // Stop all the auxiliary threads too vector<InternalAuxiliaryTask*>::iterator it; for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) { InternalAuxiliaryTask *taskStruct = *it; // Wake up each thread and join it rt_task_resume(&(taskStruct->task)); rt_task_join(&(taskStruct->task)); } } // Free any resources associated with PRU real-time audio void BeagleRT_cleanupAudio() { cleanup_render(); // Clean up the auxiliary tasks vector<InternalAuxiliaryTask*>::iterator it; for(it = gAuxTasks.begin(); it != gAuxTasks.end(); it++) { InternalAuxiliaryTask *taskStruct = *it; // Free the name string and the struct itself free(taskStruct->name); free(taskStruct); } gAuxTasks.clear(); if(gPRU != 0) delete gPRU; if(gAudioCodec != 0) delete gAudioCodec; if(gAmplifierMutePin >= 0) gpio_unexport(gAmplifierMutePin); gAmplifierMutePin = -1; } // Set the level of the DAC; affects all outputs (headphone, line, speaker) // 0dB is the maximum, -63.5dB is the minimum; 0.5dB steps int BeagleRT_setDACLevel(float decibels) { if(gAudioCodec == 0) return -1; return gAudioCodec->setDACVolume((int)floorf(decibels * 2.0 + 0.5)); } // Set the level of the ADC // 0dB is the maximum, -12dB is the minimum; 1.5dB steps int BeagleRT_setADCLevel(float decibels) { if(gAudioCodec == 0) return -1; return gAudioCodec->setADCVolume((int)floorf(decibels * 2.0 + 0.5)); } // Set the level of the onboard headphone amplifier; affects headphone // output only (not line out or speaker) // 0dB is the maximum, -63.5dB is the minimum; 0.5dB steps int BeagleRT_setHeadphoneLevel(float decibels) { if(gAudioCodec == 0) return -1; return gAudioCodec->setHPVolume((int)floorf(decibels * 2.0 + 0.5)); } // Mute or unmute the onboard speaker amplifiers // mute == 0 means unmute; otherwise mute // Returns 0 on success int BeagleRT_muteSpeakers(int mute) { int pinValue = mute ? LOW : HIGH; // Check that we have an enabled pin for controlling the mute if(gAmplifierMutePin < 0) return -1; return gpio_set_value(gAmplifierMutePin, pinValue); } // Set the verbosity level void setVerboseLevel(int level) { gRTAudioVerbose = level; }
29.419204
133
0.71581
amilo
b79dc57c8d87ed9ac355024072cc3b95897d7c8d
412
hpp
C++
src/graphics/index-buffer.hpp
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
44
2019-06-06T21:33:30.000Z
2022-03-26T06:18:23.000Z
src/graphics/index-buffer.hpp
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
1
2019-09-27T12:04:52.000Z
2019-09-29T13:30:42.000Z
src/graphics/index-buffer.hpp
guillaume-haerinck/imac-tower-defense
365a32642ea0d3ad8b2b7d63347d585c44d9f670
[ "MIT" ]
8
2019-07-26T16:44:26.000Z
2020-11-24T17:56:18.000Z
#pragma once class IndexBuffer { private: unsigned int m_rendererID; unsigned int m_count; public: IndexBuffer(); IndexBuffer(const unsigned int* data, unsigned int count); ~IndexBuffer(); void init(const unsigned int* data, unsigned int count); void bind() const; void unbind() const; inline unsigned int getCount() const { return m_count; } unsigned int getID() const { return m_rendererID; } };
20.6
59
0.735437
guillaume-haerinck
b7a22fa08bec171c2ca858844c1000ccdf52d83e
9,456
cpp
C++
Tools/DumpRenderTree/mg/LayoutTestControllerMg.cpp
VincentWei/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
6
2017-05-31T01:46:45.000Z
2018-06-12T10:53:30.000Z
Tools/Tools/DumpRenderTree/mg/LayoutTestControllerMg.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
null
null
null
Tools/Tools/DumpRenderTree/mg/LayoutTestControllerMg.cpp
FMSoftCN/mdolphin-core
48ffdcf587a48a7bb4345ae469a45c5b64ffad0e
[ "Apache-2.0" ]
2
2017-07-17T06:02:42.000Z
2018-09-19T10:08:38.000Z
#include "minigui.h" #include "config.h" #include "mdolphin.h" #include "LayoutTestController.h" #include "DumpRenderTree.h" #include "WorkQueue.h" #include "WorkQueueItem.h" #include <JavaScriptCore/JSRetainPtr.h> #include <JavaScriptCore/JSStringRef.h> #include <stdio.h> LayoutTestController::~LayoutTestController() { // FIXME: implement } void LayoutTestController::addDisallowedURL(JSStringRef url) { // FIXME: implement } void LayoutTestController::clearBackForwardList() { } JSStringRef LayoutTestController::copyDecodedHostName(JSStringRef name) { // FIXME: implement return 0; } JSStringRef LayoutTestController::copyEncodedHostName(JSStringRef name) { // FIXME: implement return 0; } void LayoutTestController::dispatchPendingLoadRequests() { // FIXME: Implement for testing fix for 6727495 } void LayoutTestController::display() { } void LayoutTestController::keepWebHistory() { // FIXME: implement } void LayoutTestController::notifyDone() { if (m_waitToDump && !topLoadingFrame && !WorkQueue::shared()->count()) { printf ("enter %s \n", __func__); dump(); } m_waitToDump = false; } JSStringRef LayoutTestController::pathToLocalResource(JSContextRef context, JSStringRef url) { // Function introduced in r28690. This may need special-casing on Windows. return JSStringRetain(url); // Do nothing on Unix. } void LayoutTestController::queueLoad(JSStringRef url, JSStringRef target) { // FIXME: We need to resolve relative URLs here WorkQueue::shared()->queue(new LoadItem(url, target)); } void LayoutTestController::setAcceptsEditing(bool acceptsEditing) { } void LayoutTestController::setAlwaysAcceptCookies(bool alwaysAcceptCookies) { // FIXME: Implement this (and restore the default value before running each test in DumpRenderTree.cpp). } void LayoutTestController::setCustomPolicyDelegate(bool, bool) { // FIXME: implement } void LayoutTestController::setMainFrameIsFirstResponder(bool flag) { // FIXME: implement } void LayoutTestController::setTabKeyCyclesThroughElements(bool cycles) { // FIXME: implement } void LayoutTestController::setUseDashboardCompatibilityMode(bool flag) { // FIXME: implement } void LayoutTestController::setUserStyleSheetEnabled(bool flag) { } void LayoutTestController::setUserStyleSheetLocation(JSStringRef path) { } void LayoutTestController::setWindowIsKey(bool windowIsKey) { // FIXME: implement } void LayoutTestController::setSmartInsertDeleteEnabled(bool flag) { // FIXME: implement } void LayoutTestController::setJavaScriptProfilingEnabled(bool flag) { } static BOOL waitUntilDoneWatchdogFired(HWND, int, DWORD) { gLayoutTestController->waitToDumpWatchdogTimerFired(); return TRUE; } void LayoutTestController::setWaitToDump(bool waitUntilDone) { static const int timeoutSeconds = 30; m_waitToDump = waitUntilDone; if (m_waitToDump) SetTimerEx(HWND_DESKTOP, waitToDumpWatchdog, timeoutSeconds * 1000, waitUntilDoneWatchdogFired); } int LayoutTestController::windowCount() { // FIXME: implement return 1; } void LayoutTestController::setPrivateBrowsingEnabled(bool privateBrowsingEnabled) { // FIXME: implement } void LayoutTestController::setJavaScriptCanAccessClipboard(bool enabled) { // FIXME: implement } void LayoutTestController::setXSSAuditorEnabled(bool enabled) { // FIXME: implement } void LayoutTestController::setFrameFlatteningEnabled(bool enabled) { // FIXME: implement } void LayoutTestController::setAllowUniversalAccessFromFileURLs(bool enabled) { // FIXME: implement } void LayoutTestController::setAllowFileAccessFromFileURLs(bool enabled) { // FIXME: implement } void LayoutTestController::setAuthorAndUserStylesEnabled(bool flag) { // FIXME: implement } void LayoutTestController::setPopupBlockingEnabled(bool popupBlockingEnabled) { // FIXME: implement } void LayoutTestController::setPluginsEnabled(bool flag) { // FIXME: Implement } bool LayoutTestController::elementDoesAutoCompleteForElementWithId(JSStringRef id) { // FIXME: implement return false; } void LayoutTestController::execCommand(JSStringRef name, JSStringRef value) { // FIXME: implement } void LayoutTestController::setPersistentUserStyleSheetLocation(JSStringRef jsURL) { // FIXME: implement } void LayoutTestController::clearPersistentUserStyleSheet() { // FIXME: implement } void LayoutTestController::clearAllDatabases() { // FIXME: implement } void LayoutTestController::setDatabaseQuota(unsigned long long quota) { // FIXME: implement } void LayoutTestController::setDomainRelaxationForbiddenForURLScheme(bool, JSStringRef) { // FIXME: implement } void LayoutTestController::setAppCacheMaximumSize(unsigned long long size) { // FIXME: implement } unsigned LayoutTestController::numberOfActiveAnimations() const { // FIXME: implement return 0; } unsigned LayoutTestController::workerThreadCount() const { // FIXME: implement return 0; } void LayoutTestController::setSelectTrailingWhitespaceEnabled(bool flag) { // FIXME: implement } bool LayoutTestController::pauseTransitionAtTimeOnElementWithId(JSStringRef propertyName, double time, JSStringRef elementId) { // FIXME: implement return false; } void LayoutTestController::setMockGeolocationPosition(double latitude, double longitude, double accuracy) { // FIXME: Implement for Geolocation layout tests. // See https://bugs.webkit.org/show_bug.cgi?id=28264. } void LayoutTestController::setMockGeolocationError(int code, JSStringRef message) { // FIXME: Implement for Geolocation layout tests. // See https://bugs.webkit.org/show_bug.cgi?id=28264. } void LayoutTestController::setIconDatabaseEnabled(bool iconDatabaseEnabled) { // FIXME: implement } bool LayoutTestController::pauseAnimationAtTimeOnElementWithId(JSStringRef animationName, double time, JSStringRef elementId) { // FIXME: implement return false; } bool LayoutTestController::sampleSVGAnimationForElementAtTime(JSStringRef animationId, double time, JSStringRef elementId) { // FIXME: implement return false; } void LayoutTestController::setCacheModel(int) { // FIXME: implement } bool LayoutTestController::isCommandEnabled(JSStringRef /*name*/) { // FIXME: implement return false; } size_t LayoutTestController::webHistoryItemCount() { // FIXME: implement return 0; } void LayoutTestController::waitForPolicyDelegate() { // FIXME: Implement this. #if 0 waitForPolicy = true; setWaitToDump(true); #endif } void LayoutTestController::overridePreference(JSStringRef /* key */, JSStringRef /* value */) { // FIXME: implement } void LayoutTestController::addUserScript(JSStringRef source, bool runAtStart) { printf("LayoutTestController::addUserScript not implemented.\n"); } void LayoutTestController::addUserStyleSheet(JSStringRef source) { printf("LayoutTestController::addUserStyleSheet not implemented.\n"); } void LayoutTestController::setDeveloperExtrasEnabled(bool enabled) { } void LayoutTestController::showWebInspector() { // FIXME: Implement this. } void LayoutTestController::closeWebInspector() { // FIXME: Implement this. } void LayoutTestController::evaluateInWebInspector(long callId, JSStringRef script) { // FIXME: Implement this. } void LayoutTestController::removeAllVisitedLinks() { // FIXME: Implement this. } void LayoutTestController::setTimelineProfilingEnabled(bool enabled) { } void LayoutTestController::evaluateScriptInIsolatedWorld(unsigned worldId, JSObjectRef globalObject, JSStringRef script) { } void LayoutTestController::disableImageLoading() { } void LayoutTestController::addOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains) { // FIXME: implement } void LayoutTestController::removeOriginAccessWhitelistEntry(JSStringRef sourceOrigin, JSStringRef destinationProtocol, JSStringRef destinationHost, bool allowDestinationSubdomains) { // FIXME: implement } void LayoutTestController::setScrollbarPolicy(JSStringRef orientation, JSStringRef policy) { // FIXME: implement } JSRetainPtr<JSStringRef> LayoutTestController::counterValueForElementById(JSStringRef id) { return 0; } int LayoutTestController::pageNumberForElementById(JSStringRef, float, float) { // FIXME: implement return -1; } int LayoutTestController::numberOfPages(float, float) { // FIXME: implement return -1; } void LayoutTestController::apiTestNewWindowDataLoadBaseURL(JSStringRef utf8Data, JSStringRef baseURL) { } void LayoutTestController::apiTestGoToCurrentBackForwardItem() { } void LayoutTestController::setSpatialNavigationEnabled(bool) { } void LayoutTestController::setWebViewEditable(bool) { } bool LayoutTestController::callShouldCloseOnWebView() { return false; } JSRetainPtr<JSStringRef> LayoutTestController::layerTreeAsText() const { return 0; } JSRetainPtr<JSStringRef> LayoutTestController::markerTextForListItem(JSContextRef context, JSValueRef nodeObject) const { return 0; } JSValueRef LayoutTestController::computedStyleIncludingVisitedInfo(JSContextRef, JSValueRef) { return 0; } void LayoutTestController::authenticateSession(JSStringRef, JSStringRef, JSStringRef) { }
21.393665
180
0.769353
VincentWei
b7a6d58765808f0bc9e9d6961d800f875ee4e177
740
cpp
C++
Difficulty 1/luhn_check_sum.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
Difficulty 1/luhn_check_sum.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
Difficulty 1/luhn_check_sum.cpp
BrynjarGeir/Kattis
a151972cbae3db04a8e6764d5fa468d0146c862b
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int tests; cin >> tests; for (int j = 0; j < tests; j++) { string number; int curr_number, ans = 0; cin >> number; int size = number.size(); bool second = false; for(int i = 1; i <= size; i++) { curr_number = stoi(number.substr(size-i, 1)); if (second) curr_number *= 2; if (curr_number > 9) { ans += curr_number % 10 + 1; } else { ans += curr_number; } second = !second; } if (ans % 10 == 0) { cout << "PASS " << endl; } else { cout << "FAIL " << endl; } } }
23.870968
57
0.412162
BrynjarGeir
b7a7a97dc4621a06fda2b867d490ded5d636c919
545
cpp
C++
examples/multithreading/bots/abstractbot.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
58
2015-08-09T14:56:35.000Z
2022-01-15T22:06:58.000Z
examples/multithreading/bots/abstractbot.cpp
mamontov-cpp/saddy-graphics-engine-2d
e25a6637fcc49cb26614bf03b70e5d03a3a436c7
[ "BSD-2-Clause" ]
245
2015-08-08T08:44:22.000Z
2022-01-04T09:18:08.000Z
examples/multithreading/bots/abstractbot.cpp
mamontov-cpp/saddy
f20a0030e18af9e0714fe56c19407fbeacc529a7
[ "BSD-2-Clause" ]
23
2015-12-06T03:57:49.000Z
2020-10-12T14:15:50.000Z
#include "abstractbot.h" bots::AbstractBot::AbstractBot() : m_strategy(nullptr) { } bots::AbstractBot::~AbstractBot() { if (m_strategy) { m_strategy->delRef(); } } void bots::AbstractBot::setStrategy(bots::shootingstrategies::ShootingStrategy* strategy) { if (m_strategy) { m_strategy->delRef(); } m_strategy = strategy; if (m_strategy) { m_strategy->addRef(); } } bots::shootingstrategies::ShootingStrategy* bots::AbstractBot::strategy() const { return m_strategy; }
16.515152
89
0.638532
mamontov-cpp
b7a7d9bfa1ca14ba95e3be793dbe511dce52eeb9
3,058
cpp
C++
third_party/WebKit/Source/modules/fetch/FetchResponseDataTest.cpp
wenfeifei/miniblink49
2ed562ff70130485148d94b0e5f4c343da0c2ba4
[ "Apache-2.0" ]
5,964
2016-09-27T03:46:29.000Z
2022-03-31T16:25:27.000Z
third_party/WebKit/Source/modules/fetch/FetchResponseDataTest.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
459
2016-09-29T00:51:38.000Z
2022-03-07T14:37:46.000Z
third_party/WebKit/Source/modules/fetch/FetchResponseDataTest.cpp
w4454962/miniblink49
b294b6eacb3333659bf7b94d670d96edeeba14c0
[ "Apache-2.0" ]
1,006
2016-09-27T05:17:27.000Z
2022-03-30T02:46:51.000Z
// Copyright 2014 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 "config.h" #include "modules/fetch/FetchResponseData.h" #include "core/dom/DOMArrayBuffer.h" #include "modules/fetch/FetchHeaderList.h" #include "platform/blob/BlobData.h" #include "public/platform/WebServiceWorkerResponse.h" #include <gtest/gtest.h> namespace blink { class FetchResponseDataTest : public ::testing::Test { public: FetchResponseData* createInternalResponse() { FetchResponseData* internalResponse = FetchResponseData::create(); internalResponse->setStatus(200); internalResponse->setURL(KURL(ParsedURLString, "http://www.example.com")); internalResponse->headerList()->append("set-cookie", "foo"); internalResponse->headerList()->append("bar", "bar"); internalResponse->headerList()->append("cache-control", "no-cache"); return internalResponse; } void CheckHeaders(const WebServiceWorkerResponse& webResponse) { EXPECT_STREQ("foo", webResponse.getHeader("set-cookie").utf8().c_str()); EXPECT_STREQ("bar", webResponse.getHeader("bar").utf8().c_str()); EXPECT_STREQ("no-cache", webResponse.getHeader("cache-control").utf8().c_str()); } }; TEST_F(FetchResponseDataTest, ToWebServiceWorkerDefaultType) { WebServiceWorkerResponse webResponse; FetchResponseData* internalResponse = createInternalResponse(); internalResponse->populateWebServiceWorkerResponse(webResponse); EXPECT_EQ(WebServiceWorkerResponseTypeDefault, webResponse.responseType()); CheckHeaders(webResponse); } TEST_F(FetchResponseDataTest, ToWebServiceWorkerBasicType) { WebServiceWorkerResponse webResponse; FetchResponseData* internalResponse = createInternalResponse(); FetchResponseData* basicResponseData = internalResponse->createBasicFilteredResponse(); basicResponseData->populateWebServiceWorkerResponse(webResponse); EXPECT_EQ(WebServiceWorkerResponseTypeBasic, webResponse.responseType()); CheckHeaders(webResponse); } TEST_F(FetchResponseDataTest, ToWebServiceWorkerCORSType) { WebServiceWorkerResponse webResponse; FetchResponseData* internalResponse = createInternalResponse(); FetchResponseData* corsResponseData = internalResponse->createCORSFilteredResponse(); corsResponseData->populateWebServiceWorkerResponse(webResponse); EXPECT_EQ(WebServiceWorkerResponseTypeCORS, webResponse.responseType()); CheckHeaders(webResponse); } TEST_F(FetchResponseDataTest, ToWebServiceWorkerOpaqueType) { WebServiceWorkerResponse webResponse; FetchResponseData* internalResponse = createInternalResponse(); FetchResponseData* opaqueResponseData = internalResponse->createOpaqueFilteredResponse(); opaqueResponseData->populateWebServiceWorkerResponse(webResponse); EXPECT_EQ(WebServiceWorkerResponseTypeOpaque, webResponse.responseType()); CheckHeaders(webResponse); } } // namespace WebCore
37.292683
93
0.773381
wenfeifei
b7a8f645c57e2970d5f4437928de8934fc50f6de
619
cpp
C++
test/ordinal/container/ordinal_range/ordinal_range_pass.cpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
105
2015-01-24T13:26:41.000Z
2022-02-18T15:36:53.000Z
test/ordinal/container/ordinal_range/ordinal_range_pass.cpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
37
2015-09-04T06:57:10.000Z
2021-09-09T18:01:44.000Z
test/ordinal/container/ordinal_range/ordinal_range_pass.cpp
jwakely/std-make
f09d052983ace70cf371bb8ddf78d4f00330bccd
[ "BSL-1.0" ]
23
2015-01-27T11:09:18.000Z
2021-10-04T02:23:30.000Z
// Copyright (C) 2016 Vicente J. Botet Escriba // // 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) // <experimental/ordinal_range.hpp> #include <experimental/ordinal_range.hpp> #include "../../Bool.hpp" #include "../../Bounded.hpp" #include <boost/detail/lightweight_test.hpp> int main() { namespace stde = std::experimental; using Indx = Bounded<1,4,unsigned char>; { stde::ordinal_range<Indx> rng; auto b = rng.begin(); BOOST_TEST(b->value==1); } return ::boost::report_errors(); }
22.107143
80
0.688207
jwakely
b7a9300cdebc7c1525815268a60aec7818d1097c
705
cpp
C++
source/pkgsrc/lang/openjdk8/patches/patch-hotspot_src_share_vm_utilities_hashtable.cpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
1
2021-11-20T22:46:39.000Z
2021-11-20T22:46:39.000Z
source/pkgsrc/lang/openjdk8/patches/patch-hotspot_src_share_vm_utilities_hashtable.cpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
source/pkgsrc/lang/openjdk8/patches/patch-hotspot_src_share_vm_utilities_hashtable.cpp
Scottx86-64/dotfiles-1
51004b1e2b032664cce6b553d2052757c286087d
[ "Unlicense" ]
null
null
null
$NetBSD: patch-hotspot_src_share_vm_utilities_hashtable.cpp,v 1.1 2015/07/03 20:40:59 fhajny Exp $ Delete obsolete (and now harmful) SunOS code. --- hotspot/src/share/vm/utilities/hashtable.cpp.orig 2015-06-10 10:31:47.000000000 +0000 +++ hotspot/src/share/vm/utilities/hashtable.cpp @@ -364,7 +364,7 @@ template class RehashableHashtable<oopDe template class Hashtable<Symbol*, mtSymbol>; template class Hashtable<Klass*, mtClass>; template class Hashtable<oop, mtClass>; -#if defined(SOLARIS) || defined(CHECK_UNHANDLED_OOPS) +#if defined(CHECK_UNHANDLED_OOPS) template class Hashtable<oop, mtSymbol>; template class RehashableHashtable<oop, mtSymbol>; #endif // SOLARIS || CHECK_UNHANDLED_OOPS
44.0625
98
0.780142
Scottx86-64
b7a949166a0b0b094aafdef28e98cab9985b4041
2,727
cpp
C++
src/3d/qgscamerapose.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/3d/qgscamerapose.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/3d/qgscamerapose.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgscamerapose.cpp -------------------------------------- Date : July 2018 Copyright : (C) 2018 by Martin Dobias Email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgscamerapose.h" #include <Qt3DRender/QCamera> #include <QDomDocument> QDomElement QgsCameraPose::writeXml( QDomDocument &doc ) const { QDomElement elemCamera = doc.createElement( QStringLiteral( "camera-pose" ) ); elemCamera.setAttribute( QStringLiteral( "x" ), mCenterPoint.x() ); elemCamera.setAttribute( QStringLiteral( "y" ), mCenterPoint.y() ); elemCamera.setAttribute( QStringLiteral( "z" ), mCenterPoint.z() ); elemCamera.setAttribute( QStringLiteral( "dist" ), mDistanceFromCenterPoint ); elemCamera.setAttribute( QStringLiteral( "pitch" ), mPitchAngle ); elemCamera.setAttribute( QStringLiteral( "heading" ), mHeadingAngle ); return elemCamera; } void QgsCameraPose::readXml( const QDomElement &elem ) { double x = elem.attribute( QStringLiteral( "x" ) ).toDouble(); double y = elem.attribute( QStringLiteral( "y" ) ).toDouble(); double z = elem.attribute( QStringLiteral( "z" ) ).toDouble(); mCenterPoint = QgsVector3D( x, y, z ); mDistanceFromCenterPoint = elem.attribute( QStringLiteral( "dist" ) ).toFloat(); mPitchAngle = elem.attribute( QStringLiteral( "pitch" ) ).toFloat(); mHeadingAngle = elem.attribute( QStringLiteral( "heading" ) ).toFloat(); } void QgsCameraPose::updateCamera( Qt3DRender::QCamera *camera ) { // basic scene setup: // - x grows to the right // - z grows to the bottom // - y grows towards camera // so a point on the plane (x',y') is transformed to (x,-z) in our 3D world camera->setUpVector( QVector3D( 0, 0, -1 ) ); camera->setPosition( QVector3D( mCenterPoint.x(), mDistanceFromCenterPoint + mCenterPoint.y(), mCenterPoint.z() ) ); camera->setViewCenter( QVector3D( mCenterPoint.x(), mCenterPoint.y(), mCenterPoint.z() ) ); camera->rotateAboutViewCenter( QQuaternion::fromEulerAngles( mPitchAngle, mHeadingAngle, 0 ) ); }
47.017241
118
0.582325
dyna-mis
b7aa44e2c5d0931d4fa140cf37788bc7d4ed7ae3
3,393
cpp
C++
sumo/src/netbuild/NBPTLine.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netbuild/NBPTLine.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netbuild/NBPTLine.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
2
2017-12-14T16:41:59.000Z
2020-10-16T17:51:27.000Z
/****************************************************************************/ /// @file NBPTLine.cpp /// @author Gregor Laemmel /// @author Nikita Cherednychek /// @date Tue, 20 Mar 2017 /// @version $Id$ /// // The representation of one direction of a single pt line /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ // Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO 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. // /****************************************************************************/ #include <utils/iodevices/OutputDevice.h> #include <utility> #include "NBPTLine.h" #include "NBPTStop.h" NBPTLine::NBPTLine(std::string name) : myName(std::move(name)), myPTLineId(-1), myRef(name) { } void NBPTLine::addPTStop(NBPTStop* pStop) { myPTStops.push_back(pStop); } std::string NBPTLine::getName() { return myName; } std::vector<NBPTStop*> NBPTLine::getStops() { return myPTStops; } void NBPTLine::write(OutputDevice& device) { device.openTag(SUMO_TAG_PT_LINE); device.writeAttr(SUMO_ATTR_ID, myPTLineId); if (!myName.empty()) { device.writeAttr(SUMO_ATTR_NAME, myName); } device.writeAttr(SUMO_ATTR_LINE, myRef); device.writeAttr("completeness", toString((double)myPTStops.size()/(double)myNumOfStops)); if (!myRoute.empty()) { device.openTag(SUMO_TAG_ROUTE); device.writeAttr(SUMO_ATTR_EDGES, getRoute()); device.closeTag(); } for (auto& myPTStop : myPTStops) { device.openTag(SUMO_TAG_BUS_STOP); device.writeAttr(SUMO_ATTR_ID, myPTStop->getID()); device.writeAttr(SUMO_ATTR_NAME, myPTStop->getName()); device.closeTag(); } // device.writeAttr(SUMO_ATTR_LANE, myLaneId); // device.writeAttr(SUMO_ATTR_STARTPOS, myStartPos); // device.writeAttr(SUMO_ATTR_ENDPOS, myEndPos); // device.writeAttr(SUMO_ATTR_FRIENDLY_POS, "true"); device.closeTag(); } void NBPTLine::setId(long long int id) { myPTLineId = id; } void NBPTLine::addWayNode(long long int way, long long int node) { std::string wayStr = toString(way); if (wayStr != myCurrentWay) { myCurrentWay = wayStr; myWays.push_back(wayStr); } myWaysNodes[wayStr].push_back(node); } const std::vector<std::string>& NBPTLine::getMyWays() const { return myWays; } std::vector<long long int>* NBPTLine::getWaysNodes(std::string wayId) { if (myWaysNodes.find(wayId) != myWaysNodes.end()) { return &myWaysNodes[wayId]; } return nullptr; } void NBPTLine::setRef(std::string ref) { myRef = std::move(ref); } std::string NBPTLine::getRoute() { std::string route; for (auto& it : myRoute) { route += (" " + it->getID()); } return route; } void NBPTLine::addEdgeVector(std::vector<NBEdge*>::iterator fr, std::vector<NBEdge*>::iterator to) { myRoute.insert(myRoute.end(), fr, to); } void NBPTLine::setMyNumOfStops(unsigned long numStops) { myNumOfStops = numStops; }
31.12844
100
0.61008
iltempe
b7abb6c084120928b4a69973d6c300eb896ff568
128
hpp
C++
command.hpp
RustedBot/Pong
8e75d64b306cc4c3db433061dd2e3418b7102354
[ "MIT" ]
null
null
null
command.hpp
RustedBot/Pong
8e75d64b306cc4c3db433061dd2e3418b7102354
[ "MIT" ]
null
null
null
command.hpp
RustedBot/Pong
8e75d64b306cc4c3db433061dd2e3418b7102354
[ "MIT" ]
null
null
null
#ifndef COMMAND_H #define COMMAND_H class Command { public: virtual void execute() = 0; private: }; #endif // COMMAND_H
9.142857
31
0.6875
RustedBot
b7ac8ed336791554465e3ec0a3097ef8fd5e260e
681
cpp
C++
acmicpc/1289.cpp
juseongkr/BOJ
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
7
2020-02-03T10:00:19.000Z
2021-11-16T11:03:57.000Z
acmicpc/1289.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2021-01-03T06:58:24.000Z
2021-01-03T06:58:24.000Z
acmicpc/1289.cpp
juseongkr/Algorithm-training
8f10a2bf9a7d695455493fbe7423347a8b648416
[ "Apache-2.0" ]
1
2020-01-22T14:34:03.000Z
2020-01-22T14:34:03.000Z
#include <iostream> #include <vector> using namespace std; #define MAX 100001 const long long MOD = 1e9+7; long long ans; vector<pair<int, int>> graph[MAX]; long long dfs(int cur, int prev) { int ret = 1; for (int i=0; i<graph[cur].size(); ++i) { int next = graph[cur][i].first; int cost = graph[cur][i].second; if (next != prev) { long long val = (dfs(next, cur) * cost) % MOD; ans = (ans + val * ret) % MOD; ret = (ret + val) % MOD; } } return ret; } int main() { int n, a, b, c; cin >> n; for (int i=1; i<n; ++i) { cin >> a >> b >> c; graph[a].push_back({b, c}); graph[b].push_back({a, c}); } dfs(1, 0); cout << ans << '\n'; return 0; }
16.214286
49
0.549192
juseongkr
b7b27c4f1b45ed4307d51498b4c671fc08275c12
12,430
cc
C++
remoting/jingle_glue/jingle_client.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2015-10-12T09:14:22.000Z
2015-10-12T09:14:22.000Z
remoting/jingle_glue/jingle_client.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
null
null
null
remoting/jingle_glue/jingle_client.cc
meego-tablet-ux/meego-app-browser
0f4ef17bd4b399c9c990a2f6ca939099495c2b9c
[ "BSD-3-Clause" ]
1
2020-11-04T07:22:28.000Z
2020-11-04T07:22:28.000Z
// Copyright (c) 2011 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 "remoting/jingle_glue/jingle_client.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/string_util.h" #include "jingle/notifier/base/gaia_token_pre_xmpp_auth.h" #include "remoting/jingle_glue/http_port_allocator.h" #include "remoting/jingle_glue/iq_request.h" #include "remoting/jingle_glue/jingle_thread.h" #include "remoting/jingle_glue/xmpp_socket_adapter.h" #include "third_party/libjingle/source/talk/base/asyncsocket.h" #include "third_party/libjingle/source/talk/base/basicpacketsocketfactory.h" #include "third_party/libjingle/source/talk/base/ssladapter.h" #include "third_party/libjingle/source/talk/p2p/base/sessionmanager.h" #include "third_party/libjingle/source/talk/p2p/base/transport.h" #include "third_party/libjingle/source/talk/p2p/client/sessionmanagertask.h" #include "third_party/libjingle/source/talk/session/tunnel/tunnelsessionclient.h" #include "third_party/libjingle/source/talk/xmpp/prexmppauth.h" #include "third_party/libjingle/source/talk/xmpp/saslcookiemechanism.h" namespace remoting { // The XmppSignalStrategy encapsulates all the logic to perform the signaling // STUN/ICE for jingle via a direct XMPP connection. // // This class is not threadsafe. XmppSignalStrategy::XmppSignalStrategy(JingleThread* jingle_thread, const std::string& username, const std::string& auth_token, const std::string& auth_token_service) : thread_(jingle_thread), username_(username), auth_token_(auth_token), auth_token_service_(auth_token_service), xmpp_client_(NULL), observer_(NULL) { } XmppSignalStrategy::~XmppSignalStrategy() { } void XmppSignalStrategy::Init(StatusObserver* observer) { observer_ = observer; buzz::Jid login_jid(username_); buzz::XmppClientSettings settings; settings.set_user(login_jid.node()); settings.set_host(login_jid.domain()); settings.set_resource("chromoting"); settings.set_use_tls(true); settings.set_token_service(auth_token_service_); settings.set_auth_cookie(auth_token_); settings.set_server(talk_base::SocketAddress("talk.google.com", 5222)); buzz::AsyncSocket* socket = new XmppSocketAdapter(settings, false); xmpp_client_ = new buzz::XmppClient(thread_->task_pump()); xmpp_client_->Connect(settings, "", socket, CreatePreXmppAuth(settings)); xmpp_client_->SignalStateChange.connect( this, &XmppSignalStrategy::OnConnectionStateChanged); xmpp_client_->Start(); } void XmppSignalStrategy::StartSession( cricket::SessionManager* session_manager) { cricket::SessionManagerTask* receiver = new cricket::SessionManagerTask(xmpp_client_, session_manager); receiver->EnableOutgoingMessages(); receiver->Start(); } void XmppSignalStrategy::EndSession() { if (xmpp_client_) { xmpp_client_->Disconnect(); // Client is deleted by TaskRunner. xmpp_client_ = NULL; } } IqRequest* XmppSignalStrategy::CreateIqRequest() { return new XmppIqRequest(thread_->message_loop(), xmpp_client_); } void XmppSignalStrategy::OnConnectionStateChanged( buzz::XmppEngine::State state) { switch (state) { case buzz::XmppEngine::STATE_START: observer_->OnStateChange(StatusObserver::START); break; case buzz::XmppEngine::STATE_OPENING: observer_->OnStateChange(StatusObserver::CONNECTING); break; case buzz::XmppEngine::STATE_OPEN: observer_->OnJidChange(xmpp_client_->jid().Str()); observer_->OnStateChange(StatusObserver::CONNECTED); break; case buzz::XmppEngine::STATE_CLOSED: observer_->OnStateChange(StatusObserver::CLOSED); // Client is destroyed by the TaskRunner after the client is // closed. Reset the pointer so we don't try to use it later. xmpp_client_ = NULL; break; default: NOTREACHED(); break; } } buzz::PreXmppAuth* XmppSignalStrategy::CreatePreXmppAuth( const buzz::XmppClientSettings& settings) { buzz::Jid jid(settings.user(), settings.host(), buzz::STR_EMPTY); return new notifier::GaiaTokenPreXmppAuth( jid.Str(), settings.auth_cookie(), settings.token_service(), notifier::GaiaTokenPreXmppAuth::kDefaultAuthMechanism); } JavascriptSignalStrategy::JavascriptSignalStrategy(const std::string& your_jid) : your_jid_(your_jid) { } JavascriptSignalStrategy::~JavascriptSignalStrategy() { } void JavascriptSignalStrategy::Init(StatusObserver* observer) { // Blast through each state since for a JavascriptSignalStrategy, we're // already connected. // // TODO(ajwong): Clarify the status API contract to see if we have to actually // walk through each state. observer->OnStateChange(StatusObserver::START); observer->OnStateChange(StatusObserver::CONNECTING); observer->OnJidChange(your_jid_); observer->OnStateChange(StatusObserver::CONNECTED); } void JavascriptSignalStrategy::StartSession( cricket::SessionManager* session_manager) { session_start_request_.reset( new SessionStartRequest(CreateIqRequest(), session_manager)); session_start_request_->Run(); } void JavascriptSignalStrategy::EndSession() { if (xmpp_proxy_) { xmpp_proxy_->DetachCallback(); } xmpp_proxy_ = NULL; } void JavascriptSignalStrategy::AttachXmppProxy( scoped_refptr<XmppProxy> xmpp_proxy) { xmpp_proxy_ = xmpp_proxy; xmpp_proxy_->AttachCallback(iq_registry_.AsWeakPtr()); } JavascriptIqRequest* JavascriptSignalStrategy::CreateIqRequest() { return new JavascriptIqRequest(&iq_registry_, xmpp_proxy_); } JingleClient::JingleClient(JingleThread* thread, SignalStrategy* signal_strategy, PortAllocatorSessionFactory* session_factory, Callback* callback) : enable_nat_traversing_(false), thread_(thread), state_(START), initialized_(false), closed_(false), initialized_finished_(false), callback_(callback), signal_strategy_(signal_strategy), port_allocator_session_factory_(session_factory) { } JingleClient::JingleClient(JingleThread* thread, SignalStrategy* signal_strategy, talk_base::NetworkManager* network_manager, talk_base::PacketSocketFactory* socket_factory, PortAllocatorSessionFactory* session_factory, Callback* callback) : enable_nat_traversing_(false), thread_(thread), state_(START), initialized_(false), closed_(false), initialized_finished_(false), callback_(callback), signal_strategy_(signal_strategy), network_manager_(network_manager), socket_factory_(socket_factory), port_allocator_session_factory_(session_factory) { } JingleClient::~JingleClient() { base::AutoLock auto_lock(state_lock_); DCHECK(!initialized_ || closed_); } void JingleClient::Init() { { base::AutoLock auto_lock(state_lock_); DCHECK(!initialized_ && !closed_); initialized_ = true; } message_loop()->PostTask( FROM_HERE, NewRunnableMethod(this, &JingleClient::DoInitialize)); } void JingleClient::DoInitialize() { DCHECK_EQ(message_loop(), MessageLoop::current()); if (!network_manager_.get()) { VLOG(1) << "Creating talk_base::NetworkManager."; network_manager_.reset(new talk_base::NetworkManager()); } if (!socket_factory_.get()) { VLOG(1) << "Creating talk_base::BasicPacketSocketFactory."; socket_factory_.reset(new talk_base::BasicPacketSocketFactory( talk_base::Thread::Current())); } port_allocator_.reset( new remoting::HttpPortAllocator( network_manager_.get(), socket_factory_.get(), port_allocator_session_factory_.get(), "transp2")); if (!enable_nat_traversing_) { port_allocator_->set_flags(cricket::PORTALLOCATOR_DISABLE_STUN | cricket::PORTALLOCATOR_DISABLE_RELAY); } // TODO(ajwong): The strategy needs a "start" command or something. Right // now, Init() implicitly starts processing events. Thus, we must have the // other fields of JingleClient initialized first, otherwise the state-change // may occur and callback into class before we're done initializing. signal_strategy_->Init(this); if (enable_nat_traversing_) { jingle_info_request_.reset( new JingleInfoRequest(signal_strategy_->CreateIqRequest())); jingle_info_request_->SetCallback( NewCallback(this, &JingleClient::OnJingleInfo)); jingle_info_request_->Run( NewRunnableMethod(this, &JingleClient::DoStartSession)); } else { DoStartSession(); } } void JingleClient::DoStartSession() { session_manager_.reset( new cricket::SessionManager(port_allocator_.get())); signal_strategy_->StartSession(session_manager_.get()); // TODO(ajwong): Major hack to synchronize state change logic. Since the Xmpp // connection starts first, it move the state to CONNECTED before we've gotten // the jingle stun and relay information. Thus, we have to delay signaling // until now. There is a parallel if to disable signaling in the // OnStateChange logic. initialized_finished_ = true; if (!closed_ && state_ == CONNECTED) { callback_->OnStateChange(this, state_); } } void JingleClient::Close() { Close(NULL); } void JingleClient::Close(Task* closed_task) { { base::AutoLock auto_lock(state_lock_); // If the client is already closed then don't close again. if (closed_) { if (closed_task) thread_->message_loop()->PostTask(FROM_HERE, closed_task); return; } closed_task_.reset(closed_task); closed_ = true; } message_loop()->PostTask( FROM_HERE, NewRunnableMethod(this, &JingleClient::DoClose)); } void JingleClient::DoClose() { DCHECK_EQ(message_loop(), MessageLoop::current()); DCHECK(closed_); session_manager_.reset(); signal_strategy_->EndSession(); // TODO(ajwong): SignalStrategy should drop all resources at EndSession(). signal_strategy_ = NULL; if (closed_task_.get()) { closed_task_->Run(); closed_task_.reset(); } } std::string JingleClient::GetFullJid() { base::AutoLock auto_lock(jid_lock_); return full_jid_; } IqRequest* JingleClient::CreateIqRequest() { return signal_strategy_->CreateIqRequest(); } MessageLoop* JingleClient::message_loop() { return thread_->message_loop(); } cricket::SessionManager* JingleClient::session_manager() { DCHECK_EQ(message_loop(), MessageLoop::current()); return session_manager_.get(); } void JingleClient::OnStateChange(State new_state) { if (new_state != state_) { state_ = new_state; { // We have to have the lock held, otherwise we cannot be sure that // the client hasn't been closed when we call the callback. base::AutoLock auto_lock(state_lock_); if (!closed_) { // TODO(ajwong): HACK! remove this. See DoStartSession() for details. // // If state is connected, only signal if initialized_finished_ is also // finished. if (state_ != CONNECTED || initialized_finished_) { callback_->OnStateChange(this, new_state); } } } } } void JingleClient::OnJidChange(const std::string& full_jid) { base::AutoLock auto_lock(jid_lock_); full_jid_ = full_jid; } void JingleClient::OnJingleInfo( const std::string& token, const std::vector<std::string>& relay_hosts, const std::vector<talk_base::SocketAddress>& stun_hosts) { if (port_allocator_.get()) { // TODO(ajwong): Avoid string processing if log-level is low. std::string stun_servers; for (size_t i = 0; i < stun_hosts.size(); ++i) { stun_servers += stun_hosts[i].ToString() + "; "; } LOG(INFO) << "Configuring with relay token: " << token << ", relays: " << JoinString(relay_hosts, ';') << ", stun: " << stun_servers; port_allocator_->SetRelayToken(token); port_allocator_->SetStunHosts(stun_hosts); port_allocator_->SetRelayHosts(relay_hosts); } else { LOG(INFO) << "Jingle info found but no port allocator."; } } } // namespace remoting
33.146667
81
0.708045
meego-tablet-ux
5d9a76fabdd5f79b03fb5b4e69757d24f1f55a0f
5,766
cpp
C++
src/resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.cpp
ringmesh/fesapi
0b518e71f805f35679a65c78332b5cb64ed97830
[ "Apache-2.0" ]
null
null
null
src/resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.cpp
ringmesh/fesapi
0b518e71f805f35679a65c78332b5cb64ed97830
[ "Apache-2.0" ]
null
null
null
src/resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.cpp
ringmesh/fesapi
0b518e71f805f35679a65c78332b5cb64ed97830
[ "Apache-2.0" ]
null
null
null
/*----------------------------------------------------------------------- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -----------------------------------------------------------------------*/ #include "resqml2_0_1/NonSealedSurfaceFrameworkRepresentation.h" #include <algorithm> #include <stdexcept> #include <sstream> #include "H5public.h" #include "resqml2_0_1/StructuralOrganizationInterpretation.h" #include "resqml2/AbstractFeatureInterpretation.h" #include "common/AbstractHdfProxy.h" #include "resqml2/AbstractLocal3dCrs.h" using namespace std; using namespace epc; using namespace RESQML2_0_1_NS; using namespace gsoap_resqml2_0_1; const char* NonSealedSurfaceFrameworkRepresentation::XML_TAG = "NonSealedSurfaceFrameworkRepresentation"; NonSealedSurfaceFrameworkRepresentation::NonSealedSurfaceFrameworkRepresentation( StructuralOrganizationInterpretation* interp, const std::string & guid, const std::string & title, const bool & isSealed): RepresentationSetRepresentation(interp) { if (!interp) throw invalid_argument("The structural organization interpretation cannot be null."); // proxy constructor gsoapProxy2_0_1 = soap_new_resqml2__obj_USCORENonSealedSurfaceFrameworkRepresentation(interp->getGsoapContext(), 1); _resqml2__NonSealedSurfaceFrameworkRepresentation* orgRep = static_cast<_resqml2__NonSealedSurfaceFrameworkRepresentation*>(gsoapProxy2_0_1); orgRep->RepresentedInterpretation = soap_new_eml20__DataObjectReference(gsoapProxy2_0_1->soap, 1); orgRep->RepresentedInterpretation->UUID.assign(interp->getUuid()); initMandatoryMetadata(); setMetadata(guid, title, "", -1, "", "", -1, "", ""); setInterpretation(interp); } void NonSealedSurfaceFrameworkRepresentation::pushBackNonSealedContactRepresentation(const unsigned int & pointCount, double * points, RESQML2_NS::AbstractLocal3dCrs* crs, COMMON_NS::AbstractHdfProxy * proxy) { if (pointCount == 0) throw invalid_argument("Contact point count cannot be zero."); if (!points) throw invalid_argument("The contact points cannot be null."); if (!proxy) throw invalid_argument("The HDF proxy cannot be null."); if (localCrs == nullptr) { localCrs = crs; localCrs->addRepresentation(this); } setHdfProxy(proxy); _resqml2__NonSealedSurfaceFrameworkRepresentation* orgRep = static_cast<_resqml2__NonSealedSurfaceFrameworkRepresentation*>(gsoapProxy2_0_1); resqml2__NonSealedContactRepresentationPart* contactRep = soap_new_resqml2__NonSealedContactRepresentationPart(gsoapProxy2_0_1->soap, 1); contactRep->Index = orgRep->NonSealedContactRepresentation.size(); orgRep->NonSealedContactRepresentation.push_back(contactRep); resqml2__PointGeometry* contactGeom = soap_new_resqml2__PointGeometry(gsoapProxy2_0_1->soap, 1); contactRep->Geometry = contactGeom; contactGeom->LocalCrs = localCrs->newResqmlReference(); resqml2__Point3dHdf5Array* contactGeomPoints = soap_new_resqml2__Point3dHdf5Array(gsoapProxy2_0_1->soap, 1); contactGeom->Points = contactGeomPoints; contactGeomPoints->Coordinates = soap_new_eml20__Hdf5Dataset(gsoapProxy2_0_1->soap, 1); contactGeomPoints->Coordinates->HdfProxy = hdfProxy->newResqmlReference(); ostringstream oss; oss << "points_contact_representation" << orgRep->NonSealedContactRepresentation.size()-1; contactGeomPoints->Coordinates->PathInHdfFile = "/RESQML/" + getUuid() + "/" + oss.str(); // HDF hsize_t numValues[2]; numValues[0] = pointCount; numValues[1] = 3; // 3 for X, Y and Z hdfProxy->writeArrayNdOfDoubleValues(getUuid(), oss.str(), points, numValues, 2); } std::string NonSealedSurfaceFrameworkRepresentation::getHdfProxyUuid() const { string result = ""; _resqml2__NonSealedSurfaceFrameworkRepresentation* orgRep = static_cast<_resqml2__NonSealedSurfaceFrameworkRepresentation*>(gsoapProxy2_0_1); if (orgRep->NonSealedContactRepresentation.size() > 0) { resqml2__NonSealedContactRepresentationPart* firstContact = static_cast<resqml2__NonSealedContactRepresentationPart*>(orgRep->NonSealedContactRepresentation[0]); if (firstContact->Geometry->soap_type() == SOAP_TYPE_gsoap_resqml2_0_1_resqml2__PointGeometry) { resqml2__PointGeometry* pointGeom = static_cast<resqml2__PointGeometry*>(firstContact->Geometry); if (pointGeom->Points->soap_type() == SOAP_TYPE_gsoap_resqml2_0_1_resqml2__Point3dHdf5Array) { return static_cast<resqml2__Point3dHdf5Array*>(pointGeom->Points)->Coordinates->HdfProxy->UUID; } } } return result; } vector<Relationship> NonSealedSurfaceFrameworkRepresentation::getAllEpcRelationships() const { vector<Relationship> result = RepresentationSetRepresentation::getAllEpcRelationships(); // supporting representations of organization sub representations for (unsigned int i = 0; i < supportingRepOfContactPatchSet.size(); i++) { Relationship rel(supportingRepOfContactPatchSet[i]->getPartNameInEpcDocument(), "", supportingRepOfContactPatchSet[i]->getUuid()); rel.setDestinationObjectType(); result.push_back(rel); } return result; }
41.482014
208
0.776968
ringmesh
5d9a9dd797a42e7794f2b88dd787c4a107c2ccc5
1,983
cpp
C++
dnn_project/dnn/util/spikes_list.cpp
alexeyche/dnn_old
58305cf486187575312cef0a753c86a8c7792196
[ "MIT" ]
null
null
null
dnn_project/dnn/util/spikes_list.cpp
alexeyche/dnn_old
58305cf486187575312cef0a753c86a8c7792196
[ "MIT" ]
null
null
null
dnn_project/dnn/util/spikes_list.cpp
alexeyche/dnn_old
58305cf486187575312cef0a753c86a8c7792196
[ "MIT" ]
null
null
null
#include "spikes_list.h" #include <dnn/base/factory.h> namespace dnn { Ptr<TimeSeries> SpikesList::convertToBinaryTimeSeries(const double &dt) const { Ptr<TimeSeries> out(Factory::inst().createObject<TimeSeries>()); out->info = info; out->setDimSize(seq.size()); double max_spike_time = std::numeric_limits<double>::min(); size_t max_size = std::numeric_limits<size_t>::min(); size_t max_id = 0; for(size_t di=0; di<seq.size(); ++di) { double t=0; for(const auto &spike_time: seq[di].values) { // cout << "dim: " << di << ", t: " << t << ", spike_time: " << spike_time << "\n"; while(t<spike_time) { out->addValue(di, 0.0); t+=dt; // cout << t << ", "; } // cout << "\n"; out->addValue(di, 1.0); t+=dt; max_spike_time = std::max(max_spike_time, spike_time); if(max_spike_time == spike_time) { max_id = di; } } max_size = std::max(max_size, out->data[di].values.size()); } // cout << "max_size: " << max_size << ", max_spike_time: " << max_spike_time << " " << max_id << "\n"; for(size_t di=0; di<out->data.size(); ++di) { double last_t = dt*out->data[di].values.size(); // cout << "dim: " << di << ", last_t: " << last_t << ", size: " << out->data[di].values.size() << "\n"; while(last_t <= max_spike_time) { out->addValue(di, 0.0); last_t +=dt; // cout << last_t << ", "; } // cout << "\n"; if(out->data[di].values.size() != max_size) { throw dnnException() << "Failed to convert spike times to " << \ "equal time series for " << di << " dimension, " << \ out->data[di].values.size() << " != max_size " << max_size << " \n"; } } return out; } }
34.789474
113
0.476551
alexeyche