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
8a8952a551dfb9ad624e5e2246991539738e0ecc
2,604
cxx
C++
AD/ADrec/AliADQAParam.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
AD/ADrec/AliADQAParam.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
2
2016-11-25T08:40:56.000Z
2019-10-11T12:29:29.000Z
AD/ADrec/AliADQAParam.cxx
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include "AliADQAParam.h" ClassImp(AliADQAParam) //_____________________________________________________________________________ AliADQAParam::AliADQAParam(): fNTdcTimeBins(3062), fTdcTimeMin(0.976562), fTdcTimeMax(300.0), fNTdcTimeBinsFlag(410), fTdcTimeMinBGFlag(50.0), fTdcTimeMaxBGFlag(90.039062), fTdcTimeMinBBFlag(170.0), fTdcTimeMaxBBFlag(210.039062), fNTdcTimeRatioBins(300), fTdcTimeRatioMin(1), fTdcTimeRatioMax(301), fNTdcWidthBins(153), fTdcWidthMin(2.343750), fTdcWidthMax(121.875000), fNChargeChannelBins(1000), fChargeChannelMin(0), fChargeChannelMax(1000), fChargeChannelZoomMin(0), fChargeChannelZoomMax(50), fNChargeSideBins(500), fChargeSideMin(1), fChargeSideMax(5000), fNChargeCorrBins(101), fChargeCorrMin(1), fChargeCorrMax(1001), fNPairTimeCorrBins(306), fPairTimeCorrMin(0.976562), fPairTimeCorrMax(299.804688), fNPairTimeDiffBins(154), fPairTimeDiffMin(-15.039062), fPairTimeDiffMax(15.039062), fNMeanTimeCorrBins(306), fMeanTimeCorrMin(50.976562), fMeanTimeCorrMax(349.804688), fChargeTrendMin(0), fChargeTrendMax(1000), fSatMed(0.1), fSatHigh(0.3), fSatHuge(0.5), fMaxPedDiff(1), fMaxPedWidth(1.5), fMaxNoTimeRate(10e-4), fMaxNoFlagRate(10e-3), fMaxBBVariation(0.1), fMaxBGVariation(0.1), fAsynchronBB(0.5), fAsynchronBG(0.5) { // // constructor // } //_____________________________________________________________________________ AliADQAParam::~AliADQAParam() { // // destructor // }
30.635294
79
0.637097
AllaMaevskaya
8a8dd6a8b02b263970793cae231b74e58765da15
5,547
cpp
C++
Plugin/Source/AudioFeatureExtractor.cpp
eupston/Deepbox
cdb0ba9a3de3a81672a9fc3610e60da9773d9ddd
[ "MIT" ]
4
2020-06-02T01:15:52.000Z
2022-01-09T22:50:30.000Z
Plugin/Source/AudioFeatureExtractor.cpp
eupston/Deepbox
cdb0ba9a3de3a81672a9fc3610e60da9773d9ddd
[ "MIT" ]
7
2020-01-28T23:13:02.000Z
2022-02-10T00:31:03.000Z
Plugin/Source/AudioFeatureExtractor.cpp
eupston/Deepbox
cdb0ba9a3de3a81672a9fc3610e60da9773d9ddd
[ "MIT" ]
2
2020-05-04T14:10:49.000Z
2020-06-02T01:17:10.000Z
// // AudioFeatureExtractor.cpp // DrumPad // // Created by eugene upston on 8/17/19. // #include "AudioFeatureExtractor.hpp" AudioFeatureExtractor::AudioFeatureExtractor(int frame_size, int hop_size, int sample_rate) { essentia::init(); AlgorithmFactory& factory = standard::AlgorithmFactory::instance(); fc = factory.create("FrameCutter", "frameSize", frame_size, "hopSize", hop_size, "startFromZero", true); win = factory.create("Windowing", "type", "hann"); logNorm = factory.create("UnaryOperator", "type", "log"); spec = factory.create("Spectrum"); mfcc = factory.create("MFCC"); specContrast = factory.create("SpectralContrast", "frameSize", frame_size + 1); energyband_high = factory.create("EnergyBand", "startCutoffFrequency", 1000, "stopCutoffFrequency", 8000); energyband_low = factory.create("EnergyBand", "startCutoffFrequency", 100, "stopCutoffFrequency", 700); eqloud = factory.create("EqualLoudness"); const char* stats[] = { "mean", "var", "min", "max" }; aggr = AlgorithmFactory::create("PoolAggregator", "defaultStats", arrayToVector<string>(stats)); connect_buffer_to_algorithms(); }; vector<Real> AudioFeatureExtractor::load_audio_buffer(std::vector<float> buffer) { vector<Real> audio_buffer; for(auto sample : buffer){ audio_buffer.push_back(sample); } audiobuffer = audio_buffer; return audiobuffer; }; void AudioFeatureExtractor::connect_buffer_to_algorithms(){ eqloud->input("signal").set(audiobuffer); eqloud->output("signal").set(audiobuffer); fc->input("signal").set(audiobuffer); // initialize framecutter with signal fc->output("frame").set(frame);// set framecutter output with the frame win->input("frame").set(frame); //set windowed frame input to the frame win->output("frame").set(windowedFrame); // set windowframe output to frame spec->input("frame").set(windowedFrame); // set spectrum input to the windowed frame spec->output("spectrum").set(spectrum); // set output of spectrum to spectrum mfcc->input("spectrum").set(spectrum); // sets input of mfcc to spectrum mfcc->output("bands").set(mfccBands); // sets output of mfcc to mfccbands mfcc->output("mfcc").set(mfccCoeffs); // set output of mfcc to mfccoeffs logNorm->input("array").set(mfccBands); logNorm->output("array").set(mfccBandsLog); specContrast->input("spectrum").set(spectrum); specContrast->output("spectralContrast").set(spectralContrast); specContrast->output("spectralValley").set(spectralValley); energyband_high->input("spectrum").set(spectrum); energyband_high->output("energyBand").set(energy_freq_band_high); energyband_low->input("spectrum").set(spectrum); energyband_low->output("energyBand").set(energy_freq_band_low); aggr->input("input").set(pool); aggr->output("output").set(aggrPool); }; void AudioFeatureExtractor::compute_algorithms() { eqloud->compute(); while (true) { // compute a frame fc->compute(); // if it was the last one (ie: it was empty), then we're done. if (!frame.size()) { break; } // if the frame is silent, just drop it and go on processing if (isSilent(frame)) continue; win->compute(); spec->compute(); mfcc->compute(); specContrast->compute(); energyband_high->compute(); energyband_low->compute(); logNorm->compute(); mfccPool.push_back(mfccCoeffs); specPool.push_back(spectralContrast); melbandlogPool.push_back(mfccBandsLog); energyhighPool.push_back(energy_freq_band_high); energylowPool.push_back(energy_freq_band_high); } }; vector<float> AudioFeatureExtractor::compute_mean_features() { std::vector<float> audio_features; aggr->compute(); vector<Real> mfcc_mean; vector<Real> spec_mean; vector<Real> melbandlog_mean; Real energyhigh_mean; Real energylow_mean; auto mean = [](vector<Real> const& v) { return std::accumulate(v.begin(), v.end(), 0LL) / v.size(); }; auto meanHStack = [](vector<vector<Real>> const& vm) { vector<Real> vMean; int vSize = vm[0].size(); for (int i = 0; i < vSize; i++) { float totalHStackMean = 0.0; for (int j = 0; j < vm.size(); j++){ auto v = vm[j]; totalHStackMean += v[i]; }; vMean.push_back(totalHStackMean / vSize); } return vMean; }; mfcc_mean = meanHStack(mfccPool); spec_mean = meanHStack(specPool); melbandlog_mean = meanHStack(melbandlogPool); energyhigh_mean = mean(energyhighPool); energylow_mean = mean(energylowPool); for(auto mfcc : mfcc_mean){ audio_features.push_back(mfcc); } for(auto spec : spec_mean){ audio_features.push_back(spec); } for(auto melband : melbandlog_mean){ audio_features.push_back(melband); } audio_features.push_back(energyhigh_mean); audio_features.push_back(energylow_mean); return audio_features; }; AudioFeatureExtractor::~AudioFeatureExtractor() { delete fc; delete win; delete spec; delete mfcc; delete aggr; delete logNorm; delete specContrast; delete energyband_low; delete energyband_high; delete eqloud; essentia::shutdown(); };
31.697143
111
0.647197
eupston
8a8fa5d0fc42b3a992a444ac8dcb44420a2cd8ac
20,359
cpp
C++
language-extensions/python/test/src/PythonExecuteTests.cpp
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
82
2019-05-24T00:36:57.000Z
2022-02-21T23:51:46.000Z
language-extensions/python/test/src/PythonExecuteTests.cpp
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
20
2019-07-05T06:12:28.000Z
2022-03-31T20:48:30.000Z
language-extensions/python/test/src/PythonExecuteTests.cpp
rabryst/sql-server-language-extensions
a6a25890d1c3e449537eaaafab706c6c1e8b51cb
[ "MIT" ]
35
2019-05-24T01:44:07.000Z
2022-02-28T13:29:44.000Z
//************************************************************************************************* // Copyright (C) Microsoft Corporation. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // // @File: PythonExecuteTests.cpp // // Purpose: // Tests the PythonExtension's implementation of the external language Execute API. // //************************************************************************************************* #include <sstream> #include "PythonExtensionApiTests.h" #include "PythonTestUtilities.h" using namespace std; namespace bp = boost::python; namespace ExtensionApiTest { // Name: ExecuteIntegerColumnsTest // // Description: // Test Execute with default script using an InputDataSet of Integer columns. // TEST_F(PythonExtensionApiTests, ExecuteIntegerColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_integerInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQLINTEGER, SQL_C_SLONG>(m_integerInfo.get()); TestExecute<SQLINTEGER, SQL_C_SLONG>( ColumnInfo<SQLINTEGER>::sm_rowsNumber, (*m_integerInfo).m_dataSet.data(), (*m_integerInfo).m_strLen_or_Ind.data(), (*m_integerInfo).m_columnNames); } // Name: ExecuteBooleanColumnsTest // // Description: // Test Execute using an InputDataSet of Boolean columns. // TEST_F(PythonExtensionApiTests, ExecuteBooleanColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_booleanInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQLCHAR, SQL_C_BIT>(m_booleanInfo.get()); TestExecute<SQLCHAR, SQL_C_BIT>( ColumnInfo<SQLCHAR>::sm_rowsNumber, (*m_booleanInfo).m_dataSet.data(), (*m_booleanInfo).m_strLen_or_Ind.data(), (*m_booleanInfo).m_columnNames); } // Name: ExecuteRealColumnsTest // // Description: // Test Execute with default script using an InputDataSet of Real columns. // TEST_F(PythonExtensionApiTests, ExecuteRealColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_realInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQLREAL, SQL_C_FLOAT>(m_realInfo.get()); TestExecute<SQLREAL, SQL_C_FLOAT>( ColumnInfo<SQLREAL>::sm_rowsNumber, (*m_realInfo).m_dataSet.data(), (*m_realInfo).m_strLen_or_Ind.data(), (*m_realInfo).m_columnNames); } // Name: ExecuteDoubleColumnsTest // // Description: // Test Execute with default script using an InputDataSet of Double columns. // TEST_F(PythonExtensionApiTests, ExecuteDoubleColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_doubleInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQLDOUBLE, SQL_C_DOUBLE>(m_doubleInfo.get()); TestExecute<SQLDOUBLE, SQL_C_DOUBLE>( ColumnInfo<SQLDOUBLE>::sm_rowsNumber, (*m_doubleInfo).m_dataSet.data(), (*m_doubleInfo).m_strLen_or_Ind.data(), (*m_doubleInfo).m_columnNames); } // Name: ExecuteBigIntColumnsTest // // Description: // Test Execute with default script using an InputDataSet of BigInteger columns. // TEST_F(PythonExtensionApiTests, ExecuteBigIntColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_bigIntInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQLBIGINT, SQL_C_SBIGINT>(m_bigIntInfo.get()); TestExecute<SQLBIGINT, SQL_C_SBIGINT>( ColumnInfo<SQLBIGINT>::sm_rowsNumber, (*m_bigIntInfo).m_dataSet.data(), (*m_bigIntInfo).m_strLen_or_Ind.data(), (*m_bigIntInfo).m_columnNames); } // Name: ExecuteSmallIntColumnsTest // // Description: // Test Execute with default script using an InputDataSet of SmallInt columns. // TEST_F(PythonExtensionApiTests, ExecuteSmallIntColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_smallIntInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQLSMALLINT, SQL_C_SSHORT>(m_smallIntInfo.get()); TestExecute<SQLSMALLINT, SQL_C_SSHORT>( ColumnInfo<SQLSMALLINT>::sm_rowsNumber, (*m_smallIntInfo).m_dataSet.data(), (*m_smallIntInfo).m_strLen_or_Ind.data(), (*m_smallIntInfo).m_columnNames); } // Name: ExecuteTinyIntColumnsTest // // Description: // Test Execute with default script using an InputDataSet of TinyInt columns. // TEST_F(PythonExtensionApiTests, ExecuteTinyIntColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_tinyIntInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQLCHAR, SQL_C_UTINYINT>(m_tinyIntInfo.get()); TestExecute<SQLCHAR, SQL_C_UTINYINT>( ColumnInfo<SQLCHAR>::sm_rowsNumber, (*m_tinyIntInfo).m_dataSet.data(), (*m_tinyIntInfo).m_strLen_or_Ind.data(), (*m_tinyIntInfo).m_columnNames); } // Name: ExecuteStringColumnsTest // // Description: // Test Execute with default script using an InputDataSet of string columns. // TEST_F(PythonExtensionApiTests, ExecuteStringColumnsTest) { SQLUSMALLINT inputSchemaColumnsNumber = 3; // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber inputSchemaColumnsNumber, m_scriptString); string stringColumn1Name = "StringColumn1"; InitializeColumn(0, stringColumn1Name, SQL_C_CHAR, m_CharSize); string stringColumn2Name = "StringColumn2"; InitializeColumn(1, stringColumn2Name, SQL_C_CHAR, m_CharSize); string stringColumn3Name = "StringColumn3"; InitializeColumn(2, stringColumn3Name, SQL_C_CHAR, m_CharSize); vector<const char*> stringCol1{ "Hello", "test", "data", "World", "-123" }; vector<const char*> stringCol2{ "", 0, nullptr, "verify", "-1" }; vector<SQLINTEGER> strLenOrIndCol1 = { static_cast<SQLINTEGER>(strlen(stringCol1[0])), static_cast<SQLINTEGER>(strlen(stringCol1[1])), static_cast<SQLINTEGER>(strlen(stringCol1[2])), static_cast<SQLINTEGER>(strlen(stringCol1[3])), static_cast<SQLINTEGER>(strlen(stringCol1[4])) }; vector<SQLINTEGER> strLenOrIndCol2 = { 0, SQL_NULL_DATA, SQL_NULL_DATA, static_cast<SQLINTEGER>(strlen(stringCol2[3])), static_cast<SQLINTEGER>(strlen(stringCol2[4])) }; vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1.data(), strLenOrIndCol2.data(), nullptr }; // Coalesce the arrays of each row of each column // into a contiguous array for each column. // vector<char> stringCol1Data = GenerateContiguousData<char>(stringCol1, strLenOrIndCol1.data()); vector<char> stringCol2Data = GenerateContiguousData<char>(stringCol2, strLenOrIndCol2.data()); void* dataSet[] = { stringCol1Data.data(), stringCol2Data.data(), nullptr }; int rowsNumber = stringCol1.size(); vector<string> columnNames{ stringColumn1Name, stringColumn2Name, stringColumn3Name }; TestExecute<SQLCHAR, SQL_C_CHAR>( rowsNumber, dataSet, strLen_or_Ind.data(), columnNames); } // Name: ExecuteWStringColumnsTest // // Description: // Test Execute with default script using an InputDataSet of wstring columns. // TEST_F(PythonExtensionApiTests, ExecuteWStringColumnsTest) { SQLUSMALLINT inputSchemaColumnsNumber = 3; // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber inputSchemaColumnsNumber, m_scriptString); string wstringColumn1Name = "WStringColumn1"; InitializeColumn(0, wstringColumn1Name, SQL_C_WCHAR, m_WCharSize); string wstringColumn2Name = "WStringColumn2"; InitializeColumn(1, wstringColumn2Name, SQL_C_WCHAR, m_WCharSize); string wstringColumn3Name = "WStringColumn3"; InitializeColumn(2, wstringColumn3Name, SQL_C_WCHAR, m_WCharSize); vector<const wchar_t*> wstringCol1{ L"Hello", L"test", L"data", L"World", L"你好" }; vector<const wchar_t*> wstringCol2{ L"", 0, nullptr, L"verify", L"-1" }; vector<SQLINTEGER> strLenOrIndCol1 = { static_cast<SQLINTEGER>(5 * sizeof(wchar_t)), static_cast<SQLINTEGER>(4 * sizeof(wchar_t)), static_cast<SQLINTEGER>(4 * sizeof(wchar_t)), static_cast<SQLINTEGER>(5 * sizeof(wchar_t)), static_cast<SQLINTEGER>(2 * sizeof(wchar_t)) }; vector<SQLINTEGER> strLenOrIndCol2 = { 0, SQL_NULL_DATA, SQL_NULL_DATA, static_cast<SQLINTEGER>(6 * sizeof(wchar_t)), static_cast<SQLINTEGER>(2 * sizeof(wchar_t)) }; vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1.data(), strLenOrIndCol2.data(), nullptr }; // Coalesce the arrays of each row of each column // into a contiguous array for each column. // vector<wchar_t> wstringCol1Data = GenerateContiguousData<wchar_t>(wstringCol1, strLenOrIndCol1.data()); vector<wchar_t> wstringCol2Data = GenerateContiguousData<wchar_t>(wstringCol2, strLenOrIndCol2.data()); void* dataSet[] = { wstringCol1Data.data(), wstringCol2Data.data(), nullptr }; int rowsNumber = wstringCol1.size(); vector<string> columnNames{ wstringColumn1Name, wstringColumn2Name, wstringColumn3Name }; TestExecute<wchar_t, SQL_C_WCHAR>( rowsNumber, dataSet, strLen_or_Ind.data(), columnNames); } // Name: ExecuteRawColumnsTest // // Description: // Test Execute with default script using an InputDataSet of binary columns. // TEST_F(PythonExtensionApiTests, ExecuteRawColumnsTest) { SQLUSMALLINT inputSchemaColumnsNumber = 3; // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber inputSchemaColumnsNumber, m_scriptString); const SQLCHAR BinaryValue1[] = { 0x01, 0x01, 0xe2, 0x40 }; const SQLCHAR BinaryValue2[] = { 0x04, 0x05, 0xe1 }; const SQLCHAR BinaryValue3[] = { 0x00, 0x00, 0x00, 0x01 }; const SQLCHAR BinaryValue4[] = { 0xff }; const SQLCHAR BinaryValue5[] = { 0x00 }; const SQLCHAR BinaryValue6[] = { 0xff, 0xff, 0xff, 0xff }; const SQLCHAR BinaryValue7[] = { 0x00, 0x12, 0xd2, 0xff, 0x00, 0x12, 0xd2, 0xff, 0x00, 0x12, 0xd2, 0xff }; string binaryColumn1Name = "BinaryColumn1"; InitializeColumn(0, binaryColumn1Name, SQL_C_BINARY, m_BinarySize); string binaryColumn2Name = "BinaryColumn2"; InitializeColumn(1, binaryColumn2Name, SQL_C_BINARY, m_BinarySize); string binaryColumn3Name = "BinaryColumn3"; InitializeColumn(2, binaryColumn3Name, SQL_C_BINARY, m_BinarySize); vector<const SQLCHAR*> binaryCol1{ BinaryValue1, BinaryValue2, BinaryValue3, BinaryValue4 }; vector<const SQLCHAR*> binaryCol2{ BinaryValue5, BinaryValue6, nullptr, BinaryValue7}; SQLINTEGER strLenOrIndCol1[] = { static_cast<SQLINTEGER>(sizeof(BinaryValue1) / m_BinarySize), static_cast<SQLINTEGER>(sizeof(BinaryValue2) / m_BinarySize), static_cast<SQLINTEGER>(sizeof(BinaryValue3) / m_BinarySize), static_cast<SQLINTEGER>(sizeof(BinaryValue4) / m_BinarySize) }; SQLINTEGER strLenOrIndCol2[] = { SQL_NULL_DATA, static_cast<SQLINTEGER>(sizeof(BinaryValue6) / m_BinarySize), SQL_NULL_DATA, static_cast<SQLINTEGER>(sizeof(BinaryValue7) / m_BinarySize) }; vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1, strLenOrIndCol2, nullptr }; // Coalesce the arrays of each row of each column // into a contiguous array for each column. // int rowsNumber = binaryCol1.size(); vector<SQLCHAR> binaryCol1Data = GenerateContiguousData<SQLCHAR>(binaryCol1, strLenOrIndCol1); vector<SQLCHAR> binaryCol2Data = GenerateContiguousData<SQLCHAR>(binaryCol2, strLenOrIndCol2); void* dataSet[] = { binaryCol1Data.data(), binaryCol2Data.data(), nullptr }; vector<string> columnNames{ binaryColumn1Name, binaryColumn2Name, binaryColumn3Name }; TestExecute<SQLCHAR, SQL_C_BINARY>( rowsNumber, dataSet, strLen_or_Ind.data(), columnNames); } // Name: ExecuteDifferentColumnsTest // // Description: // Test Execute with default script using an InputDataSet of different column types. // TEST_F(PythonExtensionApiTests, ExecuteDifferentColumnsTest) { SQLUSMALLINT inputSchemaColumnsNumber = 3; // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber inputSchemaColumnsNumber, m_scriptString); string integerColumnName = "IntegerColumn"; InitializeColumn(0, integerColumnName, SQL_C_SLONG, m_IntSize); string doubleColumnName = "DoubleColumn"; InitializeColumn(1, doubleColumnName, SQL_C_DOUBLE, m_DoubleSize); string stringColumnName = "StringColumn"; InitializeColumn(2, stringColumnName, SQL_C_CHAR, m_CharSize); vector<SQLINTEGER> intColData{ m_MaxInt, m_MinInt, 0, 1320, -1 }; vector<SQLDOUBLE> doubleColData{ m_MinDouble, 1.33, 83.98, 72.45, m_MaxDouble }; vector<const char*> stringCol{ "Hello", "test", "data", "World", "-123" }; SQLINTEGER strLenOrIndCol1[] = { 0, 0, SQL_NULL_DATA, SQL_NULL_DATA, 0 }; SQLINTEGER strLenOrIndCol3[] = { static_cast<SQLINTEGER>(strlen(stringCol[0])), static_cast<SQLINTEGER>(strlen(stringCol[1])), static_cast<SQLINTEGER>(strlen(stringCol[2])), static_cast<SQLINTEGER>(strlen(stringCol[3])), static_cast<SQLINTEGER>(strlen(stringCol[4])) }; vector<SQLINTEGER*> strLen_or_Ind{ strLenOrIndCol1, nullptr, strLenOrIndCol3 }; int rowsNumber = intColData.size(); vector<char> stringColData = GenerateContiguousData<char>(stringCol, strLenOrIndCol3); vector<void *> dataSet{ intColData.data(), doubleColData.data(), stringColData.data() }; testing::internal::CaptureStdout(); SQLUSMALLINT outputschemaColumnsNumber = 0; SQLRETURN result = Execute( *m_sessionId, m_taskId, rowsNumber, dataSet.data(), strLen_or_Ind.data(), &outputschemaColumnsNumber); ASSERT_EQ(result, SQL_SUCCESS); // Test print message was printed correctly // string output = testing::internal::GetCapturedStdout(); cout << output; ASSERT_TRUE(output.find(m_printMessage) != string::npos); try { string createDictScript = m_inputDataNameString + ".to_dict()"; bp::dict inputDataSet = bp::extract<bp::dict>(bp::eval(createDictScript.c_str(), m_mainNamespace)); createDictScript = m_outputDataNameString + ".to_dict()"; bp::dict outputDataSet = bp::extract<bp::dict>(bp::eval(createDictScript.c_str(), m_mainNamespace)); for(bp::dict ds : {inputDataSet, outputDataSet}) { bp::dict intColumn = bp::extract<bp::dict>(ds.get(integerColumnName)); CheckColumnEquality<SQLINTEGER>( rowsNumber, intColumn, dataSet[0], strLen_or_Ind[0]); bp::dict numericColumn = bp::extract<bp::dict>(ds.get(doubleColumnName)); CheckColumnEquality<SQLDOUBLE>( rowsNumber, numericColumn, dataSet[1], strLen_or_Ind[1]); bp::dict stringColumn = bp::extract<bp::dict>(ds.get(stringColumnName)); CheckStringColumnEquality( rowsNumber, stringColumn, dataSet[2], strLen_or_Ind[2]); } } catch (bp::error_already_set &) { string pyError = PythonTestUtilities::ParsePythonException(); throw runtime_error("Error running python:\n" + pyError); } } // Name: ExecuteDateTimeColumnsTest // // Description: // Test Execute with default script using an InputDataSet of DateTime columns. // TEST_F(PythonExtensionApiTests, ExecuteDateTimeColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_dateTimeInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQL_TIMESTAMP_STRUCT, SQL_C_TYPE_TIMESTAMP>(m_dateTimeInfo.get()); TestExecute<SQL_TIMESTAMP_STRUCT, SQL_C_TYPE_TIMESTAMP>( ColumnInfo<SQL_TIMESTAMP_STRUCT>::sm_rowsNumber, (*m_dateTimeInfo).m_dataSet.data(), (*m_dateTimeInfo).m_strLen_or_Ind.data(), (*m_dateTimeInfo).m_columnNames); } // Name: ExecuteDateColumnsTest // // Description: // Test Execute with default script using an InputDataSet of Date columns. // TEST_F(PythonExtensionApiTests, ExecuteDateColumnsTest) { // Initialize with a default Session that prints Hello PythonExtension // and assigns InputDataSet to OutputDataSet // InitializeSession(0, // parametersNumber (*m_dateInfo).GetColumnsNumber(), m_scriptString); InitializeColumns<SQL_DATE_STRUCT, SQL_C_TYPE_DATE>(m_dateInfo.get()); TestExecute<SQL_DATE_STRUCT, SQL_C_TYPE_DATE>( ColumnInfo<SQL_DATE_STRUCT>::sm_rowsNumber, (*m_dateInfo).m_dataSet.data(), (*m_dateInfo).m_strLen_or_Ind.data(), (*m_dateInfo).m_columnNames); } // Name: TestExecute // // Description: // Template function to Test Execute with default script that assigns Input to Output. // It tests the correctness of the: // 1. Executed script, // 2. InputDataSet and // 3. OutputDataSet // This can also be run without the validation steps by setting "validate" to false. // template<class SQLType, SQLSMALLINT dataType> void PythonExtensionApiTests::TestExecute( SQLULEN rowsNumber, void **dataSet, SQLINTEGER **strLen_or_Ind, vector<string> columnNames, bool validate) { testing::internal::CaptureStdout(); SQLUSMALLINT outputschemaColumnsNumber = 0; SQLRETURN result = Execute( *m_sessionId, m_taskId, rowsNumber, dataSet, strLen_or_Ind, &outputschemaColumnsNumber); ASSERT_EQ(result, SQL_SUCCESS); string output = testing::internal::GetCapturedStdout(); cout << output; if (validate) { // Verify print message was printed correctly // ASSERT_TRUE(output.find(m_printMessage) != string::npos); try { string createDictScript = m_inputDataNameString + ".to_dict()"; bp::dict inputDataSet = bp::extract<bp::dict>(bp::eval(createDictScript.c_str(), m_mainNamespace)); createDictScript = m_outputDataNameString + ".to_dict()"; bp::dict outputDataSet = bp::extract<bp::dict>(bp::eval(createDictScript.c_str(), m_mainNamespace)); for (SQLUSMALLINT columnIndex = 0; columnIndex < columnNames.size(); columnIndex++) { bp::dict inputColumnToTest = bp::extract<bp::dict>(inputDataSet.get(columnNames[columnIndex])); bp::dict outputColumnToTest = bp::extract<bp::dict>(outputDataSet.get(columnNames[columnIndex])); for (bp::dict column : { inputColumnToTest, outputColumnToTest }) { CheckColumnEqualityFnMap::const_iterator it = sm_FnCheckColumnEqualityMap.find(dataType); if (it == sm_FnCheckColumnEqualityMap.end()) { throw runtime_error("Unsupported column type encountered when testing column equality"); } (this->*it->second)( rowsNumber, column, dataSet[columnIndex], strLen_or_Ind[columnIndex]); } } } catch (bp::error_already_set &) { string pyError = PythonTestUtilities::ParsePythonException(); throw runtime_error("Error running python:\n" + pyError); } } } }
33.37541
109
0.707599
rabryst
8a901568d5c97eeaf88f65673ea22adde7cd071a
33,700
hxx
C++
drivers/storage/wmiprov/inc/vs_debug.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/storage/wmiprov/inc/vs_debug.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/storage/wmiprov/inc/vs_debug.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1999 Microsoft Corporation Module Name: vs_debug.hxx Abstract: Various defines for general usage Author: Adi Oltean [aoltean] 07/09/1999 Revision History: Name Date Comments aoltean 07/09/1999 Created aoltean 08/11/1999 Adding throw specification aoltean 09/03/1999 Adding DuplicateXXX functions aoltean 09/09/1999 dss -> vss aoltean 09/20/1999 Adding ThrowIf, Err, Msg, MsgNoCR, etc. --*/ #ifndef __VSS_DEBUG_HXX__ #define __VSS_DEBUG_HXX__ #if _MSC_VER > 1000 #pragma once #endif //////////////////////////////////////////////////////////////////////// // Standard foo for file name aliasing. This code block must be after // all includes of VSS header files. // #ifdef VSS_FILE_ALIAS #undef VSS_FILE_ALIAS #endif #define VSS_FILE_ALIAS "INCDEBGH" // //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// // Global constants // // @const x_nVssMsgBufferSize | Maximum buffer size in Tracer operations const x_nVssMsgBufferSize = 512; const x_nVssNumericBufferSize = 30; const x_nVssGuidBufferSize = 60; const x_nVssMaxDebugArgs = 10; const WCHAR x_wszEventLogVssSourceName[] = L"VSS"; ///////////////////////////////////////////////////////////////////////////// // Declared classes // // // @class CVssFunctionTracer | This structure is used for tracing, debugging, treating HRESULTS // in a C++ function, especially a COM server method. // struct CVssDebugInfo { // Constructors& destructors private: CVssDebugInfo(); public: CVssDebugInfo( LPCWSTR wszFile, LPCSTR szFileAlias, // Five character alias, see file drivers\volsnap\filealias.xls for mappings ULONG ulLine, DWORD dwLevel, DWORD dwIndent = 0 ); CVssDebugInfo( const CVssDebugInfo& original ); ~CVssDebugInfo() ; // Operations public: // This is used to add an numeric-type argument CVssDebugInfo operator << ( IN INT nArgument ); // This is used to add an numeric-type argument. // It will be represented in hexadecimal format. CVssDebugInfo operator << ( IN HRESULT hrArgument ); // This is used to add an numeric-type argument. // It will be represented in hexadecimal format. CVssDebugInfo operator << ( IN LONGLONG llArgument ); // This is used to add an numeric-type argument. CVssDebugInfo operator << ( IN GUID hrArgument ); // This is used to add an string-type argument CVssDebugInfo operator << ( IN LPCWSTR wszArgument ); public: LPCWSTR m_wszFile; LPCSTR m_szFileAlias; ULONG m_ulLine; DWORD m_dwLevel; DWORD m_dwIndent; // Optional argument list LPWSTR m_ppwszStrings[x_nVssMaxDebugArgs]; WORD m_wNumStrings; bool m_bOutOfMemoryOccured; mutable bool m_bStringsOwnership; }; #define VSSDBG_COORD CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_COORD, 0) #define VSSDBG_SWPRV CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_SWPRV, 0) #define VSSDBG_TESTPRV CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_TESTPRV, 0) #define VSSDBG_VSSTEST CVssDebugInfo(__WFILE__, "TST--", __LINE__, DEBUG_TRACE_VSS_TEST, 0) #define VSSDBG_VSSDEMO CVssDebugInfo(__WFILE__, "TSD--", __LINE__, DEBUG_TRACE_VSS_DEMO, 0) #define VSSDBG_EXCEPT CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_CATCH_EXCEPTIONS, 0) #define VSSDBG_GEN CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_GEN, 0) #define VSSDBG_XML CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_XML, 0) #define VSSDBG_WRITER CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_WRITER, 0) #define VSSDBG_IOCTL CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_IOCTL, 0) #define VSSDBG_SHIM CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_SHIM, 0) #define VSSDBG_SQLLIB CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_SQLLIB, 0) #define VSSDBG_VSSADMIN CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_VSS_ADMIN, 0) #define VSSDBG_STSWRITER CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_STSWRITER, 0) #define VSSDBG_SQLWRITER CVssDebugInfo(__WFILE__, VSS_FILE_ALIAS, __LINE__, DEBUG_TRACE_SQLWRITER, 0) #define VSS_STANDARD_CATCH(FT) \ catch( HRESULT CaughtHr ) { \ FT.hr = CaughtHr; \ FT.Trace( VSSDBG_EXCEPT, L"HRESULT EXCEPTION CAUGHT: hr: 0x%x", FT.hr ); \ } \ catch( ... ) { \ FT.hr = E_UNEXPECTED; \ FT.Trace( VSSDBG_EXCEPT, L"UNKNOWN EXCEPTION CAUGHT, returning hr: 0x%x", FT.hr ); \ } // // @class CVssFunctionTracer | This class is used for tracing, debugging, treating HRESULTS // in a C++ function, especially a COM server method. // class CVssFunctionTracer { class CVssOutputBuffer { private: // Must be under 512 in order to make // the lookaside allocation algortihm work efficiently! enum { nVssMsgBufferSize = 400 }; WCHAR* m_pwszBuffer; public: CVssOutputBuffer() { m_pwszBuffer = new WCHAR[nVssMsgBufferSize + 1]; } ~CVssOutputBuffer() { delete m_pwszBuffer; } INT GetBufferSize() { return nVssMsgBufferSize; }; WCHAR * GetBuffer() { return m_pwszBuffer; }; bool IsBufferValid() { return (m_pwszBuffer != NULL); }; }; // Constructors and destructors private: CVssFunctionTracer(); CVssFunctionTracer(const CVssFunctionTracer&); public: CVssFunctionTracer( IN CVssDebugInfo dbgInfo, IN const WCHAR* pwszFunctionName ); ~CVssFunctionTracer(); // Attributes public: _declspec(property(get=GetHr,put=SetHr)) HRESULT hr; // Implementation inline HRESULT GetHr() { return m_hr; }; inline void SetHr( HRESULT hr ) { m_hr = hr; }; inline bool HrFailed() { return FAILED(m_hr); }; inline bool HrSucceeded() { return SUCCEEDED(m_hr); }; // Operations public: // // Traces. // void inline __cdecl Trace( CVssDebugInfo dbgInfo, const WCHAR* pwszMsgFormat, ...); void inline TraceBuffer( CVssDebugInfo dbgInfo, DWORD dwBufferSize, PBYTE pbBuffer ); void inline __cdecl Throw( CVssDebugInfo dbgInfo, // Caller debugging info HRESULT hrToBeThrown, // The new HR to be thrown const WCHAR* pwszMsgFormat, // Message that will be displayed if throw needed ... // Additional arguments ) throw(HRESULT); void inline __cdecl ThrowIf( BOOL bThrowNeeded, // Throw an HR if and only if bThrowNeeded is TRUE. CVssDebugInfo dbgInfo, // Caller debugging info HRESULT hrToBeThrown, // The new HR to be thrown const WCHAR* pwszMsgFormat, // Message that will be displayed if throw needed ... // Additional arguments ) throw(HRESULT); // // Messages displayed at the console (only for test and demo purpose). // void __cdecl Msg( const WCHAR* pwszMsgFormat, // Message that will be displayed ... ); void __cdecl MsgNoCR( const WCHAR* pwszMsgFormat, // Message that will be displayed ... ); void __cdecl Err( CVssDebugInfo dbgInfo, // Caller debugging info HRESULT hrToBeThrown, // The new HR to be thrown const WCHAR* pwszMsgFormat, // Error message that will be displayed ... ); // // Informative message boxes (only for test and demo purpose). // void __cdecl MsgBox( const WCHAR* pwszMsgTitle, // Title of the Message box const WCHAR* pwszMsgFormat, // Message that will be displayed ... ); void __cdecl ErrBox( CVssDebugInfo dbgInfo, // Caller debugging info HRESULT hrToBeThrown, // The new HR to be thrown const WCHAR* pwszMsgFormat, // Error message that will be displayed ... ); // Trace the corresponding COM error void TraceComError(); // Log the attempt of starting VSS void LogVssStartupAttempt(); // Put a new entry in the Error Log. void __cdecl LogError( IN DWORD dwEventID, // The ID of the event IN CVssDebugInfo dbgInfo, // Caller debugging info IN WORD wType = EVENTLOG_ERROR_TYPE // Entry type ); void __cdecl TranslateError( IN CVssDebugInfo dbgInfo, IN HRESULT hr, IN LPCWSTR wszRoutine ); void inline __cdecl CheckForError( IN CVssDebugInfo dbgInfo, IN LPCWSTR wszRoutine ) { if (HrFailed()) TranslateError(dbgInfo, m_hr, wszRoutine); } // check for an error on an internal call. Do not log E_UNEXPECTED // errors void inline __cdecl CheckForErrorInternal( IN CVssDebugInfo dbgInfo, IN LPCWSTR wszRoutine ) { if (HrFailed()) { if (m_hr == E_UNEXPECTED) throw E_UNEXPECTED; else TranslateError(dbgInfo, m_hr, wszRoutine); } } void __cdecl TranslateGenericError ( IN CVssDebugInfo dbgInfo, // Caller debugging info IN HRESULT hr, IN LPCWSTR wszErrorTextFormat, IN ... ); void __cdecl LogGenericWarning ( IN CVssDebugInfo dbgInfo, // Caller debugging info IN LPCWSTR wszErrorTextFormat, IN ... ); BOOL IsDuringSetup() { return g_cDbgTrace.IsDuringSetup(); }; BOOL IsInSoftwareProvider() { return m_dwLevel == DEBUG_TRACE_VSS_SWPRV; }; // // Calls CoCreate in a cycle and performs special logging // void CoCreateInstanceWithLog( IN CVssDebugInfo dbgInfo, // Caller debugging info IN CLSID ServerClassID, IN LPCWSTR ServerName, IN DWORD dwContext, IN IID InterfaceID, OUT IUnknown ** ppUnknown ); // Attributes public: HRESULT m_hr; // Internal Data private: const WCHAR* m_pwszFunctionName; LPCSTR m_szFileAlias; ULONG m_ulLine; DWORD m_dwLevel; // At entry time DWORD m_dwIndent; // At entry time }; /////////////////////////////////////////////////////////////////////////////////////// // Class implementations // /////////////////////////////////////////////////////////////////////////////////////// // CVssDebugInfo inline CVssDebugInfo::CVssDebugInfo( LPCWSTR wszFile, LPCSTR szFileAlias, ULONG ulLine, DWORD dwLevel, DWORD dwIndent ): m_wszFile(wszFile), m_szFileAlias(szFileAlias), m_ulLine(ulLine), m_dwIndent(dwIndent), m_dwLevel(dwLevel), m_wNumStrings(0), m_bOutOfMemoryOccured(false), m_bStringsOwnership(true) { for (WORD wIndex = 0; wIndex < x_nVssMaxDebugArgs; wIndex++) m_ppwszStrings[wIndex] = NULL; } inline CVssDebugInfo::CVssDebugInfo( const CVssDebugInfo& original ) { m_wszFile = original.m_wszFile; // We suppose that this is a constant string. m_szFileAlias = original.m_szFileAlias; // We suppose that this is a constant string. m_ulLine = original.m_ulLine; m_dwIndent = original.m_dwIndent; m_dwLevel = original.m_dwLevel; m_wNumStrings = original.m_wNumStrings; m_bOutOfMemoryOccured = original.m_bOutOfMemoryOccured; // Transfer the strings ownership. // This will work even if the ownership is already transferred m_bStringsOwnership = original.m_bStringsOwnership; original.m_bStringsOwnership = false; // Transfer the strings for (WORD wIndex = 0; wIndex < x_nVssMaxDebugArgs; wIndex++) m_ppwszStrings[wIndex] = original.m_ppwszStrings[wIndex]; } inline CVssDebugInfo::~CVssDebugInfo() { if (m_bStringsOwnership) { for (WORD wIndex = 0; wIndex < x_nVssMaxDebugArgs; wIndex++) { if ( m_ppwszStrings[wIndex] != NULL ) { ::CoTaskMemFree(m_ppwszStrings[wIndex]); m_ppwszStrings[wIndex] = NULL; } } } } // This is used to add an numeric-type argument inline CVssDebugInfo CVssDebugInfo::operator << ( IN INT nArgument ) { // Converting the number into a string WCHAR wszBuffer[x_nVssNumericBufferSize + 1]; ::_snwprintf(wszBuffer, x_nVssNumericBufferSize, L"%d", nArgument); return (*this) << wszBuffer; } // This is used to add an HRESULT-type argument inline CVssDebugInfo CVssDebugInfo::operator << ( IN HRESULT hrArgument ) { // Converting the number into a string WCHAR wszBuffer[x_nVssNumericBufferSize + 1]; ::_snwprintf(wszBuffer, x_nVssNumericBufferSize, L"0x%08lx", hrArgument); return (*this) << wszBuffer; } // This is used to add an LONGLONG-type argument inline CVssDebugInfo CVssDebugInfo::operator << ( IN LONGLONG llArgument ) { // Converting the number into a string WCHAR wszBuffer[x_nVssNumericBufferSize + 1]; ::_snwprintf(wszBuffer, x_nVssNumericBufferSize, WSTR_LONGLONG_FMT, LONGLONG_PRINTF_ARG(llArgument) ); return (*this) << wszBuffer; } // This is used to add an GUID-type argument inline CVssDebugInfo CVssDebugInfo::operator << ( IN GUID guidArgument ) { // Converting the number into a string WCHAR wszBuffer[x_nVssGuidBufferSize + 1]; ::_snwprintf(wszBuffer, x_nVssGuidBufferSize, WSTR_GUID_FMT, GUID_PRINTF_ARG(guidArgument)); return (*this) << wszBuffer; } // This is used to add an string-type argument inline CVssDebugInfo CVssDebugInfo::operator << ( IN LPCWSTR wszArgument ) { if (wszArgument == NULL) { BS_ASSERT(false); return (*this); } if (m_bOutOfMemoryOccured) return (*this); // We cannot add more strings if we do not have the ownership... if (!m_bStringsOwnership) { BS_ASSERT(false); return (*this); } if (m_wNumStrings >= x_nVssMaxDebugArgs) { BS_ASSERT(false); // Improper usage (putting too many arguments) return (*this); } // Storing into the actual list of arguments. We might have an allocation error here. LPWSTR wszFormattedValue = (LPWSTR)::CoTaskMemAlloc(sizeof(WCHAR)*(1 + ::wcslen(wszArgument))); if (wszFormattedValue == NULL) { m_bOutOfMemoryOccured = true; return (*this); } ::wcscpy(wszFormattedValue, wszArgument); m_ppwszStrings[m_wNumStrings++] = wszFormattedValue; return (*this); } /////////////////////////////////////////////////////////////////////////////////////// // CVssFunctionTracer inline CVssFunctionTracer::CVssFunctionTracer( IN CVssDebugInfo dbgInfo, IN const WCHAR* pwszFunctionName ) { m_hr = S_OK; m_pwszFunctionName = pwszFunctionName; m_szFileAlias = dbgInfo.m_szFileAlias; m_ulLine = dbgInfo.m_ulLine; m_dwLevel = dbgInfo.m_dwLevel; m_dwIndent = dbgInfo.m_dwIndent; if ( g_cDbgTrace.IsTracingEnabled() && g_cDbgTrace.GetTraceEnterExit() ) { g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, m_dwIndent, m_dwLevel, m_pwszFunctionName, TRUE ); // The reason that I not allow putting here custom-defined arguments is that // if the caller put wrong references it can easily generate an AV. // And, at this point, there is no NT exceptions treatment at the caller side. g_cDbgTrace.PrintEnterExit(L""); g_cDbgTrace.PostPrint( m_dwIndent ); } } inline CVssFunctionTracer::~CVssFunctionTracer() { if ( g_cDbgTrace.IsTracingEnabled() && g_cDbgTrace.GetTraceEnterExit() ) { g_cDbgTrace.PrePrint( L"", 0UL, m_dwIndent, m_dwLevel, m_pwszFunctionName, FALSE ); g_cDbgTrace.PrintEnterExit(L"hr: 0x%08x", m_hr); g_cDbgTrace.PostPrint( m_dwIndent ); } } void inline __cdecl CVssFunctionTracer::Trace( CVssDebugInfo dbgInfo, const WCHAR* pwszMsgFormat, ...) // WARNING: This function do NOT clear the ft.hr field! { if ( !g_cDbgTrace.IsTracingEnabled() ) return; CVssOutputBuffer buffer; if (buffer.IsBufferValid()) { va_list marker; va_start( marker, pwszMsgFormat ); _vsnwprintf( buffer.GetBuffer(), buffer.GetBufferSize(), pwszMsgFormat, marker ); va_end( marker ); g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, dbgInfo.m_dwIndent, dbgInfo.m_dwLevel ); g_cDbgTrace.Print( L"%s: %s", m_pwszFunctionName, buffer.GetBuffer() ); g_cDbgTrace.PostPrint( dbgInfo.m_dwIndent ); } }; void inline CVssFunctionTracer::TraceBuffer( CVssDebugInfo dbgInfo, DWORD dwBufferSize, PBYTE pbBuffer ) { // WARNING: This function do NOT clear the ft.hr field! if ( !g_cDbgTrace.IsTracingEnabled() ) return; const nBytesPerSubgroup = 4; const nSubgroupsPerGroup = 2; const nGroupsCount = 2; const nSubgroupSize = 3*nBytesPerSubgroup + 1; // Add a space between subgroups const nGroupSize = nSubgroupSize*nSubgroupsPerGroup + 1; // Add a space between groups const nLineSize = nGroupSize*nGroupsCount + 1; // Add the zero character. WCHAR wszPrintedBufferLine[nLineSize]; WCHAR wszPrintedBufferLineInChr[nLineSize]; WCHAR wszDigits[] = L"0123456789ABCDEF"; // Print each line for (DWORD dwBufferOffset = 0; dwBufferOffset < dwBufferSize; ) { int nLineOffset = 0; int nLineOffsetChr = 0; // Print each group in the line for (int nGroupIndex = 0; nGroupIndex < nGroupsCount; nGroupIndex++) { // Print each subgroup in the group for (int nSubgroupIndex = 0; nSubgroupIndex < nSubgroupsPerGroup; nSubgroupIndex++) { // Print each byte in the subgroup for (int nByteIndex = 0; nByteIndex < nBytesPerSubgroup; nByteIndex++) { if (dwBufferOffset < dwBufferSize) { BYTE bChar = pbBuffer[dwBufferOffset]; wszPrintedBufferLineInChr[nLineOffsetChr++] = ( bChar >= 0x20 && bChar < 0x7F )? (WCHAR)bChar: L'.'; wszPrintedBufferLine[nLineOffset++] = wszDigits[pbBuffer[dwBufferOffset] / 0x10]; wszPrintedBufferLine[nLineOffset++] = wszDigits[pbBuffer[dwBufferOffset++] % 0x10]; wszPrintedBufferLine[nLineOffset++] = L' '; // Print an additional space after each group } else { wszPrintedBufferLineInChr[nLineOffsetChr++] = L'#'; wszPrintedBufferLine[nLineOffset++] = L'#'; wszPrintedBufferLine[nLineOffset++] = L'#'; wszPrintedBufferLine[nLineOffset++] = L' '; // Print an additional space after each group } } wszPrintedBufferLine[nLineOffset++] = L' '; // Print a space after each subgroup } wszPrintedBufferLine[nLineOffset++] = L' '; // Print an additional space after each group } // Put hte termination characters wszPrintedBufferLineInChr[nLineOffsetChr++] = L'\0'; wszPrintedBufferLine[nLineOffset++] = L'\0'; BS_ASSERT( nLineOffset == nLineSize ); g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, dbgInfo.m_dwIndent, dbgInfo.m_dwLevel ); g_cDbgTrace.Print( L"%s %s", wszPrintedBufferLine, wszPrintedBufferLineInChr ); g_cDbgTrace.PostPrint( dbgInfo.m_dwIndent ); } }; void inline __cdecl CVssFunctionTracer::Throw( CVssDebugInfo dbgInfo, // Caller debugging info HRESULT hrToBeThrown, // The new HR to be thrown const WCHAR* pwszMsgFormat, // Message that will be displayed if throw needed ... // Additional arguments ) throw(HRESULT) { if ( g_cDbgTrace.IsTracingEnabled() ) { if (pwszMsgFormat != NULL) { CVssOutputBuffer buffer; if (buffer.IsBufferValid()) { va_list marker; va_start( marker, pwszMsgFormat ); _vsnwprintf( buffer.GetBuffer(), buffer.GetBufferSize(), pwszMsgFormat, marker ); va_end( marker ); g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, dbgInfo.m_dwIndent, dbgInfo.m_dwLevel ); g_cDbgTrace.Print( L"%s: %s", m_pwszFunctionName, buffer.GetBuffer() ); g_cDbgTrace.PostPrint( dbgInfo.m_dwIndent ); } } g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, dbgInfo.m_dwIndent, DEBUG_TRACE_CATCH_EXCEPTIONS ); g_cDbgTrace.Print( L"%s: Throwing HRESULT code 0x%08lx. " L"Previous HRESULT code = 0x%08lx", m_pwszFunctionName, hrToBeThrown, m_hr ); g_cDbgTrace.PostPrint( DEBUG_TRACE_CATCH_EXCEPTIONS ); } m_hr = hrToBeThrown; throw( ( HRESULT )m_hr ); }; void inline __cdecl CVssFunctionTracer::ThrowIf( BOOL bThrowNeeded, // Throw an HR if and only if bThrowNeeded is TRUE. CVssDebugInfo dbgInfo, // Caller debugging info HRESULT hrToBeThrown, // The new HR to be thrown const WCHAR* pwszMsgFormat, // Message that will be displayed if throw needed ... // Additional arguments ) throw(HRESULT) // WARNING: This function clears the ft.hr field if no errors ! // Also if bThrowNeeded == false then the m_hr is reset to S_OK ! { if (!bThrowNeeded) { m_hr = S_OK; return; } if ( g_cDbgTrace.IsTracingEnabled() ) { if (pwszMsgFormat != NULL) { CVssOutputBuffer buffer; if (buffer.IsBufferValid()) { va_list marker; va_start( marker, pwszMsgFormat ); _vsnwprintf( buffer.GetBuffer(), buffer.GetBufferSize(), pwszMsgFormat, marker ); va_end( marker ); g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, dbgInfo.m_dwIndent, dbgInfo.m_dwLevel ); g_cDbgTrace.Print( L"%s: %s", m_pwszFunctionName, buffer.GetBuffer() ); g_cDbgTrace.PostPrint( dbgInfo.m_dwIndent ); } } g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, dbgInfo.m_dwIndent, DEBUG_TRACE_CATCH_EXCEPTIONS ); g_cDbgTrace.Print( L"%s: %s HRESULT code 0x%08lx. " L"Previous HRESULT code = 0x%08lx", bThrowNeeded? L"Throwing": L"Tracing", m_pwszFunctionName, hrToBeThrown, m_hr ); g_cDbgTrace.PostPrint( DEBUG_TRACE_CATCH_EXCEPTIONS ); } m_hr = hrToBeThrown; throw( ( HRESULT )m_hr ); }; // // Messages displayed at the console (only for test and demo purpose). // void inline __cdecl CVssFunctionTracer::Msg( const WCHAR* pwszMsgFormat, // Message that will be displayed ... ) { USES_CONVERSION; _ASSERTE(pwszMsgFormat); CVssOutputBuffer buffer; if (buffer.IsBufferValid()) { va_list marker; va_start( marker, pwszMsgFormat ); _vsnwprintf( buffer.GetBuffer(), buffer.GetBufferSize(), pwszMsgFormat, marker ); va_end( marker ); wprintf( L"%s\n", W2CT(buffer.GetBuffer()) ); } } void inline __cdecl CVssFunctionTracer::MsgNoCR( const WCHAR* pwszMsgFormat, // Message that will be displayed ... ) { USES_CONVERSION; _ASSERTE(pwszMsgFormat); CVssOutputBuffer buffer; if (buffer.IsBufferValid()) { va_list marker; va_start( marker, pwszMsgFormat ); _vsnwprintf( buffer.GetBuffer(), buffer.GetBufferSize(), pwszMsgFormat, marker ); va_end( marker ); wprintf( L"%s", W2CT(buffer.GetBuffer()) ); } } void inline __cdecl CVssFunctionTracer::Err( CVssDebugInfo dbgInfo, // Caller debugging info HRESULT hrToBeThrown, // The new HR to be thrown const WCHAR* pwszMsgFormat, // Error message that will be displayed ... ) { USES_CONVERSION; _ASSERTE(pwszMsgFormat); CVssOutputBuffer buffer; if (buffer.IsBufferValid()) { va_list marker; va_start( marker, pwszMsgFormat ); _vsnwprintf( buffer.GetBuffer(), buffer.GetBufferSize(), pwszMsgFormat, marker ); va_end( marker ); // Message box CVssOutputBuffer buffer2; if (!buffer2.IsBufferValid()) throw(E_OUTOFMEMORY); _snwprintf(buffer2.GetBuffer(), buffer2.GetBufferSize(), L"%s(%ld)\n%s @ [%08lx,%08lx], PID=%ld, TID=%ld\n%s", dbgInfo.m_wszFile, dbgInfo.m_ulLine, m_pwszFunctionName, dbgInfo.m_dwIndent, dbgInfo.m_dwLevel, GetCurrentProcessId(), GetCurrentThreadId(), buffer.GetBuffer() ); ::MessageBoxW( NULL, buffer2.GetBuffer(), L"Error", MB_OK); if ( g_cDbgTrace.IsTracingEnabled() ) { g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, dbgInfo.m_dwIndent, dbgInfo.m_dwLevel ); g_cDbgTrace.Print( L"%s: %s", m_pwszFunctionName, buffer2.GetBuffer() ); g_cDbgTrace.PostPrint( dbgInfo.m_dwIndent ); } wprintf( L"Error: %s\n", W2CT(buffer2.GetBuffer()) ); } if (hrToBeThrown) { m_hr = hrToBeThrown; throw( ( HRESULT )m_hr ); } } // // Informative message boxes (only for test and demo purpose). // void inline __cdecl CVssFunctionTracer::MsgBox( const WCHAR* pwszMsgTitle, // Title of the Message box const WCHAR* pwszMsgFormat, // Message that will be displayed ... ) { USES_CONVERSION; _ASSERTE(pwszMsgTitle); _ASSERTE(pwszMsgFormat); CVssOutputBuffer buffer; if (buffer.IsBufferValid()) { va_list marker; va_start( marker, pwszMsgFormat ); _vsnwprintf( buffer.GetBuffer(), buffer.GetBufferSize(), pwszMsgFormat, marker ); va_end( marker ); ::MessageBox(NULL, W2CT(buffer.GetBuffer()), W2CT(pwszMsgTitle), MB_OK); } } void inline __cdecl CVssFunctionTracer::ErrBox( CVssDebugInfo dbgInfo, // Caller debugging info HRESULT hrToBeThrown, // The new HR to be thrown const WCHAR* pwszMsgFormat, // Error message that will be displayed ... ) { USES_CONVERSION; _ASSERTE(pwszMsgFormat); CVssOutputBuffer buffer; if (buffer.IsBufferValid()) { va_list marker; va_start( marker, pwszMsgFormat ); _vsnwprintf( buffer.GetBuffer(), buffer.GetBufferSize(), pwszMsgFormat, marker ); va_end( marker ); if ( g_cDbgTrace.IsTracingEnabled() ) { g_cDbgTrace.PrePrint( dbgInfo.m_wszFile, dbgInfo.m_ulLine, dbgInfo.m_dwIndent, dbgInfo.m_dwLevel ); g_cDbgTrace.Print( L"%s: %s", m_pwszFunctionName, buffer.GetBuffer() ); g_cDbgTrace.PostPrint( dbgInfo.m_dwIndent ); } ::MessageBox(NULL, W2CT(buffer.GetBuffer()), L"Error", MB_OK); } if (hrToBeThrown) { m_hr = hrToBeThrown; throw( ( HRESULT )m_hr ); } } /*++ Routine Description: Traces the COM error description. Can be called after automation COM calls (for example XML or COM+ related) --*/ void inline CVssFunctionTracer::TraceComError() { CVssFunctionTracer ft(VSSDBG_GEN, L"CVssFunctionTracer::TraceComError"); CComPtr<IErrorInfo> pErrorInfo; HRESULT hr2 = ::GetErrorInfo(0, &pErrorInfo); if (SUCCEEDED(hr2)) { if (pErrorInfo != NULL) { BSTR bstrDescription; HRESULT hr3 = pErrorInfo->GetDescription(&bstrDescription); if (SUCCEEDED(hr3)) { ft.Trace(VSSDBG_GEN, L"Error info description: %s", bstrDescription); ::SysFreeString(bstrDescription); } else ft.Trace(VSSDBG_GEN, L"Warning: Error getting error description = 0x%08lx", hr3); } } else ft.Trace(VSSDBG_GEN, L"Warning: Error getting error info = 0x%08lx", hr2); } void inline __cdecl CVssFunctionTracer::LogError( IN DWORD dwEventID, // The ID of the event IN CVssDebugInfo dbgInfo, // Caller debugging info IN WORD wType // By default it is EVENTLOG_ERROR_TYPE ) { CVssFunctionTracer ft(VSSDBG_GEN, L"CVssFunctionTracer::LogError"); try { LPCWSTR ppwszStrings[x_nVssMaxDebugArgs]; CHAR szFileLine[32]; CHAR szTemp[34]; // Max length of string from _ultoa() // Create the four lines of binary data output in the data section of the event log message. // First the Caller debugging info: ::strncpy( szFileLine, dbgInfo.m_szFileAlias, 8 ); ::_ultoa( dbgInfo.m_ulLine, szTemp, 10 ); ::strncpy( szFileLine + 8, szTemp, 8 ); // strncpy has the nice property of zeroing out unuse chars. // Now info on the ft at point of construction: ::strncpy( szFileLine + 16, m_szFileAlias, 8 ); ::_ultoa( m_ulLine, szTemp, 10 ); ::strncpy( szFileLine + 24, szTemp, 8 ); // strncpy has the nice property of zeroing out unuse chars. // Fill out the strings that are given as arguments WORD wNumStrings = dbgInfo.m_wNumStrings; for( WORD wIndex = 0; wIndex < dbgInfo.m_wNumStrings; wIndex++ ) ppwszStrings[wIndex] = const_cast<LPCWSTR>(dbgInfo.m_ppwszStrings[wIndex]); // Get a handle to use with ReportEvent() HANDLE hEventSource = ::RegisterEventSourceW( NULL, // IN LPCWSTR lpUNCServerName, x_wszEventLogVssSourceName // IN LPCWSTR lpSourceName ); if (hEventSource == NULL) ft.Throw( VSSDBG_SHIM, E_UNEXPECTED, L"Error on RegisterEventSourceW 0x%08lx", GetLastError()); // Write to event log. BOOL bRet = ::ReportEventW( hEventSource, // IN HANDLE hEventLog, wType, // IN WORD wType, 0, // IN WORD wCategory, dwEventID, // IN DWORD dwEventID, NULL, // IN PSID lpUserSid, wNumStrings, // IN WORD wNumStrings, sizeof( szFileLine ), // IN DWORD dwDataSize, ppwszStrings, // IN LPCWSTR *lpStrings, szFileLine // IN LPVOID lpRawData ); if ( !bRet ) ft.Trace( VSSDBG_SHIM, L"Error on ReportEventW 0x%08lx", GetLastError()); // Close the handle to the event log bRet = ::DeregisterEventSource( hEventSource ); if ( !bRet ) ft.Throw( VSSDBG_SHIM, E_UNEXPECTED, L"Error on DeregisterEventSource 0x%08lx", GetLastError()); } VSS_STANDARD_CATCH(ft) } // // Set the file alias to unknown in case a module doesn't set it's alias. // #undef VSS_FILE_ALIAS #define VSS_FILE_ALIAS "UNKNOWN" #endif // __VSS_DEBUG_HXX__
34.213198
119
0.584214
npocmaka
8a90ed4298270d1b4f2c9bb389450478c301a050
407
cpp
C++
codes/21fall/hw02/素数和.cpp
OneForward/TACpp
4dab30b9ac174cf1a73166ae60385377c6ad18ab
[ "MIT" ]
7
2020-09-17T04:48:18.000Z
2021-11-17T08:57:25.000Z
codes/21fall/hw02/素数和.cpp
OneForward/TACpp
4dab30b9ac174cf1a73166ae60385377c6ad18ab
[ "MIT" ]
1
2021-11-01T11:55:52.000Z
2021-11-01T12:39:58.000Z
codes/21fall/hw02/素数和.cpp
OneForward/TACpp
4dab30b9ac174cf1a73166ae60385377c6ad18ab
[ "MIT" ]
8
2020-09-18T01:10:12.000Z
2021-05-15T12:57:23.000Z
#include <iostream> using namespace std; int main() { int n, k; cin >> n >> k; int sum = 0; for(int x = n; k and x >= 2; x--) { bool isprime = true; for(int i = 2; i * i <= x; i++) if(x % i == 0) { isprime = false; break; } if (isprime) { k--; sum += x; cout << x << " "; } } cout << sum; return 0; }
18.5
54
0.375921
OneForward
8a945dfae0f130f1327ae1476642b45a88b5c71a
597
hpp
C++
include/epiworld/location-bones.hpp
gvegayon/world-epi
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
[ "MIT" ]
null
null
null
include/epiworld/location-bones.hpp
gvegayon/world-epi
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
[ "MIT" ]
null
null
null
include/epiworld/location-bones.hpp
gvegayon/world-epi
197d8cc0e8fb86c06ec1ac2df6316e89d4857218
[ "MIT" ]
null
null
null
#ifndef EPIWORLD_LOCATION_BONES_HPP #define EPIWORLD_LOCATION_BONES_HPP template<typename TSeq> class Person; template<typename TSeq> class Location { private: int capacity; std::string location_name; int id; std::vector< Person<TSeq> * >; /** * @brief Spatial location parameters * */ ///@{ epiworld_double longitude = 0.0; epiworld_double latitude = 0.0; epiworld_double altitude = 0.0; ///@} public: add_person(Person<TSeq> & p); add_person(Person<TSeq> * p); size_t count() const; void reset(); }; #endif
15.710526
41
0.633166
gvegayon
8a9956eff87be835e571772d340ff7e33734c2a5
2,684
cpp
C++
jni/FPSCounter.cpp
vladiant/Android-Camera-Native-Processor
77ed523ee2ead146cab6c2fd963d0a2982d3804f
[ "Apache-2.0" ]
1
2015-08-24T01:18:54.000Z
2015-08-24T01:18:54.000Z
jni/FPSCounter.cpp
vladiant/Android-Camera-Native-Processor
77ed523ee2ead146cab6c2fd963d0a2982d3804f
[ "Apache-2.0" ]
null
null
null
jni/FPSCounter.cpp
vladiant/Android-Camera-Native-Processor
77ed523ee2ead146cab6c2fd963d0a2982d3804f
[ "Apache-2.0" ]
null
null
null
#include "FPSCounter.h" #include <time.h> //#define DEBUG 1 #define FPSCOUNTER_LOG_TAG "QCCommon:FPSCounter" #ifdef DEBUG #include <android/log.h> #define DPRINTF(...) \ __android_log_print(ANDROID_LOG_DEBUG, FPSCOUNTER_LOG_TAG, __VA_ARGS__) #else #define DPRINTF(...) // noop \ #endif #define IPRINTF(...) \ __android_log_print(ANDROID_LOG_INFO, FPSCOUNTER_LOG_TAG, __VA_ARGS__) #define EPRINTF(...) \ __android_log_print(ANDROID_LOG_ERROR, FPSCOUNTER_LOG_TAG, __VA_ARGS__) #define WPRINTF(...) \ __android_log_print(ANDROID_LOG_WARN, FPSCOUNTER_LOG_TAG, __VA_ARGS__) //------------------------------------------------------------------------------ /// @brief Default constructor //------------------------------------------------------------------------------ FPSCounter::FPSCounter() { DPRINTF("FPSCounter::FPSCounter"); Reset(); } //------------------------------------------------------------------------------ /// @brief to be called every frame to update the fps count //------------------------------------------------------------------------------ void FPSCounter::FrameTick() { DPRINTF("FPSCounter::FrameTick"); struct timeval tv; struct timezone tz; uint64_t curTime; gettimeofday(&tv, &tz); curTime = tv.tv_sec * SECOND + tv.tv_usec; if (curTime - mLastTime > 10 * SECOND) { Reset(); } else { //Increament frame count mFrameCount++; // Calculate seconds elapsed since start. float sec = (float) (curTime - mStartTime) / (float) SECOND; if (sec > 0.0) { mFPS = (float) (mFrameCount) / sec; sec = (float) (curTime - mLastTime) / (float) SECOND; if (sec > 0.0) { if (mSecIIR > 0.0) { //TODO: Define constants for filter coefficient mSecIIR = (sec + (29.0 * mSecIIR)) / (float) 30.0; } else { mSecIIR = sec; } } } mLastTime = curTime; mFilteredFPS = mSecIIR > 0.0 ? 1 / mSecIIR : -1.0; } } //------------------------------------------------------------------------------ /// @brief resets the timer and frames //------------------------------------------------------------------------------ void FPSCounter::Reset() { struct timeval tv; struct timezone tz; gettimeofday(&tv, &tz); mStartTime = tv.tv_sec * SECOND + tv.tv_usec; mLastTime = mStartTime; mFrameCount = 0; mSecIIR = 0.; mFPS = 0.; mFilteredFPS = 0.; } //------------------------------------------------------------------------------ /// @brief Default destructor //------------------------------------------------------------------------------ FPSCounter::~FPSCounter() { DPRINTF("FPSCounter::~FPSCounter"); }
27.387755
81
0.488823
vladiant
8a9aa8c94318b73d946dbf800a0ef68190903bbb
927
cpp
C++
cf/ac/1454C.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
cf/ac/1454C.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
cf/ac/1454C.cpp
vitorgt/problem-solving
11fa59de808f7a113c08454b4aca68b01410892e
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int INF = 0x3f3f3f3f; int main(int argc, const char **argv) { std::ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL); int t = 0, n = 0, a = 0, a_prev = 0, first = 0; unordered_map<int, int> breaks; cin >> t; while (t--) { breaks.clear(); cin >> n >> first; n--; a = first; a_prev = first; while (n--) { cin >> a; if (a != a_prev) breaks[a]++; a_prev = a; } if (breaks.find(first) == breaks.end()) breaks[first] = 0; for (auto b : breaks) if (b.first != a) breaks[b.first]++; a_prev = INF; for (auto b : breaks) if (b.second < a_prev) a_prev = b.second; cout << (a_prev == INF ? 0 : a_prev) << endl; } return 0; }
21.55814
68
0.443366
vitorgt
8a9b291b2f30699d3bcdcdaa174f261c14649e18
9,635
cpp
C++
source/xml/XmlParser.cpp
fmidev/smartmet-plugin-wcs
60aee4d3ef9d2bba5de44b4a871f669fc1b47d08
[ "MIT" ]
null
null
null
source/xml/XmlParser.cpp
fmidev/smartmet-plugin-wcs
60aee4d3ef9d2bba5de44b4a871f669fc1b47d08
[ "MIT" ]
8
2017-04-07T13:14:46.000Z
2018-04-25T08:04:22.000Z
source/xml/XmlParser.cpp
fmidev/smartmet-plugin-wcs
60aee4d3ef9d2bba5de44b4a871f669fc1b47d08
[ "MIT" ]
1
2017-06-03T19:07:22.000Z
2017-06-03T19:07:22.000Z
#include "xml/XmlParser.h" #include "xml/XmlUtils.h" #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/filesystem.hpp> #include <boost/serialization/map.hpp> #include <curl/curl.h> #include <macgyver/TypeName.h> #include <xercesc/framework/LocalFileInputSource.hpp> #include <xercesc/framework/MemBufInputSource.hpp> #include <xercesc/framework/XMLGrammarPoolImpl.hpp> #include <xercesc/sax/ErrorHandler.hpp> #include <xercesc/sax/SAXParseException.hpp> #include <xercesc/util/BinFileInputStream.hpp> #include <xercesc/util/Janitor.hpp> #include <xercesc/util/XMLEntityResolver.hpp> #include <cerrno> #include <fstream> #include <iostream> #include <sstream> #include <stdexcept> #include <string> namespace SmartMet { namespace Plugin { namespace WCS { namespace Xml { namespace fs = boost::filesystem; Parser::Parser(bool stop_on_error, xercesc::XMLGrammarPool *grammar_pool) : xercesc::XercesDOMParser(nullptr, xercesc::XMLPlatformUtils::fgMemoryManager, grammar_pool), error_handler(new XmlErrorHandler(stop_on_error)) { // Enable XML namespace handling setDoNamespaces(true); // Always do schema validation setValidationScheme(xercesc::XercesDOMParser::Val_Always); // Do not continue on fatal error setExitOnFirstFatalError(true); // setValidationConstraintFatal(true); setDoSchema(true); setLoadSchema(true); setHandleMultipleImports(true); // Do not parse schemas each time but keep already parsed schemas // from earlier parsed XML documents. This is much faster useCachedGrammarInParse(true); // Cannot save grammars to locked pool // cacheGrammarFromParse(true); setErrorHandler(error_handler.get()); } Parser::~Parser() {} boost::shared_ptr<xercesc::DOMDocument> Parser::parse_file( const std::string &file_name, Parser::root_element_cb_t root_element_cb) { xercesc::Janitor<XMLCh> fn(xercesc::XMLString::transcode(file_name.c_str())); xercesc::LocalFileInputSource input(fn.get()); return parse_input(input, root_element_cb); } boost::shared_ptr<xercesc::DOMDocument> Parser::parse_string( const std::string &xml_data, const std::string &doc_id, Parser::root_element_cb_t root_element_cb) { xercesc::MemBufInputSource input( (const XMLByte *)xml_data.c_str(), xml_data.length(), doc_id.c_str()); return parse_input(input, root_element_cb); } boost::shared_ptr<xercesc::DOMDocument> Parser::parse_input( xercesc::InputSource &input, Parser::root_element_cb_t root_element_cb) { error_handler->resetErrors(); try { this->root_element_cb = root_element_cb; this->parse(input); } catch (XmlError &error) // cannot be const { // Add messages to the exception object if an exception // has been thrown while parsing and messages are not yet added if (error.get_messages().empty()) { error.add_messages(error_handler->get_messages()); } throw; } // Verify that there are no errors. Throw an exception otherwise error_handler->check_errors("XML parser failed"); boost::shared_ptr<xercesc::DOMDocument> result(this->adoptDocument()); return result; } std::list<std::string> Parser::get_messages() const { return error_handler->get_messages(); } void Parser::startElement(const xercesc::XMLElementDecl &elemDecl, const unsigned int uriId, const XMLCh *const prefixName, const xercesc::RefVectorOf<xercesc::XMLAttr> &attrList, const XMLSize_t attrCount, const bool isEmpty, const bool isRoot) { if (isRoot) { using Xml::to_string; RootElemInfo root_info; const auto *qname = elemDecl.getElementName(); root_info.prefix = to_string(prefixName); // qname->getPrefix()); root_info.nqname = to_string(qname->getLocalPart()); const std::string name = (root_info.prefix == "" ? std::string("") : root_info.prefix + ":") + root_info.nqname; for (int i = 0; i < (int)attrCount; i++) { const xercesc::XMLAttr *attr = attrList.elementAt(i); const std::string attr_name = to_string(attr->getQName()); const std::string attr_value = to_string(attr->getValue()); root_info.attr_map[attr_name] = attr_value; } std::string xmlns_name = std::string("xmlns"); if (root_info.prefix != "") xmlns_name = xmlns_name + ":" + root_info.prefix; // std::cout << "@@@ name='" << name << "'\n" // << "@@@ local_name='" << root_info.nqname << "'\n" // << "@@@ base_name='" << to_string(elemDecl.getBaseName()) << "'\n" // << "@@@ prefix='" << root_info.prefix << "'\n" // << "@@@ xmlns attr name='" << xmlns_name << "'" << std::endl; if (root_info.attr_map.count(xmlns_name) > 0 and root_element_cb) { root_info.ns_uri = root_info.attr_map[xmlns_name]; root_element_cb(root_info); } } inherited::startElement(elemDecl, uriId, prefixName, attrList, attrCount, isEmpty, isRoot); } class ParserMT::EntityResolver : public xercesc::XMLEntityResolver { std::map<std::string, std::string> cache; public: EntityResolver() {} virtual ~EntityResolver() {} virtual xercesc::InputSource *resolveEntity(xercesc::XMLResourceIdentifier *resource_identifier) { const XMLCh *x_public_id = resource_identifier->getPublicId(); const XMLCh *x_system_id = resource_identifier->getSystemId(); const XMLCh *x_base_uri = resource_identifier->getBaseURI(); const std::string public_id = to_opt_string(x_public_id).first; const std::string system_id = to_opt_string(x_system_id).first; const std::string base_uri = to_opt_string(x_base_uri).first; std::string remote_uri; if (is_url(system_id)) { remote_uri = system_id; } else if (system_id == "") { return nullptr; } else if ((*system_id.begin() == '/') or (*base_uri.begin() == '/')) { return new xercesc::LocalFileInputSource(x_base_uri, x_system_id); } else { std::size_t pos = base_uri.find_last_of("/"); if (pos == std::string::npos) return nullptr; remote_uri = base_uri.substr(0, pos + 1) + system_id; } if (cache.count(remote_uri)) { const std::string &src = cache.at(remote_uri); std::size_t len = src.length(); char *data = new char[len + 1]; memcpy(data, src.c_str(), len + 1); xercesc::Janitor<XMLCh> x_remote_id(xercesc::XMLString::transcode(remote_uri.c_str())); return new xercesc::MemBufInputSource( reinterpret_cast<XMLByte *>(data), len, x_remote_id.get(), true /* adopt buffer */); } else { return nullptr; } } template <class Archive> void serialize(Archive &ar, const unsigned int version) { (void)version; ar &BOOST_SERIALIZATION_NVP(cache); } bool is_url(const std::string &str) { return (str.substr(0, 7) == "http://") or (str.substr(0, 8) == "https://"); } }; ParserMT::ParserMT(const std::string &grammar_pool_file_name, bool stop_on_error) : grammar_pool_file_name(grammar_pool_file_name), stop_on_error(stop_on_error) { grammar_pool.reset(new xercesc::XMLGrammarPoolImpl); try { xercesc::BinFileInputStream input(grammar_pool_file_name.c_str()); grammar_pool->deserializeGrammars(&input); grammar_pool->lockPool(); } catch (const xercesc::XMLException &err) { std::cerr << METHOD_NAME << ": failed to read Xerces-C grammar pool dump file '" << grammar_pool_file_name << "': C++ exception type is '" << Fmi::get_type_name(&err) << "', message '" << to_opt_string(err.getMessage()).first << "'" << std::endl; throw; } } ParserMT::~ParserMT() {} Parser *ParserMT::get() { Parser *parser = t_parser.get(); if (parser == nullptr) { t_parser.reset(new Parser(stop_on_error, grammar_pool.get())); parser = t_parser.get(); } if (entity_resolver and not parser->getXMLEntityResolver()) parser->setXMLEntityResolver(entity_resolver.get()); return parser; } void ParserMT::load_schema_cache(const std::string &file_name) { std::ifstream input; input.exceptions(std::ios::failbit | std::ios::badbit); input.open(file_name.c_str()); boost::archive::text_iarchive ia(input); std::unique_ptr<EntityResolver> tmp(new EntityResolver); ia >> *tmp; this->entity_resolver.swap(tmp); } boost::shared_ptr<xercesc::DOMDocument> str2xmldom(const std::string &src, const std::string &doc_id) { xercesc::XercesDOMParser parser; XmlErrorHandler error_handler(true); parser.setDoNamespaces(true); parser.setValidationScheme(xercesc::XercesDOMParser::Val_Never); // parser.setExitOnFirstFatalError(true); parser.setErrorHandler(&error_handler); xercesc::MemBufInputSource input((const XMLByte *)src.c_str(), src.length(), doc_id.c_str()); try { parser.parse(input); } catch (XmlError &error) // cannot be const { // Add messages to the exception object if an exception // has been thrown while parsing and messages are not yet added if (error.get_messages().empty()) { error.add_messages(error_handler.get_messages()); } throw; } // Verify that parse suceeded and throw XmlError otherwise error_handler.check_errors("XML parser failed"); boost::shared_ptr<xercesc::DOMDocument> result(parser.adoptDocument()); return result; } } // namespace Xml } // namespace WCS } // namespace Plugin } // namespace SmartMet
30.782748
99
0.677426
fmidev
8a9dba15b91951c2a56486d36a5d2695ef2f2944
244
cpp
C++
fillingdiamonds.cpp
AaryamanBhardwaj/Codeforces-Solutions
d33c75bfa493b16a3c1dfc67e52b578a40872199
[ "MIT" ]
1
2021-04-29T20:06:55.000Z
2021-04-29T20:06:55.000Z
fillingdiamonds.cpp
AaryamanBhardwaj/Competitive-Programming-Solutions
d33c75bfa493b16a3c1dfc67e52b578a40872199
[ "MIT" ]
null
null
null
fillingdiamonds.cpp
AaryamanBhardwaj/Competitive-Programming-Solutions
d33c75bfa493b16a3c1dfc67e52b578a40872199
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio; cin.tie(NULL); cout.tie(NULL); int t,n; cin>>t; for(int i=0;i<t;i++) { cin>>n; cout<<n<<endl; } }
16.266667
31
0.479508
AaryamanBhardwaj
8a9fd895102be4df8c040ea685638f258ca9db5c
9,535
cc
C++
pdf/fading_controls.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
pdf/fading_controls.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
pdf/fading_controls.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.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 "pdf/fading_controls.h" #include "base/logging.h" #include "base/stl_util.h" #include "pdf/draw_utils.h" #include "pdf/resource_consts.h" #include "ppapi/cpp/input_event.h" namespace chrome_pdf { const uint32 kFadingAlphaShift = 64; const uint32 kSplashFadingAlphaShift = 16; FadingControls::FadingControls() : state_(NONE), current_transparency_(kOpaqueAlpha), fading_timer_id_(0), current_capture_control_(kInvalidControlId), fading_timeout_(kFadingTimeoutMs), alpha_shift_(kFadingAlphaShift), splash_(false), splash_timeout_(0) { } FadingControls::~FadingControls() { STLDeleteElements(&controls_); } bool FadingControls::CreateFadingControls( uint32 id, const pp::Rect& rc, bool visible, Control::Owner* owner, uint8 transparency) { current_transparency_ = transparency; return Control::Create(id, rc, visible, owner); } void FadingControls::Paint(pp::ImageData* image_data, const pp::Rect& rc) { // When this control is set to invisible the individual controls are not. // So we need to check for visible() here. if (!visible()) return; std::list<Control*>::iterator iter; for (iter = controls_.begin(); iter != controls_.end(); ++iter) { (*iter)->Paint(image_data, rc); } } bool FadingControls::HandleEvent(const pp::InputEvent& event) { if (!visible()) return false; pp::MouseInputEvent mouse_event(event); if (mouse_event.is_null()) return NotifyControls(event); pp::Point pt = mouse_event.GetPosition(); bool is_mouse_click = mouse_event.GetType() == PP_INPUTEVENT_TYPE_MOUSEDOWN || mouse_event.GetType() == PP_INPUTEVENT_TYPE_MOUSEUP; if (rect().Contains(pt)) { CancelSplashMode(); FadeIn(); // Eat mouse click if are invisible or just fading in. // That prevents accidental clicks on the controls for touch devices. bool eat_mouse_click = (state_ == FADING_IN || current_transparency_ == kTransparentAlpha); if (eat_mouse_click && is_mouse_click && mouse_event.GetButton() == PP_INPUTEVENT_MOUSEBUTTON_LEFT) return true; // Eat this event here. } if ((!rect().Contains(pt)) || event.GetType() == PP_INPUTEVENT_TYPE_MOUSELEAVE) { if (!splash_) FadeOut(); pp::MouseInputEvent event_leave(pp::MouseInputEvent( owner()->GetInstance(), PP_INPUTEVENT_TYPE_MOUSELEAVE, event.GetTimeStamp(), event.GetModifiers(), mouse_event.GetButton(), mouse_event.GetPosition(), mouse_event.GetClickCount(), mouse_event.GetMovement())); return NotifyControls(event_leave); } return NotifyControls(event); } void FadingControls::OnTimerFired(uint32 timer_id) { if (timer_id == fading_timer_id_) { int32 current_alpha = static_cast<int32>(current_transparency_); if (state_ == FADING_IN) current_alpha += alpha_shift_; else if (state_ == FADING_OUT) current_alpha -= alpha_shift_; if (current_alpha >= kOpaqueAlpha) { state_ = NONE; current_alpha = kOpaqueAlpha; } else if (current_alpha <= kTransparentAlpha) { state_ = NONE; current_alpha = kTransparentAlpha; } current_transparency_ = static_cast<uint8>(current_alpha); // Invalidate controls with new alpha transparency. std::list<Control*>::iterator iter; for (iter = controls_.begin(); iter != controls_.end(); ++iter) { // We are going to invalidate the whole FadingControls area, to // allow simultaneous drawing. (*iter)->AdjustTransparency(current_transparency_, false); } owner()->Invalidate(id(), GetControlsRect()); if (state_ != NONE) // Fading still in progress. fading_timer_id_ = owner()->ScheduleTimer(id(), fading_timeout_); else OnFadingComplete(); } else { // Dispatch timer to controls. std::list<Control*>::iterator iter; for (iter = controls_.begin(); iter != controls_.end(); ++iter) { (*iter)->OnTimerFired(timer_id); } } } void FadingControls::EventCaptureReleased() { if (current_capture_control_ != kInvalidControlId) { // Remove previous catpure. Control* ctrl = GetControl(current_capture_control_); if (ctrl) ctrl->EventCaptureReleased(); } } void FadingControls::MoveBy(const pp::Point& offset, bool invalidate) { std::list<Control*>::iterator iter; for (iter = controls_.begin(); iter != controls_.end(); ++iter) { // We invalidate entire FadingControl later if needed. (*iter)->MoveBy(offset, false); } Control::MoveBy(offset, invalidate); } void FadingControls::OnEvent(uint32 control_id, uint32 event_id, void* data) { owner()->OnEvent(control_id, event_id, data); } void FadingControls::Invalidate(uint32 control_id, const pp::Rect& rc) { owner()->Invalidate(control_id, rc); } uint32 FadingControls::ScheduleTimer(uint32 control_id, uint32 timeout_ms) { // TODO(gene): implement timer routine properly. NOTIMPLEMENTED(); //owner()->ScheduleTimer(control_id); return 0; } void FadingControls::SetEventCapture(uint32 control_id, bool set_capture) { if (control_id == current_capture_control_) { if (!set_capture) // Remove event capture. current_capture_control_ = kInvalidControlId; } else { EventCaptureReleased(); current_capture_control_ = control_id; } } void FadingControls::SetCursor(uint32 control_id, PP_CursorType_Dev cursor_type) { owner()->SetCursor(control_id, cursor_type); } pp::Instance* FadingControls::GetInstance() { return owner()->GetInstance(); } bool FadingControls::AddControl(Control* control) { DCHECK(control); if (control->owner() != this) return false; if (!rect().Contains(control->rect())) return false; control->AdjustTransparency(current_transparency_, false); controls_.push_back(control); return true; } void FadingControls::RemoveControl(uint32 control_id) { if (current_capture_control_ == control_id) { current_capture_control_ = kInvalidControlId; } std::list<Control*>::iterator iter; for (iter = controls_.begin(); iter != controls_.end(); ++iter) { if ((*iter)->id() == control_id) { delete (*iter); controls_.erase(iter); break; } } } Control* FadingControls::GetControl(uint32 id) { std::list<Control*>::iterator iter; for (iter = controls_.begin(); iter != controls_.end(); ++iter) { if ((*iter)->id() == id) return *iter; } return NULL; } pp::Rect FadingControls::GetControlsRect() { pp::Rect rc; std::list<Control*>::iterator iter; for (iter = controls_.begin(); iter != controls_.end(); ++iter) { rc = rc.Union((*iter)->rect()); } return rc; } bool FadingControls::ExpandLeft(int offset) { pp::Rect rc = rect(); rc.set_width(rc.width() + offset); rc.set_x(rc.x() - offset); if (!rc.Contains(GetControlsRect())) return false; // No need to invalidate since we are expanding triggering area only. SetRect(rc, false); return true; } void FadingControls::Splash(uint32 time_ms) { splash_ = true; splash_timeout_ = time_ms; alpha_shift_ = kSplashFadingAlphaShift; FadeIn(); } bool FadingControls::NotifyControls(const pp::InputEvent& event) { // First pass event to a control that current capture is set to. Control* ctrl = GetControl(current_capture_control_); if (ctrl) { if (ctrl->HandleEvent(event)) return true; } std::list<Control*>::iterator iter; for (iter = controls_.begin(); iter != controls_.end(); ++iter) { // Now pass event to all control except control with capture, // since we already passed to it above. if ((*iter) != ctrl && (*iter)->HandleEvent(event)) return true; } return false; } void FadingControls::FadeIn() { bool already_visible = (state_ == NONE && current_transparency_ == kOpaqueAlpha); if (state_ != FADING_IN && !already_visible) { state_ = FADING_IN; fading_timer_id_ = owner()->ScheduleTimer(id(), fading_timeout_); } if (already_visible) OnFadingComplete(); } void FadingControls::FadeOut() { bool already_invisible = (state_ == NONE && current_transparency_ == kTransparentAlpha); if (state_ != FADING_OUT && !already_invisible) { state_ = FADING_OUT; fading_timer_id_ = owner()->ScheduleTimer(id(), fading_timeout_); } if (already_invisible) OnFadingComplete(); } void FadingControls::OnFadingComplete() { DCHECK(current_transparency_ == kOpaqueAlpha || current_transparency_ == kTransparentAlpha); // In the splash mode following states are possible: // Fade-in complete: splash_==true, splash_timeout_ != 0 // We need to schedule timer for splash_timeout_. // Splash timeout complete: splash_==true, splash_timeout_ == 0 // We need to fade out still using splash settings. // Fade-out complete: current_transparency_ == kTransparentAlpha // We need to cancel splash mode and go back to normal settings. if (splash_) { if (current_transparency_ == kOpaqueAlpha) { if (splash_timeout_) { fading_timer_id_ = owner()->ScheduleTimer(id(), splash_timeout_); splash_timeout_ = 0; } else { FadeOut(); } } else { CancelSplashMode(); } } } void FadingControls::CancelSplashMode() { splash_ = false; alpha_shift_ = kFadingAlphaShift; } } // namespace chrome_pdf
30.078864
78
0.684636
kjthegod
8aa27cdb4afdade9c5a921ddd8fcc678afff5575
8,236
cpp
C++
src/Services/RenderService/DecoderRenderImageLoader.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Services/RenderService/DecoderRenderImageLoader.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Services/RenderService/DecoderRenderImageLoader.cpp
irov/Mengine
b76e9f8037325dd826d4f2f17893ac2b236edad8
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "DecoderRenderImageLoader.h" #include "Interface/PrefetcherServiceInterface.h" #include "Interface/CodecServiceInterface.h" #include "Interface/MemoryServiceInterface.h" #include "Kernel/Logger.h" #include "Kernel/DocumentHelper.h" #include "Kernel/FileStreamHelper.h" #include "Kernel/Assertion.h" #include "Kernel/AssertionMemoryPanic.h" #include "Kernel/TextureHelper.h" #include "Kernel/PixelFormatHelper.h" #include "Kernel/DocumentableHelper.h" #include "Kernel/FileGroupHelper.h" #include "stdex/memorycopy.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// DecoderRenderImageLoader::DecoderRenderImageLoader() : m_codecFlags( 0 ) { } ////////////////////////////////////////////////////////////////////////// DecoderRenderImageLoader::~DecoderRenderImageLoader() { } ////////////////////////////////////////////////////////////////////////// bool DecoderRenderImageLoader::initialize( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath, const ConstString & _codecType, uint32_t _codecFlags ) { ImageDecoderInterfacePtr decoder; if( PREFETCHER_SERVICE() ->getImageDecoder( _fileGroup, _filePath, &decoder ) == false ) { decoder = this->createImageDecoder_( _fileGroup, _filePath, _codecType ); MENGINE_ASSERTION_MEMORY_PANIC( decoder, "invalid create decoder '%s' codec '%s' (doc: %s)" , Helper::getFileGroupFullPath( _fileGroup, _filePath ) , _codecType.c_str() , MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" ) ); } else { if( decoder->rewind() == false ) { LOGGER_ERROR( "invalid rewind decoder '%s' codec '%s' (doc: %s)" , Helper::getFileGroupFullPath( _fileGroup, _filePath ) , _codecType.c_str() , MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" ) ); return false; } } m_decoder = decoder; m_codecFlags = _codecFlags; return true; } ////////////////////////////////////////////////////////////////////////// void DecoderRenderImageLoader::getImageDesc( RenderImageDesc * const _desc ) const { const ImageCodecDataInfo * dataInfo = m_decoder->getCodecDataInfo(); _desc->mipmaps = dataInfo->mipmaps; _desc->width = dataInfo->width; _desc->height = dataInfo->height; _desc->format = dataInfo->format; } ////////////////////////////////////////////////////////////////////////// bool DecoderRenderImageLoader::load( const RenderImageInterfacePtr & _image ) const { uint32_t image_width = _image->getHWWidth(); uint32_t image_height = _image->getHWHeight(); uint32_t mipmap = 0; Rect rect; rect.left = 0; rect.top = 0; rect.right = image_width; rect.bottom = image_height; RenderImageLockedInterfacePtr locked = _image->lock( 0, rect, false ); size_t pitch = 0; void * textureBuffer = locked->getBuffer( &pitch ); MENGINE_ASSERTION_MEMORY_PANIC( textureBuffer, "invalid lock mipmap %u rect %u:%u-%u:%u" , 0 , rect.left , rect.top , rect.right , rect.bottom ); size_t mipmap_size = pitch * image_height; EPixelFormat HWPixelFormat = _image->getHWPixelFormat(); ImageDecoderData data; data.buffer = textureBuffer; data.size = mipmap_size; data.pitch = pitch; data.format = HWPixelFormat; data.mipmap = mipmap; data.flags = m_codecFlags; if( m_decoder->decode( &data ) == 0 ) { LOGGER_ERROR( "invalid decode for" ); _image->unlock( locked, 0, false ); return false; } if( _image->getUpscalePow2() == true ) { uint32_t mipmap_width = image_width >> mipmap; uint32_t mipmap_height = image_height >> mipmap; uint32_t pixel_size = Helper::getPixelFormatChannels( HWPixelFormat ); const ImageCodecDataInfo * dataInfo = m_decoder->getCodecDataInfo(); // copy pixels on the edge for better image quality if( dataInfo->width != mipmap_width ) { uint8_t * image_data = static_cast<uint8_t *>(textureBuffer); for( uint32_t j = 0; j != dataInfo->height; ++j ) { stdex::memorycopy( image_data, dataInfo->width * pixel_size, image_data + (dataInfo->width - 1) * pixel_size, pixel_size ); image_data += pitch; } } if( dataInfo->height != mipmap_height ) { uint8_t * image_data = static_cast<uint8_t *>(textureBuffer); stdex::memorycopy( image_data, dataInfo->height * pitch, image_data + (dataInfo->height - 1) * pitch, dataInfo->width * pixel_size ); } } _image->unlock( locked, 0, true ); return true; } ////////////////////////////////////////////////////////////////////////// MemoryInterfacePtr DecoderRenderImageLoader::getMemory( uint32_t _codecFlags, const DocumentPtr & _doc ) const { MemoryBufferInterfacePtr memory = MEMORY_SERVICE() ->createMemoryBuffer( _doc ); MENGINE_ASSERTION_MEMORY_PANIC( memory ); const ImageCodecDataInfo * dataInfo = m_decoder->getCodecDataInfo(); uint32_t channels = Helper::getPixelFormatChannels( dataInfo->format ); size_t pitch = dataInfo->width * channels; size_t dataSize = pitch * dataInfo->height; void * buffer = memory->newBuffer( dataSize ); ImageDecoderData data; data.buffer = buffer; data.size = dataSize; data.pitch = pitch; data.format = dataInfo->format; data.flags = _codecFlags; data.mipmap = 0; if( m_decoder->decode( &data ) == 0 ) { LOGGER_ERROR( "invalid decode for" ); return nullptr; } return memory; } ////////////////////////////////////////////////////////////////////////// ImageDecoderInterfacePtr DecoderRenderImageLoader::createImageDecoder_( const FileGroupInterfacePtr & _fileGroup, const FilePath & _filePath, const ConstString & _codecType ) const { InputStreamInterfacePtr stream = Helper::openInputStreamFile( _fileGroup, _filePath, false, false, MENGINE_DOCUMENT_FACTORABLE ); MENGINE_ASSERTION_MEMORY_PANIC( stream, "invalid open stream '%s' codec '%s' (doc: %s)" , Helper::getFileGroupFullPath( _fileGroup, _filePath ) , _codecType.c_str() , MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" ) ); MENGINE_ASSERTION_FATAL( stream->size() != 0, "empty stream '%s' codec '%s' (doc: %s)" , Helper::getFileGroupFullPath( _fileGroup, _filePath ) , _codecType.c_str() , MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" ) ); ImageDecoderInterfacePtr decoder = CODEC_SERVICE() ->createDecoder( _codecType, MENGINE_DOCUMENT_FACTORABLE ); MENGINE_ASSERTION_MEMORY_PANIC( decoder, "invalid create decoder '%s' codec '%s' (doc: %s)" , Helper::getFileGroupFullPath( _fileGroup, _filePath ) , _codecType.c_str() , MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" ) ); if( decoder->prepareData( stream ) == false ) { LOGGER_ERROR( "invalid prepare data '%s' codec '%s' (doc: %s)" , Helper::getFileGroupFullPath( _fileGroup, _filePath ) , _codecType.c_str() , MENGINE_DOCUMENTABLE_STR( this, "DecoderRenderImageLoader" ) ); return nullptr; } return decoder; } ////////////////////////////////////////////////////////////////////////// }
35.65368
184
0.559131
irov
8aa7eecdf7aa3e3c789ce373d12c8ee96817582e
6,468
cpp
C++
Solution/RTS Group Movement/RTS Group Movement/CritterSheep.cpp
Sandruski/RTS-Group-Movement
d0a5985b2e9780963784a67d8a97ce09d1b38f34
[ "MIT" ]
18
2018-11-28T03:14:22.000Z
2022-01-26T05:37:01.000Z
Solution/RTS Group Movement/RTS Group Movement/CritterSheep.cpp
Sandruski/RTS-Group-Movement
d0a5985b2e9780963784a67d8a97ce09d1b38f34
[ "MIT" ]
null
null
null
Solution/RTS Group Movement/RTS Group Movement/CritterSheep.cpp
Sandruski/RTS-Group-Movement
d0a5985b2e9780963784a67d8a97ce09d1b38f34
[ "MIT" ]
5
2018-04-07T11:02:12.000Z
2021-03-18T08:46:46.000Z
#include "Defs.h" #include "p2Log.h" #include "CritterSheep.h" #include "j1App.h" #include "j1Render.h" #include "j1Collision.h" #include "j1Particles.h" #include "j1Map.h" #include "j1Pathfinding.h" #include "j1EntityFactory.h" #include "j1Movement.h" #include "j1PathManager.h" #include "Goal.h" #include "j1Scene.h" // isFrameByFrame #include "j1Input.h" // isFrameByFrame #include "Brofiler\Brofiler.h" CritterSheep::CritterSheep(fPoint pos, iPoint size, int currLife, uint maxLife, const UnitInfo& unitInfo, const CritterSheepInfo& critterSheepInfo) :DynamicEntity(pos, size, currLife, maxLife, unitInfo), critterSheepInfo(critterSheepInfo) { // XML loading /// Animations CritterSheepInfo info = (CritterSheepInfo&)App->entities->GetDynamicEntityInfo(DynamicEntityType_CritterSheep); this->critterSheepInfo.up = info.up; this->critterSheepInfo.down = info.down; this->critterSheepInfo.left = info.left; this->critterSheepInfo.right = info.right; this->critterSheepInfo.upLeft = info.upLeft; this->critterSheepInfo.upRight = info.upRight; this->critterSheepInfo.downLeft = info.downLeft; this->critterSheepInfo.downRight = info.downRight; this->critterSheepInfo.deathUpLeft = info.deathUpLeft; this->critterSheepInfo.deathUpRight = info.deathUpRight; this->critterSheepInfo.deathDownLeft = info.deathDownLeft; this->critterSheepInfo.deathDownRight = info.deathDownRight; LoadAnimationsSpeed(); // Initialize the goals brain->RemoveAllSubgoals(); brain->AddGoal_Wander(5); // Collisions CreateEntityCollider(EntitySide_NoSide); entityCollider->isTrigger = true; } void CritterSheep::Move(float dt) { // Save mouse position (world and map coords) int x, y; App->input->GetMousePosition(x, y); iPoint mousePos = App->render->ScreenToWorld(x, y); iPoint mouseTile = App->map->WorldToMap(mousePos.x, mousePos.y); iPoint mouseTilePos = App->map->MapToWorld(mouseTile.x, mouseTile.y); // --------------------------------------------------------------------- // Is the unit dead? /// The unit must fit the tile (it is more attractive for the player) if (currLife <= 0 && unitState != UnitState_Die && singleUnit->IsFittingTile()) { isDead = true; // If the player dies, remove all their goals brain->RemoveAllSubgoals(); } UpdatePaws(); // --------------------------------------------------------------------- // PROCESS THE CURRENTLY ACTIVE GOAL brain->Process(dt); UnitStateMachine(dt); // Update animations ChangeAnimation(); if (!isDead) // Update colliders UpdateEntityColliderPos(); } void CritterSheep::Draw(SDL_Texture* sprites) { if (animation != nullptr) App->render->Blit(sprites, pos.x, pos.y, &(animation->GetCurrentFrame())); if (isSelected) DebugDrawSelected(); } void CritterSheep::DebugDrawSelected() { const SDL_Rect entitySize = { pos.x, pos.y, size.x, size.y }; App->render->DrawQuad(entitySize, color.r, color.g, color.b, 255, false); for (uint i = 0; i < unitInfo.priority; ++i) { const SDL_Rect entitySize = { pos.x + 2 * i, pos.y + 2 * i, size.x - 4 * i, size.y - 4 * i }; App->render->DrawQuad(entitySize, color.r, color.g, color.b, 255, false); } } void CritterSheep::OnCollision(ColliderGroup* c1, ColliderGroup* c2, CollisionState collisionState) { } // State machine void CritterSheep::UnitStateMachine(float dt) { switch (unitState) { case UnitState_Wander: break; case UnitState_Die: // Remove the corpse when a certain time is reached if (deadTimer.ReadSec() >= TIME_REMOVE_CORPSE) isRemove = true; break; case UnitState_Idle: case UnitState_NoState: default: break; } } // ------------------------------------------------------------- // Animations bool CritterSheep::ChangeAnimation() { bool ret = false; // The unit is dead if (isDead) { animation = &critterSheepInfo.deathDownLeft; ret = true; return ret; } // The unit is moving else { switch (GetUnitDirection()) { case UnitDirection_Up: animation = &critterSheepInfo.up; ret = true; break; case UnitDirection_NoDirection: case UnitDirection_Down: animation = &critterSheepInfo.down; ret = true; break; case UnitDirection_Left: animation = &critterSheepInfo.left; ret = true; break; case UnitDirection_Right: animation = &critterSheepInfo.right; ret = true; break; case UnitDirection_UpLeft: animation = &critterSheepInfo.upLeft; ret = true; break; case UnitDirection_UpRight: animation = &critterSheepInfo.upRight; ret = true; break; case UnitDirection_DownLeft: animation = &critterSheepInfo.downLeft; ret = true; break; case UnitDirection_DownRight: animation = &critterSheepInfo.downRight; ret = true; break; } return ret; } return ret; } // Paws void CritterSheep::UpdatePaws() { // Add footprints along the critter's path if (singleUnit->currTile.x != -1 && singleUnit->currTile.y != -1 && singleUnit->nextTile.x != -1 && singleUnit->nextTile.y != -1) { if (lastPaw != nullptr) { // Reset the animation of the last paw if (GetUnitDirection() != UnitDirection_NoDirection && !lastPaw->isRemove) { lastPaw->isRemove = true; switch (GetUnitDirection()) { case UnitDirection_Up: lastPaw->animation = App->particles->GetSheepPawsInfo().up; break; case UnitDirection_NoDirection: case UnitDirection_Down: lastPaw->animation = App->particles->GetSheepPawsInfo().down; break; case UnitDirection_Left: lastPaw->animation = App->particles->GetSheepPawsInfo().left; break; case UnitDirection_Right: lastPaw->animation = App->particles->GetSheepPawsInfo().right; break; case UnitDirection_UpLeft: lastPaw->animation = App->particles->GetSheepPawsInfo().upLeft; break; case UnitDirection_UpRight: lastPaw->animation = App->particles->GetSheepPawsInfo().upRight; break; case UnitDirection_DownLeft: lastPaw->animation = App->particles->GetSheepPawsInfo().downLeft; break; case UnitDirection_DownRight: lastPaw->animation = App->particles->GetSheepPawsInfo().downRight; break; } } } // Create a new paw if (lastPawTile != singleUnit->currTile) { iPoint currTilePos = App->map->MapToWorld(singleUnit->currTile.x, singleUnit->currTile.y); lastPaw = App->particles->AddParticle(App->particles->paws, currTilePos); lastPawTile = singleUnit->currTile; } } }
22.615385
238
0.685838
Sandruski
8aa9442dbe4ad7567dfaa52eeea232c5bd38278f
8,741
cpp
C++
lib/api/CorrelationVector.cpp
lulululululu/cpp_client_telemetry
211acc586225d3f030fbf8bee016c4ab48e1c96a
[ "Apache-2.0" ]
1
2021-04-27T12:54:48.000Z
2021-04-27T12:54:48.000Z
lib/api/CorrelationVector.cpp
lulululululu/cpp_client_telemetry
211acc586225d3f030fbf8bee016c4ab48e1c96a
[ "Apache-2.0" ]
1
2021-03-03T11:37:10.000Z
2021-03-03T11:37:10.000Z
lib/api/CorrelationVector.cpp
isabella232/cpp_client_telemetry
46a7d65089799c216207ae4758980158affced47
[ "Apache-2.0" ]
null
null
null
// // Copyright (c) 2015-2020 Microsoft Corporation and Contributors. // SPDX-License-Identifier: Apache-2.0 // #include "CorrelationVector.hpp" #include "utils/StringUtils.hpp" // for SplitString and AreAllCharactersWhitelisted #include <vector> #include <random> #include <limits> using std::string; using std::mutex; using std::vector; #ifdef max #undef max #endif namespace MAT_NS_BEGIN { // Note: CV spec reserves the last character for the "!" suffix identifying sealed values. // This effectively means we have one less character to use. // (so 64 is reduced to 63 for v1 and 128 is reduced to 127 for v2). const size_t CorrelationVector::c_maxCVLength_v1 = 63; const size_t CorrelationVector::c_baseCVLength_v1 = 16; const size_t CorrelationVector::c_maxCVLength_v2 = 127; const size_t CorrelationVector::c_baseCVLength_v2 = 22; const string CorrelationVector::s_base64CharSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; const string CorrelationVector::s_base10CharSet = "0123456789"; const string CorrelationVector::s_maxVectorElementValue = "4294967295"; CorrelationVector::CorrelationVector() { } bool CorrelationVector::Initialize(int version) { std::lock_guard<mutex> lock(m_lock); if (version != 1 && version != 2) { return false; } m_maxLength = (version == 1 ? c_maxCVLength_v1 : c_maxCVLength_v2); size_t baseLength = (version == 1 ? c_baseCVLength_v1 : c_baseCVLength_v2); m_currentVector = 0; m_baseVector = InitializeInternal(baseLength); m_isInitialized = true; return true; } void CorrelationVector::Uninitialize() { std::lock_guard<mutex> lock(m_lock); m_currentVector = 0; m_baseVector = ""; m_isInitialized = false; } bool CorrelationVector::IsInitialized() { return m_isInitialized; } string CorrelationVector::InitializeInternal(size_t baseLength) { string result = ""; std::random_device randomDevice; std::uniform_int_distribution<int> base64Dist(0, 63); for (size_t i = 0; i < baseLength; i++) { result += s_base64CharSet[base64Dist(randomDevice)]; } return result; } string CorrelationVector::GetNextValue() { std::lock_guard<mutex> lock(m_lock); string result = GetValueInternal(); IncrementInternal(); return result; } string CorrelationVector::GetValue() { std::lock_guard<mutex> lock(m_lock); return GetValueInternal(); } string CorrelationVector::GetValueInternal() { if (m_isInitialized) { return m_baseVector + "." + std::to_string(m_currentVector); } return string { }; } bool CorrelationVector::Extend() { std::lock_guard<mutex> lock(m_lock); bool result = false; if (CanExtendInternal()) { m_baseVector = GetValueInternal(); m_currentVector = 0; result = true; } return result; } bool CorrelationVector::Increment() { std::lock_guard<mutex> lock(m_lock); return IncrementInternal(); } bool CorrelationVector::IncrementInternal() { bool result = false; if (CanIncrementInternal()) { m_currentVector++; result = true; } return result; } bool CorrelationVector::CanExtend() { std::lock_guard<mutex> lock(m_lock); return CanExtendInternal(); } bool CorrelationVector::CanIncrement() { std::lock_guard<mutex> lock(m_lock); return CanIncrementInternal(); } bool CorrelationVector::CanExtendInternal() { if (!m_isInitialized) { return false; } // extending is appending ".0" size_t newLength = GetLengthInternal(m_currentVector) + 2; return (newLength <= m_maxLength); } bool CorrelationVector::CanIncrementInternal() { if (!m_isInitialized) { return false; } if (m_currentVector == std::numeric_limits<unsigned int>::max()) { return false; } // incrementing is adding one to m_currentVector size_t newLength = GetLengthInternal(m_currentVector + 1); return (newLength <= m_maxLength); } size_t CorrelationVector::GetLengthInternal(size_t vectorValue) { size_t vectorSize = GetDigitCount(vectorValue); // base + "." + numeric representation of m_currentVector return (m_baseVector.length() + 1 + vectorSize); } size_t CorrelationVector::GetDigitCount(size_t value) { size_t digitCount = 1; while (value > 9) { value /= 10; digitCount++; } return digitCount; } bool CorrelationVector::SetValue(const string& cv) { std::lock_guard<mutex> lock(m_lock); // handle a special case: the last character could a "!", meaning that the vector is sealed for extension if ((cv.length() == c_maxCVLength_v1 + 1 || cv.length() == c_maxCVLength_v2 + 1) && cv[cv.length() - 1] == '!') { } vector<string> parts; StringUtils::SplitString(cv, '.', parts); if (parts.size() == 0) { return false; } size_t maxLength = 0; for (size_t i = 0; i < parts.size(); i++) { // the first character group must be a base64 string or a certain length if (i == 0) { if (parts[i].length() == c_baseCVLength_v1) { maxLength = c_maxCVLength_v1; } else if (parts[i].length() == c_baseCVLength_v2) { maxLength = c_maxCVLength_v2; } else { return false; } if (!StringUtils::AreAllCharactersWhitelisted(parts[i], s_base64CharSet)) { return false; } } // all other character groups must be non-empty, decimal digits if (i != 0 && (parts[i].length() == 0 || !StringUtils::AreAllCharactersWhitelisted(parts[i], s_base10CharSet))) { return false; } } // validate the full cV length based on the known cV version if (cv.length() > maxLength) { return false; } if (parts.size() == 1) { // init with just the base value m_baseVector = parts[0]; m_currentVector = 0; } else { size_t lastDot = cv.find_last_of("."); bool parsingFailed = false; string vectorString = cv.substr(lastDot + 1, string::npos); // note: unsigned long is 32-bit on 32-bit arm devices unsigned long currentVector = 0; try { // do a manual string comparison before trying to parse the value to avoid throwing an exception if (vectorString.length() == 0 || vectorString.length() > s_maxVectorElementValue.length() || (vectorString.length() == s_maxVectorElementValue.length() && vectorString > s_maxVectorElementValue)) { parsingFailed = true; } else { currentVector = std::stoul(vectorString); } } catch (std::invalid_argument&) { parsingFailed = true; } catch (std::out_of_range&) { parsingFailed = true; } if (parsingFailed || currentVector > std::numeric_limits<unsigned int>::max()) { return false; } m_baseVector = cv.substr(0, lastDot); m_currentVector = currentVector; } m_maxLength = maxLength; m_isInitialized = true; return true; } } MAT_NS_END
26.812883
123
0.534493
lulululululu
8aac52f4140b0956ea099c9c6df0d59fb4333113
7,572
hpp
C++
include/MAS.hpp
arqueffe/cmapf-solver
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
[ "MIT" ]
null
null
null
include/MAS.hpp
arqueffe/cmapf-solver
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
[ "MIT" ]
1
2021-07-29T15:13:42.000Z
2021-07-29T15:13:42.000Z
include/MAS.hpp
arqueffe/cmapf-solver
30f38f72ae278bdc6ca5cc6efc8cd53dbf13f119
[ "MIT" ]
null
null
null
/* Copyright (c) 2021 Arthur Queffelec * * 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. */ #pragma once #include <map> #include <stack> #include <limits> #include <vector> #include <set> #include <memory> #include <utility> #include <Solver.hpp> #include <LowLevel.hpp> namespace decoupled { template <class GraphMove, class GraphComm> class MAS : public Solver<GraphMove, GraphComm> { private: std::map<std::pair<Node, size_t>, float> pheromone_map_; decoupled::low_level::NegativeAStar<GraphMove, GraphComm> astar; float evaporation_ = 0.8f; int max_iteration_ = 200; public: MAS(const Instance<GraphMove, GraphComm>& instance, const Objective& objective) : Solver<GraphMove, GraphComm>(instance, objective), astar(this->instance_) { Execution exec; for (Agent agt = 0; agt < static_cast<Agent>(this->instance_.nb_agents()); agt++) { Path p = astar.ComputeShortestPath(this->instance_.start()[agt], this->instance_.goal()[agt]); exec.PushBack(std::make_shared<const Path>(p)); } this->execution_ = exec; UpdatePheromoneMap(exec); } void UpdatePheromoneMap(const Execution& exec) { std::map<std::pair<Node, size_t>, int> count_map; for (Agent i = 0; i < static_cast<Agent>(this->instance_.nb_agents()); i++) { auto path_i = exec.get_path(i); for (size_t time = 0; time < path_i->size(); time++) { Node pos_i = path_i->GetAtTimeOrLast(time); const std::set<Node>& neighbors = this->instance_.graph().communication().get_neighbors(pos_i); for (Node n : neighbors) { auto found = count_map.find(std::make_pair(n, time)); if (found != count_map.end()) found->second++; else count_map.insert(std::make_pair(std::make_pair(n, time), 1)); } } } // Evaporate for (auto& pair : pheromone_map_) { pair.second = (1 - evaporation_) * pair.second; } // Lay now pheromones for (auto& pair : count_map) { auto found = pheromone_map_.find(pair.first); if (found != pheromone_map_.end()) found->second += pair.second; else pheromone_map_.insert(std::make_pair(pair.first, static_cast<float>(pair.second))); } } Node SelectStep(Agent agt, Node current, size_t time) { size_t good_strategy = (size_t)rand() % 2; const std::set<Node>& neighbors = this->instance_.graph().movement().get_neighbors(current); if (good_strategy == 0) { double choice = static_cast<double>(rand() / std::numeric_limits<int>::max()); float sum_pheromone = 0.0f; for (auto n : neighbors) { auto found = pheromone_map_.find(std::make_pair(n, time)); if (found != pheromone_map_.end()) sum_pheromone += found->second * (1 / (this->instance_.graph().movement().get_distance(n, this->instance_.goal()[agt]) + 1)); } float current_pheromone = 0.0f; for (auto n : neighbors) { auto found = pheromone_map_.find(std::make_pair(n, time)); float pheromone_value = current_pheromone; if (found != pheromone_map_.end()) pheromone_value += found->second * (1 / (this->instance_.graph().movement().get_distance(n, this->instance_.goal()[agt]) + 1)) / sum_pheromone; if (choice <= pheromone_value) return n; current_pheromone = pheromone_value; } } else { Path p = astar.ComputeShortestPath(current, this->instance_.goal()[agt]); return p[1]; } // No pheromone pick random size_t random_strategy = (size_t)rand() % 2; if (random_strategy == 0) { Node min_node = std::numeric_limits<Node>::max(); size_t min_dist = std::numeric_limits<size_t>::max(); for (auto n : neighbors) { size_t current_dist = this->instance_.graph().movement().get_distance(n, this->instance_.goal()[agt]); if (current_dist < min_dist) { min_dist = current_dist; min_node = n; } } if (min_node == std::numeric_limits<Node>::max()) throw "Potential error of node selection"; return min_node; } else { size_t default_choice = (size_t)rand() % neighbors.size(); auto it = neighbors.begin(); std::advance(it, default_choice); return *it; } } size_t CountDisconnection(const Execution& exec) { size_t count = 0; size_t exec_max_size = 0; for (Agent agt = 0; agt < static_cast<Agent>(this->instance_.nb_agents()); agt++) if (exec_max_size < exec.get_path(agt)->size()) exec_max_size = exec.get_path(agt)->size(); for (size_t time = 0; time < exec_max_size; time++) { size_t agent_count = 0; std::stack<Agent> agent_stack; std::vector<bool> agent_treated = std::vector<bool>(this->instance_.nb_agents(), false); agent_stack.push(0); while (!agent_stack.empty()) { Agent a = agent_stack.top(); agent_stack.pop(); if (agent_treated[a]) continue; agent_treated[a] = true; agent_count++; Node aPos = exec.get_path(a)->GetAtTimeOrLast(time); for (Agent b = 0; b < static_cast<Agent>(this->instance_.nb_agents()); ++b) { if (a != b && !agent_treated[b]) { Node bPos = exec.get_path(b)->GetAtTimeOrLast(b); const std::set<Node>& neighbors = this->instance_.graph().communication().get_neighbors(aPos); if (neighbors.find(bPos) != neighbors.end()) { agent_stack.push(b); } } } } if (agent_count != this->instance_.nb_agents()) count++; } return count; } bool StepCompute() override { Execution exec; size_t previous_disc = CountDisconnection(this->execution_); if (previous_disc == 0) return true; for (Agent agt = 0; agt < static_cast<Agent>(this->instance_.nb_agents()); agt++) { Path path_agt; path_agt.PushBack(this->instance_.start()[agt]); while (path_agt[path_agt.size() - 1] != this->instance_.goal()[agt]) { Node next_node = SelectStep(agt, path_agt[path_agt.size() - 1], path_agt.size()); path_agt.PushBack(next_node); } exec.PushBack(std::make_shared<const Path>(path_agt)); } if (this->objective_.cost(exec) < this->objective_.cost(this->execution_) || CountDisconnection(exec) < previous_disc) { std::cout << "Iteration: " << max_iteration_ << std::endl; std::cout << "Execution Size: " << this->objective_.cost(exec) << std::endl; std::cout << "Disconnection Count: " << CountDisconnection(exec) << std::endl; this->execution_ = exec; } UpdatePheromoneMap(exec); max_iteration_--; if (max_iteration_ == 0) return true; return false; } }; } // namespace decoupled
37.86
120
0.612388
arqueffe
8aad8ca5d1849658a70c74ae1cc57250cc6efad7
3,350
cpp
C++
test/unit/testEkf.cpp
tmcg0/bioslam
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
[ "MIT" ]
6
2021-01-26T19:31:46.000Z
2022-03-10T15:33:49.000Z
test/unit/testEkf.cpp
tmcg0/bioslam
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
[ "MIT" ]
8
2021-01-26T16:12:22.000Z
2021-08-12T18:39:36.000Z
test/unit/testEkf.cpp
tmcg0/bioslam
d59f07733cb3a9a1de8e6dea4b1fb745d706da09
[ "MIT" ]
1
2021-05-02T18:47:42.000Z
2021-05-02T18:47:42.000Z
// -------------------------------------------------------------------- // // (c) Copyright 2021 Massachusetts Institute of Technology // // Author: Tim McGrath // // All rights reserved. See LICENSE file for license information. // // -------------------------------------------------------------------- // // testing of EKF implementations against APDM manufacturer UKF for the Opal v2 #include "imuPoseEstimator.h" #include "VarStrToCharMap.h" #include "testutils.h" #include "mathutils.h" int main(){ // --- settings --- // double tolDeg=5.0; // ---------------- // // setup stuff VarStrToCharMap::clear(); //std::string dataFileToUse=testutils::getTestDataFile("20170719-113432-Y13_TUG_13.h5"); std::string dataFileToUse=testutils::getTestDataFile("20170411-154746-Y1_TUG_6.h5"); std::map<std::string,imu> ImuMap=imu::getImuMapFromDataFile(dataFileToUse); // imu::printLabelsInFile(dataFileToUse); std::string imuLabel="Right Thigh"; imu testImu=ImuMap[imuLabel]; testutils::runtime_assert(testImu.length()>0); std::cout<<"test imu contains "<<testImu.length()<<" measurements ("<<testImu.relTimeSec[testImu.length()-1]<<" seconds)"<<std::endl; imuPoseEstimator poseProblem(testImu, "unitTest"); // get APDM orientatioon std::vector<gtsam::Rot3> rAPDM=gtsamutils::imuOrientation(testImu); // get APDM orientation as a gtsam::Rot3 set // remember that APDM orientation and my EKF is [N->B] // get orientation according to EKF Eigen::MatrixXd q_B_to_N=mathutils::simpleImuOrientationForwardBackwardEkfWrapper(gtsamutils::gyroMatrix(poseProblem.m_imu), gtsamutils::accelMatrix(poseProblem.m_imu), poseProblem.m_imu.getDeltaT(), 4); std::vector<gtsam::Rot3> rEKF(q_B_to_N.rows()), rRel(q_B_to_N.rows()); std::vector<double> yawSqErr(rAPDM.size()), pitchSqErr(rAPDM.size()), rollSqErr(rAPDM.size()); for(uint k=0;k<q_B_to_N.rows();k++){ // convert into a vector of rot3 rEKF[k]=gtsam::Rot3(q_B_to_N(k,0),q_B_to_N(k,1),q_B_to_N(k,2),q_B_to_N(k,3)); rRel[k]=rAPDM[k]*rEKF[k].inverse(); // R[EKF->APDM]=R[N->APDM]*R[N->EKF]' //std::cout<<"relative orientation ["<<k<<"] rpy()="<<rRel[k].rpy().transpose()<<std::endl; gtsam::Vector3 rpyErr=rRel[k].rpy(); yawSqErr[k]=pow(rpyErr[2],2); pitchSqErr[k]=pow(rpyErr[1],2); rollSqErr[k]=pow(rpyErr[0],2); } // now compute RMSEs double yawRMSE = sqrt((std::accumulate(yawSqErr.begin(), yawSqErr.end(), 0.0))/yawSqErr.size()); double pitchRMSE = sqrt((std::accumulate(pitchSqErr.begin(), pitchSqErr.end(), 0.0))/pitchSqErr.size()); double rollRMSE = sqrt((std::accumulate(rollSqErr.begin(), rollSqErr.end(), 0.0))/rollSqErr.size()); std::cout<<"[roll, pitch, yaw] RMSE = ["<<rollRMSE<<", "<<pitchRMSE<<", "<<yawRMSE<<"]"<<std::endl; // assess if these errors are good enough if(pitchRMSE*180.0/M_PI>tolDeg){ std::cerr<<"error: pitch rmse ("<<pitchRMSE*180.0/M_PI<<" deg) greater than tolerance ("<<tolDeg<<" deg)"<<std::endl; return 1; } if(rollRMSE*180.0/M_PI>tolDeg){ std::cerr<<"error: roll rmse ("<<rollRMSE*180.0/M_PI<<" deg) greater than tolerance ("<<tolDeg<<" deg)"<<std::endl; return 1; } return 0; }
53.174603
207
0.61791
tmcg0
8aae41844ee5e21fe31f4a1c2e2131d05b24499d
4,686
cpp
C++
shaders/src/sib_color_hls_adjust.cpp
caron/sitoa
52a0a4b35f51bccb6223a8206d04b40edc80071c
[ "Apache-2.0" ]
34
2018-02-01T16:13:48.000Z
2021-07-16T07:37:47.000Z
shaders/src/sib_color_hls_adjust.cpp
625002974/sitoa
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
[ "Apache-2.0" ]
72
2018-02-16T17:30:41.000Z
2021-11-22T11:41:45.000Z
shaders/src/sib_color_hls_adjust.cpp
625002974/sitoa
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
[ "Apache-2.0" ]
15
2018-02-15T15:36:58.000Z
2021-04-14T03:54:25.000Z
/************************************************************************************************************************************ Copyright 2017 Autodesk, Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ************************************************************************************************************************************/ #include "color_utils.h" AI_SHADER_NODE_EXPORT_METHODS(SIBColorHLSAdjustMethods); enum SIBColorHLSAdjustParams { p_color, p_master_h, p_master_l, p_master_s, p_red_h, p_red_l, p_red_s, p_green_h, p_green_l, p_green_s, p_blue_h, p_blue_l, p_blue_s, p_cyan_h, p_cyan_l, p_cyan_s, p_yellow_h, p_yellow_l, p_yellow_s, p_magenta_h, p_magenta_l, p_magenta_s }; node_parameters { AiParameterRGBA( "color" , 1.0f , 1.0f , 1.0f, 1.0f ); AiParameterFlt ( "master_h" , 0.0f ); AiParameterFlt ( "master_l" , 0.0f ); AiParameterFlt ( "master_s" , 0.0f ); AiParameterFlt ( "red_h" , 0.0f ); AiParameterFlt ( "red_l" , 0.0f ); AiParameterFlt ( "red_s" , 0.0f ); AiParameterFlt ( "green_h" , 0.0f ); AiParameterFlt ( "green_l" , 0.0f ); AiParameterFlt ( "green_s" , 0.0f ); AiParameterFlt ( "blue_h" , 0.0f ); AiParameterFlt ( "blue_l" , 0.0f ); AiParameterFlt ( "blue_s" , 0.0f ); AiParameterFlt ( "cyan_h" , 0.0f ); AiParameterFlt ( "cyan_l" , 0.0f ); AiParameterFlt ( "cyan_s" , 0.0f ); AiParameterFlt ( "yellow_h" , 0.0f ); AiParameterFlt ( "yellow_l" , 0.0f ); AiParameterFlt ( "yellow_s" , 0.0f ); AiParameterFlt ( "magenta_h", 0.0f ); AiParameterFlt ( "magenta_l", 0.0f ); AiParameterFlt ( "magenta_s", 0.0f ); } namespace { typedef struct { float master_h; float master_l; float master_s; float red_h; float red_l; float red_s; float green_h; float green_l; float green_s; float blue_h; float blue_l; float blue_s; float cyan_h; float cyan_l; float cyan_s; float yellow_h; float yellow_l; float yellow_s; float magenta_h; float magenta_l; float magenta_s; } ShaderData; } node_initialize { AiNodeSetLocalData(node, AiMalloc(sizeof(ShaderData))); } node_update { ShaderData* data = (ShaderData*)AiNodeGetLocalData(node); data->master_h = AiNodeGetFlt(node, "master_h"); data->master_l = AiNodeGetFlt(node, "master_l"); data->master_s = AiNodeGetFlt(node, "master_s"); data->red_h = AiNodeGetFlt(node, "red_h"); data->red_l = AiNodeGetFlt(node, "red_l"); data->red_s = AiNodeGetFlt(node, "red_s"); data->green_h = AiNodeGetFlt(node, "green_h"); data->green_l = AiNodeGetFlt(node, "green_l"); data->green_s = AiNodeGetFlt(node, "green_s"); data->blue_h = AiNodeGetFlt(node, "blue_h"); data->blue_l = AiNodeGetFlt(node, "blue_l"); data->blue_s = AiNodeGetFlt(node, "blue_s"); data->cyan_h = AiNodeGetFlt(node, "cyan_h"); data->cyan_l = AiNodeGetFlt(node, "cyan_l"); data->cyan_s = AiNodeGetFlt(node, "cyan_s"); data->yellow_h = AiNodeGetFlt(node, "yellow_h"); data->yellow_l = AiNodeGetFlt(node, "yellow_l"); data->yellow_s = AiNodeGetFlt(node, "yellow_s"); data->magenta_h = AiNodeGetFlt(node, "magenta_h"); data->magenta_l = AiNodeGetFlt(node, "magenta_l"); data->magenta_s = AiNodeGetFlt(node, "magenta_s"); } node_finish { AiFree(AiNodeGetLocalData(node)); } shader_evaluate { ShaderData* data = (ShaderData*)AiNodeGetLocalData(node); AtRGBA result = AiShaderEvalParamRGBA(p_color); // r3D February 16 2011 This shader is not finished! // HLS Corrections if (data->master_h!=0.0f || data->master_s!=0.0f || data->master_l!=0.0f) { AtRGBA hls = RGBAtoHLS(result); // H hls.r += (hls.r*360.0f) + data->master_h; hls.r /= 360.0f; // L hls.b += (hls.b*200.0f) + data->master_s; hls.b /= 200.0f; hls.b = AiClamp(hls.b, 0.0f ,1.0f); // S hls.g += (hls.g*200.0f) + data->master_l; hls.g /= 200.0f; hls.g = AiClamp(hls.g, 0.0f, 1.0f); result = HLStoRGBA(hls); } sg->out.RGBA() = result; }
28.748466
134
0.611182
caron
8ab2382789f1721c8ec390d4be91264673489863
2,231
cpp
C++
src/Graph/Graph.cpp
Fra98/graph-coloring
c7773cf092687f73f0469bb5bc57af4506e4ce1b
[ "MIT" ]
null
null
null
src/Graph/Graph.cpp
Fra98/graph-coloring
c7773cf092687f73f0469bb5bc57af4506e4ce1b
[ "MIT" ]
null
null
null
src/Graph/Graph.cpp
Fra98/graph-coloring
c7773cf092687f73f0469bb5bc57af4506e4ce1b
[ "MIT" ]
null
null
null
#include "Graph.h" Graph::Graph(int V, int E) : V(V), E(E) { _vertices.reserve(V); for(int i=0; i<V; i++) _vertices.emplace_back(Vertex{i}); } unsigned int Graph::getV() const { return V; } unsigned int Graph::getE() const { return E; } std::vector<Vertex> &Graph::getVertices(){ return _vertices; } Vertex &Graph::getVertex(unsigned int pos) { return _vertices[pos]; } void Graph::addEdge(int v1, int v2) { _vertices[v1].addEdge(v2); } unsigned int Graph::getMaxDegree() const { unsigned int maxDegree = 0; for(int i=0; i<V; i++) { auto deg = _vertices[i].getDegree(); if(deg > maxDegree) maxDegree = deg; } return maxDegree; } bool Graph::isColored() { for(int i=0; i<V; i++) { Vertex &v = _vertices[i]; int v_col = v.getColor(); if(v_col == UNCOLORED) return false; auto& adjV = v.getAdjV(); for(auto j : adjV) { int v2_col = _vertices[j].getColor(); if (v2_col == v_col || v2_col == UNCOLORED) return false; } } return true; } void Graph::resetColors() { for(int i=0; i<V; i++) _vertices[i].setColor(UNCOLORED); } void Graph::colorVertexMinimum(Vertex &v) { Colors C; auto& adjV = v.getAdjV(); // C = { colors of all colored neighbors of v } for(auto j : adjV) { int cj = _vertices[j].getColor(); if(cj != UNCOLORED) C.addColor(cj); } // Smallest color not in C int minCol = C.findMinCol(); v.setColor(minCol); } int Graph::numColorsUsed() { int num = 0, tmpC; std::unordered_set<int> colors_table; for(int i=0; i<V; i++) { tmpC = _vertices[i].getColor(); if(!colors_table.count(tmpC) && tmpC != UNCOLORED) { colors_table.emplace(tmpC); num++; } } return num; } bool Graph::isMIS(const boost::dynamic_bitset<> &vMap) { for(int i=0; i<V; i++) { auto& adjV = _vertices[i].getAdjV(); for(auto j : adjV) if(vMap[i] && vMap[j]) return false; } return true; } void Graph::setEdgeNumber(unsigned int E) { this->E = E; }
20.46789
60
0.544151
Fra98
8ab23b0cdc6b4efac8499f43265a76b33cf15f04
4,638
cpp
C++
SGPLibraryCode/modules/sgp_core/common/sgp_Colour.cpp
phoenixzz/VoronoiMapGen
5afd852f8bb0212baba9d849178eb135f62df903
[ "MIT" ]
11
2017-03-03T03:31:15.000Z
2019-03-01T17:09:12.000Z
SGPLibraryCode/modules/sgp_core/common/sgp_Colour.cpp
phoenixzz/VoronoiMapGen
5afd852f8bb0212baba9d849178eb135f62df903
[ "MIT" ]
null
null
null
SGPLibraryCode/modules/sgp_core/common/sgp_Colour.cpp
phoenixzz/VoronoiMapGen
5afd852f8bb0212baba9d849178eb135f62df903
[ "MIT" ]
2
2017-03-03T03:31:17.000Z
2021-05-27T21:50:43.000Z
namespace ColourHelpers { static uint8 floatToUInt8 (const float n) noexcept { return n <= 0.0f ? 0 : (n >= 1.0f ? 255 : (uint8) (n * 255.0f)); } } Colour BLACKCOLOR(0,0,0); Colour WHITECOLOR(255,255,255); Colour REDCOLOR(255,0,0); Colour GREENCOLOR(0,255,0); Colour BLUECOLOR(0,0,255); //============================================================================== Colour::Colour() noexcept : red(0), green(0), blue(0), alpha(0) { } Colour::Colour (const Colour& other) noexcept : red(other.red), green(other.green), blue(other.blue), alpha(other.alpha) { } Colour& Colour::operator= (const Colour& other) noexcept { red = other.red; green = other.green; blue = other.blue; alpha = other.alpha; return *this; } bool Colour::operator== (const Colour& other) const noexcept { return (red == other.red) && (green == other.green) && (blue == other.blue) && (alpha == other.alpha); } bool Colour::operator!= (const Colour& other) const noexcept { return (red != other.red) || (green != other.green) || (blue != other.blue) || (alpha != other.alpha); } //============================================================================== Colour::Colour (const uint32 _argb) noexcept { alpha = uint8((_argb & 0xFF000000) >> 24); red = uint8((_argb & 0x00FF0000) >> 16); green = uint8((_argb & 0x0000FF00) >> 8); blue = uint8(_argb & 0x000000FF); } Colour::Colour (const uint8 _red, const uint8 _green, const uint8 _blue) noexcept { alpha = 0xff; red = _red; green = _green; blue = _blue; } Colour Colour::fromRGB (const uint8 _red, const uint8 _green, const uint8 _blue) noexcept { return Colour (_red, _green, _blue); } Colour::Colour (const uint8 _red, const uint8 _green, const uint8 _blue, const uint8 _alpha) noexcept { red = _red; green = _green; blue = _blue; alpha = _alpha; } Colour Colour::fromRGBA (const uint8 _red, const uint8 _green, const uint8 _blue, const uint8 _alpha) noexcept { return Colour (_red, _green, _blue, _alpha); } Colour::Colour (const uint8 _red, const uint8 _green, const uint8 _blue, const float _alpha) noexcept { alpha = ColourHelpers::floatToUInt8 (_alpha); red = _red; green = _green; blue = _blue; } Colour Colour::fromFloatRGBA (const float _red, const float _green, const float _blue, const float _alpha) noexcept { return Colour (ColourHelpers::floatToUInt8 (_red), ColourHelpers::floatToUInt8 (_green), ColourHelpers::floatToUInt8 (_blue), _alpha); } Colour::~Colour() noexcept { } float Colour::getFloatRed() const noexcept { return getRed() / 255.0f; } float Colour::getFloatGreen() const noexcept { return getGreen() / 255.0f; } float Colour::getFloatBlue() const noexcept { return getBlue() / 255.0f; } float Colour::getFloatAlpha() const noexcept { return getAlpha() / 255.0f; } uint32 Colour::getARGB() const noexcept { return uint32((alpha << 24) | (red << 16) | (green << 8) | blue); } uint32 Colour::getRGBA() const noexcept { return uint32((red << 24) | (green << 16) | (blue << 8) | alpha); } //============================================================================== bool Colour::isTransparent() const noexcept { return getAlpha() == 0; } bool Colour::isOpaque() const noexcept { return getAlpha() == 0xff; } void Colour::setAlpha (const uint8 newAlpha) noexcept { alpha = newAlpha; } void Colour::setAlpha (const float newAlpha) noexcept { jassert (newAlpha >= 0 && newAlpha <= 1.0f); alpha = ColourHelpers::floatToUInt8 (newAlpha); } //============================================================================== Colour Colour::greyLevel (const float brightness) noexcept { const uint8 level = ColourHelpers::floatToUInt8 (brightness); return Colour (level, level, level); } //============================================================================== String Colour::toString() const { return String::toHexString ((int)getARGB()); } Colour Colour::fromString (const String& encodedColourString) { return Colour ((uint32) encodedColourString.getHexValue32()); } String Colour::toDisplayStringRGBA (const bool includeAlphaValue) const { return String::toHexString ((int) (getRGBA() & (includeAlphaValue ? 0xffffffff : 0xffffff00))) .dropLastCharacters ( includeAlphaValue ? 0 : 2) .toUpperCase(); } String Colour::toDisplayStringARGB (const bool includeAlphaValue) const { return String::toHexString ((int) (getARGB() & (includeAlphaValue ? 0xffffffff : 0x00ffffff))) .paddedLeft ('0', includeAlphaValue ? 8 : 6) .toUpperCase(); }
28.109091
138
0.614489
phoenixzz
8ab4082a9063f74963159b25e5eb8dd16bab086c
21,375
hpp
C++
Nostra Utils/src/header/nostrautils/core/StdIncludes.hpp
Lehks/NostraUtils
ef1b2d492a1358775752a2a7621c714d86bf96b2
[ "MIT" ]
10
2018-01-07T01:00:11.000Z
2021-09-16T14:08:45.000Z
NostraUtils/Nostra Utils/src/header/nostrautils/core/StdIncludes.hpp
Lehks/NostraEngine
0d610dcd97ba482fd8f183795140c38728c3a6b3
[ "MIT" ]
107
2018-04-06T10:15:47.000Z
2018-09-28T07:13:46.000Z
NostraUtils/Nostra Utils/src/header/nostrautils/core/StdIncludes.hpp
Lehks/NostraEngine
0d610dcd97ba482fd8f183795140c38728c3a6b3
[ "MIT" ]
null
null
null
#ifndef NOU_CORE_STD_INCLUDES_HPP #define NOU_CORE_STD_INCLUDES_HPP #include <cstddef> #include <cstdint> #include <type_traits> #if __has_include("Config.hpp") #include "Config.hpp" #endif /** \file core/StdIncludes.hpp \author Lukas Reichmann \version 1.0.1 \since 1.0.0 \brief A file that should be included in all other header files of NOU. This provides, along other things, the namespace macros and the primitive types. */ /** \brief The name of the main namespace of NOU. All components of NOU are nested in sub-namespaces of this namespace. */ #ifndef NOU #define NOU nostra::utils #endif /** \brief The name of the namespace that contains all core-components of NOU. */ #ifndef NOU_CORE #define NOU_CORE core #endif /** \brief The name of the namespace that contains all components that are related to data structures and/or algorithms. */ #ifndef NOU_DAT_ALG #define NOU_DAT_ALG dat_alg #endif /** \brief The name of the namespace that contains all components that are related to file management. */ #ifndef NOU_FILE_MNGT #define NOU_FILE_MNGT file_mngt #endif /** \brief The name of the namespace that contains all components that are related to math. */ #ifndef NOU_MATH #define NOU_MATH math #endif /** \brief The name of the namespace that contains all components that are related to memory management. */ #ifndef NOU_MEM_MNGT #define NOU_MEM_MNGT mem_mngt #endif /** \brief The name of the namespace that contains all components that are related to threading. */ #ifndef NOU_THREAD #define NOU_THREAD thread #endif /** \brief The operating system identifier for Microsoft Windows. \details The operating system identifier for Microsoft Windows. This macro is always defined, to check if the current operating system is Windows, use \code{.cpp} #if NOU_OS == NOU_OS_WINDOWS \endcode */ #ifndef NOU_OS_WINDOWS #define NOU_OS_WINDOWS 0 #endif /** \brief The operating system identifier for Linux. \details The operating system identifier for Linux. This macro is always defined, to check if the current operating system is Linux, use \code{.cpp} #if NOU_OS == NOU_OS_LINUX \endcode */ #ifndef NOU_OS_LINUX #define NOU_OS_LINUX 1 #endif /** \brief The operating system identifier for Unix. \details The operating system identifier for Unix. This macro is always defined, to check if the current operating system is Unix, use \code{.cpp} #if NOU_OS == NOU_OS_UNIX \endcode */ #ifndef NOU_OS_UNIX #define NOU_OS_UNIX 2 #endif /** \brief The operating system identifier for Macintosh. \details The operating system identifier for Apple Macintosh. This macro is always defined, to check if the current operating system is Macintosh, use \code{.cpp} #if NOU_OS == NOU_OS_MAC \endcode */ #ifndef NOU_OS_MAC #define NOU_OS_MAC 2 #endif /** \brief The operating system identifier for an unknown system. \details The operating system identifier for an unknown system. This macro is always defined, to check if the current operating system is unknown, use \code{.cpp} #if NOU_OS == NOU_OS_UNKNOWN \endcode An unknown operating system does not cause an error per-se, however, it may cause major problems (e.g. the value for NOU_OS_LIBRARY will not be set properly). */ #ifndef NOU_OS_UNKNOWN #define NOU_OS_UNKNOWN 3 #endif /** \brief The operating system identifier for the Doxygen documentation. \details The operating system identifier for an Doxygen documentation. This macro is always defined, but it does not serve any purpose when using the library. In the documentation files NOU_OS will be defined as this identifier. */ #ifndef NOU_OS_DOXYGEN #define NOU_OS_DOXYGEN 4 #endif /** \brief Defined as the identifier of the current operating system. \details This macro is defined as the identifier of the current operating system. To check for a certain operating system, use \code{.cpp} #if NOU_OS == NOU_OS_* \endcode and replace * with the os name. If the current os is unknown, the value will be NOU_OS_UNKNOWN. An unknown operating system does not cause an error per se, however, it may cause major problems (e.g. the value for NOU_OS_LIBRARY will not be set properly). */ #ifndef NOU_OS # ifdef _WIN32 # define NOU_OS NOU_OS_WINDOWS # elif defined __linux__ # define NOU_OS NOU_OS_LINUX # elif defined __unix__ # define NOU_OS NOU_OS_UNIX # elif defined __APPLE__ # define NOU_OS NOU_OS_MAC # elif defined __DOXYGEN__ //__DOXYGEN__ is defined in the Doxyfile # define NOU_OS NOU_OS_DOXYGEN # else # define NOU_OS NOU_OS_UNKNOWN # endif #endif /** \brief This macro should be defined by a user if the library is used as a dynamically linked library (<tt>.dll</tt>) on MS Windows. \details For optimization purposes, functions that will be imported from a DLL should be marked with <tt>__declspec(dllimport)</tt> on MS Windows when using the Visual C++ compiler. If this macro is defined, all symbols that were exported into a DLL will be marked for import. \note This macro will never be defined on itself, this must always be done by a user before any of NOU files are included. */ #ifndef NOU_DLL # if NOU_OS == NOU_OS_DOXYGEN //Define NOU_DLL to make it appear in the doc # define NOU_DLL # else //Do not define # endif #endif /** \brief The library system identifier for the Windows.h. \details The library system identifier for the Windows.h. This macro is always defined, to check if the current operating system supports the Windows.h, use \code{.cpp} #if NOU_OS_LIBRARY == NOU_OS_LIBRARY_WIN_H \endcode */ #ifndef NOU_OS_LIBRARY_WIN_H #define NOU_OS_LIBRARY_WIN_H 0 #endif /** \brief The library system identifier for a the POSIX library. \details The library system identifier for a the POSIX library. This macro is always defined, to check if the current operating system supports the POSIX library, use \code{.cpp} #if NOU_OS_LIBRARY == NOU_OS_LIBRARY_POSIX \endcode */ #ifndef NOU_OS_LIBRARY_POSIX #define NOU_OS_LIBRARY_POSIX 1 #endif /** \brief The system library identifier for the Doxygen documentation. \details The system library identifier for an Doxygen documentation. This macro is always defined, but it does not serve any purpose when using the library. In the documentation files NOU_OS_LIBRARY will show up defined as this identifier. */ #ifndef NOU_OS_LIBRARY_DOXYGEN #define NOU_OS_LIBRARY_DOXYGEN 2 #endif /** \brief Defined as the identifier of the current supported os library. \details This macro is defined as the identifier of the current supported os library. To check for a certain library, use \code{.cpp} #if NOU_OS_LIBRARY == NOU_OS_LIBRARY_* \endcode and replace * with the library name. If there is no appropriate library available, a \#error directive will be triggered. \todo Verify! */ #ifndef NOU_OS_LIBRARY # if NOU_OS == NOU_OS_WINDOWS # define NOU_OS_LIBRARY NOU_OS_LIBRARY_WIN_H # elif NOU_OS == NOU_OS_LINUX || NOU_OS == NOU_OS_UNIX || NOU_OS == NOU_OS_MAC # define NOU_OS_LIBRARY NOU_OS_LIBRARY_POSIX # elif NOU_OS == NOU_OS_DOXYGEN # define NOU_OS_LIBRARY NOU_OS_LIBRARY_DOXYGEN # else # error Both Windows.h and POSIX are not supported. # endif #endif /** \brief The compiler identifier for Visual C++. \details The compiler identifier for Visual C++. This macro is always defined, to check if the current compiler is Visual C++, use \code{.cpp} #if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP \endcode */ #ifndef NOU_COMPILER_VISUAL_CPP #define NOU_COMPILER_VISUAL_CPP 0 #endif /** \brief The compiler identifier for GNU GCC or g++. \details The compiler identifier for GNU GCC or g++. This macro is always defined, to check if the current compiler is GNU GCC or g++, use \code{.cpp} #if NOU_COMPILER == NOU_COMPILER_GCC \endcode */ #ifndef NOU_COMPILER_GCC #define NOU_COMPILER_GCC 1 #endif /** \brief The compiler identifier for Clang. \details The compiler identifier for Clang. This macro is always defined, to check if the current compiler is Clang, use \code{.cpp} #if NOU_COMPILER == NOU_COMPILER_CLANG \endcode */ #ifndef NOU_COMPILER_CLANG #define NOU_COMPILER_CLANG 2 #endif /** \brief The compiler identifier for Intel C++. \details The compiler identifier for Intel C++. This macro is always defined, to check if the current compiler is Intel C++, use \code{.cpp} #if NOU_COMPILER == NOU_COMPILER_INTEL_CPP \endcode */ #ifndef NOU_COMPILER_INTEL_CPP #define NOU_COMPILER_INTEL_CPP 3 #endif /** \brief The compiler identifier for MinGW. \details The compiler identifier for MinGW. This macro is always defined, to check if the current compiler is MinGW, use \code{.cpp} #if NOU_COMPILER == NOU_COMPILER_MIN_GW \endcode */ #ifndef NOU_COMPILER_MIN_GW #define NOU_COMPILER_MIN_GW 4 #endif /** \brief The compiler identifier for an unknown compiler. \details The compiler identifier for an unknown compiler. This macro is always defined, to check if the current compiler is unknown, use \code{.cpp} #if NOU_COMPILER == NOU_COMPILER_UNKNOWN \endcode An unknown compiler does not cause an error per-se, however, it may cause major problems (e.g. the value of NOU_FUNC will not be set properly). */ #ifndef NOU_COMPILER_UNKNOWN #define NOU_COMPILER_UNKNOWN 5 #endif /** \brief The compiler identifier for the Doxygen documentation. \details The compiler identifier for an Doxygen documentation. This macro is always defined, but it does not serve any purpose when using the library. In the documentation files, NOU_COMPILER will be defined as this identifier. */ #ifndef NOU_COMPILER_DOXYGEN #define NOU_COMPILER_DOXYGEN 6 #endif /** \brief Defined as the identifier of the current compiler. \details This macro is defined as the identifier of the current compiler. To check for a certain compiler, use \code{.cpp} #if NOU_COMPILER == NOU_COMPILER_* \endcode and replace * with the compiler name. \todo Verify! */ #ifndef NOU_COMPILER # ifdef __clang__ //This has to be placed first (b/c Clang also defines __GNUC__ and _MSC_VER) # define NOU_COMPILER NOU_COMPILER_CLANG # elif defined _MSC_VER # define NOU_COMPILER NOU_COMPILER_VISUAL_CPP # elif defined __GNUC__ # define NOU_COMPILER NOU_COMPILER_GCC # elif defined __INTEL_COMPILER # define NOU_COMPILER NOU_COMPILER_INTEL_CPP # elif defined __MINGW32__ # define NOU_COMPILER NOU_COMPILER_MIN_GW # elif defined __DOXYGEN__ # define NOU_COMPILER NOU_COMPILER_DOXYGEN # else # define NOU_COMPILER NOU_COMPILER_UNKNOWN # endif #endif /** \brief A macro that is used to export functions into libraries. \todo Verify (esp. with other compilers) */ #ifndef NOU_EXPORT_FUNC # if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP # define NOU_EXPORT_FUNC __declspec(dllexport) # else # define NOU_EXPORT_FUNC # endif #endif /** \brief A macro that is used to import functions a function from a library. \todo Verify (esp. with other compilers) */ #ifndef NOU_IMPORT_FUNC # if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP # define NOU_IMPORT_FUNC __declspec(dllimport) # else # define NOU_IMPORT_FUNC # endif #endif /** \brief A macro that either exports or imports a function from a library. \details A macro that either exports or imports a function from a library. This macro will import, if NOU_DLL is defined and export if it is not. NOU_DLL definitions should always be correctly handled by CMake and does not need user-interaction. */ #ifndef NOU_FUNC # ifdef NOU_DLL # define NOU_FUNC NOU_IMPORT_FUNC # else # define NOU_FUNC NOU_EXPORT_FUNC # endif #endif /** \param major The major part of the version. \param minor The minor part of the version. \param patch The patch part of the version. \brief Creates a 32 bit version number. \details Creates a 32 bit version number (more precisely a nou::uint32) that consists of the passed parameters. The format is major.minor.patch. E.g: NOU_MAKE_VERSION(1, 2, 3) creates the version 1.2.3. Versions made by this macro can be compared using the usual operators (<, >, <=, >=, ==, !=). The single parts can be read from a version using NOU_VERSION_MAJOR, NOU_VERSION_MINOR and NOU_VERSION_PATCH respectively. The sizes of the single parts in bit are: Part | Size | Maximum value ----- | ---- | ------------- major | 8 | 255 minor | 9 | 511 patch | 15 | 32.767 \warning These values should never be overflowed since in this case bits will be cut off. */ #ifndef NOU_MAKE_VERSION #define NOU_MAKE_VERSION(major, minor, patch) \ static_cast<NOU::uint32> \ (((major << 24) & 0b11111111000000000000000000000000) | \ ((minor << 15) & 0b00000000111111111000000000000000) | \ (patch & 0b00000000000000000111111111111111)) #endif /** \param version The version to retrieve the major part from. \brief Retrieves the major part of a version that was made using NOU_MAKE_VERSION. */ #ifndef NOU_VERSION_MAJOR #define NOU_VERSION_MAJOR(version) static_cast<NOU::uint32> \ ((version & 0b11111111000000000000000000000000) >> (24)) #endif /** \param version The version to retrieve the major part from. \brief Retrieves the minor part of a version that was made using NOU_MAKE_VERSION. */ #ifndef NOU_VERSION_MINOR #define NOU_VERSION_MINOR(version) static_cast<NOU::uint32> \ ((version & 0b00000000111111111000000000000000) >> (15)) #endif /** \param version The version to retrieve the major part from. \brief Retrieves the patch part of a version that was made using NOU_MAKE_VERSION. */ #ifndef NOU_VERSION_PATCH #define NOU_VERSION_PATCH(version) static_cast<NOU::uint32>(version & 0b00000000000000000111111111111111) #endif /** \brief The maximum value of the major part of a version when creating a version with NOU_MAKE_VERSION. */ #ifndef NOU_VERSION_MAJOR_MAX #define NOU_VERSION_MAJOR_MAX static_cast<NOU::uint32>(255) #endif /** \brief The maximum value of the minor part of a version when creating a version with NOU_MAKE_VERSION. */ #ifndef NOU_VERSION_MINOR_MAX #define NOU_VERSION_MINOR_MAX static_cast<NOU::uint32>(511) #endif /** \brief The maximum value of the patch part of a version when creating a version with NOU_MAKE_VERSION. */ #ifndef NOU_VERSION_PATCH_MAX #define NOU_VERSION_PATCH_MAX static_cast<NOU::uint32>(32767) #endif /** \brief The first version of NOU. */ #ifndef NOU_VERSION_1_0_0 #define NOU_VERSION_1_0_0 NOU_MAKE_VERSION(1, 0, 0) #endif /** \brief The first patch for version 1.0.0 of NOU. */ #ifndef NOU_VERSION_1_0_1 #define NOU_VERSION_1_0_1 NOU_MAKE_VERSION(1, 0, 1) #endif /** \brief The current version of NOU. */ //This will be configured by Config.hpp, which is generated by CMake. There is the default-versiob 0.0.0 to //stop IDEs from generating errors because of undefined macros. #ifdef NOU_IS_CONFIG_FILE_PRESENT # ifndef NOU_VERSION # define NOU_VERSION NOU_MAKE_VERSION(NOU_INTERNAL_VERSION_MAJOR, \ NOU_INTERNAL_VERSION_MINOR, \ NOU_INTERNAL_VERSION_PATCH) # endif #else # ifndef NOU_VERSION # define NOU_VERSION NOU_MAKE_VERSION(0, 0, 0) # endif #endif /** \brief The version of the compiler in a normalized form. \todo Verify! */ #ifndef NOU_COMPILER_VERSION # if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP # if defined _MSC_FULL_VER //From this version on, an additional bit is used to determine the version # if _MSC_FULL_VER >= 150030729 # define NOU_COMPILER_VERSION NOU_MAKE_VERSION((_MSC_FULL_VER % 1'00'00'00000) / 1'00'00000, \ (_MSC_FULL_VER % 1'00'00000) / 1'00000, _MSC_FULL_VER % 1'00000) # else # define NOU_COMPILER_VERSION NOU_MAKE_VERSION((_MSC_FULL_VER % 100'00'0000) / 100'0000, \ (_MSC_FULL_VER % 100'0000) / 10000, _MSC_FULL_VER % 1000) # endif # else # define NOU_COMPILER_VERSION NOU_MAKE_VERSION(((_MSC_VER % 10000) / 100), (_MSC_VER % 100), 0) # endif # elif NOU_COMPILER == NOU_COMPILER_GCC # if defined __GNUC_PATCHLEVEL__ # define NOU_COMPILER_VERSION NOU_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) # else # define NOU_COMPILER_VERSION NOU_MAKE_VERSION(__GNUC__, __GNUC_MINOR__, 0) # endif # elif NOU_COMPILER == NOU_COMPILER_CLANG # define NOU_COMPILER_VERSION NOU_MAKE_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) # elif NOU_COMPILER == NOU_COMPILER_INTEL_CPP # define NOU_COMPILER_VERSION NOU_MAKE_VERSION(((__INTEL_COMPILER % 10000) / 100), \ (__INTEL_COMPILER % 100), 0) # elif NOU_COMPILER == NOU_COMPILER_MIN_GW # define NOU_COMPILER_VERSION NOU_MAKE_VERSION(__MINGW32_MAJOR_VERSION, __MINGW32_MINOR_VERSION, 0) # elif NOU_COMPILER == NOU_COMPILER_DOXYGEN # define NOU_COMPILER_VERSION NOU_VERSION_MIN # elif NOU_COMPILER == NOU_COMPILER_UNKNOWN # define NOU_COMPILER_VERSION NOU_VERSION_MAX # endif #endif /** \param ... The expression to convert. \brief Converts any expression into a const char*. */ #ifndef NOU_STRINGIFY #define NOU_STRINGIFY(...) #__VA_ARGS__ #endif /** \brief Returns the result of __LINE__ as a c-string (NOU_STRINGIFY(__LINE__) would not work). */ #ifndef NOU_LINE_STRING #define NOU_LINE_STRING_HELPER(str) NOU_STRINGIFY(str) #define NOU_LINE_STRING NOU_LINE_STRING_HELPER(__LINE__) #endif /** \brief Expands to a string literal with the function signature of the function that this macro was placed in. \note Although this macro is platform independent, it is not guaranteed that using this macro in the same function on different platforms also produces the same result. */ #ifndef NOU_FUNC_NAME # if NOU_COMPILER == NOU_COMPILER_VISUAL_CPP # define NOU_FUNC_NAME __FUNCSIG__ # elif NOU_COMPILER == NOU_COMPILER_GCC # define NOU_FUNC_NAME NOU_STRINGIFY(__PRETTY_FUNCTION__) # elif NOU_COMPILER == NOU_COMPILER_CLANG # define NOU_FUNC_NAME NOU_STRINGIFY(__PRETTY_FUNCTION__) # elif NOU_COMPILER == NOU_COMPILER_INTEL_CPP # define NOU_FUNC_NAME __func__ ///\Todo check # elif NOU_COMPILER == NOU_COMPILER_MIN_GW # define NOU_FUNC_NAME __func__ ///\Todo check # elif NOU_COMPILER == NOU_COMPILER_DOXYGEN # define NOU_FUNC_NAME __FUNCSIG__ # else # define NOU_FUNC_NAME __func__ # endif #endif /** \brief A macro that is only defined if the library should be compiled in C++14 compatiblity mode. \details A macro that is only defined if the library should be compiled in C++14 compatiblity mode. Usually, this is defined by CMake. */ #if NOU_COMPILER == NOU_COMPILER_DOXYGEN //Only present for Doxygen #define NOU_CPP14_COMPATIBILITY #endif namespace NOU::NOU_CORE { /** \return (In the member type "type") The type that was chosen. \brief Chooses from the available floating point types <tt>float</tt>, <tt>float</tt> and <tt>long double</tt> one that has a size of 32 bit. If none of the have a size of 32 bit, long double will be chosen. */ struct ChooseFloat32 : std::conditional<sizeof(float) == 4, float, typename std::conditional_t<sizeof(double) == 4, double, long double > > {}; /** \return (In the member type "type") The type that was chosen. \brief Chooses from the available floating point types <tt>float</tt>, <tt>float</tt> and <tt>long double</tt> one that has a size of 64 bit. If none of the have a size of 32 bit, long double will be chosen. */ struct ChooseFloat64 : std::conditional<sizeof(float) == 8, float, typename std::conditional_t<sizeof(double) == 8, double, long double > > {}; } namespace NOU { /** \brief A signed integer type with a width of 8 bit. */ using int8 = std::int8_t; /** \brief An unsigned integer type with a width of 8 bit. */ using uint8 = std::uint8_t; /** \brief A signed integer type with a width of 16 bit. */ using int16 = std::int16_t; /** \brief An unsigned integer type with a width of 16 bit. */ using uint16 = std::uint16_t; /** \brief A signed integer type with a width of 32 bit. */ using int32 = std::int32_t; /** \brief An unsigned integer type with a width of 32 bit. */ using uint32 = std::uint32_t; /** \brief A signed integer type with a width of 64 bit. */ using int64 = std::int64_t; /** \brief An unsigned integer type with a width of 64 bit. */ using uint64 = std::uint64_t; /** \brief An unsigned integer type that is defined as the integer that is the maximum size of any object. */ using sizeType = std::size_t; /** \brief A boolean type. */ using boolean = bool; /** \brief A type that is one byte. */ using byte = unsigned char; /** \brief A character type with a width of 8 bit. */ using char8 = char; /** \brief A character type with a width of 16 bit. */ using char16 = char16_t; /** \brief A character type with a width of 32 bit. */ using char32 = char32_t; /** \brief A floating point type with a width of 32 bit. \note If the compiler does not support a 32 bit float, this will be the largest floating point type available. */ using float32 = NOU_CORE::ChooseFloat32::type; /** \brief A floating point type with a width of 64 bit. \note If the compiler does not support a 64 bit float, this will be the largest floating point type available. */ using float64 = NOU_CORE::ChooseFloat64::type; } #endif
25.753012
110
0.744281
Lehks
8abc3b2e3c04cf48acc8604ab6b46f44a727dab2
4,138
cpp
C++
source/og-core/math/ConvexHull.cpp
OpenWebGlobe/Application-SDK
b819ca8ccb44b70815f6c5332cfb041ea23dab61
[ "MIT" ]
4
2015-12-20T01:38:05.000Z
2019-07-02T11:01:29.000Z
source/og-core/math/ConvexHull.cpp
OpenWebGlobe/Application-SDK
b819ca8ccb44b70815f6c5332cfb041ea23dab61
[ "MIT" ]
null
null
null
source/og-core/math/ConvexHull.cpp
OpenWebGlobe/Application-SDK
b819ca8ccb44b70815f6c5332cfb041ea23dab61
[ "MIT" ]
6
2015-01-20T09:18:39.000Z
2021-02-06T08:19:30.000Z
/******************************************************************************* Project : foundation Purpose : compute convex hull using graham scan. Creation Date : 16.1.2009 Author : Martin Christen Copyright : This source code file is copyright (c) FHNW 2009 *******************************************************************************/ #include "ConvexHull.h" #include <iostream> #include <algorithm> #include <cmath> #include <float.h> #include <vector> #include <map> #include <iterator> // constatns we need for ccw function later #define CCW_LEFT_TURN 1 #define CCW_RIGHT_TURN -1 #define CCW_COLINEAR 0 namespace math { double OPENGLOBE_API dist(const ElevationPoint &a, const ElevationPoint &b); void OPENGLOBE_API FirstPointToLowerLeft(std::vector<ElevationPoint> &points); int OPENGLOBE_API ccw(const ElevationPoint &a, const ElevationPoint &b, const ElevationPoint &origin); void OPENGLOBE_API graham_scan(std::vector<ElevationPoint>& points, std::vector<ElevationPoint> &chull); struct point_angle_functor { ElevationPoint p0; point_angle_functor() {} point_angle_functor(const ElevationPoint &p) : p0(p) {} bool operator()(const ElevationPoint &a, const ElevationPoint &b) { int res; res = ccw(a, b, p0); if (res == CCW_LEFT_TURN) { return true; } else if (res == CCW_COLINEAR) { double da, db; da = dist(p0, a); db = dist(p0, b); if (da < db) return true; } return false; } }; //----------------------------------------------------------------------------- void graham_scan(std::vector<ElevationPoint>& points, std::vector<ElevationPoint> &chull) { if (points.size() <= 3) { std::copy(points.begin(), points.end(), std::back_inserter(chull)); return; } bool done; ElevationPoint next2last, last; FirstPointToLowerLeft(points); sort(points.begin()+1, points.end(), point_angle_functor(points[0])); chull.push_back(points[0]); chull.push_back(points[1]); for (size_t i = 2; i < points.size(); i++) { done = false; while (!done && chull.size() > 1) { last = chull.back(); next2last = chull [chull.size()-2]; if (ccw(last, points[i], next2last) != CCW_LEFT_TURN) chull.pop_back(); else done = true; } chull.push_back(points[i]); } } //----------------------------------------------------------------------------- // runs through the points vector to find the lowest, left-most point and sets first points with it. void FirstPointToLowerLeft(std::vector<ElevationPoint> &points) { for (size_t i = 1; i < points.size(); i++) { if (points[i].y < points[0].y) { std::swap(points[0], points[i]); } else if (points[i].y == points[0].y && points[i].x < points[0].x) { std::swap(points[0], points[i]); } } } //----------------------------------------------------------------------------- int ccw(const ElevationPoint &a, const ElevationPoint &b, const ElevationPoint &origin) { ElevationPoint v1, v2; double cp_z; v1.x = a.x - origin.x; v1.y = a.y - origin.y; v2.x = b.x - origin.x; v2.y = b.y - origin.y; cp_z = v1.x * v2.y - v1.y * v2.x; if (cp_z > DBL_EPSILON) { return CCW_LEFT_TURN; } else if (cp_z < -DBL_EPSILON) { return CCW_RIGHT_TURN; } return CCW_COLINEAR; } //----------------------------------------------------------------------------- double dist(const ElevationPoint &a, const ElevationPoint &b) { double x, y; x = a.x - b.x; y = a.y - b.y; return (sqrt(double(x*x + y*y))); } //----------------------------------------------------------------------------- }
25.078788
107
0.483084
OpenWebGlobe
8ac793e44e8e8d4225e2a0c34ac3e03107361623
3,563
cc
C++
src/common_audio/vad/main/test/unit_test/unit_test.cc
freedesktop-unofficial-mirror/pulseaudio__webrtc-audio-processing
9413986e79cf01958ee6dfb95a89de0d71a44221
[ "BSD-3-Clause" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
src/common_audio/vad/main/test/unit_test/unit_test.cc
freedesktop-unofficial-mirror/pulseaudio__webrtc-audio-processing
9413986e79cf01958ee6dfb95a89de0d71a44221
[ "BSD-3-Clause" ]
null
null
null
src/common_audio/vad/main/test/unit_test/unit_test.cc
freedesktop-unofficial-mirror/pulseaudio__webrtc-audio-processing
9413986e79cf01958ee6dfb95a89de0d71a44221
[ "BSD-3-Clause" ]
5
2015-10-30T17:35:19.000Z
2021-06-04T01:39:27.000Z
/* * Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ /* * This file includes the implementation of the VAD unit tests. */ #include <cstring> #include "unit_test.h" #include "webrtc_vad.h" class VadEnvironment : public ::testing::Environment { public: virtual void SetUp() { } virtual void TearDown() { } }; VadTest::VadTest() { } void VadTest::SetUp() { } void VadTest::TearDown() { } TEST_F(VadTest, ApiTest) { VadInst *vad_inst; int i, j, k; short zeros[960]; short speech[960]; char version[32]; // Valid test cases int fs[3] = {8000, 16000, 32000}; int nMode[4] = {0, 1, 2, 3}; int framelen[3][3] = {{80, 160, 240}, {160, 320, 480}, {320, 640, 960}} ; int vad_counter = 0; memset(zeros, 0, sizeof(short) * 960); memset(speech, 1, sizeof(short) * 960); speech[13] = 1374; speech[73] = -3747; // WebRtcVad_get_version() WebRtcVad_get_version(version); //printf("API Test for %s\n", version); // Null instance tests EXPECT_EQ(-1, WebRtcVad_Create(NULL)); EXPECT_EQ(-1, WebRtcVad_Init(NULL)); EXPECT_EQ(-1, WebRtcVad_Assign(NULL, NULL)); EXPECT_EQ(-1, WebRtcVad_Free(NULL)); EXPECT_EQ(-1, WebRtcVad_set_mode(NULL, nMode[0])); EXPECT_EQ(-1, WebRtcVad_Process(NULL, fs[0], speech, framelen[0][0])); EXPECT_EQ(WebRtcVad_Create(&vad_inst), 0); // Not initialized tests EXPECT_EQ(-1, WebRtcVad_Process(vad_inst, fs[0], speech, framelen[0][0])); EXPECT_EQ(-1, WebRtcVad_set_mode(vad_inst, nMode[0])); // WebRtcVad_Init() tests EXPECT_EQ(WebRtcVad_Init(vad_inst), 0); // WebRtcVad_set_mode() tests EXPECT_EQ(-1, WebRtcVad_set_mode(vad_inst, -1)); EXPECT_EQ(-1, WebRtcVad_set_mode(vad_inst, 4)); for (i = 0; i < sizeof(nMode)/sizeof(nMode[0]); i++) { EXPECT_EQ(WebRtcVad_set_mode(vad_inst, nMode[i]), 0); } // WebRtcVad_Process() tests EXPECT_EQ(-1, WebRtcVad_Process(vad_inst, fs[0], NULL, framelen[0][0])); EXPECT_EQ(-1, WebRtcVad_Process(vad_inst, 12000, speech, framelen[0][0])); EXPECT_EQ(-1, WebRtcVad_Process(vad_inst, fs[0], speech, framelen[1][1])); EXPECT_EQ(WebRtcVad_Process(vad_inst, fs[0], zeros, framelen[0][0]), 0); for (i = 0; i < sizeof(fs)/sizeof(fs[0]); i++) { for (j = 0; j < sizeof(framelen[0])/sizeof(framelen[0][0]); j++) { for (k = 0; k < sizeof(nMode)/sizeof(nMode[0]); k++) { EXPECT_EQ(WebRtcVad_set_mode(vad_inst, nMode[k]), 0); // printf("%d\n", WebRtcVad_Process(vad_inst, fs[i], speech, framelen[i][j])); if (vad_counter < 9) { EXPECT_EQ(WebRtcVad_Process(vad_inst, fs[i], speech, framelen[i][j]), 1); } else { EXPECT_EQ(WebRtcVad_Process(vad_inst, fs[i], speech, framelen[i][j]), 0); } vad_counter++; } } } EXPECT_EQ(0, WebRtcVad_Free(vad_inst)); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); VadEnvironment* env = new VadEnvironment; ::testing::AddGlobalTestEnvironment(env); return RUN_ALL_TESTS(); }
28.733871
94
0.615212
freedesktop-unofficial-mirror
8ac9405fe0d63a0013f2279d0aa7667fec81f3d8
13,292
cpp
C++
DBProCompiler/DBPCompiler/StructTable.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
231
2018-01-28T00:06:56.000Z
2022-03-31T21:39:56.000Z
DBProCompiler/DBPCompiler/StructTable.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
9
2016-02-10T10:46:16.000Z
2017-12-06T17:27:51.000Z
DBProCompiler/DBPCompiler/StructTable.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
66
2018-01-28T21:54:52.000Z
2022-02-16T22:50:57.000Z
// StructTable.cpp: implementation of the CStructTable class. // ////////////////////////////////////////////////////////////////////// // Common Includes #define _CRT_SECURE_NO_DEPRECATE #pragma warning(disable : 4996) #include "StructTable.h" // Special access to global pointer to struct table (so can do full scan) extern CStructTable* g_pStructTable; #ifdef __AARON_STRUCPERF__ # define ALLOWED_LOWER "abcdefghijklmnopqrstuvwxyz" # define ALLOWED_UPPER "ABCDEFGHIJKLMNOPQRSTUVWXYZ" # define ALLOWED_ALPHA ALLOWED_LOWER ALLOWED_UPPER # define ALLOWED_DIGIT "0123456789" # define ALLOWED_ALNUM ALLOWED_ALPHA ALLOWED_DIGIT # define ALLOWED_IDENT ALLOWED_ALNUM "_" # define ALLOWED_TYPES "#$%" # define ALLOWED_SCOPE ":" # define ALLOWED_INTRN "&@ " # define ALLOWED_MISCL ALLOWED_TYPES ALLOWED_INTRN ALLOWED_SCOPE # define ALLOWED_DBVAR ALLOWED_IDENT ALLOWED_MISCL typedef db3::TDictionary<CStructTable> map_type; typedef db3::TDictionary<CStructTable>::SEntry entry_type; map_type CStructTable::g_Table(ALLOWED_DBVAR, map_type::Insensitive, map_type::DeleteEntries); #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CStructTable::CStructTable() { m_dwTypeMode=0; m_dwTypeValue=0; m_pTypeName=NULL; m_cTypeChar=0; m_dwSize=0; m_pDecChain=NULL; m_pDecBlock=NULL; m_pNext=NULL; } CStructTable::~CStructTable() { SAFE_DELETE(m_pTypeName); SAFE_DELETE(m_pDecChain); SAFE_DELETE(m_pDecBlock); } void CStructTable::Free(void) { CStructTable* pCurrent = this; while(pCurrent) { CStructTable* pNext = pCurrent->GetNext(); delete pCurrent; pCurrent = pNext; } } void CStructTable::Add(CStructTable* pNew) { CStructTable* pCurrent = this; while(pCurrent->m_pNext) { pCurrent=pCurrent->GetNext(); } pCurrent->m_pNext=pNew; } void CStructTable::SetStructDefaults(void) { // Default datatypes and sizes SetStruct(1, "integer", 'L', 4); AddStruct(2, "float", 'F', 4); AddStruct(3, "string", 'S', 4); AddStruct(4, "boolean", 'B', 1); AddStruct(5, "byte", 'Y', 1); AddStruct(6, "word", 'W', 2); AddStruct(7, "dword", 'D', 4); AddStruct(8, "double float", 'O', 8); AddStruct(9, "double integer", 'R', 8); AddStruct(10,"label", 'P', 4); AddStruct(20,"dabel", 'Q', 4); AddStruct(101, "integer array", 'm', 4); AddStruct(102, "float array", 'g', 4); AddStruct(103, "string array", 't', 4); AddStruct(104, "boolean array", 'c', 4); AddStruct(105, "byte array", 'z', 4); AddStruct(106, "word array", 'x', 4); AddStruct(107, "dword array", 'e', 4); AddStruct(108, "double float array", 'u', 4); AddStruct(109, "double integer array", 'v', 4); AddStruct(501, "anytype non casted", 'X', 4); AddStruct(1001, "userdefined var ptr", 'E', 4); AddStruct(1101, "userdefined array ptr",'e', 4); } bool CStructTable::SetStruct(DWORD dwValue, LPSTR pStructName, unsigned char cStructChar, DWORD dwSize) { // Set Struct Data CStr* pStrTypeName = new CStr(pStructName); SetTypeMode(0); SetTypeValue(dwValue); SetTypeName(pStrTypeName); SetTypeChar(cStructChar); SetTypeSize(dwSize); #ifdef __AARON_STRUCPERF__ entry_type *entry = g_Table.Lookup(pStructName); assert_msg(!!entry, "g_Table.Lookup() failed!"); assert_msg(!entry->P, "Struct already exists"); entry->P = this; #endif return true; } bool CStructTable::AddStruct(DWORD dwValue, LPSTR pStructName, unsigned char cStructChar, DWORD dwSize) { // Create structure CStructTable* pNewType = new CStructTable; // Set Struct Data CStr* pStrTypeName = new CStr(pStructName); pNewType->SetTypeMode(0); pNewType->SetTypeValue(dwValue); pNewType->SetTypeName(pStrTypeName); pNewType->SetTypeChar(cStructChar); pNewType->SetTypeSize(dwSize); pNewType->SetDecChain(NULL); pNewType->SetTypeBlock(NULL); #ifdef __AARON_STRUCPERF__ entry_type *entry = g_Table.Lookup(pStructName); assert_msg(!!entry, "g_Table.Lookup() failed!"); assert_msg(!entry->P, "Struct already exists"); entry->P = pNewType; #endif // Add Struct to list Add(pNewType); // Complete return true; } bool CStructTable::AddStructUserType(DWORD dwMode, LPSTR pStructName, unsigned char cStructChar, CDeclaration* pDecChain, CStatement* pTypeBlock, DWORD dwStructTypeMode, bool* pbReportError, DWORD dwParamInUserFunction ) { // Only add if unique if(DoesTypeEvenExist(pStructName)!=NULL) return false; // lee - 150206 - u60 - add only if known type at this point (typeA before typeB if typeB uses typeA) CDeclaration* pCurrent = pDecChain; if ( pCurrent ) { // check all dec types while ( pCurrent ) { if ( strcmp ( pCurrent->GetType()->GetStr(), "" )!=NULL ) { if ( g_pStructTable->DoesTypeEvenExist ( pCurrent->GetType()->GetStr() )==false ) { // fail here as type is unknown and so cannot create a struct based on an unknown type if ( pbReportError ) *pbReportError = true; return false; } } pCurrent = pCurrent->GetNext(); } } // Create structure CStructTable* pNewType = new CStructTable; // When get a zero mode if(dwMode==0) { // Generate unique type value for it (starting at 1001...) dwMode=1001; } // Set Struct Data CStr* pStrTypeName = new CStr(pStructName); pNewType->SetTypeMode(dwStructTypeMode); pNewType->SetTypeValue(dwMode); pNewType->SetTypeName(pStrTypeName); pNewType->SetTypeChar(cStructChar); pNewType->SetTypeSize(0); pNewType->SetDecChain(pDecChain); pNewType->SetTypeBlock(pTypeBlock); #ifdef __AARON_STRUCPERF__ entry_type *entry = g_Table.Lookup(pStructName); assert_msg(!!entry, "g_Table.Lookup() failed!"); assert_msg(!entry->P, "Struct already exists"); entry->P = pNewType; #endif // U73 - 230309 - added param count for Diggory (new debugger) pNewType->SetParamInUserFunction ( dwParamInUserFunction ); // Add Struct to list Add(pNewType); // Complete return true; } bool CStructTable::AddStructUserType(DWORD dwMode, LPSTR pStructName, unsigned char cStructChar, CDeclaration* pDecChain, CStatement* pTypeBlock, DWORD dwStructTypeMode, bool* pbReportError ) { return AddStructUserType( dwMode, pStructName, cStructChar, pDecChain, pTypeBlock, dwStructTypeMode, pbReportError, 0 ); } bool CStructTable::AddStructUserType(DWORD dwMode, LPSTR pStructName, unsigned char cStructChar, CDeclaration* pDecChain, CStatement* pTypeBlock, DWORD dwStructTypeMode ) { return AddStructUserType( dwMode, pStructName, cStructChar, pDecChain, pTypeBlock, dwStructTypeMode, NULL ); } bool CStructTable::CalculateAllSizes(void) { DWORD dwAttempts=0; DWORD dwStructuresMax=0; bool bKeepGoing=true; while(bKeepGoing) { bKeepGoing=false; DWORD dwCountStructures=0; CStructTable* pCurrent = this; while(pCurrent) { dwCountStructures++; if(dwCountStructures>dwStructuresMax) dwStructuresMax=dwCountStructures; if(pCurrent->CalculateSize()==false) bKeepGoing=true; pCurrent = pCurrent->GetNext(); } // Drop out with error if cannot resolve type sizes if(dwAttempts>dwStructuresMax) { g_pErrorReport->AddErrorString("Failed to 'CalculateAllSizes::dwAttempts>dwStructuresMax'"); return false; } dwAttempts++; } // Complete return true; } bool CStructTable::CalculateSize(void) { // Calculate sizes of dec chain if have one if(m_pDecChain) { bool bSecondPass = true; while ( bSecondPass ) { // do first pass bSecondPass = false; // calculate size DWORD dwCumilitiveSize=0; CDeclaration* pDec = m_pDecChain; while(pDec) { if(pDec->GetName()) { if(g_pStructTable->DoesTypeEvenExist(pDec->GetType()->GetStr())) { //leefix - 300305 - bytes must be stored in DWORDS (as they are passed onto stack as such) DWORD dwSize=g_pStructTable->GetSizeOfType(pDec->GetType()->GetStr()); if ( dwSize <4 ) dwSize=4; if(pDec->GetArrFlag()==1) dwSize=4; if(dwSize>0) { // Calculate full size of field using array value DWORD dwArraySize = (DWORD)pDec->GetArrValue()->GetValue(); if(dwArraySize>0) { // Array determines final field size dwSize*=dwArraySize; } // Set Offset within declaration for struct-field-offset reference pDec->SetOffset(dwCumilitiveSize); pDec->SetDataSize(dwSize); dwCumilitiveSize+=dwSize; } else { g_pErrorReport->AddErrorString("Failed to 'CalculateSize::dwSize>0'"); return false; } } else { DWORD LineNumber = pDec->GetLineNumber(); g_pErrorReport->SetError(LineNumber, ERR_SYNTAX+35, pDec->GetType()->GetStr()); return false; } } pDec = pDec->GetNext(); } // leefix - 220604 - u54 - If not on DWORD boundary int iRemainder = dwCumilitiveSize % 4; if ( iRemainder > 0 ) { // NOT DWORD boundary - add fillers iRemainder = 4-iRemainder; for ( int i=0; i<iRemainder; i++ ) { CDeclaration* pNewDec = new CDeclaration; pNewDec->SetDecData(0, "", "___filler", "byte", "", 0); m_pDecChain->Add ( pNewDec ); } // do again bSecondPass = true; } else { // Assign total to size member of SetTypeSize(dwCumilitiveSize); } } } // Complete return true; } CStructTable* CStructTable::DoesTypeEvenExist(LPSTR pName) { #ifdef __AARON_STRUCPERF__ entry_type *entry = g_Table.Lookup(pName); if (!entry) return NULL; return (CStructTable *)entry->P; #else if(GetTypeName()) if(stricmp(pName, GetTypeName()->GetStr())==NULL) return this; if(GetNext()) return GetNext()->DoesTypeEvenExist(pName); return NULL; #endif } DWORD CStructTable::GetSizeOfType(LPSTR pName) { if(GetTypeName()) if(stricmp(pName, GetTypeName()->GetStr())==NULL) return GetTypeSize(); if(GetNext()) return GetNext()->GetSizeOfType(pName); return 0; } CDeclaration* CStructTable::FindDecInType(LPSTR pTypename, LPSTR pFieldname) { #ifdef __AARON_STRUCPERF__ CStructTable *struc; CDeclaration *dec; entry_type *entry; entry = g_Table.Lookup(pTypename); if (!entry || !entry->P) return NULL; struc = (CStructTable *)entry->P; for(dec=struc->m_pDecChain; dec; dec=dec->GetNext()) { if (stricmp(dec->GetName()->GetStr(), pFieldname)==0) break; } return dec; #else if(stricmp(GetTypeName()->GetStr(), pTypename)==NULL) { if(m_pDecChain) { CDeclaration* pDec = m_pDecChain; while(pDec) { if(stricmp(pDec->GetName()->GetStr(), pFieldname)==NULL) { return pDec; } pDec = pDec->GetNext(); } } return NULL; } if(GetNext()) return GetNext()->FindDecInType(pTypename, pFieldname); else return NULL; #endif } CDeclaration* CStructTable::FindFieldInType(LPSTR pTypename, LPSTR pFieldname, LPSTR* pReturnType, DWORD* pdwArrFlag, DWORD* pdwOffset) { CDeclaration* pDec = FindDecInType(pTypename, pFieldname); if(pDec) { // Create string and copy typename of field *pReturnType = new char[pDec->GetType()->Length()+1]; strcpy(*pReturnType, pDec->GetType()->GetStr()); *pdwArrFlag=pDec->GetArrFlag(); *pdwOffset=pDec->GetOffset(); return pDec; } // Not found soft fail return NULL; } bool CStructTable::FindOffsetFromField(LPSTR pTypename, LPSTR pFieldname, DWORD* pReturnOffset, DWORD* pdwSizeData) { CDeclaration* pDec = FindDecInType(pTypename, pFieldname); if(pDec) { // Extract offset data from dec in type struct *pReturnOffset = pDec->GetOffset(); *pdwSizeData = pDec->GetDataSize(); return true; } // Not found soft fail return false; } int CStructTable::FindIndex(LPSTR pTypename) { int iIndex = 0; CStructTable* pCurrent = this; while(pCurrent) { // if find type, exit now to retain iIndex if ( stricmp ( pCurrent->GetTypeName()->GetStr(), pTypename )==NULL ) break; // next structure pCurrent = pCurrent->GetNext(); iIndex++; } // return found index return iIndex; } bool CStructTable::WriteDBMHeader(void) { // Blank Line CStr strDBMBlank(1); if(g_pDBMWriter->OutputDBM(&strDBMBlank)==false) return false; // Title CStr strDBMLine(256); strDBMLine.SetText("DEBUG:"); if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false; return true; } bool CStructTable::WriteDBM(void) { // Write out text CStr strDBMLine(256); // Structure Type if(GetTypeMode()==0) { strDBMLine.SetText("STRUCT@"); } if(GetTypeMode()==1) { strDBMLine.SetText("USERSTRUCT@"); } if(GetTypeMode()==2) { strDBMLine.SetText("FS@"); } strDBMLine.AddText(m_pTypeName); strDBMLine.AddText(" Overall Size:"); strDBMLine.AddNumericText(m_dwSize); // U73 - 230309 - added for Diggory Debugger if(GetTypeMode()==2) { strDBMLine.AddText(" Parameter Count:"); strDBMLine.AddNumericText(m_dwParamInUserFunction); } // User Types has a blank to make reading easier if(m_pDecChain) { CStr strDBMBlank(1); if(g_pDBMWriter->OutputDBM(&strDBMBlank)==false) return false; } // Output type details if(g_pDBMWriter->OutputDBM(&strDBMLine)==false) return false; // Write out fields of type if(m_pDecChain) { if(m_pDecChain->WriteDBM()==false) return false; } // Write next one if(GetNext()) { if((GetNext()->WriteDBM())==false) return false; } // Complete return true; }
24.167273
220
0.68703
domydev
8acc45474017e9ba601ad3c32c234ded9cf26a09
3,163
hpp
C++
Examples/OpcPlcManager/src/OpcPlcManagerComponent.hpp
Siddu96/CppExamples
7b890a7e387a6a1504982f610f8a886312d49854
[ "MIT" ]
18
2019-02-22T14:24:19.000Z
2022-01-24T12:41:41.000Z
Examples/OpcPlcManager/src/OpcPlcManagerComponent.hpp
Siddu96/CppExamples
7b890a7e387a6a1504982f610f8a886312d49854
[ "MIT" ]
25
2019-06-12T12:20:38.000Z
2022-02-09T07:57:28.000Z
Examples/OpcPlcManager/src/OpcPlcManagerComponent.hpp
Siddu96/CppExamples
7b890a7e387a6a1504982f610f8a886312d49854
[ "MIT" ]
18
2019-03-14T08:41:33.000Z
2022-01-27T01:36:18.000Z
#pragma once #include "Arp/System/Core/Arp.h" #include "Arp/System/Acf/ComponentBase.hpp" #include "Arp/System/Acf/IApplication.hpp" #include "Arp/Plc/Commons/Meta/MetaComponentBase.hpp" #include "Arp/System/Commons/Logging.h" #include "Arp/System/Commons/Threading/WorkerThread.hpp" #include "Arp/Plc/Domain/Services/IPlcManagerService2.hpp" namespace OpcPlcManager { using namespace Arp; using namespace Arp::System::Acf; using namespace Arp::Plc::Commons::Meta; using namespace Arp::Plc::Domain::Services; //#acfcomponent class OpcPlcManagerComponent : public ComponentBase, public MetaComponentBase, private Loggable<OpcPlcManagerComponent> { public: // typedefs public: // construction/destruction OpcPlcManagerComponent(IApplication& application, const String& name); virtual ~OpcPlcManagerComponent() = default; public: // IComponent operations void Initialize() override; void SubscribeServices()override; void LoadSettings(const String& settingsPath)override; void SetupSettings()override; void PublishServices()override; void LoadConfig() override; void SetupConfig() override; void ResetConfig() override; void Dispose()override; void PowerDown()override; public: // MetaComponentBase operations void RegisterComponentPorts() override; private: // methods OpcPlcManagerComponent(const OpcPlcManagerComponent& arg) = delete; OpcPlcManagerComponent& operator= (const OpcPlcManagerComponent& arg) = delete; public: // static factory operations static IComponent::Ptr Create(Arp::System::Acf::IApplication& application, const String& name); private: // fields WorkerThread workerThreadInstance; IPlcManagerService2::Ptr plcManagerService2Ptr = nullptr; private: // methods void workerThreadBody(void); public: // ports // One struct is defined for each OPC UA method // Each struct contains the method input and output parameters, // and two special UA_* variables. struct GET_PLC_STATE { //#attributes(Input|Opc) Arp::int16 UA_MethodState = 0; //#attributes(Output|Opc) Arp::uint32 state = 0; //#attributes(Output|Opc) Arp::uint32 UA_StatusCode = 0; }; struct START { //#attributes(Input|Opc) Arp::uint8 startKind = 0; //#attributes(Input|Opc) Arp::boolean async = false; //#attributes(Input|Opc) Arp::int16 UA_MethodState = 0; //#attributes(Output|Opc) Arp::uint32 UA_StatusCode = 0; }; struct STOP { //#attributes(Input|Opc) Arp::boolean async = false; //#attributes(Input|Opc) Arp::int16 UA_MethodState = 0; //#attributes(Output|Opc) Arp::uint32 UA_StatusCode = 0; }; // Now the port variables themselves //#port GET_PLC_STATE GetPlcState; //#port START Start; //#port STOP Stop; }; inline IComponent::Ptr OpcPlcManagerComponent::Create(Arp::System::Acf::IApplication& application, const String& name) { return IComponent::Ptr(new OpcPlcManagerComponent(application, name)); } } // end of namespace OpcPlcManager
27.99115
119
0.69902
Siddu96
8ace25887d25917d2cdfb7b38d3adfc887ad773d
2,611
cpp
C++
tsplp/src/LinearVariableComposition.cpp
sebrockm/mtsp-vrp
28955855d253f51fcb9397a0b22c6774f66f8d55
[ "MIT" ]
null
null
null
tsplp/src/LinearVariableComposition.cpp
sebrockm/mtsp-vrp
28955855d253f51fcb9397a0b22c6774f66f8d55
[ "MIT" ]
null
null
null
tsplp/src/LinearVariableComposition.cpp
sebrockm/mtsp-vrp
28955855d253f51fcb9397a0b22c6774f66f8d55
[ "MIT" ]
null
null
null
#include "LinearVariableComposition.hpp" #include "Variable.hpp" #include <algorithm> tsplp::LinearVariableComposition tsplp::operator*(double factor, LinearVariableComposition linearComp) { for (auto& coef : linearComp.m_coefficients) coef *= factor; linearComp.m_constant *= factor; return linearComp; } tsplp::LinearVariableComposition tsplp::operator+(LinearVariableComposition lhs, LinearVariableComposition rhs) { auto& biggerOne = lhs.m_coefficients.size() > rhs.m_coefficients.size() ? lhs : rhs; const auto& smallerOne = lhs.m_coefficients.size() > rhs.m_coefficients.size() ? rhs : lhs; return std::move(biggerOne += smallerOne); } tsplp::LinearVariableComposition tsplp::operator+(LinearVariableComposition lhs, double rhs) { lhs.m_constant += rhs; return lhs; } tsplp::LinearVariableComposition& tsplp::operator+=(LinearVariableComposition& lhs, LinearVariableComposition const& rhs) { for (size_t i = 0; i < rhs.m_variables.size(); ++i) { const auto iter = std::upper_bound(lhs.m_variables.begin(), lhs.m_variables.end(), rhs.m_variables[i], VariableLess{}); if (iter != lhs.m_variables.end() && iter->GetId() == rhs.m_variables[i].GetId()) { const auto id = static_cast<size_t>(iter - lhs.m_variables.begin()); lhs.m_coefficients[id] += rhs.m_coefficients[i]; } else { const auto coefIter = lhs.m_coefficients.begin() + (iter - lhs.m_variables.begin()); lhs.m_variables.insert(iter, rhs.m_variables[i]); lhs.m_coefficients.insert(coefIter, rhs.m_coefficients[i]); } } lhs.m_constant += rhs.m_constant; return lhs; } tsplp::LinearVariableComposition tsplp::operator-(LinearVariableComposition operand) { for (auto& coef : operand.m_coefficients) coef *= -1.0; operand.m_constant *= -1.0; return operand; } tsplp::LinearVariableComposition tsplp::operator-(LinearVariableComposition lhs, LinearVariableComposition rhs) { return std::move(lhs) + (-std::move(rhs)); } tsplp::LinearVariableComposition::LinearVariableComposition(double constant) : m_constant(constant) { } tsplp::LinearVariableComposition::LinearVariableComposition(const Variable& variable) : m_variables{ variable }, m_coefficients{ 1 } { } double tsplp::LinearVariableComposition::Evaluate(const Model& model) const { double result = m_constant; for (size_t i = 0; i < m_coefficients.size(); ++i) result += m_coefficients[i] * m_variables[i].GetObjectiveValue(model); return result; }
30.011494
127
0.695136
sebrockm
8acfa0924b6d75af5d6a02806fa3522c2625cab5
12,242
cpp
C++
src/linereader.cpp
px86/hush
a8837bd99799757395417cf2ec48ebf56107b145
[ "MIT" ]
null
null
null
src/linereader.cpp
px86/hush
a8837bd99799757395417cf2ec48ebf56107b145
[ "MIT" ]
2
2022-02-28T05:24:22.000Z
2022-02-28T06:38:46.000Z
src/linereader.cpp
px86/hush
a8837bd99799757395417cf2ec48ebf56107b145
[ "MIT" ]
null
null
null
#include <cctype> #include <fstream> #include <iostream> #include <string> #include <sys/ioctl.h> #include <unistd.h> #include "linereader.hpp" // Word delimeters const char *delimeters = " \t\n:-_'\"()[]{}"; TermHandle::TermHandle() { m_raw_mode_enabled = false; // Save default termios. if (tcgetattr(STDIN_FILENO, &m_orig_termios)) { perror("Error: tcgetattr failed"); exit(EXIT_FAILURE); } // Settings for raw mode. m_raw_termios.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON); m_raw_termios.c_oflag &= ~OPOST; m_raw_termios.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN); m_raw_termios.c_cflag &= ~(CSIZE | PARENB); m_raw_termios.c_cflag |= CS8; // minimum number of bytes to read before returning m_raw_termios.c_cc[VMIN] = 1; // timeout in deci-seconds (1/10) (Does it matter now?) m_raw_termios.c_cc[VTIME] = 1; } inline void TermHandle::enable_raw_mode() { if (m_raw_mode_enabled) return; if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &m_raw_termios)) { perror("Error: tcsetattr failed while trying to enable raw mode"); exit(EXIT_FAILURE); } m_raw_mode_enabled = true; } inline void TermHandle::disable_raw_mode() { if (!m_raw_mode_enabled) return; if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &m_orig_termios)) { perror("Error: tcsetattr failed while trying to disable raw mode"); exit(EXIT_FAILURE); } m_raw_mode_enabled = false; } auto LineReader::readline(const char *prompt) -> std::string { m_term.enable_raw_mode(); // Add a new string to m_history. m_history.push_back(""); m_line = m_history.rbegin(); m_insert_char_at = 0; m_cursor_position = m_term.get_cursor_position(); m_last_was_yank = false; auto draw_line = [this, prompt]() { std::cout << "\x1b[" << m_cursor_position.row << ';' << m_cursor_position.col << 'H'; // Clear the screen from current line to the bottom std::cout << "\r\x1b[J" << prompt << *m_line; // Put the cursor at the current insertion position auto cols_left = m_line->size() - m_insert_char_at; if (cols_left > 0) std::cout << "\x1b[" << cols_left << "D"; std::cout.flush(); }; bool done = false; while (!done) { draw_line(); int32_t key = m_term.read_key(); if (key == -1) { perror("Error: read_key returned '-1'"); continue; } else done = process_key(key); } m_term.disable_raw_mode(); return *m_line; } inline auto TermHandle::read_key() const -> std::int32_t { auto read_byte = []() { char byte; if (read(STDIN_FILENO, &byte, 1) != 1) { perror("Error: read failed while trying to read a byte"); exit(EXIT_FAILURE); } else return byte; }; char seq[4]; seq[0] = read_byte(); if (seq[0] != '\x1b') return seq[0]; seq[1] = read_byte(); switch (seq[1]) { case 'f' : return ALT_f; case 'b' : return ALT_b; case 'd' : return ALT_d; case 'l' : return ALT_l; case 'u' : return ALT_u; case 'c' : return ALT_c; case 't' : return ALT_t; case 'y' : return ALT_y; case '[' : seq[2] = read_byte(); if (seq[2]>='0' && seq[2]<='9') { seq[3] = read_byte(); if (seq[3] == '~') { // \x1b [ ? ~ switch (seq[2]) { case '1': return HOME_KEY; case '3': return DEL_KEY; case '4': return END_KEY; case '5': return PAGE_UP; case '6': return PAGE_DOWN; case '7': return HOME_KEY; case '8': return END_KEY; } } } else { // \x1b [ ? switch (seq[2]) { case 'A': return ARROW_UP; case 'B': return ARROW_DOWN; case 'C': return ARROW_RIGHT; case 'D': return ARROW_LEFT; case 'H': return HOME_KEY; case 'F': return END_KEY; } } default: return '\x1b'; } } inline auto TermHandle::get_cursor_position() const -> Position { char buff[32]; size_t pos = 0; // \x1b[6n query for cursor position. if (write(STDOUT_FILENO, "\x1b[6n", 4) < 4) { perror("Error: write failed in get_cursor_position"); exit(EXIT_FAILURE); } while (pos < sizeof(buff)) { if (read(STDIN_FILENO, buff + pos, 1) == -1) { perror("Error: read failed in get_cursor_position"); exit(EXIT_FAILURE); } if (buff[pos++] == 'R') break; } buff[pos] = '\0'; Position cursor_pos; sscanf(buff, "\x1b[%ud;%udR", &cursor_pos.row, &cursor_pos.col); return cursor_pos; } inline auto LineReader::process_key(int key) -> bool { // Return 'true' to quit, 'false' to continue processing more keys. if (key != CTRL_KEY('y') && key != ALT_y) m_last_was_yank = false; switch (key) { case ENTER_KEY: if (m_line->empty()) { m_history.pop_back(); m_cursor_position = m_term.get_cursor_position(); } // return from readline std::cout << "\r\n"; return true; case CTRL_KEY('h'): case BACKSPACE: if (m_insert_char_at > 0) m_line->erase(--m_insert_char_at, 1); break; case DEL_KEY: case CTRL_KEY('d'): if (m_line->empty()) { m_good = false; m_term.disable_raw_mode(); close(STDIN_FILENO); return true; // end the loop } if (m_insert_char_at < m_line->size()) m_line->erase(m_insert_char_at, 1); break; case CTRL_KEY('c'): // Discard the current line. std::cout << "\x1b[31m" "^C" "\x1b[m\n"; m_cursor_position = m_term.get_cursor_position(); m_line->clear(); m_insert_char_at = 0; break; case CTRL_KEY('l'): m_cursor_position.row = 1; break; case HOME_KEY: case CTRL_KEY('a'): m_insert_char_at = 0; break; case END_KEY: case CTRL_KEY('e'): m_insert_char_at = m_line->size(); break; case ARROW_LEFT: case CTRL_KEY('b'): if (m_insert_char_at > 0) --m_insert_char_at; break; case ARROW_RIGHT: case CTRL_KEY('f'): if (m_insert_char_at < m_line->size()) ++m_insert_char_at; break; case ARROW_DOWN: case CTRL_KEY('n'): if (m_line != m_history.rbegin()) { --m_line; m_insert_char_at = m_line->size(); } break; case ARROW_UP: case CTRL_KEY('p'): if (m_line != m_history.rend()-1) { ++m_line; m_insert_char_at = m_line->size(); } break; case ALT_f: { auto i = m_line->find_first_not_of(delimeters, m_insert_char_at); if (i != std::string::npos) i = m_line->find_first_of(delimeters, i+1); m_insert_char_at = (i != std::string::npos) ? i:m_line->size(); } break; case ALT_b: { if (m_insert_char_at == 0) break; auto i = m_line->find_last_not_of(delimeters, m_insert_char_at - 1); if (i != std::string::npos) i = m_line->find_last_of(delimeters, i); m_insert_char_at = (i != std::string::npos) ? ++i : 0; } break; case ALT_d: { auto i = m_line->find_first_not_of(delimeters, m_insert_char_at); if (i != std::string::npos) i = m_line->find_first_of(delimeters, i+1); auto j = (i != std::string::npos) ? i:m_line->size(); m_line->erase(m_insert_char_at, j-m_insert_char_at); } break; case ALT_l: { auto i = m_line->find_first_not_of(delimeters, m_insert_char_at); if (i == std::string::npos) break; auto j = m_line->find_first_of(delimeters, i+1); if (j == std::string::npos) j = m_line->size(); for (auto t=i; t<j; ++t) {m_line->at(t) = tolower(m_line->at(t));}; m_insert_char_at = j; } break; case ALT_u: { auto i = m_line->find_first_not_of(delimeters, m_insert_char_at); if (i == std::string::npos) break; auto j = m_line->find_first_of(delimeters, i+1); if (j == std::string::npos) j = m_line->size(); for (auto t=i; t<j; ++t) {m_line->at(t) = toupper(m_line->at(t));}; m_insert_char_at = j; } break; case ALT_c: { auto i = m_line->find_first_not_of(delimeters, m_insert_char_at); if (i == std::string::npos) break; m_line->at(i) = toupper(m_line->at(i)); auto j = m_line->find_first_of(delimeters, i+1); if (j == std::string::npos) j = m_line->size(); for (auto t=i+1; t<j; ++t) {m_line->at(t) = tolower(m_line->at(t));}; m_insert_char_at = j; } break; case CTRL_KEY('t'): if (m_insert_char_at != 0 && m_line->size() > 1) { if (m_insert_char_at == m_line->size()) { char c = m_line->at(m_insert_char_at-2); m_line->at(m_insert_char_at - 2) = m_line->at(m_insert_char_at - 1); m_line->at(m_insert_char_at - 1) = c; } else { char c = m_line->at(m_insert_char_at-1); m_line->at(m_insert_char_at - 1) = m_line->at(m_insert_char_at); m_line->at(m_insert_char_at) = c; ++m_insert_char_at; } } break; case ALT_t: if (m_insert_char_at != 0 && m_insert_char_at != m_line->size() && m_line->size() > 2) { // r for right, and l for left hand side word size_t r_start, r_end, l_start, l_end; if (std::isspace(m_line->at(m_insert_char_at))) { r_start = m_line->find_first_not_of(delimeters, m_insert_char_at); if (r_start == std::string::npos) break; } else { r_start = m_line->find_last_of(delimeters, m_insert_char_at); if (r_start == std::string::npos) break; else r_start++; } r_end = m_line->find_first_of(delimeters, r_start); if (r_end == std::string::npos) r_end = m_line->size(); else r_end--; l_end = m_line->find_last_not_of(delimeters, r_start-1); if (l_end == std::string::npos) break; l_start = m_line->find_last_of(delimeters, l_end); if (l_start == std::string::npos) l_start = 0; else l_start++; auto wr = m_line->substr(r_start, r_end - r_start + 1); auto wl = m_line->substr(l_start, l_end - l_start + 1); m_line->erase(r_start, wr.size()); m_line->insert(r_start, wl, 0, wl.size()); m_line->erase(l_start, wl.size()); m_line->insert(l_start, wr, 0, wr.size()); m_insert_char_at = r_start + wr.size(); } break; case CTRL_KEY('k'): { auto killed_text = m_line->substr(m_insert_char_at, m_line->size() - m_insert_char_at); m_killring.push_back(killed_text); m_current_kill = m_killring.rbegin(); m_line->erase(m_insert_char_at, m_line->size() - m_insert_char_at); } break; case CTRL_KEY('u'): { auto killed_text = m_line->substr(0, m_insert_char_at); m_killring.push_back(killed_text); m_current_kill = m_killring.rbegin(); m_line->erase(0, m_insert_char_at); m_insert_char_at = 0; } break; case CTRL_KEY('y'): if (m_killring.empty()) break; m_line->insert(m_insert_char_at, *m_current_kill); m_insert_char_at += m_current_kill->size(); m_last_was_yank = true; break; case ALT_y: if (!m_last_was_yank || m_killring.size() == 1) break; m_insert_char_at -= m_current_kill->size(); m_line->erase(m_insert_char_at, m_current_kill->size()); ++m_current_kill; if (m_current_kill == m_killring.rend()) m_current_kill = m_killring.rbegin(); m_line->insert(m_insert_char_at, *m_current_kill); m_insert_char_at += m_current_kill->size(); break; default: // Insert non-control characters to the current line at 'm_insert_char_at' position. if (!iscntrl(key)) { if (m_insert_char_at >= 0 and m_insert_char_at < m_line->size()) { m_line->insert(m_line->begin() + m_insert_char_at, key); } else if (m_insert_char_at == m_line->size()) { m_line->push_back(key); } m_insert_char_at++; } } return false; } LineReader::LineReader(const char *historypath) { m_historypath = historypath; auto history_file = std::ifstream(historypath); if (history_file) { std::string hist_line; while (history_file) { std::getline(history_file, hist_line); if (!hist_line.empty()) m_history.push_back(hist_line); } } } LineReader::~LineReader() { if (m_historypath != nullptr) { auto history_file = std::ofstream(m_historypath); if (history_file) { for (const auto& hist_lin: m_history) history_file << hist_lin << '\n'; history_file.close(); } } }
26.440605
88
0.611746
px86
8ad24bf0de4c4a683c9d6568ba43b091a7658883
3,500
cpp
C++
tests/operators/glob.cpp
shlyamster/sqlite_orm
a6c07b588a173f93c9a818371dd07c199442791d
[ "BSD-3-Clause" ]
1
2021-12-27T15:23:13.000Z
2021-12-27T15:23:13.000Z
tests/operators/glob.cpp
shlyamster/sqlite_orm
a6c07b588a173f93c9a818371dd07c199442791d
[ "BSD-3-Clause" ]
null
null
null
tests/operators/glob.cpp
shlyamster/sqlite_orm
a6c07b588a173f93c9a818371dd07c199442791d
[ "BSD-3-Clause" ]
null
null
null
/** * Obtained from here https://www.tutlane.com/tutorial/sqlite/sqlite-glob-operator */ #include <sqlite_orm/sqlite_orm.h> #include <catch2/catch.hpp> #include <vector> // std::vector #include <algorithm> // std::find_if, std::count using namespace sqlite_orm; TEST_CASE("Glob") { struct Employee { int id = 0; std::string firstName; std::string lastName; float salary = 0; int deptId = 0; }; auto storage = make_storage({}, make_table("emp_master", make_column("emp_id", &Employee::id, primary_key(), autoincrement()), make_column("first_name", &Employee::firstName), make_column("last_name", &Employee::lastName), make_column("salary", &Employee::salary), make_column("dept_id", &Employee::deptId))); storage.sync_schema(); std::vector<Employee> employees = { Employee{1, "Honey", "Patel", 10100, 1}, Employee{2, "Shweta", "Jariwala", 19300, 2}, Employee{3, "Vinay", "Jariwala", 35100, 3}, Employee{4, "Jagruti", "Viras", 9500, 2}, Employee{5, "Shweta", "Rana", 12000, 3}, Employee{6, "sonal", "Menpara", 13000, 1}, Employee{7, "Yamini", "Patel", 10000, 2}, Employee{8, "Khyati", "Shah", 500000, 3}, Employee{9, "Shwets", "Jariwala", 19400, 2}, }; storage.replace_range(employees.begin(), employees.end()); auto expectIds = [](const std::vector<Employee> &employees, const std::vector<decltype(Employee::id)> ids) { for(auto expectedId: ids) { REQUIRE(find_if(employees.begin(), employees.end(), [expectedId](auto &employee) { return employee.id == expectedId; }) != employees.end()); } return false; }; { auto employees = storage.get_all<Employee>(where(glob(&Employee::salary, "1*"))); REQUIRE(employees.size() == 6); expectIds(employees, {1, 2, 5, 6, 7, 9}); } { auto employees = storage.get_all<Employee>(where(glob(&Employee::firstName, "Shwet?"))); REQUIRE(employees.size() == 3); expectIds(employees, {2, 5, 9}); } { auto employees = storage.get_all<Employee>(where(glob(&Employee::lastName, "[A-J]*"))); REQUIRE(employees.size() == 3); expectIds(employees, {2, 3, 9}); } { auto employees = storage.get_all<Employee>(where(glob(&Employee::lastName, "[^A-J]*"))); REQUIRE(employees.size() == 6); expectIds(employees, {1, 4, 5, 6, 7, 8}); } { auto rows = storage.select(glob(&Employee::firstName, "S*")); REQUIRE(rows.size() == 9); auto trueValuesCount = std::count(rows.begin(), rows.end(), true); REQUIRE(trueValuesCount == 3); } { auto rows = storage.select(glob(distinct(&Employee::firstName), "S*")); REQUIRE(rows.size() == 2); auto trueValuesCount = std::count(rows.begin(), rows.end(), true); REQUIRE(trueValuesCount == 1); } { auto rows = storage.select(columns(not glob(&Employee::firstName, "S*"))); REQUIRE(rows.size() == 9); auto trueValuesCount = std::count(rows.begin(), rows.end(), std::tuple<bool>{true}); REQUIRE(trueValuesCount == 6); } }
39.325843
112
0.542
shlyamster
e9d732db267539b08f646e55fea4cf543af7a048
1,785
cc
C++
daemon/cmdline.cc
BenHuddleston/kv_engine
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
[ "MIT", "BSD-3-Clause" ]
104
2017-05-22T20:41:57.000Z
2022-03-24T00:18:34.000Z
daemon/cmdline.cc
BenHuddleston/kv_engine
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
[ "MIT", "BSD-3-Clause" ]
3
2017-11-14T08:12:46.000Z
2022-03-03T11:14:17.000Z
daemon/cmdline.cc
BenHuddleston/kv_engine
78123c9aa2c2feb24b7c31eecc862bf2ed6325e4
[ "MIT", "BSD-3-Clause" ]
71
2017-05-22T20:41:59.000Z
2022-03-29T10:34:32.000Z
/* * Copyright 2021-Present Couchbase, Inc. * * Use of this software is governed by the Business Source License included * in the file licenses/BSL-Couchbase.txt. As of the Change Date specified * in that file, in accordance with the Business Source License, use of this * software will be governed by the Apache License, Version 2.0, included in * the file licenses/APL2.txt. */ #include "cmdline.h" #include "config_parse.h" #include "memcached.h" #include "settings.h" #include <getopt.h> #include <iostream> #include <vector> static std::string config_file; static void usage() { std::cerr << "memcached " << get_server_version() << R"( -C file Read configuration from file -h print this help and exit )"; } void parse_arguments(int argc, char** argv) { const std::vector<option> options = { {"config", required_argument, nullptr, 'C'}, {"help", no_argument, nullptr, 'h'}, {nullptr, 0, nullptr, 0}}; int cmd; // Tell getopt to restart the parsing (if we used getopt before calling // this method) optind = 1; while ((cmd = getopt_long(argc, argv, "C:h", options.data(), nullptr)) != EOF) { switch (cmd) { case 'C': config_file = optarg; break; case 'h': usage(); std::exit(EXIT_SUCCESS); default: usage(); std::exit(EXIT_FAILURE); } } if (config_file.empty()) { std::cerr << "Configuration file must be specified with -C" << std::endl; std::exit(EXIT_FAILURE); } load_config_file(config_file, Settings::instance()); } const std::string& get_config_file() { return config_file; }
25.869565
78
0.594398
BenHuddleston
e9d89881e76248c58c7aaedebc10be0c0534fc2e
934
cpp
C++
LiberoEngine/src/IComponent.cpp
Kair0z/LiberoEngine2D
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
[ "MIT" ]
null
null
null
LiberoEngine/src/IComponent.cpp
Kair0z/LiberoEngine2D
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
[ "MIT" ]
null
null
null
LiberoEngine/src/IComponent.cpp
Kair0z/LiberoEngine2D
79fb93d7bbb5f5e6b805da6826c64ffa520989c3
[ "MIT" ]
null
null
null
#include "PCH.h" #include "IComponent.h" #include "LiberoECS_EntityMaster.h" namespace Libero { const ComponentID IComponent::GetID() const { return m_ID; } const EntityID IComponent::GetOwner() const { return m_Owner; } IEntity* IComponent::GetOwnerEntity() const { if (!m_pEntityMasterRef) return nullptr; return m_pEntityMasterRef->GetEntity(GetOwner()); } void IComponent::SetActive(bool active) { m_IsActive = active; } bool IComponent::IsActive() const { return m_IsActive; } const bool IComponent::operator==(const IComponent& other) const { return !(*this != other); } const bool IComponent::operator!=(const IComponent& other) const { if (m_ID != other.m_ID) return true; if (m_Owner != other.m_Owner) return true; return false; } std::ofstream& IComponent::ToFile(std::ofstream& ofs) const { ofs << "- Unwritten Component: TODO... \n"; ofs << "\n"; return ofs; } }
17.622642
65
0.687366
Kair0z
e9defe1ad3ba9ffbca335060dec63dec5ac82040
1,671
cpp
C++
demboyz/netmessages/svc_getcvarvalue.cpp
juniorsgithub/demboyz
73ba4f105e5670ab07334e867a3f57fb1de2ff55
[ "MIT" ]
42
2015-09-24T01:14:26.000Z
2021-12-25T14:28:40.000Z
demboyz/netmessages/svc_getcvarvalue.cpp
juniorsgithub/demboyz
73ba4f105e5670ab07334e867a3f57fb1de2ff55
[ "MIT" ]
3
2015-10-11T17:51:07.000Z
2018-07-14T01:04:05.000Z
demboyz/netmessages/svc_getcvarvalue.cpp
juniorsgithub/demboyz
73ba4f105e5670ab07334e867a3f57fb1de2ff55
[ "MIT" ]
12
2015-07-16T02:26:34.000Z
2021-09-13T23:29:36.000Z
#include "svc_getcvarvalue.h" #include "base/bitfile.h" #include "base/jsonfile.h" namespace NetHandlers { bool SVC_GetCvarValue_BitRead_Internal(BitRead& bitbuf, SourceGameContext& context, NetMsg::SVC_GetCvarValue* data) { data->cookie = bitbuf.ReadSBitLong(32); bitbuf.ReadString(data->cvarName, sizeof(data->cvarName)); return !bitbuf.IsOverflowed(); } bool SVC_GetCvarValue_BitWrite_Internal(BitWrite& bitbuf, const SourceGameContext& context, NetMsg::SVC_GetCvarValue* data) { bitbuf.WriteSBitLong(data->cookie, 32); bitbuf.WriteString(data->cvarName); return !bitbuf.IsOverflowed(); } bool SVC_GetCvarValue_JsonRead_Internal(JsonRead& jsonbuf, SourceGameContext& context, NetMsg::SVC_GetCvarValue* data) { base::JsonReaderObject reader = jsonbuf.ParseObject(); assert(!reader.HasReadError()); data->cookie = reader.ReadInt32("cookie"); reader.ReadString("cvarName", data->cvarName, sizeof(data->cvarName)); return !reader.HasReadError(); } bool SVC_GetCvarValue_JsonWrite_Internal(JsonWrite& jsonbuf, const SourceGameContext& context, NetMsg::SVC_GetCvarValue* data) { jsonbuf.Reset(); jsonbuf.StartObject(); jsonbuf.WriteInt32("cookie", data->cookie); jsonbuf.WriteString("cvarName", data->cvarName); jsonbuf.EndObject(); return jsonbuf.IsComplete(); } void SVC_GetCvarValue_ToString_Internal(std::ostringstream& out, NetMsg::SVC_GetCvarValue* data) { out << "svc_GetCvarValue: cvar: " << data->cvarName << ", cookie: " << data->cookie; } }
35.553191
130
0.681029
juniorsgithub
e9e063d717b44e77c25c9861ddaa856f0258c513
768
cpp
C++
source/circle.cpp
Vani4ka/programmiersprachen_aufgabenblatt_4
f1171f2c274f2d503691932a20fd0a31bc2f6ded
[ "MIT" ]
null
null
null
source/circle.cpp
Vani4ka/programmiersprachen_aufgabenblatt_4
f1171f2c274f2d503691932a20fd0a31bc2f6ded
[ "MIT" ]
null
null
null
source/circle.cpp
Vani4ka/programmiersprachen_aufgabenblatt_4
f1171f2c274f2d503691932a20fd0a31bc2f6ded
[ "MIT" ]
null
null
null
#include <iostream> #include "circle.hpp" #include <math.h> #include <cmath> Circle::Circle(Vec2 const& c, float r): center_{c}, radius_{r}, color_{{0.0}} {} Circle::Circle(Vec2 const& c, float r, Color const& col): center_{c}, radius_{r}, color_{col} {} Vec2 Circle::getCenter() const { return center_; } float Circle::getRadius() const { return radius_; } bool operator<( Circle const& c1 , Circle const& c2 ) { if(c1.getRadius()<c2.getRadius()) { return true; } else return false; } bool operator>( Circle const& c1 , Circle const& c2 ) { if(c1.getRadius()>c2.getRadius()) { return true; } else return false; } bool operator==( Circle const& c1 , Circle const& c2 ) { if (c1.getRadius()==c2.getRadius()) { return true; } else return false; }
17.066667
57
0.66276
Vani4ka
e9e254b9a80e5608f03e319cceb11e38dedd2cdb
7,869
hpp
C++
src/include/libmath/CVector2.hpp
pedrospeixoto/sweet
224248181e92615467c94b4e163596017811b5eb
[ "MIT" ]
null
null
null
src/include/libmath/CVector2.hpp
pedrospeixoto/sweet
224248181e92615467c94b4e163596017811b5eb
[ "MIT" ]
null
null
null
src/include/libmath/CVector2.hpp
pedrospeixoto/sweet
224248181e92615467c94b4e163596017811b5eb
[ "MIT" ]
1
2019-03-27T01:17:59.000Z
2019-03-27T01:17:59.000Z
/* * Copyright 2010 Martin Schreiber * * 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. * * Author: Martin Schreiber (schreiberx@gmail.com) */ /* * CHANGELOG: * * 2008-02-27: martin schreiber * dist2(); * * 2008-10-22: martin schreiber * made some modifications to use generic vector CVector * */ #ifndef __CVECTOR_HH #error "dont include CVector3.hpp directly!" #endif #ifndef __CVECTOR2_HH #define __CVECTOR2_HH #include <iostream> #include <cmath> /** * \brief 2D Vector handler */ template <typename T> class CVector<2,T> { public: T data[2]; ///< vector data /** * default constructor */ inline CVector() { setZero(); } /** * initialize vector with (x0, x1) */ inline CVector(const T x0, const T x1) { data[0] = x0; data[1] = x1; } /** * initialize all vector components with the scalar value 'x' */ inline CVector(const T x) { data[0] = x; data[1] = x; } /** * initialize vector components with the array 'v' */ inline CVector(const T v[2]) { data[0] = v[0]; data[1] = v[1]; } /** * set all components of vector to 0 */ inline void setZero() { data[0] = T(0); data[1] = T(0); } /** * return normalized (length=1) vector */ inline CVector getNormal() { CVector<2,T> v = *this; T inv_length = 1.0f/sqrtf(v[0]*v[0] + v[1]*v[1]); v[0] *= inv_length; v[1] *= inv_length; return v; } /** * compute and return the dot product of this vector and 'v' * \return dot product */ inline T getDotProd(const CVector<2,T> &v) { return v.data[0]*data[0] + v.data[1]*data[1]; } /** * compute and return the cross product of this vector and 'a' * \return cross product */ inline T getCrossProd(CVector<2,T> &a) { return data[0]*a.data[1] - data[1]*a.data[0]; } /** * return elements in cube. * e.g. if the vector components give the resolution of a cube, this function returns the number of cells */ inline T elements() { return (data[0]*data[1]); } /** * return length of vector */ inline T length() { return std::sqrt(data[0]*data[0] + data[1]*data[1]); } /** * return (length*length) of vector */ inline T length2() { return data[0]*data[0] + data[1]*data[1]; } /** * return square distance to other point */ inline T dist2(const CVector<2,T> &v) { CVector<2,T> d = CVector<2,T>(v.data[0] - data[0], v.data[1] - data[1]); return (d[0]*d[0] + d[1]*d[1]); } /** * return distance to other point */ inline T dist(const CVector<2,T> &v) { CVector<2,T> d = CVector<2,T>(v.data[0] - data[0], v.data[1] - data[1]); return sqrtf(d[0]*d[0] + d[1]*d[1]); } /** * normalize the vector */ inline void normalize() { T il = 1/length(); data[0] *= il; data[1] *= il; } /** * clamp to values -1 and 1 */ inline void clamp1_1() { data[0] = (data[0] < -1 ? -1 : (data[0] > 1 ? 1 : data[0])); data[1] = (data[1] < -1 ? -1 : (data[1] > 1 ? 1 : data[1])); } /******************* * OPERATORS *******************/ /// assign values of a[2] to this vector and return reference to this vector inline CVector<2,T>& operator=(const T a[2]) { data[0] = a[0]; data[1] = a[1]; return *this; }; /// assign values of vector a to this vector and return reference to this vector inline CVector<2,T>& operator=(CVector<2,T> const& a) { data[0] = a.data[0]; data[1] = a.data[1]; return *this; }; /// return negative of this vector inline CVector<2,T> operator-() { return CVector<2,T>(-data[0], -data[1]); } /// return new vector (this+a) inline CVector<2,T> operator+(const T a) { return CVector<2,T>(data[0]+a, data[1]+a); } /// return new vector (this-a) inline CVector<2,T> operator-(const T a) { return CVector<2,T>(data[0]-a, data[1]-a); } /// return new vector with component wise (this*a) inline CVector<2,T> operator*(const T a) { return CVector<2,T>(data[0]*a, data[1]*a); } /// return new vector with component wise (this/a) inline CVector<2,T> operator/(const T a) { return CVector<2,T>(data[0]/a, data[1]/a); } /// add a to this vector and return reference to this vector inline CVector<2,T>& operator+=(const T a) { data[0] += a; data[1] += a; return *this; } /// subtract a from this vector and return reference to this vector inline CVector<2,T>& operator-=(const T a) { data[0] -= a; data[1] -= a; return *this; } /// multiply each component of this vector with scalar a and return reference to this vector inline CVector<2,T>& operator*=(const T a) { data[0] *= a; data[1] *= a; return *this; } /// divide each component of this vector by scalar a and return reference to this vector inline CVector<2,T>& operator/=(const T a) { data[0] /= a; data[1] /= a; return *this; } // CVector /// return new vector with sum of this vector and v inline CVector<2,T> operator+(const CVector<2,T> &v) { return CVector<2,T>(data[0]+v.data[0], data[1]+v.data[1]); } /// return new vector with subtraction of vector v from this vector inline CVector<2,T> operator-(const CVector<2,T> &v) { return CVector<2,T>(data[0]-v.data[0], data[1]-v.data[1]); } /// return new vector with values of this vector multiplied component wise with vector v inline CVector<2,T> operator*(const CVector<2,T> &v) { return CVector<2,T>(data[0]*v.data[0], data[1]*v.data[1]); } /// return new vector with values of this vector divided component wise by components of vector v inline CVector<2,T> operator/(const CVector<2,T> &v) { return CVector<2,T>(data[0]/v.data[0], data[1]/v.data[1]); } /// return this vector after adding v inline CVector<2,T>& operator+=(const CVector<2,T> &v) { data[0] += v.data[0]; data[1] += v.data[1]; return *this; } /// return this vector after subtracting v inline CVector<2,T>& operator-=(const CVector<2,T> &v) { data[0] -= v.data[0]; data[1] -= v.data[1]; return *this; } /// return true, if each component of the vector is equal to the corresponding component of vector v inline bool operator==(const CVector<2,T> &v) { return bool(data[0] == v.data[0] && data[1] == v.data[1]); } /// return true, if at lease component of the vector is not equal to the corresponding component of vector v inline bool operator!=(const CVector<2,T> &v) { return bool(data[0] != v.data[0] || data[1] != v.data[1]); } /** * access element i */ inline T& operator[](const int i) { #if DEBUG if (i < 0 || i >= 2) { std::cerr << "OUT OF ARRAY ACCESS!!! creating null exception..." << std::endl; *((int*)(0)) = 0; } #endif return data[i]; } /** * \brief compare set for sort operation */ struct compareSet { /** * compare set operator */ inline bool operator()(CVector<2,T> *v1, CVector<2,T> *v2) { if ((*v1)[0] != (*v2)[0]) return (*v1)[0] < (*v2)[0]; if ((*v1)[1] != (*v2)[1]) return (*v1)[1] < (*v2)[1]; return false; } /** * compare set operator */ inline bool operator()(const CVector<2,T> &v1, const CVector<2,T> &v2) { if (v1.data[0] != v2.data[0]) return v1.data[0] < v2.data[0]; if (v1.data[1] != v2.data[1]) return v1.data[1] < v2.data[1]; return false; } }; }; typedef CVector<2,double> vec2d; typedef CVector<2,float> vec2f; typedef CVector<2,int> vec2i; template <class T> inline ::std::ostream& operator<<(::std::ostream &co, const CVector<2,T> &v) { return co << "[" << v.data[0] << ", " << v.data[1] << "]"; } #endif
26.674576
118
0.617868
pedrospeixoto
e9e4e388634e975ce798ef203d17f703330834ee
2,061
hpp
C++
include/wui/theme/theme_impl.hpp
ud84/wui
354260df9882c3e582c2a337a4bbb8be6e030e13
[ "BSL-1.0" ]
1
2021-12-18T16:38:30.000Z
2021-12-18T16:38:30.000Z
include/wui/theme/theme_impl.hpp
ud84/wui
354260df9882c3e582c2a337a4bbb8be6e030e13
[ "BSL-1.0" ]
null
null
null
include/wui/theme/theme_impl.hpp
ud84/wui
354260df9882c3e582c2a337a4bbb8be6e030e13
[ "BSL-1.0" ]
null
null
null
// // Copyright (c) 2021-2022 Anton Golovkov (udattsk at gmail dot com) // // 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) // // Official repository: https://github.com/ud84/wui // #pragma once #include <wui/theme/i_theme.hpp> #include <map> namespace wui { class theme_impl : public i_theme { public: theme_impl(const std::string &name); virtual std::string get_name() const; virtual void set_color(const std::string &control, const std::string &value, color color_); virtual color get_color(const std::string &control, const std::string &value) const; virtual void set_dimension(const std::string &control, const std::string &value, int32_t dimension); virtual int32_t get_dimension(const std::string &control, const std::string &value) const; virtual void set_string(const std::string &control, const std::string &value, const std::string &str); virtual const std::string &get_string(const std::string &control, const std::string &value) const; virtual void set_font(const std::string &control, const std::string &value, const font &font_); virtual font get_font(const std::string &control, const std::string &value) const; virtual void set_image(const std::string &name, const std::vector<uint8_t> &data); virtual const std::vector<uint8_t> &get_image(const std::string &name); #ifdef _WIN32 virtual void load_resource(int32_t resource_index, const std::string &resource_section); #endif virtual void load_json(const std::string &json); virtual void load_file(const std::string &file_name); virtual void load_theme(const i_theme &theme_); virtual bool is_ok() const; private: std::string name; std::map<std::string, int32_t> ints; std::map<std::string, std::string> strings; std::map<std::string, font> fonts; std::map<std::string, std::vector<uint8_t>> imgs; std::string dummy_string; std::vector<uint8_t> dummy_image; bool ok; }; }
31.707692
106
0.716157
ud84
e9e5000faa8a69367e000cbb2c571573836a9eda
1,179
cpp
C++
30.substring-with-concatenation-of-all-words.161398902.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
30.substring-with-concatenation-of-all-words.161398902.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
30.substring-with-concatenation-of-all-words.161398902.ac.cpp
blossom2017/Leetcode
8bcfc2d5eeb344a1489b0d84a9a81a9f5d61281b
[ "Apache-2.0" ]
null
null
null
class Solution { public: vector<int> findSubstring(string s, vector<string>& words) { vector<int> ans; if(s.length()==0||words.size()==0)return ans; int len = words[0].length(); unordered_map<string,int>mp; for(int i=0;i<words.size();i++)mp[words[i]]++; int n = s.length(); int num = words.size(); for(int i=0;i<n-len*num+1;i++) { unordered_map<string,int> seen; int j=0; // cout<<"nnn"<<endl; while(j<num) { string t = s.substr(i+j*len,len); // cout<<t<<endl; if(mp.find(t)!=mp.end()) { // cout<<"hhh"; seen[t]++; // cout<<seen[t]<<" "; if(seen[t]>mp[t])break; } else { // cout<<"jjjj"; break; } j++; } if(j==num)ans.push_back(i); } return ans; } };
24.5625
64
0.336726
blossom2017
e9e62f7c86944755dd76b27b8f9776653deb0b4c
4,630
cpp
C++
SharedMemory_ut.cpp
jfern2011/SharedMemory
4b481b437159b6832c3095b49a182088e801cb74
[ "MIT" ]
null
null
null
SharedMemory_ut.cpp
jfern2011/SharedMemory
4b481b437159b6832c3095b49a182088e801cb74
[ "MIT" ]
null
null
null
SharedMemory_ut.cpp
jfern2011/SharedMemory
4b481b437159b6832c3095b49a182088e801cb74
[ "MIT" ]
null
null
null
#include <csignal> #include <cstdlib> #include <iostream> #include <utility> #include <vector> #include "util.h" #include "SharedMemory.h" bool sigint_raised = false; void sig_hander(int num) { std::printf("caught signal [%d]. exiting...\n", num); std::fflush(stdout); sigint_raised = true; } namespace SharedMemory { class MemoryManger_ut { public: MemoryManger_ut() { } ~MemoryManger_ut() { } int allocate(size_t size) { int id = _manager.allocate(size); if (id == -1) { std::printf("Not enough space. \n"); std::fflush(stdout); } else print(); return id; } void free(int id) { if (!_manager.free(id)) { std::printf("Invalid ID: %d\n", id); std::fflush(stdout); } else print(); } bool init(void* addr, size_t size) { AbortIfNot(_manager.init(addr, size), false); _buf_size = size; return true; } void print() { auto in_use = _manager._in_use; auto vacant = _manager._vacant; auto all = in_use; all.insert(all.end(), vacant.begin(), vacant.end()); for (auto iter = all.begin(), end = all.end(); iter != end; ++iter) { std::printf(" | %2d: %2lu",iter->id,iter->size); } std::printf(" |\n"); std::fflush(stdout); } bool run() { while (true) { std::cout << "> "; std::fflush(stdout); char _input[256]; std::cin.getline(_input, 256); std::string input(_input); Util::str_v args; Util::split(input, args); if (Util::trim(args[0]) == "allocate") { if (args.size() < 2) std::cout << "usage: allocate <size>" << std::endl; else { int size = Util::str_to_int32(args[1],10); if (errno == 0) { allocate(static_cast<size_t>(size)); } else { std::cout << "cannot convert " << args[1] << std::endl; errno = 0; } } } else if (Util::trim(args[0]) == "free") { if (args.size() < 2) std::cout << "usage: free <id>" << std::endl; else { int id = Util::str_to_int32(args[1],10); if (errno == 0) { free(id); } else { std::cout << "cannot convert " << args[1] << std::endl; errno = 0; } } } else if (Util::trim(args[0]) == "quit") break; else std::cout << "unknown command: " << args[0] << std::endl; } return true; } private: size_t _buf_size; SharedMemory::MemoryManager _manager; }; } bool run_MemoryManager_ut(int argc, char** argv) { SharedMemory::MemoryManger_ut test; void* addr = NULL; if (argc > 1) { int size = Util::str_to_int32(argv[1],10); if (errno == 0) { addr = std::malloc(size); if (addr == NULL) std::cout << "error: malloc()" << std::endl; else { test.init(addr, size); test.run(); std::free(addr); } } else std::cout << "errno = " << errno << std::endl; } else std::cout << "usage: " << argv[0] << " <pool size>" << std::endl; return true; } int main(int argc, char** argv) { //run_MemoryManager_ut(argc, argv); SharedMemory::RemoteMemory remote1, remote2; AbortIfNot(remote1.create("test1", SharedMemory::read_write, 10), false); AbortIfNot(remote2.create("test2", SharedMemory::read_only, 10), false); //std::signal(SIGINT, &sig_hander); while (!sigint_raised) { std::cout << "> "; std::fflush(stdout); char _input[256]; std::cin.getline(_input, 256); std::string input(_input); Util::str_v args; Util::split(input, args); if (Util::trim(args[0]) == "write") { if (args.size() < 2) std::cout << "usage: write <data>" << std::endl; else { // Clients read from this AbortIfNot(remote2.write(args[1].c_str(), args[1].size()), 1); } } else if (Util::trim(args[0]) == "read") { if (args.size() < 2) std::cout << "usage: read <data>" << std::endl; else { int size = Util::str_to_int32(args[1],10); if (errno == 0) { char *data = static_cast<char*>(std::malloc(size+1)); AbortIf(data == NULL, 1); // Clients write to this AbortIfNot(remote1.read(data, size), 1); data[size] = '\0'; std::printf("received '%s'\n", data); std::fflush(stdout); std::free(data); } else { std::cout << "cannot convert " << args[1] << std::endl; errno = 0; } } } else if (Util::trim(args[0]) == "quit") { break; } else std::cout << "unknown command: " << args[0] << std::endl; } return 0; }
17.471698
58
0.534125
jfern2011
e9e702d3b43f911b547cbb1a5951222ae323cc31
645
cpp
C++
1400/50/1459a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
1
2020-07-03T15:55:52.000Z
2020-07-03T15:55:52.000Z
1400/50/1459a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
null
null
null
1400/50/1459a.cpp
actium/cf
d7be128c3a9adb014a231a399f1c5f19e1ab2a38
[ "Unlicense" ]
3
2020-10-01T14:55:28.000Z
2021-07-11T11:33:58.000Z
#include <iostream> #include <string> void answer(size_t v) { constexpr const char* s[3] = { "EQUAL", "BLUE", "RED" }; std::cout << s[v] << '\n'; } void solve(const std::string& r, const std::string& b) { const size_t n = r.length(); unsigned kr = 0, kb = 0; for (size_t i = 0; i < n; ++i) { kr += (r[i] > b[i]); kb += (b[i] > r[i]); } answer((kr != kb) + (kr > kb)); } void test_case() { size_t n; std::cin >> n; std::string r, b; std::cin >> r >> b; solve(r, b); } int main() { size_t t; std::cin >> t; while (t-- > 0) test_case(); return 0; }
14.333333
60
0.458915
actium
e9e73ca68e2ef65353fe7064e6924ac6922d4f7f
308
cpp
C++
PacManController/src/keyboard/IKBCommandManager.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
5
2019-12-23T22:45:46.000Z
2021-11-11T06:27:12.000Z
PacManController/src/keyboard/IKBCommandManager.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
null
null
null
PacManController/src/keyboard/IKBCommandManager.cpp
BeardedPlatypus/PacMan
319e9776582cf9118b38c72d31855fb4c598e986
[ "MIT" ]
1
2021-11-11T06:27:14.000Z
2021-11-11T06:27:14.000Z
#include "stdafx.h" #include "keyboard/IKBCommandManager.h" #include "keyboard/KBCommandManager.h" namespace pacman { namespace controller { namespace keyboard { std::unique_ptr<IKeyboardCommandManager> IKeyboardCommandManager::Construct() { return std::make_unique<KeyboardCommandManager>(); } } } }
17.111111
79
0.779221
BeardedPlatypus
e9e9385a5a8431fa61ce9b7951c11f58af218a45
22,672
cpp
C++
nfc/src/DOOM/neo/renderer/RenderWorld_defs.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
nfc/src/DOOM/neo/renderer/RenderWorld_defs.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
nfc/src/DOOM/neo/renderer/RenderWorld_defs.cpp
1337programming/leviathan
ca9a31b45c25fd23f361d67136ae5ac6b98d2628
[ "Apache-2.0" ]
null
null
null
/* =========================================================================== Doom 3 BFG Edition GPL Source Code Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company. This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code"). Doom 3 BFG Edition Source Code 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. Doom 3 BFG Edition Source Code 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 Doom 3 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>. In addition, the Doom 3 BFG Edition Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Doom 3 BFG Edition Source Code. If not, please request a copy in writing from id Software at the address below. If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA. =========================================================================== */ #pragma hdrstop #include "../idlib/precompiled.h" #include "tr_local.h" /* ================================================================================= ENTITY DEFS ================================================================================= */ /* ================= R_DeriveEntityData ================= */ void R_DeriveEntityData( idRenderEntityLocal * entity ) { R_AxisToModelMatrix( entity->parms.axis, entity->parms.origin, entity->modelMatrix ); idRenderMatrix::CreateFromOriginAxis( entity->parms.origin, entity->parms.axis, entity->modelRenderMatrix ); // calculate the matrix that transforms the unit cube to exactly cover the model in world space idRenderMatrix::OffsetScaleForBounds( entity->modelRenderMatrix, entity->localReferenceBounds, entity->inverseBaseModelProject ); // calculate the global model bounds by inverse projecting the unit cube with the 'inverseBaseModelProject' idRenderMatrix::ProjectedBounds( entity->globalReferenceBounds, entity->inverseBaseModelProject, bounds_unitCube, false ); } /* =================== R_FreeEntityDefDerivedData Used by both FreeEntityDef and UpdateEntityDef Does not actually free the entityDef. =================== */ void R_FreeEntityDefDerivedData( idRenderEntityLocal *def, bool keepDecals, bool keepCachedDynamicModel ) { // demo playback needs to free the joints, while normal play // leaves them in the control of the game if ( common->ReadDemo() ) { if ( def->parms.joints ) { Mem_Free16( def->parms.joints ); def->parms.joints = NULL; } if ( def->parms.callbackData ) { Mem_Free( def->parms.callbackData ); def->parms.callbackData = NULL; } for ( int i = 0; i < MAX_RENDERENTITY_GUI; i++ ) { if ( def->parms.gui[ i ] ) { delete def->parms.gui[ i ]; def->parms.gui[ i ] = NULL; } } } // free all the interactions while ( def->firstInteraction != NULL ) { def->firstInteraction->UnlinkAndFree(); } def->dynamicModelFrameCount = 0; // clear the dynamic model if present if ( def->dynamicModel ) { def->dynamicModel = NULL; } if ( !keepDecals ) { R_FreeEntityDefDecals( def ); R_FreeEntityDefOverlay( def ); } if ( !keepCachedDynamicModel ) { delete def->cachedDynamicModel; def->cachedDynamicModel = NULL; } // free the entityRefs from the areas areaReference_t * next = NULL; for ( areaReference_t * ref = def->entityRefs; ref != NULL; ref = next ) { next = ref->ownerNext; // unlink from the area ref->areaNext->areaPrev = ref->areaPrev; ref->areaPrev->areaNext = ref->areaNext; // put it back on the free list for reuse def->world->areaReferenceAllocator.Free( ref ); } def->entityRefs = NULL; } /* =================== R_FreeEntityDefDecals =================== */ void R_FreeEntityDefDecals( idRenderEntityLocal *def ) { def->decals = NULL; } /* =================== R_FreeEntityDefFadedDecals =================== */ void R_FreeEntityDefFadedDecals( idRenderEntityLocal *def, int time ) { if ( def->decals != NULL ) { def->decals->RemoveFadedDecals( time ); } } /* =================== R_FreeEntityDefOverlay =================== */ void R_FreeEntityDefOverlay( idRenderEntityLocal *def ) { def->overlays = NULL; } /* =============== R_CreateEntityRefs Creates all needed model references in portal areas, chaining them to both the area and the entityDef. Bumps tr.viewCount, which means viewCount can change many times each frame. =============== */ void R_CreateEntityRefs( idRenderEntityLocal *entity ) { if ( entity->parms.hModel == NULL ) { entity->parms.hModel = renderModelManager->DefaultModel(); } // if the entity hasn't been fully specified due to expensive animation calcs // for md5 and particles, use the provided conservative bounds. if ( entity->parms.callback != NULL ) { entity->localReferenceBounds = entity->parms.bounds; } else { entity->localReferenceBounds = entity->parms.hModel->Bounds( &entity->parms ); } // some models, like empty particles, may not need to be added at all if ( entity->localReferenceBounds.IsCleared() ) { return; } if ( r_showUpdates.GetBool() && ( entity->localReferenceBounds[1][0] - entity->localReferenceBounds[0][0] > 1024.0f || entity->localReferenceBounds[1][1] - entity->localReferenceBounds[0][1] > 1024.0f ) ) { common->Printf( "big entityRef: %f,%f\n", entity->localReferenceBounds[1][0] - entity->localReferenceBounds[0][0], entity->localReferenceBounds[1][1] - entity->localReferenceBounds[0][1] ); } // derive entity data R_DeriveEntityData( entity ); // bump the view count so we can tell if an // area already has a reference tr.viewCount++; // push the model frustum down the BSP tree into areas entity->world->PushFrustumIntoTree( entity, NULL, entity->inverseBaseModelProject, bounds_unitCube ); } /* ================================================================================= LIGHT DEFS ================================================================================= */ /* ======================== R_ComputePointLightProjectionMatrix Computes the light projection matrix for a point light. ======================== */ static float R_ComputePointLightProjectionMatrix( idRenderLightLocal * light, idRenderMatrix & localProject ) { assert( light->parms.pointLight ); // A point light uses a box projection. // This projects into the 0.0 - 1.0 texture range instead of -1.0 to 1.0 clip space range. localProject.Zero(); localProject[0][0] = 0.5f / light->parms.lightRadius[0]; localProject[1][1] = 0.5f / light->parms.lightRadius[1]; localProject[2][2] = 0.5f / light->parms.lightRadius[2]; localProject[0][3] = 0.5f; localProject[1][3] = 0.5f; localProject[2][3] = 0.5f; localProject[3][3] = 1.0f; // identity perspective return 1.0f; } static const float SPOT_LIGHT_MIN_Z_NEAR = 8.0f; static const float SPOT_LIGHT_MIN_Z_FAR = 16.0f; /* ======================== R_ComputeSpotLightProjectionMatrix Computes the light projection matrix for a spot light. ======================== */ static float R_ComputeSpotLightProjectionMatrix( idRenderLightLocal * light, idRenderMatrix & localProject ) { const float targetDistSqr = light->parms.target.LengthSqr(); const float invTargetDist = idMath::InvSqrt( targetDistSqr ); const float targetDist = invTargetDist * targetDistSqr; const idVec3 normalizedTarget = light->parms.target * invTargetDist; const idVec3 normalizedRight = light->parms.right * ( 0.5f * targetDist / light->parms.right.LengthSqr() ); const idVec3 normalizedUp = light->parms.up * ( -0.5f * targetDist / light->parms.up.LengthSqr() ); localProject[0][0] = normalizedRight[0]; localProject[0][1] = normalizedRight[1]; localProject[0][2] = normalizedRight[2]; localProject[0][3] = 0.0f; localProject[1][0] = normalizedUp[0]; localProject[1][1] = normalizedUp[1]; localProject[1][2] = normalizedUp[2]; localProject[1][3] = 0.0f; localProject[3][0] = normalizedTarget[0]; localProject[3][1] = normalizedTarget[1]; localProject[3][2] = normalizedTarget[2]; localProject[3][3] = 0.0f; // Set the falloff vector. // This is similar to the Z calculation for depth buffering, which means that the // mapped texture is going to be perspective distorted heavily towards the zero end. const float zNear = Max( light->parms.start * normalizedTarget, SPOT_LIGHT_MIN_Z_NEAR ); const float zFar = Max( light->parms.end * normalizedTarget, SPOT_LIGHT_MIN_Z_FAR ); const float zScale = ( zNear + zFar ) / zFar; localProject[2][0] = normalizedTarget[0] * zScale; localProject[2][1] = normalizedTarget[1] * zScale; localProject[2][2] = normalizedTarget[2] * zScale; localProject[2][3] = - zNear * zScale; // now offset to the 0.0 - 1.0 texture range instead of -1.0 to 1.0 clip space range idVec4 projectedTarget; localProject.TransformPoint( light->parms.target, projectedTarget ); const float ofs0 = 0.5f - projectedTarget[0] / projectedTarget[3]; localProject[0][0] += ofs0 * localProject[3][0]; localProject[0][1] += ofs0 * localProject[3][1]; localProject[0][2] += ofs0 * localProject[3][2]; localProject[0][3] += ofs0 * localProject[3][3]; const float ofs1 = 0.5f - projectedTarget[1] / projectedTarget[3]; localProject[1][0] += ofs1 * localProject[3][0]; localProject[1][1] += ofs1 * localProject[3][1]; localProject[1][2] += ofs1 * localProject[3][2]; localProject[1][3] += ofs1 * localProject[3][3]; return 1.0f / ( zNear + zFar ); } /* ======================== R_ComputeParallelLightProjectionMatrix Computes the light projection matrix for a parallel light. ======================== */ static float R_ComputeParallelLightProjectionMatrix( idRenderLightLocal * light, idRenderMatrix & localProject ) { assert( light->parms.parallel ); // A parallel light uses a box projection. // This projects into the 0.0 - 1.0 texture range instead of -1.0 to 1.0 clip space range. localProject.Zero(); localProject[0][0] = 0.5f / light->parms.lightRadius[0]; localProject[1][1] = 0.5f / light->parms.lightRadius[1]; localProject[2][2] = 0.5f / light->parms.lightRadius[2]; localProject[0][3] = 0.5f; localProject[1][3] = 0.5f; localProject[2][3] = 0.5f; localProject[3][3] = 1.0f; // identity perspective return 1.0f; } /* ================= R_DeriveLightData Fills everything in based on light->parms ================= */ static void R_DeriveLightData( idRenderLightLocal * light ) { // decide which light shader we are going to use if ( light->parms.shader != NULL ) { light->lightShader = light->parms.shader; } else if ( light->lightShader == NULL ) { if ( light->parms.pointLight ) { light->lightShader = tr.defaultPointLight; } else { light->lightShader = tr.defaultProjectedLight; } } // get the falloff image light->falloffImage = light->lightShader->LightFalloffImage(); if ( light->falloffImage == NULL ) { // use the falloff from the default shader of the correct type const idMaterial * defaultShader; if ( light->parms.pointLight ) { defaultShader = tr.defaultPointLight; // Touch the default shader. to make sure it's decl has been parsed ( it might have been purged ). declManager->Touch( static_cast< const idDecl *>( defaultShader ) ); light->falloffImage = defaultShader->LightFalloffImage(); } else { // projected lights by default don't diminish with distance defaultShader = tr.defaultProjectedLight; // Touch the light shader. to make sure it's decl has been parsed ( it might have been purged ). declManager->Touch( static_cast< const idDecl *>( defaultShader ) ); light->falloffImage = defaultShader->LightFalloffImage(); } } // ------------------------------------ // compute the light projection matrix // ------------------------------------ idRenderMatrix localProject; float zScale = 1.0f; if ( light->parms.parallel ) { zScale = R_ComputeParallelLightProjectionMatrix( light, localProject ); } else if ( light->parms.pointLight ) { zScale = R_ComputePointLightProjectionMatrix( light, localProject ); } else { zScale = R_ComputeSpotLightProjectionMatrix( light, localProject ); } // set the old style light projection where Z and W are flipped and // for projected lights lightProject[3] is divided by ( zNear + zFar ) light->lightProject[0][0] = localProject[0][0]; light->lightProject[0][1] = localProject[0][1]; light->lightProject[0][2] = localProject[0][2]; light->lightProject[0][3] = localProject[0][3]; light->lightProject[1][0] = localProject[1][0]; light->lightProject[1][1] = localProject[1][1]; light->lightProject[1][2] = localProject[1][2]; light->lightProject[1][3] = localProject[1][3]; light->lightProject[2][0] = localProject[3][0]; light->lightProject[2][1] = localProject[3][1]; light->lightProject[2][2] = localProject[3][2]; light->lightProject[2][3] = localProject[3][3]; light->lightProject[3][0] = localProject[2][0] * zScale; light->lightProject[3][1] = localProject[2][1] * zScale; light->lightProject[3][2] = localProject[2][2] * zScale; light->lightProject[3][3] = localProject[2][3] * zScale; // transform the lightProject float lightTransform[16]; R_AxisToModelMatrix( light->parms.axis, light->parms.origin, lightTransform ); for ( int i = 0; i < 4; i++ ) { idPlane temp = light->lightProject[i]; R_LocalPlaneToGlobal( lightTransform, temp, light->lightProject[i] ); } // adjust global light origin for off center projections and parallel projections // we are just faking parallel by making it a very far off center for now if ( light->parms.parallel ) { idVec3 dir = light->parms.lightCenter; if ( dir.Normalize() == 0.0f ) { // make point straight up if not specified dir[2] = 1.0f; } light->globalLightOrigin = light->parms.origin + dir * 100000.0f; } else { light->globalLightOrigin = light->parms.origin + light->parms.axis * light->parms.lightCenter; } // Rotate and translate the light projection by the light matrix. // 99% of lights remain axis aligned in world space. idRenderMatrix lightMatrix; idRenderMatrix::CreateFromOriginAxis( light->parms.origin, light->parms.axis, lightMatrix ); idRenderMatrix inverseLightMatrix; if ( !idRenderMatrix::Inverse( lightMatrix, inverseLightMatrix ) ) { idLib::Warning( "lightMatrix invert failed" ); } // 'baseLightProject' goes from global space -> light local space -> light projective space idRenderMatrix::Multiply( localProject, inverseLightMatrix, light->baseLightProject ); // Invert the light projection so we can deform zero-to-one cubes into // the light model and calculate global bounds. if ( !idRenderMatrix::Inverse( light->baseLightProject, light->inverseBaseLightProject ) ) { idLib::Warning( "baseLightProject invert failed" ); } // calculate the global light bounds by inverse projecting the zero to one cube with the 'inverseBaseLightProject' idRenderMatrix::ProjectedBounds( light->globalLightBounds, light->inverseBaseLightProject, bounds_zeroOneCube, false ); } /* ==================== R_FreeLightDefDerivedData Frees all references and lit surfaces from the light ==================== */ void R_FreeLightDefDerivedData( idRenderLightLocal *ldef ) { // remove any portal fog references for ( doublePortal_t *dp = ldef->foggedPortals; dp != NULL; dp = dp->nextFoggedPortal ) { dp->fogLight = NULL; } // free all the interactions while ( ldef->firstInteraction != NULL ) { ldef->firstInteraction->UnlinkAndFree(); } // free all the references to the light areaReference_t * nextRef = NULL; for ( areaReference_t * lref = ldef->references; lref != NULL; lref = nextRef ) { nextRef = lref->ownerNext; // unlink from the area lref->areaNext->areaPrev = lref->areaPrev; lref->areaPrev->areaNext = lref->areaNext; // put it back on the free list for reuse ldef->world->areaReferenceAllocator.Free( lref ); } ldef->references = NULL; } /* =============== WindingCompletelyInsideLight =============== */ static bool WindingCompletelyInsideLight( const idWinding *w, const idRenderLightLocal *ldef ) { for ( int i = 0; i < w->GetNumPoints(); i++ ) { if ( idRenderMatrix::CullPointToMVP( ldef->baseLightProject, (*w)[i].ToVec3(), true ) ) { return false; } } return true; } /* ====================== R_CreateLightDefFogPortals When a fog light is created or moved, see if it completely encloses any portals, which may allow them to be fogged closed. ====================== */ static void R_CreateLightDefFogPortals( idRenderLightLocal *ldef ) { ldef->foggedPortals = NULL; if ( !ldef->lightShader->IsFogLight() ) { return; } // some fog lights will explicitly disallow portal fogging if ( ldef->lightShader->TestMaterialFlag( MF_NOPORTALFOG ) ) { return; } for ( areaReference_t * lref = ldef->references; lref != NULL; lref = lref->ownerNext ) { // check all the models in this area portalArea_t * area = lref->area; for ( portal_t * prt = area->portals; prt != NULL; prt = prt->next ) { doublePortal_t * dp = prt->doublePortal; // we only handle a single fog volume covering a portal // this will never cause incorrect drawing, but it may // fail to cull a portal if ( dp->fogLight ) { continue; } if ( WindingCompletelyInsideLight( prt->w, ldef ) ) { dp->fogLight = ldef; dp->nextFoggedPortal = ldef->foggedPortals; ldef->foggedPortals = dp; } } } } /* ================= R_CreateLightRefs ================= */ void R_CreateLightRefs( idRenderLightLocal * light ) { // derive light data R_DeriveLightData( light ); // determine the areaNum for the light origin, which may let us // cull the light if it is behind a closed door // it is debatable if we want to use the entity origin or the center offset origin, // but we definitely don't want to use a parallel offset origin light->areaNum = light->world->PointInArea( light->globalLightOrigin ); if ( light->areaNum == -1 ) { light->areaNum = light->world->PointInArea( light->parms.origin ); } // bump the view count so we can tell if an // area already has a reference tr.viewCount++; // if we have a prelight model that includes all the shadows for the major world occluders, // we can limit the area references to those visible through the portals from the light center. // We can't do this in the normal case, because shadows are cast from back facing triangles, which // may be in areas not directly visible to the light projection center. if ( light->parms.prelightModel != NULL && r_useLightPortalFlow.GetBool() && light->lightShader->LightCastsShadows() ) { light->world->FlowLightThroughPortals( light ); } else { // push the light frustum down the BSP tree into areas light->world->PushFrustumIntoTree( NULL, light, light->inverseBaseLightProject, bounds_zeroOneCube ); } R_CreateLightDefFogPortals( light ); } /* ================================================================================= WORLD MODEL & LIGHT DEFS ================================================================================= */ /* =================== R_FreeDerivedData ReloadModels and RegenerateWorld call this =================== */ void R_FreeDerivedData() { for ( int j = 0; j < tr.worlds.Num(); j++ ) { idRenderWorldLocal * rw = tr.worlds[j]; for ( int i = 0; i < rw->entityDefs.Num(); i++ ) { idRenderEntityLocal * def = rw->entityDefs[i]; if ( def == NULL ) { continue; } R_FreeEntityDefDerivedData( def, false, false ); } for ( int i = 0; i < rw->lightDefs.Num(); i++ ) { idRenderLightLocal * light = rw->lightDefs[i]; if ( light == NULL ) { continue; } R_FreeLightDefDerivedData( light ); } } } /* =================== R_CheckForEntityDefsUsingModel =================== */ void R_CheckForEntityDefsUsingModel( idRenderModel *model ) { for ( int j = 0; j < tr.worlds.Num(); j++ ) { idRenderWorldLocal * rw = tr.worlds[j]; for ( int i = 0; i < rw->entityDefs.Num(); i++ ) { idRenderEntityLocal * def = rw->entityDefs[i]; if ( !def ) { continue; } if ( def->parms.hModel == model ) { //assert( 0 ); // this should never happen but Radiant messes it up all the time so just free the derived data R_FreeEntityDefDerivedData( def, false, false ); } } } } /* =================== R_ReCreateWorldReferences ReloadModels and RegenerateWorld call this =================== */ void R_ReCreateWorldReferences() { // let the interaction generation code know this // shouldn't be optimized for a particular view tr.viewDef = NULL; for ( int j = 0; j < tr.worlds.Num(); j++ ) { idRenderWorldLocal * rw = tr.worlds[j]; for ( int i = 0; i < rw->entityDefs.Num(); i++ ) { idRenderEntityLocal * def = rw->entityDefs[i]; if ( def == NULL ) { continue; } // the world model entities are put specifically in a single // area, instead of just pushing their bounds into the tree if ( i < rw->numPortalAreas ) { rw->AddEntityRefToArea( def, &rw->portalAreas[i] ); } else { R_CreateEntityRefs( def ); } } for ( int i = 0; i < rw->lightDefs.Num(); i++ ) { idRenderLightLocal * light = rw->lightDefs[i]; if ( light == NULL ) { continue; } renderLight_t parms = light->parms; light->world->FreeLightDef( i ); rw->UpdateLightDef( i, &parms ); } } } /* ==================== R_ModulateLights_f Modifies the shaderParms on all the lights so the level designers can easily test different color schemes ==================== */ void R_ModulateLights_f( const idCmdArgs &args ) { if ( !tr.primaryWorld ) { return; } if ( args.Argc() != 4 ) { common->Printf( "usage: modulateLights <redFloat> <greenFloat> <blueFloat>\n" ); return; } float modulate[3]; for ( int i = 0; i < 3; i++ ) { modulate[i] = atof( args.Argv( i+1 ) ); } int count = 0; for ( int i = 0; i < tr.primaryWorld->lightDefs.Num(); i++ ) { idRenderLightLocal * light = tr.primaryWorld->lightDefs[i]; if ( light != NULL ) { count++; for ( int j = 0; j < 3; j++ ) { light->parms.shaderParms[j] *= modulate[j]; } } } common->Printf( "modulated %i lights\n", count ); }
32.067893
366
0.663065
1337programming
e9edde5b50c9f3d89fa09922086f558dba2df378
645
cpp
C++
atcoder/abc089_c.cpp
Doarakko/competitive-programming
5ae78c501664af08a3f16c81dbd54c68310adec8
[ "MIT" ]
1
2017-07-11T16:47:29.000Z
2017-07-11T16:47:29.000Z
atcoder/abc089_c.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
1
2021-02-07T09:10:26.000Z
2021-02-07T09:10:26.000Z
atcoder/abc089_c.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, const char * argv[]) { int N; cin >> N; char c; int a[4] = {0, 0, 0, 0}; for (int i = 0; i < N; i++) { cin >> c; if (c == 'P') { a[0] = 1; }else if (c == 'W'){ a[1] = 1; }else if (c == 'G'){ a[2] = 1; }else if (c == 'Y'){ a[3] = 1; } } int cnt = 0; for (int i = 0; i < 4; i++) { if (a[i] == 1) { cnt++; } } if (cnt == 3) { cout << "Three" << endl; }else{ cout << "Four" << endl; } return 0; }
19.545455
41
0.316279
Doarakko
e9ef30d7bda6a42370f3d1d7ad244e0675ef01ec
129
cpp
C++
lib/3d/blanks/SetBndValues.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
lib/3d/blanks/SetBndValues.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
lib/3d/blanks/SetBndValues.cpp
dcseal/finess
766e583ae9e84480640c7c3b3c157bf40ab87fe4
[ "BSD-3-Clause" ]
null
null
null
#include "tensors.h" // Periodic boundary conditions void SetBndValues(const dTensor2& node, dTensorBC3& aux, dTensorBC3& q) {}
21.5
71
0.75969
dcseal
e9ef881c8e5e58f168fe21988c1c3f1530fcdc88
13,862
cc
C++
util/ssc_planner/src/ssc_planner/ssc_visualizer.cc
GallopWind/epsilon-learn
74dc723fbc9797f3bd05bee30f6f9b9acceeec17
[ "MIT" ]
186
2020-09-22T10:57:57.000Z
2022-03-30T15:52:15.000Z
util/ssc_planner/src/ssc_planner/ssc_visualizer.cc
Yufei-Wei/EPSILON
155f1b1c4dae3ae29287d5b0b967d7d6ce230c73
[ "MIT" ]
16
2020-10-19T02:55:49.000Z
2022-01-14T08:17:06.000Z
util/ssc_planner/src/ssc_planner/ssc_visualizer.cc
Yufei-Wei/EPSILON
155f1b1c4dae3ae29287d5b0b967d7d6ce230c73
[ "MIT" ]
66
2020-09-28T01:51:57.000Z
2022-03-25T08:39:04.000Z
/** * @file ssc_visualizer.cc * @author HKUST Aerial Robotics Group * @brief implementation for ssc visualizer * @version 0.1 * @date 2019-02 * @copyright Copyright (c) 2019 */ #include "ssc_planner/ssc_visualizer.h" namespace planning { SscVisualizer::SscVisualizer(ros::NodeHandle nh, int node_id) : nh_(nh), node_id_(node_id) { std::cout << "node_id_ = " << node_id_ << std::endl; std::string ssc_map_vis_topic = std::string("/vis/agent_") + std::to_string(node_id_) + std::string("/ssc/map_vis"); std::string ego_vehicle_vis_topic = std::string("/vis/agent_") + std::to_string(node_id_) + std::string("/ssc/ego_fs_vis"); std::string forward_trajs_vis_topic = std::string("/vis/agent_") + std::to_string(node_id_) + std::string("/ssc/forward_trajs_vis"); std::string sur_vehicle_trajs_vis_topic = std::string("/vis/agent_") + std::to_string(node_id_) + std::string("/ssc/sur_vehicle_trajs_vis"); std::string corridor_vis_topic = std::string("/vis/agent_") + std::to_string(node_id_) + std::string("/ssc/corridor_vis"); std::string qp_vis_topic = std::string("/vis/agent_") + std::to_string(node_id_) + std::string("/ssc/qp_vis"); ssc_map_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(ssc_map_vis_topic, 1); qp_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(qp_vis_topic, 1); ego_vehicle_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(ego_vehicle_vis_topic, 1); forward_trajs_pub_ = nh_.advertise<visualization_msgs::MarkerArray>( forward_trajs_vis_topic, 1); sur_vehicle_trajs_pub_ = nh_.advertise<visualization_msgs::MarkerArray>( sur_vehicle_trajs_vis_topic, 1); corridor_pub_ = nh_.advertise<visualization_msgs::MarkerArray>(corridor_vis_topic, 1); } void SscVisualizer::VisualizeDataWithStamp(const ros::Time &stamp, const SscPlanner &planner) { start_time_ = planner.time_origin(); // std::cout << "[SscMapTime]Sys time stamp = " << stamp << std::endl; VisualizeSscMap(stamp, planner.p_ssc_map()); VisualizeEgoVehicleInSscSpace(stamp, planner.fs_ego_vehicle()); VisualizeForwardTrajectoriesInSscSpace(stamp, planner.forward_trajs_fs(), planner.p_ssc_map()); VisualizeSurroundingVehicleTrajInSscSpace( stamp, planner.surround_forward_trajs_fs(), planner.p_ssc_map()); VisualizeCorridorsInSscSpace( stamp, planner.p_ssc_map()->driving_corridor_vec(), planner.p_ssc_map()); VisualizeQpTrajs(stamp, planner.qp_trajs()); } void SscVisualizer::VisualizeQpTrajs( const ros::Time &stamp, const vec_E<common::BezierSpline<5, 2>> &trajs) { if (trajs.empty()) { printf("[SscQP]No valid qp trajs.\n"); return; } int id = 0; visualization_msgs::MarkerArray traj_mk_arr; for (int i = 0; i < static_cast<int>(trajs.size()); i++) { visualization_msgs::Marker traj_mk; traj_mk.type = visualization_msgs::Marker::LINE_STRIP; traj_mk.action = visualization_msgs::Marker::MODIFY; traj_mk.id = id++; Vecf<2> pos; for (decimal_t t = trajs[i].begin(); t < trajs[i].end() + kEPS; t += 0.02) { if (trajs[i].evaluate(t, 0, &pos) == kSuccess) { geometry_msgs::Point pt; pt.x = pos[0]; pt.y = pos[1]; pt.z = t - start_time_; traj_mk.points.push_back(pt); } } common::VisualizationUtil::FillScaleColorInMarker( Vec3f(0.2, 0.2, 0.2), common::cmap.at("magenta"), &traj_mk); traj_mk_arr.markers.push_back(traj_mk); } int num_markers = static_cast<int>(traj_mk_arr.markers.size()); common::VisualizationUtil::FillHeaderIdInMarkerArray( stamp, std::string("ssc_map"), last_qp_traj_mk_cnt, &traj_mk_arr); qp_pub_.publish(traj_mk_arr); last_qp_traj_mk_cnt = num_markers; } void SscVisualizer::VisualizeSscMap(const ros::Time &stamp, const SscMap *p_ssc_map) { visualization_msgs::MarkerArray map_marker_arr; visualization_msgs::Marker map_marker; common::VisualizationUtil::GetRosMarkerCubeListUsingGripMap3D( p_ssc_map->p_3d_grid(), stamp, "ssc_map", Vec3f(0, 0, 0), &map_marker); auto origin = p_ssc_map->p_3d_grid()->origin(); decimal_t s_len = p_ssc_map->config().map_resolution[0] * p_ssc_map->config().map_size[0]; decimal_t x = s_len / 2 - p_ssc_map->config().s_back_len + origin[0]; decimal_t y = 0; // decimal_t z = t_len / 2; std::array<decimal_t, 3> aabb_coord = {x, y, 0}; std::array<decimal_t, 3> aabb_len = {s_len, 3.5, 0.01}; common::AxisAlignedBoundingBoxND<3> map_aabb(aabb_coord, aabb_len); visualization_msgs::Marker map_aabb_marker; map_aabb_marker.header.frame_id = "ssc_map"; map_aabb_marker.header.stamp = stamp; map_aabb_marker.id = 1; common::VisualizationUtil::GetRosMarkerCubeUsingAxisAlignedBoundingBox3D( map_aabb, common::ColorARGB(0.2, 1, 0, 1), &map_aabb_marker); map_marker_arr.markers.push_back(map_marker); map_marker_arr.markers.push_back(map_aabb_marker); ssc_map_pub_.publish(map_marker_arr); } void SscVisualizer::VisualizeEgoVehicleInSscSpace( const ros::Time &stamp, const common::FsVehicle &fs_ego_vehicle) { if (fs_ego_vehicle.vertices.empty()) return; visualization_msgs::MarkerArray ego_vehicle_mks; visualization_msgs::Marker ego_contour_marker; common::ColorARGB color(0.8, 1.0, 0.0, 0.0); decimal_t dt = fs_ego_vehicle.frenet_state.time_stamp - start_time_; vec_E<Vec2f> contour = fs_ego_vehicle.vertices; contour.push_back(contour.front()); common::VisualizationUtil::GetRosMarkerLineStripUsing2DofVecWithOffsetZ( contour, color, Vec3f(0.3, 0.3, 0.3), dt, 0, &ego_contour_marker); ego_contour_marker.header.frame_id = "ssc_map"; ego_contour_marker.header.stamp = stamp; ego_vehicle_mks.markers.push_back(ego_contour_marker); visualization_msgs::Marker ego_fs_mk; common::VisualizationUtil::GetRosMarkerSphereUsingPoint( Vec3f(fs_ego_vehicle.frenet_state.vec_s[0], fs_ego_vehicle.frenet_state.vec_dt[0], dt), common::cmap.at("red"), Vec3f(0.3, 0.3, 0.3), 1, &ego_fs_mk); ego_fs_mk.header.frame_id = "ssc_map"; ego_fs_mk.header.stamp = stamp; ego_vehicle_mks.markers.push_back(ego_fs_mk); ego_vehicle_pub_.publish(ego_vehicle_mks); } void SscVisualizer::VisualizeForwardTrajectoriesInSscSpace( const ros::Time &stamp, const vec_E<vec_E<common::FsVehicle>> &trajs, const SscMap *p_ssc_map) { if (trajs.empty()) return; visualization_msgs::MarkerArray trajs_markers; int id_cnt = 0; // common::ColorARGB color = common::cmap.at("gold"); // color.a = 0.4; for (int i = 0; i < static_cast<int>(trajs.size()); ++i) { if (trajs[i].empty()) continue; for (int k = 0; k < static_cast<int>(trajs[i].size()); ++k) { visualization_msgs::Marker vehicle_marker; vec_E<Vec2f> contour = trajs[i][k].vertices; bool is_valid = true; for (const auto v : contour) { if (v(0) <= 0) { is_valid = false; break; } } if (!is_valid) { continue; } common::ColorARGB color = common::GetJetColorByValue( static_cast<decimal_t>(k), static_cast<decimal_t>(trajs[i].size() - 1), 0.0); contour.push_back(contour.front()); decimal_t dt = trajs[i][k].frenet_state.time_stamp - start_time_; common::VisualizationUtil::GetRosMarkerLineStripUsing2DofVecWithOffsetZ( contour, color, Vec3f(0.1, 0.1, 0.1), dt, id_cnt++, &vehicle_marker); trajs_markers.markers.push_back(vehicle_marker); visualization_msgs::Marker fs_mk; auto fs = trajs[i][k].frenet_state; decimal_t x = fs.vec_s[0]; decimal_t y = fs.vec_dt[0]; common::VisualizationUtil::GetRosMarkerSphereUsingPoint( Vec3f(x, y, dt), common::cmap.at("cyan"), Vec3f(0.2, 0.2, 0.2), id_cnt++, &fs_mk); trajs_markers.markers.push_back(fs_mk); } } int num_markers = static_cast<int>(trajs_markers.markers.size()); common::VisualizationUtil::FillHeaderIdInMarkerArray( stamp, std::string("ssc_map"), last_forward_traj_mk_cnt, &trajs_markers); forward_trajs_pub_.publish(trajs_markers); last_forward_traj_mk_cnt = num_markers; } void SscVisualizer::VisualizeSurroundingVehicleTrajInSscSpace( const ros::Time &stamp, const vec_E<std::unordered_map<int, vec_E<common::FsVehicle>>> &trajs_set, const SscMap *p_ssc_map) { visualization_msgs::MarkerArray trajs_markers; if (!trajs_set.empty()) { auto trajs = trajs_set.front(); if (!trajs.empty()) { int id_cnt = 0; for (auto it = trajs.begin(); it != trajs.end(); ++it) { if (it->second.empty()) continue; for (int k = 0; k < static_cast<int>(it->second.size()); ++k) { visualization_msgs::Marker vehicle_marker; common::ColorARGB color = common::GetJetColorByValue( static_cast<decimal_t>(k), static_cast<decimal_t>(it->second.size() - 1), 0.0); vec_E<Vec2f> contour = it->second[k].vertices; bool is_valid = true; for (const auto v : contour) { if (v(0) <= 0) { is_valid = false; break; } } if (!is_valid) { continue; } contour.push_back(contour.front()); decimal_t dt = it->second[k].frenet_state.time_stamp - start_time_; common::VisualizationUtil:: GetRosMarkerLineStripUsing2DofVecWithOffsetZ( contour, color, Vec3f(0.1, 0.1, 0.1), dt, id_cnt++, &vehicle_marker); vehicle_marker.header.frame_id = "ssc_map"; vehicle_marker.header.stamp = stamp; trajs_markers.markers.push_back(vehicle_marker); } } } } int num_markers = static_cast<int>(trajs_markers.markers.size()); common::VisualizationUtil::FillHeaderIdInMarkerArray( stamp, std::string("ssc_map"), last_sur_vehicle_traj_mk_cnt, &trajs_markers); sur_vehicle_trajs_pub_.publish(trajs_markers); last_sur_vehicle_traj_mk_cnt = num_markers; } void SscVisualizer::VisualizeCorridorsInSscSpace( const ros::Time &stamp, const vec_E<common::DrivingCorridor> corridor_vec, const SscMap *p_ssc_map) { if (corridor_vec.empty()) return; visualization_msgs::MarkerArray corridor_vec_marker; int id_cnt = 0; for (const auto &corridor : corridor_vec) { // if (corridor.is_valid) continue; int cube_cnt = 0; for (const auto &driving_cube : corridor.cubes) { // * Show seeds common::ColorARGB color = common::GetJetColorByValue( cube_cnt, corridor.cubes.size() - 1, -kEPS); for (const auto &seed : driving_cube.seeds) { visualization_msgs::Marker seed_marker; decimal_t s_x, s_y, s_z; p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(seed(0), 0, &s_x); p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(seed(1), 1, &s_y); p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim(seed(2), 2, &s_z); common::VisualizationUtil::GetRosMarkerSphereUsingPoint( Vec3f(s_x, s_y, s_z - start_time_), color, Vec3f(0.3, 0.3, 0.3), id_cnt++, &seed_marker); corridor_vec_marker.markers.push_back(seed_marker); } // * Show driving cube decimal_t x_max, x_min; decimal_t y_max, y_min; decimal_t z_max, z_min; p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim( driving_cube.cube.upper_bound[0], 0, &x_max); p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim( driving_cube.cube.lower_bound[0], 0, &x_min); p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim( driving_cube.cube.upper_bound[1], 1, &y_max); p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim( driving_cube.cube.lower_bound[1], 1, &y_min); p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim( driving_cube.cube.upper_bound[2], 2, &z_max); p_ssc_map->p_3d_grid()->GetGlobalMetricUsingCoordOnSingleDim( driving_cube.cube.lower_bound[2], 2, &z_min); decimal_t dx = x_max - x_min; decimal_t dy = y_max - y_min; decimal_t dz = z_max - z_min; decimal_t x = x_min + dx / 2.0; decimal_t y = y_min + dy / 2.0; decimal_t z = z_min - start_time_ + dz / 2.0; std::array<decimal_t, 3> aabb_coord = {x, y, z}; std::array<decimal_t, 3> aabb_len = {dx, dy, dz}; common::AxisAlignedBoundingBoxND<3> map_aabb(aabb_coord, aabb_len); visualization_msgs::Marker map_aabb_marker; map_aabb_marker.id = id_cnt++; common::VisualizationUtil::GetRosMarkerCubeUsingAxisAlignedBoundingBox3D( map_aabb, common::ColorARGB(0.15, 0.3, 1.0, 0.3), &map_aabb_marker); corridor_vec_marker.markers.push_back(map_aabb_marker); ++cube_cnt; } } int num_markers = static_cast<int>(corridor_vec_marker.markers.size()); common::VisualizationUtil::FillHeaderIdInMarkerArray( ros::Time::now(), std::string("ssc_map"), last_corridor_mk_cnt, &corridor_vec_marker); corridor_pub_.publish(corridor_vec_marker); last_corridor_mk_cnt = num_markers; } } // namespace planning
42.391437
80
0.65171
GallopWind
e9f04c5099fe4f84319edcfc163033dcf4bf189d
11,669
cpp
C++
tests/Move_strategies_test.cpp
mjcaisse/CDT-plusplus
fa11dd19c806a96afbb48e406234e82cae62029a
[ "BSD-3-Clause" ]
null
null
null
tests/Move_strategies_test.cpp
mjcaisse/CDT-plusplus
fa11dd19c806a96afbb48e406234e82cae62029a
[ "BSD-3-Clause" ]
null
null
null
tests/Move_strategies_test.cpp
mjcaisse/CDT-plusplus
fa11dd19c806a96afbb48e406234e82cae62029a
[ "BSD-3-Clause" ]
null
null
null
/// Causal Dynamical Triangulations in C++ using CGAL /// /// Copyright © 2015-2020 Adam Getchell /// /// Checks that Metropolis algorithm runs properly. /// @file Move_strategies_test.cpp /// @brief Tests for the Metropolis-Hastings algorithm /// @author Adam Getchell #include "Move_always.hpp" //#include "Metropolis.hpp" #include <catch2/catch.hpp> using namespace std; // bool IsProbabilityRange(CGAL::Gmpzf const& arg) { return arg > 0 && arg <= 1; // } SCENARIO("MoveStrategy<MOVE_ALWAYS> special member and swap properties", "[move strategies]") { GIVEN("A Move always move strategy.") { WHEN("Special members are examined.") { THEN("It is no-throw destructible.") { REQUIRE(is_nothrow_destructible_v<MoveAlways3>); REQUIRE(is_nothrow_destructible_v<MoveAlways4>); } THEN("It is no-throw default constructible.") { CHECK(is_nothrow_default_constructible_v<MoveAlways3>); CHECK(is_nothrow_default_constructible_v<MoveAlways4>); } THEN("It is no-throw copy constructible.") { CHECK(is_nothrow_copy_constructible_v<MoveAlways3>); CHECK(is_nothrow_copy_constructible_v<MoveAlways4>); } THEN("It is no-throw copy assignable.") { CHECK(is_nothrow_copy_assignable_v<MoveAlways3>); CHECK(is_nothrow_copy_assignable_v<MoveAlways4>); } THEN("It is no-throw move constructible.") { CHECK(is_nothrow_move_constructible_v<MoveAlways3>); CHECK(is_nothrow_move_constructible_v<MoveAlways4>); } THEN("It is no-throw move assignable.") { CHECK(is_nothrow_move_assignable_v<MoveAlways3>); CHECK(is_nothrow_move_assignable_v<MoveAlways4>); } THEN("It is no-throw swappable.") { REQUIRE(is_nothrow_swappable_v<MoveAlways3>); REQUIRE(is_nothrow_swappable_v<MoveAlways4>); } THEN("It is constructible from 2 parameters.") { REQUIRE(is_constructible_v<MoveAlways3, Int_precision, Int_precision>); REQUIRE(is_constructible_v<MoveAlways4, Int_precision, Int_precision>); } } } } SCENARIO("Using the Move always algorithm", "[move strategies]") { GIVEN("A correctly-constructed Manifold3.") { auto constexpr simplices = static_cast<Int_precision>(640); auto constexpr timeslices = static_cast<Int_precision>(4); Manifold3 manifold(simplices, timeslices); REQUIRE(manifold.is_correct()); WHEN("A MoveStrategy3 is constructed.") { auto constexpr passes = static_cast<Int_precision>(10); auto constexpr checkpoint = static_cast<Int_precision>(5); MoveAlways3 mover(passes, checkpoint); THEN("The correct passes and checkpoints are instantiated.") { CHECK(mover.passes() == passes); CHECK(mover.checkpoint() == checkpoint); } THEN("Attempted moves and successful moves are zero-initialized.") { CHECK(mover.get_attempted().two_three_moves<3>() == 0); CHECK(mover.get_successful().two_three_moves<3>() == 0); CHECK(mover.get_attempted().three_two_moves<3>() == 0); CHECK(mover.get_successful().three_two_moves<3>() == 0); CHECK(mover.get_attempted().two_six_moves<3>() == 0); CHECK(mover.get_successful().two_six_moves<3>() == 0); CHECK(mover.get_attempted().six_two_moves<3>() == 0); CHECK(mover.get_successful().six_two_moves<3>() == 0); CHECK(mover.get_attempted().four_four_moves<3>() == 0); CHECK(mover.get_successful().four_four_moves<3>() == 0); } } WHEN("A MoveAlways3 algorithm is used.") { auto constexpr passes = static_cast<Int_precision>(1); auto constexpr checkpoint = static_cast<Int_precision>(1); MoveAlways3 mover(passes, checkpoint); THEN("The correct passes and checkpoints are instantiated.") { CHECK(mover.passes() == passes); CHECK(mover.checkpoint() == checkpoint); } THEN("Attempted moves and successful moves are zero-initialized.") { CHECK(mover.get_attempted().two_three_moves<3>() == 0); CHECK(mover.get_successful().two_three_moves<3>() == 0); CHECK(mover.get_attempted().three_two_moves<3>() == 0); CHECK(mover.get_successful().three_two_moves<3>() == 0); CHECK(mover.get_attempted().two_six_moves<3>() == 0); CHECK(mover.get_successful().two_six_moves<3>() == 0); CHECK(mover.get_attempted().six_two_moves<3>() == 0); CHECK(mover.get_successful().six_two_moves<3>() == 0); CHECK(mover.get_attempted().four_four_moves<3>() == 0); CHECK(mover.get_successful().four_four_moves<3>() == 0); } THEN("A lot of moves are made.") { // auto result = mover(manifold); // CHECK(result.is_valid()); } } } GIVEN("A 4D manifold.") { WHEN("A MoveStrategy4 is constructed.") { auto constexpr passes = static_cast<Int_precision>(1); auto constexpr checkpoint = static_cast<Int_precision>(1); MoveAlways4 mover(passes, checkpoint); THEN("The correct passes and checkpoints are instantiated.") { CHECK(mover.passes() == passes); CHECK(mover.checkpoint() == checkpoint); } THEN("Attempted moves and successful moves are zero-initialized.") { CHECK(mover.get_attempted().two_four_moves<4>() == 0); CHECK(mover.get_successful().two_four_moves<4>() == 0); } } } } // SCENARIO("Using the Metropolis algorithm", "[metropolis][!mayfail][!hide]") //{ // constexpr auto Alpha = static_cast<long double>(0.6); // constexpr auto K = static_cast<long double>(1.1); // constexpr auto Lambda = static_cast<long double>(0.1); // constexpr auto passes = static_cast<Int_precision>(10); // constexpr auto output_every_n_passes = static_cast<Int_precision>(1); // GIVEN("A correctly-constructed SimplicialManifold.") // { // constexpr auto simplices = static_cast<Int_precision>(640); // constexpr auto timeslices = static_cast<Int_precision>(4); // SimplicialManifold universe(make_triangulation(simplices, timeslices)); // // It is correctly constructed // CHECK(universe.triangulation); // CHECK(universe.geometry->number_of_cells() == // universe.triangulation->number_of_finite_cells()); // CHECK(universe.geometry->number_of_edges() == // universe.triangulation->number_of_finite_edges()); // CHECK(universe.geometry->N0() == // universe.triangulation->number_of_vertices()); // CHECK(universe.triangulation->dimension() == 3); // CHECK(fix_timeslices(universe.triangulation)); // CHECK(universe.triangulation->is_valid()); // CHECK(universe.triangulation->tds().is_valid()); // WHEN("A Metropolis function object is constructed.") // { // Metropolis testrun(Alpha, K, Lambda, passes, output_every_n_passes); // THEN("The Metropolis function object is initialized correctly.") // { // CHECK(testrun.Alpha() == Alpha); // CHECK(testrun.K() == K); // CHECK(testrun.Lambda() == Lambda); // CHECK(testrun.Passes() == passes); // CHECK(testrun.Checkpoint() == output_every_n_passes); // CHECK(testrun.TwoThreeMoves() == 0); // CHECK(testrun.SuccessfulTwoThreeMoves() == 0); // CHECK(testrun.ThreeTwoMoves() == 0); // CHECK(testrun.SuccessfulThreeTwoMoves() == 0); // CHECK(testrun.TwoSixMoves() == 0); // CHECK(testrun.SuccessfulTwoSixMoves() == 0); // CHECK(testrun.SixTwoMoves() == 0); // CHECK(testrun.SuccessfulSixTwoMoves() == 0); // CHECK(testrun.FourFourMoves() == 0); // CHECK(testrun.SuccessfulFourFourMoves() == 0); // } // } // WHEN("The Metropolis functor is called.") // { // // Initialize Metropolis function object with passes and checkpoints = 1 // Metropolis testrun(Alpha, K, Lambda, 1, 1); // // Call function object // auto result = std::move(testrun(universe)); // std::cout << "Results:\n"; // std::cout << "N1_TL = " << result.geometry->N1_TL() << "\n"; // std::cout << "N3_31 = " << result.geometry->N3_31() << "\n"; // std::cout << "N3_22 = " << result.geometry->N3_22() << "\n"; // std::cout << "There were " << testrun.TwoThreeMoves() // << " attempted (2,3) moves and " // << testrun.SuccessfulTwoThreeMoves() // << " successful (2,3) moves.\n"; // std::cout << "There were " << testrun.ThreeTwoMoves() // << " attempted (3,2) moves and " // << testrun.SuccessfulThreeTwoMoves() // << " successful (3,2) moves.\n"; // std::cout << "There were " << testrun.TwoSixMoves() // << " attempted (2,6) moves and " // << testrun.SuccessfulTwoSixMoves() // << " successful (2,6) moves.\n"; // std::cout << "There were " << testrun.SixTwoMoves() // << " attempted (6,2) moves and " // << testrun.SuccessfulSixTwoMoves() // << " successful (6,2) moves.\n"; // THEN("The result is a valid SimplicialManifold.") // { // CHECK(result.triangulation); // CHECK(result.geometry->number_of_cells() == // result.triangulation->number_of_finite_cells()); // CHECK(result.geometry->number_of_edges() == // result.triangulation->number_of_finite_edges()); // CHECK(result.geometry->N0() == // result.triangulation->number_of_vertices()); // CHECK(result.triangulation->dimension() == 3); // CHECK(fix_timeslices(result.triangulation)); // CHECK(result.triangulation->tds().is_valid()); // // VolumePerTimeslice(result); // // CHECK(result.geometry->max_timevalue().get() == timeslices); // CHECK(result.geometry->min_timevalue().get() == 1); // } // // THEN("A1 is calculated for each move.") // { // auto A1_23 = testrun.CalculateA1(move_type::TWO_THREE); // auto A1_32 = testrun.CalculateA1(move_type::THREE_TWO); // auto A1_26 = testrun.CalculateA1(move_type::TWO_SIX); // auto A1_62 = testrun.CalculateA1(move_type::SIX_TWO); // // CHECK(IsProbabilityRange(A1_23)); // std::cout << "A1 for (2,3) moves is: " << A1_23 << '\n'; // CHECK(IsProbabilityRange(A1_32)); // std::cout << "A1 for (3,2) moves is: " << A1_32 << '\n'; // CHECK(IsProbabilityRange(A1_26)); // std::cout << "A1 for (2,6) moves is: " << A1_26 << '\n'; // CHECK(IsProbabilityRange(A1_62)); // std::cout << "A1 for (6,2) moves is: " << A1_62 << '\n'; // } // THEN("A2 is calculated for each move.") // { // auto A2_23 = testrun.CalculateA2(move_type::TWO_THREE); // auto A2_32 = testrun.CalculateA2(move_type::THREE_TWO); // auto A2_26 = testrun.CalculateA2(move_type::TWO_SIX); // auto A2_62 = testrun.CalculateA2(move_type::SIX_TWO); // // CHECK(IsProbabilityRange(A2_23)); // std::cout << "A2 for (2,3) moves is: " << A2_23 << '\n'; // CHECK(IsProbabilityRange(A2_32)); // std::cout << "A2 for (2,3) moves is: " << A2_32 << '\n'; // CHECK(IsProbabilityRange(A2_26)); // std::cout << "A2 for (2,6) moves is: " << A2_26 << '\n'; // CHECK(IsProbabilityRange(A2_62)); // std::cout << "A2 for (6,2) moves is: " << A2_62 << '\n'; // } // } // } //}
41.675
80
0.607421
mjcaisse
e9f07ad42638a0b2200c97f2c529c0caac914fd2
2,477
cpp
C++
mysql-server/storage/ndb/src/ndbapi/Ndberr.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/src/ndbapi/Ndberr.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/storage/ndb/src/ndbapi/Ndberr.cpp
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "API.hpp" static void update(const NdbError & _err){ NdbError & error = (NdbError &) _err; ndberror_struct ndberror = (ndberror_struct)error; ndberror_update(&ndberror); error = NdbError(ndberror); } const NdbError & Ndb::getNdbError(int code){ theError.code = code; update(theError); return theError; } const NdbError & Ndb::getNdbError() const { update(theError); return theError; } const NdbError & NdbDictionaryImpl::getNdbError() const { update(m_error); return m_error; } const NdbError & NdbTransaction::getNdbError() const { update(theError); return theError; } const NdbError & NdbOperation::getNdbError() const { update(theError); return theError; } const NdbError & NdbBlob::getNdbError() const { update(theError); return theError; } const NdbError & NdbEventOperationImpl::getNdbError() const { update(m_error); return m_error; } const NdbError & NdbDictInterface::getNdbError() const { update(m_error); return m_error; } const NdbError & NdbQueryBuilderImpl::getNdbError() const { update(m_error); return m_error; } const NdbError & NdbQueryImpl::getNdbError() const { update(m_error); return m_error; } const NdbIndexStat::Error & NdbIndexStatImpl::getNdbError() const { update(m_error); return m_error; }
22.116071
79
0.741219
silenc3502
e9f138b66379a299ac02d00c229cfbe3bc482fda
3,071
cpp
C++
unit/src/RemovePlanarityTest.cpp
volkerschmidts/titania
1ad441a7f9481392e21216a2be86b20b1d090a97
[ "MIT" ]
null
null
null
unit/src/RemovePlanarityTest.cpp
volkerschmidts/titania
1ad441a7f9481392e21216a2be86b20b1d090a97
[ "MIT" ]
1
2022-03-24T03:54:06.000Z
2022-03-25T15:32:09.000Z
unit/src/RemovePlanarityTest.cpp
volkerschmidts/titania
1ad441a7f9481392e21216a2be86b20b1d090a97
[ "MIT" ]
null
null
null
#include "RemovePlanarityTest.hpp" #include "StanIPC.h" #include "main.h" #include <Atom.hpp> #include <Declarations.hpp> #include <LinAlg.hpp> #include <Molecule.hpp> #include <Output.hpp> #include <Structure.hpp> #include <StructureSimulator.hpp> CPPUNIT_TEST_SUITE_REGISTRATION(RemovePlanarityTest); RemovePlanarityTest::RemovePlanarityTest() { CurrMol = ipcStan(); for (Atom *CurrAtom = CurrMol->getHeadStruc()->getHeadAtom(); CurrAtom; CurrAtom = CurrAtom->getNext()) { Eigen::Vector3d coord = CurrAtom->Coordinates2Eigen(StructureOptions::Initial); // flatten initial coordinates along z-axis coord(2) = 0.0; CurrAtom->setCoordinates(coord, StructureOptions::Initial); } Flags flags; Sim = new StructureSimulator(CurrMol->getHeadStruc(), flags); } RemovePlanarityTest::~RemovePlanarityTest() { delete Sim; delete CurrMol; } void RemovePlanarityTest::testRemovePlanarity() { // fix random seed to something we know works, otherwise the // constraints might be too strict for a randomly large displacement srand(1632403515); BasicInformation baseInformation; Structure *CurrStruc = CurrMol->getHeadStruc(); std::string titania_unit_path = TITANIA_UNIT_TESTS_DIR__; baseInformation.xyzFile.open( (titania_unit_path + "/systems/cppunit_input.tna.out.removePlanarity.xyz"), std::ios::binary | std::ios::out | std::ios::trunc); outputXYZ(CurrStruc->getHeadAtom(), baseInformation, StructureOptions::Initial, "flattened structure"); removePlanarity(CurrStruc, *Sim, baseInformation); // For the IPC geometry with all z-coordinates set to 0.0 (see constructor // above), the initial eigensystem of the inertia tensor is: // // Moments of Inertia // 174.659920 415.561870 590.221790 // // After the coordinates are mangled by the Simplex Minimizer called by // removePlanarity() the moments of inertia will no longer satisfy the // planarity condition (I_z = Ix + Iy). // The actual values of the moments of inertia will be different for each // diastereoisomer, and as the function uses rand() to mutate the initial // planar geometry, we don't know at which diastereoisomer the minimizer // will arrive. // // The threshold in this test is set to a relaxed / optimized // value of 200. For a proper, relaxed IPC geometry, a value around // I_z - (Ix + Iy) = -232 is expected. With the limited constraints imposed // in removePlanarity(), this may not be reached. Manual calculations with // the current implementation and the above seed yield a value of -221.068025. // double MINIMUM_PLANARITY_VIOLATION = 200; Tensor *ITensor = CurrStruc->CalculateInertiaTensor(StructureOptions::Initial); Eigen::Vector3d MomentsOfInertia = ITensor->getEvals(); outputXYZ(CurrStruc->getHeadAtom(), baseInformation, StructureOptions::Initial, "de-flattened structure"); CPPUNIT_ASSERT( fabs(MomentsOfInertia(2) - (MomentsOfInertia(1) + MomentsOfInertia(0))) > MINIMUM_PLANARITY_VIOLATION); }
33.747253
80
0.727125
volkerschmidts
e9f23668d6fd9e5a6c18fedf6e58e3679a4da77f
3,957
cpp
C++
src/DynamixelMotor.cpp
sylvaing19/ardyno
87b00809581f469fe84beefe3d701fef223cd524
[ "BSD-2-Clause" ]
5
2018-12-09T18:13:03.000Z
2021-12-16T20:07:51.000Z
src/DynamixelMotor.cpp
sylvaing19/dynamixel_teensy
87b00809581f469fe84beefe3d701fef223cd524
[ "BSD-2-Clause" ]
null
null
null
src/DynamixelMotor.cpp
sylvaing19/dynamixel_teensy
87b00809581f469fe84beefe3d701fef223cd524
[ "BSD-2-Clause" ]
null
null
null
#include "DynamixelMotor.h" DynamixelDevice::DynamixelDevice(DynamixelInterface &aInterface, DynamixelID aID): mInterface(aInterface), mStatusReturnLevel(255), mID(aID) { mStatus = DYN_STATUS_OK; if (mID == BROADCAST_ID) { mStatusReturnLevel = 0; } } uint8_t DynamixelDevice::statusReturnLevel() { if (mStatusReturnLevel == 255) { init(); } return mStatusReturnLevel; } void DynamixelDevice::statusReturnLevel(uint8_t aSRL) { write(DYN_ADDRESS_SRL, aSRL); if (status() == DYN_STATUS_OK) { mStatusReturnLevel = aSRL; } } uint16_t DynamixelDevice::model() { uint16_t result; read(DYN_ADDRESS_ID, result); return result; } uint8_t DynamixelDevice::firmware() { uint8_t result; read(DYN_ADDRESS_FIRMWARE, result); return result; } void DynamixelDevice::communicationSpeed(uint32_t aSpeed) { uint8_t value = 2000000 / aSpeed - 1; if (value != 0) // forbid 2MBd rate, because it is out of spec, and can be difficult to undo { write(DYN_ADDRESS_BAUDRATE, value); } } DynamixelStatus DynamixelDevice::init() { mStatusReturnLevel = 1; DynamixelStatus status = ping(); if (status != DYN_STATUS_OK) { mStatusReturnLevel = 0; return status; } status = read(DYN_ADDRESS_SRL, mStatusReturnLevel); if (status & (DYN_STATUS_COM_ERROR | DYN_STATUS_TIMEOUT)) { mStatusReturnLevel = 0; } else if (status != DYN_STATUS_OK) { mStatusReturnLevel = 0; return status; } return DYN_STATUS_OK; } DynamixelMotor::DynamixelMotor(DynamixelInterface &aInterface, DynamixelID aId): DynamixelDevice(aInterface, aId) {} void DynamixelMotor::wheelMode() { jointMode(0,0); } void DynamixelMotor::jointMode(uint16_t aCWLimit, uint16_t aCCWLimit) { uint32_t data = (aCWLimit | (uint32_t(aCCWLimit) << 16)); write(DYN_ADDRESS_CW_LIMIT, data); } void DynamixelMotor::enableTorque(bool aTorque) { write(DYN_ADDRESS_ENABLE_TORQUE, uint8_t(aTorque?1:0)); } DynamixelStatus DynamixelMotor::alarmShutdown(uint8_t aMode) { aMode &= B01111111; return write(DYN_ADDRESS_ALARM_SHUTDOWN, aMode); } DynamixelStatus DynamixelMotor::speed(uint16_t aSpeed) { return write(DYN_ADDRESS_GOAL_SPEED, aSpeed); } DynamixelStatus DynamixelMotor::torqueLimit(uint16_t aTorque) { return write(DYN_ADDRESS_TORQUE_LIMIT, aTorque); } DynamixelStatus DynamixelMotor::goalPosition(uint16_t aPosition) { return write(DYN_ADDRESS_GOAL_POSITION, aPosition); } DynamixelStatus DynamixelMotor::goalPositionDegree(uint16_t posDeg) { return goalPosition(posDeg * 3.41); } void DynamixelMotor::recoverTorque() { uint16_t currentPosition = -1; if (!(read(DYN_ADDRESS_CURRENT_POSITION, currentPosition) & DYN_STATUS_COM_ERROR)) { if (currentPosition != (uint16_t)-1) { write(DYN_ADDRESS_GOAL_POSITION, currentPosition); } } uint16_t torque = 0x3FF; if (read(DYN_ADDRESS_MAX_TORQUE, torque) & DYN_STATUS_COM_ERROR) { write(DYN_ADDRESS_TORQUE_LIMIT, 0x3FF); } else { write(DYN_ADDRESS_TORQUE_LIMIT, torque); } enableTorque(); } DynamixelStatus DynamixelMotor::resetSecuritySettings() { DynamixelStatus status = 0; status |= write(DYN_ADDRESS_TEMP_LIMIT, (uint8_t)85); status |= write(DYN_ADDRESS_LOW_VOLTAGE_LIMIT, (uint8_t)60); status |= write(DYN_ADDRESS_HIGH_VOLTAGE_LIMIT, (uint8_t)140); status |= write(DYN_ADDRESS_MAX_TORQUE, (uint16_t)0x3FF); status |= write(DYN_ADDRESS_ALARM_LED, (uint8_t)36); status |= write(DYN_ADDRESS_ALARM_SHUTDOWN, (uint8_t)36); return status; } void DynamixelMotor::setId(uint8_t newId) { write(DYN_ADDRESS_ID, newId); mID = newId; } void DynamixelMotor::led(uint8_t aState) { write(DYN_ADDRESS_LED, aState); } DynamixelStatus DynamixelMotor::currentPosition(uint16_t &aPosition) { aPosition = UINT16_MAX; return read(DYN_ADDRESS_CURRENT_POSITION, aPosition); } DynamixelStatus DynamixelMotor::currentPositionDegree(uint16_t &aPosition) { DynamixelStatus status = currentPosition(aPosition); aPosition = (uint16_t)((float)aPosition / 3.41); return status; }
21.505435
93
0.760425
sylvaing19
e9f2b90b29c56da8ae57cf0ed91c7ab47f6a8ba1
36,069
hpp
C++
src/cpp_json/cpp_json__document.hpp
mrange/cppjson
553795705eeda5e2add18dd3345a4c01a9b4de99
[ "Apache-2.0" ]
null
null
null
src/cpp_json/cpp_json__document.hpp
mrange/cppjson
553795705eeda5e2add18dd3345a4c01a9b4de99
[ "Apache-2.0" ]
null
null
null
src/cpp_json/cpp_json__document.hpp
mrange/cppjson
553795705eeda5e2add18dd3345a4c01a9b4de99
[ "Apache-2.0" ]
null
null
null
// ---------------------------------------------------------------------------------------------- // Copyright 2015 Mårten Rånge // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------------------- #ifndef CPP_JSON__DOCUMENT_H #define CPP_JSON__DOCUMENT_H #include <algorithm> #include <array> #include <cmath> #include <cwchar> #include <cstdio> #include <deque> #include <memory> #include <string> #include <type_traits> #include <vector> #include <utility> #include <tuple> #include "cpp_json__parser.hpp" #define CPP_JSON__NO_COPY_MOVE(name) \ name (name const &) = delete; \ name (name && ) = delete; \ name & operator= (name const &) = delete; \ name & operator= (name && ) = delete; namespace cpp_json { namespace document { using doc_string_type = std::wstring ; using doc_strings_type = std::vector<doc_string_type>; using doc_char_type = doc_string_type::value_type ; using doc_iter_type = doc_char_type const * ; namespace details { constexpr auto default_size = 16U; constexpr auto window_size = 70U; constexpr auto hwindow_size = window_size / 2; struct json_element__null ; struct json_element__bool ; struct json_element__number ; struct json_element__string ; struct json_element__array ; struct json_element__object ; struct json_element__error ; struct json_document__impl ; } // Implement json_element_visitor to traverse the JSON DOM using 'apply' method struct json_element_visitor { using ptr = std::shared_ptr<json_element_visitor> ; json_element_visitor () = default; virtual ~json_element_visitor () = default; CPP_JSON__NO_COPY_MOVE (json_element_visitor); virtual bool visit (details::json_element__null const & v) = 0; virtual bool visit (details::json_element__bool const & v) = 0; virtual bool visit (details::json_element__number const & v) = 0; virtual bool visit (details::json_element__string const & v) = 0; virtual bool visit (details::json_element__object const & v) = 0; virtual bool visit (details::json_element__array const & v) = 0; virtual bool visit (details::json_element__error const & v) = 0; }; struct json_element { using ptr = json_element const *; json_element () = default; virtual ~json_element () = default; CPP_JSON__NO_COPY_MOVE (json_element); // Returns the number of children (object/array) virtual std::size_t size () const = 0; // Returns the child at index (object/array) // if out of bounds returns an error DOM element virtual ptr at (std::size_t idx) const = 0; // Returns the child with name (object) // if not found returns an error DOM element virtual ptr get (doc_string_type const & name) const = 0; // Returns all member names (object) // May contain duplicates, is in order virtual doc_strings_type names () const = 0; // Returns true if DOM element represents an error virtual bool is_error () const = 0; // Returns true if DOM element represents an scalar virtual bool is_scalar () const = 0; // Returns true if DOM element represents a null value virtual bool is_null () const = 0; // Converts the value to a boolean value virtual bool as_bool () const = 0; // Converts the value to a double value virtual double as_number () const = 0; // Converts the value to a string value virtual doc_string_type as_string () const = 0; // Applies the JSON element visitor to the element virtual bool apply (json_element_visitor & v) const = 0; }; struct json_document { using ptr = std::shared_ptr<json_document> ; json_document () = default; virtual ~json_document () = default; CPP_JSON__NO_COPY_MOVE (json_document); // Gets the root element of the JSON document virtual json_element::ptr root () const = 0; // Creates a string from a JSON document virtual doc_string_type to_string () const = 0; }; namespace details { using array_members = std::vector<json_element::ptr> ; using object_members = std::vector<std::tuple<doc_string_type, json_element::ptr>> ; inline void to_string (doc_string_type & value, double d) { if (std::isnan (d)) { value += L"\"NaN\""; } else if (std::isinf (d) && d < 0) { value += L"\"-Inf\""; } else if (std::isinf (d)) { value += L"\"+Inf\""; } else { constexpr auto bsz = 64U; wchar_t buffer[bsz]; std::swprintf (buffer, bsz, L"%G", d); value += buffer; } } struct json_non_printable_chars { using non_printable_char = std::array<doc_char_type , 8 >; using non_printable_chars = std::array<non_printable_char , 32>; json_non_printable_chars () { for (auto iter = 0U; iter < table.size (); ++iter) { auto && v = table[iter]; std::fill (v.begin (), v.end (), 0); auto fmt = L"\\u%04x"; switch (iter) { case '\b': fmt = L"\\b"; break; case '\f': fmt = L"\\f"; break; case '\n': fmt = L"\\n"; break; case '\r': fmt = L"\\r"; break; case '\t': fmt = L"\\t"; break; } std::swprintf (v.data (), v.size (), fmt, iter); } } static json_non_printable_chars const & get () { // TODO: Race condition issue (until compilers widely support magic statics) static json_non_printable_chars non_printable_chars; return non_printable_chars; } inline void append (doc_string_type & s, doc_char_type ch) const noexcept { if (ch < table.size ()) { auto p = table[ch].data (); while (*p) { s += *p++; } } else { s += ch; } } private: non_printable_chars table; }; struct json_element__base : json_element { json_document__impl const * doc; inline explicit json_element__base (json_document__impl const * doc) : doc (doc) { } ptr error_element () const; ptr null_element () const; }; struct json_element__scalar : json_element__base { inline explicit json_element__scalar (json_document__impl const * doc) : json_element__base (doc) { } std::size_t size () const override { return 0; } ptr at (std::size_t /*idx*/) const override { return error_element (); } ptr get (doc_string_type const & /*name*/) const override { return error_element (); } doc_strings_type names () const override { return doc_strings_type (); } bool is_error () const override { return false; } bool is_scalar () const override { return true; } }; struct json_element__null : json_element__scalar { inline explicit json_element__null (json_document__impl const * doc) : json_element__scalar (doc) { } bool is_null () const override { return true; } bool as_bool () const override { return false; } double as_number () const override { return 0.0; } doc_string_type as_string () const { return L"null"; } bool apply (json_element_visitor & v) const { return v.visit (*this); } }; struct json_element__bool : json_element__scalar { bool const value; inline explicit json_element__bool (json_document__impl const * doc, bool v) : json_element__scalar (doc) , value (v) { } bool is_null () const override { return false; } bool as_bool () const override { return value; } double as_number () const override { return value ? 1.0 : 0.0; } doc_string_type as_string () const override { return value ? L"true" : L"false" ; } bool apply (json_element_visitor & v) const { return v.visit (*this); } }; struct json_element__number : json_element__scalar { double const value; inline explicit json_element__number (json_document__impl const * doc, double v) : json_element__scalar (doc) , value (v) { } bool is_null () const override { return false; } bool as_bool () const override { return value != 0.0; } double as_number () const override { return value; } doc_string_type as_string () const override { doc_string_type result; result.reserve (default_size); to_string (result, value); return result; } bool apply (json_element_visitor & v) const { return v.visit (*this); } }; struct json_element__string : json_element__scalar { doc_string_type const value; inline explicit json_element__string (json_document__impl const * doc, doc_string_type v) : json_element__scalar (doc) , value (std::move (v)) { } bool is_null () const override { return false; } bool as_bool () const override { return !value.empty (); } double as_number () const override { doc_char_type * e = nullptr; return std::wcstof (value.c_str (), &e); } doc_string_type as_string () const override { return value; } bool apply (json_element_visitor & v) const { return v.visit (*this); } }; struct json_element__container : json_element__base { inline explicit json_element__container (json_document__impl const * doc) : json_element__base (doc) { } bool is_error () const override { return false; } bool is_scalar () const override { return false; } bool is_null () const override { return false; } bool as_bool () const override { return false; } double as_number () const override { return 0.0; } doc_string_type as_string () const override { return doc_string_type (); } }; struct json_element__array : json_element__container { array_members members; inline explicit json_element__array ( json_document__impl const * doc , array_members && members ) : json_element__container (doc) , members (std::move (members)) { } std::size_t size () const override { return members.size (); } ptr at (std::size_t idx) const override { if (idx < members.size ()) { return members[idx]; } else { return error_element (); } } ptr get (doc_string_type const & /*name*/) const override { return error_element (); } doc_strings_type names () const override { return doc_strings_type (); } bool apply (json_element_visitor & v) const { return v.visit (*this); } }; struct json_element__object : json_element__container { object_members members; inline explicit json_element__object ( json_document__impl const * doc , object_members && members ) : json_element__container (doc) , members (std::move (members)) { } std::size_t size () const override { return members.size (); } ptr at (std::size_t idx) const override { if (idx < size ()) { return std::get<1> (members[idx]); } else { return error_element (); } } ptr get (doc_string_type const & name) const override { for (auto && kv : members) { if (std::get<0> (kv) == name) { return std::get<1> (kv); } } return error_element (); } doc_strings_type names () const override { doc_strings_type result; result.reserve (members.size ()); for (auto && kv : members) { result.push_back (std::get<0> (kv)); } return result; } bool apply (json_element_visitor & v) const { return v.visit (*this); } }; struct json_element__error : json_element__base { inline explicit json_element__error (json_document__impl const * doc) : json_element__base (doc) { } std::size_t size () const override { return 0; } ptr at (std::size_t /*idx*/) const override { return error_element (); } ptr get (doc_string_type const & /*name*/) const override { return error_element (); } doc_strings_type names () const override { return doc_strings_type (); } bool is_error () const override { return true; } bool is_scalar () const override { return true; } bool is_null () const override { return false; } bool as_bool () const override { return false; } double as_number () const override { return 0.0; } doc_string_type as_string () const override { return L"\"error\""; } bool apply (json_element_visitor & v) const { return v.visit (*this); } }; struct json_element_visitor__to_string : json_element_visitor { doc_string_type value; inline void ch (doc_char_type c) { switch (c) { case '\"': value += L"\\\""; break; case '\\': value += L"\\\\"; break; case '/': value += L"\\/"; break; default: json_non_printable_chars::get ().append (value, c); break; } } inline void str (doc_string_type const & s) { value += L'"'; for (auto && c : s) { ch (c); } value += L'"'; } bool visit (json_element__null const & /*v*/) override { value += L"null"; return true; } bool visit (json_element__bool const & v) override { value += (v.value ? L"true" : L"false"); return true; } bool visit (json_element__number const & v) override { to_string (value, v.value); return true; } bool visit (json_element__string const & v) override { str (v.value); return true; } bool visit (json_element__array const & v) override { value += L'['; auto b = 0; auto e = v.size (); for (auto iter = b; iter < e; ++iter) { if (iter > b) { value += L", "; } auto && c = v.members[iter]; if (c) { c->apply (*this); } else { value += L"null"; } } value += L']'; return true; } bool visit (json_element__object const & v) override { value += L'{'; auto b = 0; auto e = v.size (); for (auto iter = b; iter < e; ++iter) { if (iter > b) { value += L", "; } auto && kv = v.members[iter]; auto && k = std::get<0> (kv); auto && c = std::get<1> (kv); str (k); value += L':'; if (c) { c->apply (*this); } else { value += L"null"; } } value += L'}'; return true; } bool visit (json_element__error const & v) override { str (v.as_string ()); return true; } }; struct json_document__impl : json_document { using tptr = std::shared_ptr<json_document__impl> ; json_element__null const null_value ; json_element__bool const true_value ; json_element__bool const false_value ; json_element__error const error_value ; std::deque<json_element__number> number_values ; std::deque<json_element__string> string_values ; std::deque<json_element__object> object_values ; std::deque<json_element__array > array_values ; json_element::ptr root_value ; json_document__impl () : null_value (this) , true_value (this, true) , false_value (this, false) , error_value (this) , root_value (&null_value) { } json_element::ptr root () const override { return root_value; } doc_string_type to_string () const override { details::json_element_visitor__to_string visitor; CPP_JSON__ASSERT (root_value); root_value->apply (visitor); return std::move (visitor.value); } details::json_element__number * create_number (double v) { number_values.emplace_back (this, v); return & number_values.back (); } details::json_element__string * create_string (doc_string_type && v) { string_values.emplace_back (this, std::move (v)); return & string_values.back (); } details::json_element__array * create_array (array_members && members) { array_values.emplace_back (this, std::move (members)); return & array_values.back (); } details::json_element__object * create_object (object_members && members) { object_values.emplace_back (this, std::move (members)); return & object_values.back (); } }; struct json_element_context : std::enable_shared_from_this<json_element_context> { using ptr = std::shared_ptr<json_element_context> ; using ptrs = std::vector<ptr> ; json_document__impl & document; inline json_element_context (json_document__impl & doc) : document (doc) { } virtual ~json_element_context () = default; CPP_JSON__NO_COPY_MOVE (json_element_context); virtual bool add_value (json_element::ptr const & json ) = 0; virtual bool set_key (doc_string_type && key ) = 0; virtual json_element::ptr create_element ( ptrs & array_contexts , ptrs & object_contexts ) = 0; }; using json_element_contexts = json_element_context::ptrs; struct json_element_context__root : json_element_context { inline json_element_context__root (json_document__impl & doc) : json_element_context (doc) { } virtual bool add_value (json_element::ptr const & json) override { CPP_JSON__ASSERT (json); document.root_value = json; return true; } virtual bool set_key (doc_string_type && /*key*/) override { CPP_JSON__ASSERT (false); return true; } virtual json_element::ptr create_element ( json_element_contexts & /*array_contexts */ , json_element_contexts & /*object_contexts*/ ) override { return document.root_value; } }; struct json_element_context__array : json_element_context { array_members values; inline json_element_context__array (json_document__impl & doc) : json_element_context (doc) { } virtual bool add_value (json_element::ptr const & json) override { CPP_JSON__ASSERT (json); values.push_back (json); return true; } virtual bool set_key (doc_string_type && /*key*/) override { CPP_JSON__ASSERT (false); return true; } virtual json_element::ptr create_element ( json_element_contexts & array_contexts , json_element_contexts & /*object_contexts*/ ) override { auto cap = values.capacity (); values.shrink_to_fit (); auto result = document.create_array (std::move (values)); array_contexts.push_back (shared_from_this ()); values.reserve (cap); return result; } }; struct json_element_context__object : json_element_context { doc_string_type key ; object_members values; inline json_element_context__object (json_document__impl & doc) : json_element_context (doc) { } virtual bool add_value (json_element::ptr const & json) override { CPP_JSON__ASSERT (json); values.push_back (std::make_tuple (std::move (key), json)); return true; } virtual bool set_key (doc_string_type && k) override { key = std::move (k); return true; } virtual json_element::ptr create_element ( json_element_contexts & /*array_contexts */ , json_element_contexts & object_contexts ) override { auto cap = values.capacity (); values.shrink_to_fit (); auto result = document.create_object (std::move (values)); object_contexts.push_back (shared_from_this ()); values.reserve (cap); return result; } }; // string_builder is used to build json strings as it has a slightly lower overhead than std::vector // (on VS2015 RTM). It gives a measureable benefit as JSON documents often has lot of string values template<typename TChar> struct string_builder { using char_type = TChar; static_assert (std::is_pod<char_type>::value, "char_type must be POD type"); inline string_builder () noexcept : cap (default_size) , sz (0) , str (static_cast<char_type *> (std::malloc (cap * sizeof (char_type)))) { CPP_JSON__ASSERT (str); } CPP_JSON__NO_COPY_MOVE (string_builder); inline ~string_builder () noexcept { free (str); } inline void clear () noexcept { sz = 0; } inline void push_back (char_type ch) noexcept { if (sz >= cap) { cap <<= 1; str = static_cast<char_type *> (std::realloc (str, cap * sizeof (char_type))); CPP_JSON__ASSERT (str); CPP_JSON__ASSERT (sz < cap); } str[sz] = ch; ++sz; } inline std::basic_string<char_type> create_string () const { return std::basic_string<char_type> (str, sz); } private: std::size_t cap ; std::size_t sz ; char_type * str ; }; struct builder_json_context { using string_type = doc_string_type ; using char_type = doc_char_type ; using iter_type = doc_iter_type ; json_document__impl::tptr document ; string_builder<char_type> current_string ; json_element_contexts element_context ; json_element_contexts array_contexts ; json_element_contexts object_contexts ; inline builder_json_context () : document (std::make_shared<json_document__impl> ()) { element_context.reserve (default_size); element_context.reserve (default_size); element_context.reserve (default_size); element_context.push_back (std::make_shared<json_element_context__root> (*document)); } CPP_JSON__NO_COPY_MOVE (builder_json_context); inline void expected_char (std::size_t /*pos*/, char_type /*ch*/) noexcept { } inline void expected_chars (std::size_t /*pos*/, string_type const & /*chs*/) noexcept { } inline void expected_token (std::size_t /*pos*/, string_type const & /*token*/) noexcept { } inline void unexpected_token (std::size_t /*pos*/, string_type const & /*token*/) noexcept { } inline void clear_string () { current_string.clear (); } inline void push_char (char_type ch) { current_string.push_back (ch); } inline void push_wchar_t (wchar_t ch) { current_string.push_back (ch); } inline string_type get_string () { return current_string.create_string (); } inline bool pop () { CPP_JSON__ASSERT (!element_context.empty ()); auto back = element_context.back (); CPP_JSON__ASSERT (back); element_context.pop_back (); CPP_JSON__ASSERT (!element_context.empty ()); auto && next = element_context.back (); CPP_JSON__ASSERT (next); auto && element = back->create_element (array_contexts, object_contexts); CPP_JSON__ASSERT (element); next->add_value (element); return true; } bool array_begin () { if (array_contexts.empty ()) { element_context.push_back (std::make_shared<json_element_context__array> (*document)); } else { element_context.push_back (array_contexts.back ()); array_contexts.pop_back (); } return true; } bool array_end () { return pop (); } bool object_begin () { if (object_contexts.empty ()) { element_context.push_back (std::make_shared<json_element_context__object> (*document)); } else { element_context.push_back (object_contexts.back ()); object_contexts.pop_back (); } return true; } bool member_key (string_type && s) { CPP_JSON__ASSERT (!element_context.empty ()); auto && back = element_context.back (); CPP_JSON__ASSERT (back); back->set_key (std::move (s)); return true; } bool object_end () { return pop (); } bool bool_value (bool b) { auto v = b ? &document->true_value : &document->false_value ; CPP_JSON__ASSERT (!element_context.empty ()); auto && back = element_context.back (); CPP_JSON__ASSERT (back); back->add_value (v); return true; } bool null_value () { auto v = &document->null_value; CPP_JSON__ASSERT (!element_context.empty ()); auto && back = element_context.back (); CPP_JSON__ASSERT (back); back->add_value (v); return true; } bool string_value (string_type && s) { auto v = document->create_string (std::move (s)); CPP_JSON__ASSERT (!element_context.empty ()); auto && back = element_context.back (); CPP_JSON__ASSERT (back); back->add_value (v); return true; } bool number_value (double d) { auto v = document->create_number (d); CPP_JSON__ASSERT (!element_context.empty ()); auto && back = element_context.back (); CPP_JSON__ASSERT (back); back->add_value (v); return true; } }; struct error_json_context { using string_type = doc_string_type ; using char_type = doc_char_type ; using iter_type = doc_iter_type ; std::size_t error_pos ; string_type current_string; std::vector<char_type> exp_chars ; std::vector<string_type> exp_tokens ; std::vector<string_type> unexp_tokens ; inline error_json_context () : error_pos (0) { exp_chars.reserve (default_size); exp_tokens.reserve (default_size); unexp_tokens.reserve (default_size); } CPP_JSON__NO_COPY_MOVE (error_json_context); void expected_char (std::size_t pos, char_type ch) { if (error_pos == pos) { exp_chars.push_back (ch); } } void expected_chars (std::size_t pos, string_type const & chs) { if (error_pos == pos) { for (auto && ch : chs) { expected_char (pos, ch); } } } void expected_token (std::size_t pos, string_type const & token) { if (error_pos == pos) { exp_tokens.push_back (token); } } void unexpected_token (std::size_t pos, string_type const & token) { if (error_pos == pos) { unexp_tokens.push_back (token); } } inline void clear_string () { } inline void push_char (char_type /*ch*/) { } inline void push_wchar_t (wchar_t /*ch*/) { } inline string_type const & get_string () noexcept { return current_string; } inline bool array_begin () { return true; } inline bool array_end () { return true; } inline bool object_begin () { return true; } inline bool member_key (string_type const & /*s*/) { return true; } inline bool object_end () { return true; } inline bool bool_value (bool /*b*/) { return true; } inline bool null_value () { return true; } inline bool string_value (string_type const & /*s*/) { return true; } inline bool number_value (double /*d*/) { return true; } }; inline json_element::ptr json_element__base::error_element () const { return & doc->error_value; } inline json_element::ptr json_element__base::null_element () const { return & doc->null_value; } } struct json_parser { // Parses a JSON string into a JSON document 'result' if successful. // 'pos' indicates the first non-consumed character (which may lay beyond the last character in the input string) static bool parse (doc_string_type const & json, std::size_t & pos, json_document::ptr & result) { auto begin = json.data () ; auto end = begin + json.size (); cpp_json::parser::json_parser<details::builder_json_context> jp (begin, end); if (jp.try_parse__json ()) { pos = jp.pos (); result = jp.document; return true; } else { pos = jp.pos (); result.reset (); return false; } } // Parses a JSON string into a JSON document 'result' if successful. // If parse fails 'error' contains an error description. // 'pos' indicates the first non-consumed character (which may lay beyond the last character in the input string) static bool parse (doc_string_type const & json, std::size_t & pos, json_document::ptr & result, doc_string_type & error) { auto begin = json.data () ; auto end = begin + json.size (); cpp_json::parser::json_parser<details::builder_json_context> jp (begin, end); if (jp.try_parse__json ()) { pos = jp.pos (); result = jp.document; return true; } else { pos = jp.pos (); result.reset (); cpp_json::parser::json_parser<details::error_json_context> ejp (begin, end); ejp.error_pos = jp.pos (); auto eresult = ejp.try_parse__json (); CPP_JSON__ASSERT (!eresult); auto sz = ejp.exp_chars.size () + ejp.exp_tokens.size (); std::vector<doc_string_type> expected = std::move (ejp.exp_tokens); std::vector<doc_string_type> unexpected = std::move (ejp.unexp_tokens); expected.reserve (sz); for (auto ch : ejp.exp_chars) { details::error_json_context::char_type token[] = {'\'', ch, '\'', 0}; expected.push_back (doc_string_type (token)); } std::sort (expected.begin (), expected.end ()); std::sort (unexpected.begin (), unexpected.end ()); expected.erase (std::unique (expected.begin (), expected.end ()), expected.end ()); unexpected.erase (std::unique (unexpected.begin (), unexpected.end ()), unexpected.end ()); doc_string_type msg; auto newline = [&msg] () { msg += L'\n'; }; msg += L"Failed to parse input as JSON"; newline (); auto left = pos < details::hwindow_size ? 0U : pos - details::hwindow_size; auto right = std::min (json.size (), left + details::window_size); auto apos = pos - left; for (auto iter = left; iter < right; ++iter) { auto c = json[iter]; if (c < ' ') { msg += ' '; } else { msg += c; } } newline (); for (auto iter = 0U; iter < apos; ++iter) { msg += L'-'; } msg += L"^ Pos: "; { constexpr auto bsz = 12U; wchar_t spos[bsz] = {}; std::swprintf (spos, bsz, L"%zd", pos); msg += spos; } auto append = [&msg, &newline] (wchar_t const * prepend, std::vector<doc_string_type> const & vs) { CPP_JSON__ASSERT (prepend); if (!vs.empty ()) { newline (); msg += prepend; auto sz = vs.size(); for (auto iter = 0U; iter < sz; ++iter) { if (iter == 0U) { } else if (iter + 1U == sz) { msg += L" or "; } else { msg += L", "; } msg += vs[iter]; } } }; append (L"Expected: " , expected); append (L"Unexpected: " , unexpected); error = std::move (msg); return false; } } }; } } #endif // CPP_JSON__DOCUMENT_H
24.420447
125
0.535723
mrange
e9f3df48926e0b921adc4f4b77206fb004842a8c
4,726
cpp
C++
src/desktop/app/ComponentManager.cpp
varunamachi/tanyatu
ce055e0fb0b688054fe19ef39b09a6ca655e2457
[ "MIT" ]
1
2018-01-07T18:11:04.000Z
2018-01-07T18:11:04.000Z
src/desktop/app/ComponentManager.cpp
varunamachi/tanyatu
ce055e0fb0b688054fe19ef39b09a6ca655e2457
[ "MIT" ]
null
null
null
src/desktop/app/ComponentManager.cpp
varunamachi/tanyatu
ce055e0fb0b688054fe19ef39b09a6ca655e2457
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright (c) 2014 Varuna L Amachi. 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 <QHBoxLayout> #include <QSplitter> #include <QIcon> #include "ComponentManager.h" using namespace GreenChilli; ComponentManager *ComponentManager::s_instance = 0; void ComponentManager::destroy() { if( s_instance ) { delete s_instance; } } ComponentManager* ComponentManager::get() { if( ! s_instance ) { s_instance = new ComponentManager(); } return s_instance; } ComponentManager::ComponentManager( QWidget *parent ) : QWidget( parent ) { setupUi(); } ComponentManager::~ComponentManager() { m_nameToIndex.clear(); qDeleteAll( m_components.begin(), m_components.end() ); } void ComponentManager::setupUi() { m_mainWidget = new QStackedWidget( this ); m_buttonLayout = new QHBoxLayout(); QHBoxLayout *topLayout = new QHBoxLayout(); m_buttonLayout->addStretch(); topLayout->addLayout( m_buttonLayout ); topLayout->addStretch(); QVBoxLayout *mainLayout = new QVBoxLayout(); mainLayout->addLayout( topLayout ); mainLayout->addWidget( m_mainWidget ); mainLayout->setContentsMargins( QMargins() ); mainLayout->setSpacing( 0 ); m_mainWidget->setContentsMargins( QMargins() ); m_buttonLayout->setContentsMargins( 4, 2, 0, 0 ); m_buttonLayout->setSpacing( 5 ); this->setLayout( mainLayout ); } QList< ChilliComponent *> ComponentManager::allComponents() const { return m_components.values(); } const ChilliComponent* ComponentManager::component( QString componentId ) const { return m_components.value( componentId ); } const ChilliComponent *ComponentManager::currentComponent() const { QWidget *widget = m_mainWidget->currentWidget(); if( widget ) { return static_cast< ChilliComponent *>( widget ); } return 0; } void ComponentManager::addComponent( GreenChilli::ChilliComponent *component ) { if( component && ! m_components.contains( component->componentId() )) { m_components.insert( component->componentId(), component ); IndexButton *button = new IndexButton( m_components.size() - 1, component->componentName(), this ); m_buttons.append( button ); m_nameToIndex.insert( component->componentId(), m_components.size() - 1 ); m_buttonLayout->insertWidget( m_buttonLayout->count() - 1, button ); connect( button, SIGNAL( activated( int )), this, SLOT( onIndexSelected( int ))); m_mainWidget->addWidget( component ); component->setContentsMargins( QMargins() ); emit componentAdded( component ); if( m_components.size() == 1 ) { button->setChecked( true ); m_mainWidget->setCurrentIndex( 0 ); } } } void ComponentManager::selectComponent( QString componentId ) { if( m_nameToIndex.contains( componentId )) { int index = m_nameToIndex.value( componentId ); m_buttons.at( m_mainWidget->currentIndex() )->setChecked( false ); m_buttons.at( index )->setChecked( true ); m_mainWidget->setCurrentIndex( index ); emit componentSelected( m_components.value( componentId )); } } void ComponentManager::onIndexSelected( int row ) { m_buttons.at( m_mainWidget->currentIndex() )->setChecked( false ); m_mainWidget->setCurrentIndex( row ); }
30.688312
80
0.655946
varunamachi
e9f788748cb58234056260f15c69225482563ced
29,958
hpp
C++
lighter_int.hpp
snake5/lighter
dfaaaeadf00d2a9302f937c9b8138202b4e58ef5
[ "MIT" ]
5
2015-08-31T15:37:47.000Z
2020-09-30T11:57:24.000Z
lighter_int.hpp
snake5/lighter
dfaaaeadf00d2a9302f937c9b8138202b4e58ef5
[ "MIT" ]
null
null
null
lighter_int.hpp
snake5/lighter
dfaaaeadf00d2a9302f937c9b8138202b4e58ef5
[ "MIT" ]
null
null
null
#pragma once #define _USE_MATH_DEFINES #include <math.h> #include <string.h> #include <stdio.h> #include <float.h> #include <vector> #include <string> #include <algorithm> #include "lighter.h" #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # undef _WIN32_WINNT # define _WIN32_WINNT 0x0600 # undef WINVER # define WINVER 0x0600 # include <windows.h> # define ltrthread_sleep( ms ) Sleep( (DWORD) ms ) # define ltrmutex_t CRITICAL_SECTION # define ltrcondvar_t CONDITION_VARIABLE # define ltrthread_t HANDLE # define threadret_t DWORD __stdcall # define threadarg_t void* # define ltrthread_create( toT, func, data ) toT = CreateThread( NULL, 1024, func, data, 0, NULL ) # define ltrthread_self() GetCurrentThread() # define ltrthread_join( T ) for(;;){ WaitForMultipleObjects( 1, &T, TRUE, INFINITE ); CloseHandle( T ); break; } # define ltrthread_equal( T1, T2 ) (T1 == T2) # define ltrmutex_init( M ) InitializeCriticalSection( &M ) # define ltrmutex_destroy( M ) DeleteCriticalSection( &M ) # define ltrmutex_lock( M ) EnterCriticalSection( &M ) # define ltrmutex_unlock( M ) LeaveCriticalSection( &M ) # define ltrcondvar_init( CV ) InitializeConditionVariable( &(CV) ) # define ltrcondvar_destroy( CV ) # define ltrcondvar_sleep( CV, M ) SleepConditionVariableCS( &(CV), &(M), INFINITE ) # define ltrcondvar_wakeall( CV ) WakeAllConditionVariable( &(CV) ) static int ltrnumcpus() { SYSTEM_INFO sysinfo; GetSystemInfo( &sysinfo ); return sysinfo.dwNumberOfProcessors; } #else # include <unistd.h> # include <pthread.h> static void ltrthread_sleep( uint32_t ms ) { if( ms >= 1000 ) { sleep( ms / 1000 ); ms %= 1000; } if( ms > 0 ) { usleep( ms * 1000 ); } } # define ltrmutex_t pthread_mutex_t # define ltrcondvar_t pthread_cond_t # define ltrthread_t pthread_t # define threadret_t void* # define threadarg_t void* # define ltrthread_create( toT, func, data ) pthread_create( &toT, NULL, func, data ) # define ltrthread_self() pthread_self() # define ltrthread_join( T ) pthread_join( T, NULL ) # define ltrthread_equal( T1, T2 ) pthread_equal( T1, T2 ) # define ltrmutex_init( M ) pthread_mutex_init( &M, NULL ) # define ltrmutex_destroy( M ) pthread_mutex_destroy( &M ) # define ltrmutex_lock( M ) pthread_mutex_lock( &M ) # define ltrmutex_unlock( M ) pthread_mutex_unlock( &M ) # define ltrcondvar_init( CV ) pthread_cond_init( &(CV), NULL ) # define ltrcondvar_destroy( CV ) pthread_cond_destroy( &(CV) ) # define ltrcondvar_sleep( CV, M ) pthread_cond_wait( &(CV), &(M) ) # define ltrcondvar_wakeall( CV ) pthread_cond_broadcast( &(CV) ) static int ltrnumcpus() { return sysconf( _SC_NPROCESSORS_ONLN ); } #endif #ifndef FORCEINLINE #ifdef _MSC_VER #define FORCEINLINE __forceinline #else #define FORCEINLINE inline __attribute__((__always_inline__)) #endif #endif struct LTRMutex { LTRMutex(){ ltrmutex_init( mutex ); } ~LTRMutex(){ ltrmutex_destroy( mutex ); } void Lock(){ ltrmutex_lock( mutex ); } void Unlock(){ ltrmutex_unlock( mutex ); } void SleepCV( ltrcondvar_t* cv ){ ltrcondvar_sleep( *cv, mutex ); } ltrmutex_t mutex; }; struct LTRMutexLock { LTRMutexLock( LTRMutex& m ) : mutex( m ){ m.Lock(); } ~LTRMutexLock(){ mutex.Unlock(); } LTRMutex& mutex; }; struct LTRWorker { struct IO { void* shared; void* item; size_t i; }; typedef void (*WorkProc) (IO*); LTRWorker() : m_shared( NULL ), m_items( NULL ), m_itemSize( 0 ), m_itemCount( 0 ), m_nextItem( 0 ), m_numDone( 0 ), m_workProc( NULL ), m_exit( false ) { ltrcondvar_init( m_hasWork ); ltrcondvar_init( m_hasDone ); } ~LTRWorker() { m_exit = true; ltrcondvar_wakeall( m_hasWork ); for( size_t i = 0; i < m_threads.size(); ++i ) { ltrthread_join( m_threads[ i ] ); } ltrcondvar_destroy( m_hasWork ); ltrcondvar_destroy( m_hasDone ); } void Init( int nt = ltrnumcpus() ) { if( m_threads.size() ) return; m_threads.resize( nt ); for( int i = 0; i < nt; ++i ) { ltrthread_create( m_threads[ i ], threadproc, this ); } } void WaitForEnd() { m_mutex.Lock(); while( m_numDone < m_itemCount ) { m_mutex.SleepCV( &m_hasDone ); } m_shared = NULL; m_items = NULL; m_itemSize = 0; m_itemCount = 0; m_nextItem = 0; m_numDone = 0; m_workProc = NULL; m_mutex.Unlock(); } void DoWork( void* shared, void* items, size_t size, size_t count, WorkProc wp, bool stay = true ) { m_mutex.Lock(); m_shared = shared; m_items = (char*) items; m_itemSize = size; m_itemCount = count; m_nextItem = 0; m_numDone = 0; m_workProc = wp; ltrcondvar_wakeall( m_hasWork ); m_mutex.Unlock(); if( stay ) WaitForEnd(); } void IntProcess() { m_mutex.Lock(); while( !m_exit ) { if( m_nextItem < m_itemCount ) { size_t myitem = m_nextItem++; m_mutex.Unlock(); IO io = { m_shared, m_items + myitem * m_itemSize, myitem }; m_workProc( &io ); m_mutex.Lock(); m_numDone++; if( m_numDone < m_itemCount ) continue; // there may be more work } ltrcondvar_wakeall( m_hasDone ); m_mutex.SleepCV( &m_hasWork ); } m_mutex.Unlock(); } static threadret_t threadproc( threadarg_t arg ) { LTRWorker* w = (LTRWorker*) arg; w->IntProcess(); return 0; } void* m_shared; char* m_items; size_t m_itemSize; size_t m_itemCount; size_t m_nextItem; size_t m_numDone; WorkProc m_workProc; std::vector< ltrthread_t > m_threads; LTRMutex m_mutex; volatile bool m_exit; ltrcondvar_t m_hasWork; ltrcondvar_t m_hasDone; }; #define SMALL_FLOAT 0.001f // #define LTR_DEBUG 1 #ifdef LTR_DEBUG #define DBG( x ) x #else #define DBG( x ) #endif FORCEINLINE float randf(){ return (float) rand() / (float) RAND_MAX; } FORCEINLINE float safe_fdiv( float x, float d ){ return d ? x / d : 0; } double ltr_gettime(); template< class T > FORCEINLINE T TMIN( const T& a, const T& b ){ return a < b ? a : b; } template< class T > FORCEINLINE T TMAX( const T& a, const T& b ){ return a > b ? a : b; } template< class T > FORCEINLINE void TMEMSET( T* a, size_t c, const T& v ) { for( size_t i = 0; i < c; ++i ) a[ i ] = v; } template< class T > FORCEINLINE void TMEMCOPY( T* a, const T* src, size_t c ){ memcpy( a, src, c * sizeof(T) ); } template< class T, class S > FORCEINLINE T TLERP( const T& a, const T& b, const S& s ){ return a * ( S(1) - s ) + b * s; } template< class T > FORCEINLINE typename T::value_type* VDATA( T& vec, size_t at = 0 ){ return ( vec.size() ? &vec[0] : (typename T::value_type*) NULL ) + at; } struct Vec2 { float x, y; static Vec2 Create( float x ){ Vec2 v = { x, x }; return v; } static Vec2 Create( float x, float y ){ Vec2 v = { x, y }; return v; } FORCEINLINE Vec2 operator + () const { return *this; } FORCEINLINE Vec2 operator - () const { Vec2 v = { -x, -y }; return v; } FORCEINLINE Vec2 operator + ( const Vec2& o ) const { Vec2 v = { x + o.x, y + o.y }; return v; } FORCEINLINE Vec2 operator - ( const Vec2& o ) const { Vec2 v = { x - o.x, y - o.y }; return v; } FORCEINLINE Vec2 operator * ( const Vec2& o ) const { Vec2 v = { x * o.x, y * o.y }; return v; } FORCEINLINE Vec2 operator / ( const Vec2& o ) const { Vec2 v = { x / o.x, y / o.y }; return v; } FORCEINLINE Vec2 operator + ( float f ) const { Vec2 v = { x + f, y + f }; return v; } FORCEINLINE Vec2 operator - ( float f ) const { Vec2 v = { x - f, y - f }; return v; } FORCEINLINE Vec2 operator * ( float f ) const { Vec2 v = { x * f, y * f }; return v; } FORCEINLINE Vec2 operator / ( float f ) const { Vec2 v = { x / f, y / f }; return v; } FORCEINLINE Vec2& operator += ( const Vec2& o ){ x += o.x; y += o.y; return *this; } FORCEINLINE Vec2& operator -= ( const Vec2& o ){ x -= o.x; y -= o.y; return *this; } FORCEINLINE Vec2& operator *= ( const Vec2& o ){ x *= o.x; y *= o.y; return *this; } FORCEINLINE Vec2& operator /= ( const Vec2& o ){ x /= o.x; y /= o.y; return *this; } FORCEINLINE Vec2& operator += ( float f ){ x += f; y += f; return *this; } FORCEINLINE Vec2& operator -= ( float f ){ x -= f; y -= f; return *this; } FORCEINLINE Vec2& operator *= ( float f ){ x *= f; y *= f; return *this; } FORCEINLINE Vec2& operator /= ( float f ){ x /= f; y /= f; return *this; } FORCEINLINE bool operator == ( const Vec2& o ) const { return x == o.x && y == o.y; } FORCEINLINE bool operator != ( const Vec2& o ) const { return x != o.x || y != o.y; } FORCEINLINE Vec2 Perp() const { Vec2 v = { y, -x }; return v; } FORCEINLINE float LengthSq() const { return x * x + y * y; } FORCEINLINE float Length() const { return sqrtf( LengthSq() ); } FORCEINLINE Vec2 Normalized() const { float lensq = LengthSq(); if( lensq == 0 ) { Vec2 v = { 0, 0 }; return v; } float invlen = 1.0f / sqrtf( lensq ); Vec2 v = { x * invlen, y * invlen }; return v; } void Dump( FILE* f ) const { fprintf( f, "Vec2 ( %.2f %.2f )\n", x, y ); } }; static FORCEINLINE Vec2 V2( float x, float y ){ Vec2 o = { x, y }; return o; } FORCEINLINE float Vec2Dot( const Vec2& v1, const Vec2& v2 ){ return v1.x * v2.x + v1.y * v2.y; } FORCEINLINE float Vec2Cross( const Vec2& v1, const Vec2& v2 ) { return ( v1.x * v2.y ) - ( v1.y * v2.x ); } struct Vec3 { float x, y, z; static FORCEINLINE Vec3 Create( float x ){ Vec3 v = { x, x, x }; return v; } static FORCEINLINE Vec3 Create( float x, float y, float z ){ Vec3 v = { x, y, z }; return v; } static FORCEINLINE Vec3 CreateFromPtr( const float* x ){ Vec3 v = { x[0], x[1], x[2] }; return v; } static FORCEINLINE Vec3 CreateRandomVector( float maxdist ) { float a = randf() * (float)M_PI * 2; float b = randf() * (float)M_PI; float d = randf() * maxdist; float ac = cos( a ), as = sin( a ); float bc = cos( b ), bs = sin( b ); Vec3 v = { ac * bs * d, as * bs * d, bc * d }; return v; } static FORCEINLINE Vec3 CreateRandomVectorDirDvg( const Vec3& dir, float dvg ); static FORCEINLINE Vec3 CreateSpiralDirVector( const Vec3& dir, float randoff, int i, int sample_count ); static FORCEINLINE Vec3 Min( const Vec3& a, const Vec3& b ){ return Create( TMIN( a.x, b.x ), TMIN( a.y, b.y ), TMIN( a.z, b.z ) ); } static FORCEINLINE Vec3 Max( const Vec3& a, const Vec3& b ){ return Create( TMAX( a.x, b.x ), TMAX( a.y, b.y ), TMAX( a.z, b.z ) ); } FORCEINLINE Vec3 operator + () const { return *this; } FORCEINLINE Vec3 operator - () const { Vec3 v = { -x, -y, -z }; return v; } FORCEINLINE Vec3 operator + ( const Vec3& o ) const { Vec3 v = { x + o.x, y + o.y, z + o.z }; return v; } FORCEINLINE Vec3 operator - ( const Vec3& o ) const { Vec3 v = { x - o.x, y - o.y, z - o.z }; return v; } FORCEINLINE Vec3 operator * ( const Vec3& o ) const { Vec3 v = { x * o.x, y * o.y, z * o.z }; return v; } FORCEINLINE Vec3 operator / ( const Vec3& o ) const { Vec3 v = { x / o.x, y / o.y, z / o.z }; return v; } FORCEINLINE Vec3 operator + ( float f ) const { Vec3 v = { x + f, y + f, z + f }; return v; } FORCEINLINE Vec3 operator - ( float f ) const { Vec3 v = { x - f, y - f, z - f }; return v; } FORCEINLINE Vec3 operator * ( float f ) const { Vec3 v = { x * f, y * f, z * f }; return v; } FORCEINLINE Vec3 operator / ( float f ) const { Vec3 v = { x / f, y / f, z / f }; return v; } FORCEINLINE Vec3& operator += ( const Vec3& o ){ x += o.x; y += o.y; z += o.z; return *this; } FORCEINLINE Vec3& operator -= ( const Vec3& o ){ x -= o.x; y -= o.y; z -= o.z; return *this; } FORCEINLINE Vec3& operator *= ( const Vec3& o ){ x *= o.x; y *= o.y; z *= o.z; return *this; } FORCEINLINE Vec3& operator /= ( const Vec3& o ){ x /= o.x; y /= o.y; z /= o.z; return *this; } FORCEINLINE Vec3& operator += ( float f ){ x += f; y += f; z += f; return *this; } FORCEINLINE Vec3& operator -= ( float f ){ x -= f; y -= f; z -= f; return *this; } FORCEINLINE Vec3& operator *= ( float f ){ x *= f; y *= f; z *= f; return *this; } FORCEINLINE Vec3& operator /= ( float f ){ x /= f; y /= f; z /= f; return *this; } FORCEINLINE bool operator == ( const Vec3& o ) const { return x == o.x && y == o.y && z == o.z; } FORCEINLINE bool operator != ( const Vec3& o ) const { return x != o.x || y != o.y || z != o.z; } FORCEINLINE bool IsZero() const { return x == 0 && y == 0 && z == 0; } FORCEINLINE bool NearZero() const { return fabs(x) < SMALL_FLOAT && fabs(y) < SMALL_FLOAT && fabs(z) < SMALL_FLOAT; } FORCEINLINE float LengthSq() const { return x * x + y * y + z * z; } FORCEINLINE float Length() const { return sqrtf( LengthSq() ); } FORCEINLINE Vec3 Normalized() const { float lensq = LengthSq(); if( lensq == 0 ) { Vec3 v = { 0, 0, 0 }; return v; } float invlen = 1.0f / sqrtf( lensq ); Vec3 v = { x * invlen, y * invlen, z * invlen }; return v; } void Dump( FILE* f ) const { fprintf( f, "Vec3 ( %.2f %.2f %.2f )\n", x, y, z ); } }; FORCEINLINE Vec3 operator + ( float f, const Vec3& v ){ Vec3 out = { f + v.x, f + v.y, f + v.z }; return out; } FORCEINLINE Vec3 operator - ( float f, const Vec3& v ){ Vec3 out = { f - v.x, f - v.y, f - v.z }; return out; } FORCEINLINE Vec3 operator * ( float f, const Vec3& v ){ Vec3 out = { f * v.x, f * v.y, f * v.z }; return out; } FORCEINLINE Vec3 operator / ( float f, const Vec3& v ){ Vec3 out = { f / v.x, f / v.y, f / v.z }; return out; } static FORCEINLINE Vec3 V3( float x ){ Vec3 o = { x, x, x }; return o; } static FORCEINLINE Vec3 V3( float x, float y, float z ){ Vec3 o = { x, y, z }; return o; } static FORCEINLINE Vec3 V3P( const float* x ){ Vec3 o = { x[0], x[1], x[2] }; return o; } FORCEINLINE float Vec3Dot( const Vec3& v1, const Vec3& v2 ){ return v1.x * v2.x + v1.y * v2.y + v1.z * v2.z; } FORCEINLINE Vec3 Vec3Cross( const Vec3& v1, const Vec3& v2 ) { Vec3 out = { v1.y * v2.z - v1.z * v2.y, v1.z * v2.x - v1.x * v2.z, v1.x * v2.y - v1.y * v2.x, }; return out; } Vec3 Vec3::CreateRandomVectorDirDvg( const Vec3& dir, float dvg ) { float a = randf() * (float)M_PI * 2; float b = randf() * (float)M_PI * dvg; float ac = cos( a ), as = sin( a ); float bc = cos( b ), bs = sin( b ); Vec3 diffvec = { dir.y, -dir.z, dir.x }; Vec3 up = Vec3Cross( dir, diffvec ).Normalized(); Vec3 rt = Vec3Cross( dir, up ); return ac * bs * rt + as * bs * up + bc * dir; } #define DEG2RAD( x ) ((x)/180.0f*(float)M_PI) Vec3 Vec3::CreateSpiralDirVector( const Vec3& dir, float randoff, int i, int sample_count ) { float q = ( i + 0.5f ) / sample_count; float cos_side = sqrt( q ); float sin_side = sin( acos( cos_side ) ); float angle = ( i + randoff ) * DEG2RAD( 137.508f ); float cos_around = cos( angle ); float sin_around = sin( angle ); Vec3 diffvec = { dir.y, -dir.z, dir.x }; Vec3 up = Vec3Cross( dir, diffvec ).Normalized(); Vec3 rt = Vec3Cross( dir, up ); return cos_around * sin_side * rt + sin_around * sin_side * up + cos_side * dir; } struct Vec4 { float x, y, z, w; FORCEINLINE Vec4 operator + ( const Vec4& o ) const { Vec4 v = { x + o.x, y + o.y, z + o.z, w + o.w }; return v; } FORCEINLINE Vec4 operator - ( const Vec4& o ) const { Vec4 v = { x - o.x, y - o.y, z - o.z, w - o.w }; return v; } FORCEINLINE Vec4 operator * ( float f ) const { Vec4 v = { x * f, y * f, z * f, w * f }; return v; } Vec3 ToVec3() const { return Vec3::Create( x, y, z ); } }; static FORCEINLINE Vec4 V4( float x ){ Vec4 o = { x, x, x, x }; return o; } static FORCEINLINE Vec4 V4( float x, float y, float z, float w ){ Vec4 o = { x, y, z, w }; return o; } static FORCEINLINE Vec4 V4( const Vec3& v, float w ){ Vec4 o = { v.x, v.y, v.z, w }; return o; } struct Mat4 { union { float a[16]; float m[4][4]; }; void SetIdentity() { for( int i = 0; i < 4; ++i ) for( int j = 0; j < 4; ++j ) m[i][j] = i == j; } static Mat4 CreateIdentity() { Mat4 m; m.SetIdentity(); return m; } FORCEINLINE Vec3 Transform( const Vec3& v, float w ) const { Vec3 out = { v.x * m[0][0] + v.y * m[1][0] + v.z * m[2][0] + m[3][0] * w, v.x * m[0][1] + v.y * m[1][1] + v.z * m[2][1] + m[3][1] * w, v.x * m[0][2] + v.y * m[1][2] + v.z * m[2][2] + m[3][2] * w, }; return out; } FORCEINLINE Vec3 TransformPos( const Vec3& pos ) const { return Transform( pos, 1.0f ); } FORCEINLINE Vec3 TransformNormal( const Vec3& nrm ) const { return Transform( nrm, 0.0f ); } bool InvertTo( Mat4& out ); FORCEINLINE void Transpose() { std::swap( m[1][0], m[0][1] ); std::swap( m[2][0], m[0][2] ); std::swap( m[3][0], m[0][3] ); std::swap( m[2][1], m[1][2] ); std::swap( m[3][1], m[1][3] ); std::swap( m[3][2], m[2][3] ); } void GenNormalMatrix( Mat4& out ) const { out.m[0][0] = m[0][0]; out.m[0][1] = m[0][1]; out.m[0][2] = m[0][2]; out.m[1][0] = m[1][0]; out.m[1][1] = m[1][1]; out.m[1][2] = m[1][2]; out.m[2][0] = m[2][0]; out.m[2][1] = m[2][1]; out.m[2][2] = m[2][2]; out.m[0][3] = out.m[1][3] = out.m[2][3] = 0; out.m[3][0] = out.m[3][1] = out.m[3][2] = 0; out.m[3][3] = 1; out.InvertTo( out ); out.Transpose(); } void Dump( FILE* f ) const { fprintf( f, "Mat4 (\n" ); fprintf( f, " %.2f %.2f %.2f %.2f\n", m[0][0], m[0][1], m[0][2], m[0][3] ); fprintf( f, " %.2f %.2f %.2f %.2f\n", m[1][0], m[1][1], m[1][2], m[1][3] ); fprintf( f, " %.2f %.2f %.2f %.2f\n", m[2][0], m[2][1], m[2][2], m[2][3] ); fprintf( f, " %.2f %.2f %.2f %.2f\n", m[3][0], m[3][1], m[3][2], m[3][3] ); fprintf( f, ")\n" ); } }; typedef std::vector< u32 > U32Vector; typedef std::vector< float > FloatVector; typedef std::vector< Vec2 > Vec2Vector; typedef std::vector< Vec3 > Vec3Vector; typedef std::vector< Vec4 > Vec4Vector; typedef std::vector< Mat4 > Mat4Vector; typedef std::vector< ltr_WorkOutput > WorkOutputVector; float TriangleArea( const Vec3& P1, const Vec3& P2, const Vec3& P3 ); float CalculateSampleArea( const Vec2& tex1, const Vec2& tex2, const Vec2& tex3, const Vec3& pos1, const Vec3& pos2, const Vec3& pos3 ); void TransformPositions( Vec3* out, Vec3* arr, size_t count, const Mat4& matrix ); void TransformNormals( Vec3* out, Vec3* arr, size_t count, const Mat4& matrix ); void RasterizeTriangle2D( Vec3* image, i32 width, i32 height, const Vec2& p1, const Vec2& p2, const Vec2& p3, const Vec3& v1, const Vec3& v2, const Vec3& v3 ); void RasterizeTriangle2D_x2_ex( Vec3* img1, Vec3* img2, Vec4* img3, i32 width, i32 height, float margin, const Vec2& p1, const Vec2& p2, const Vec2& p3, const Vec3& va1, const Vec3& va2, const Vec3& va3, const Vec3& vb1, const Vec3& vb2, const Vec3& vb3, const Vec4& vc1, const Vec4& vc2, const Vec4& vc3 ); void Generate_Gaussian_Kernel( float* out, int ext, float radius ); void Convolve_Transpose( float* src, float* dst, u32 width, u32 height, int blur_ext, float* kernel, float* tmp ); void Downsample2X( float* dst, unsigned dstW, unsigned dstH, float* src, unsigned srcW, unsigned srcH ); // BSP tree // - best split plane is chosen by triangle normals and general direction of vertex positions (longest projection) // - triangles are split to fit in the node struct AABB3 { Vec3 bbmin; Vec3 bbmax; FORCEINLINE bool Valid() const { return bbmin.x <= bbmax.x && bbmin.y <= bbmax.y && bbmin.z <= bbmax.z; } FORCEINLINE Vec3 Center() const { return ( bbmin + bbmax ) * 0.5f; } FORCEINLINE float Volume() const { return ( bbmax.x - bbmin.x ) * ( bbmax.y - bbmin.y ) * ( bbmax.z - bbmin.z ); } }; struct Triangle { Vec3 P1, P2, P3; bool CheckIsUseful() const { Vec3 e1 = P2 - P1, e2 = P3 - P1; return !Vec3Cross( e1, e2 ).NearZero(); } void GetAABB( AABB3& out ) const { out.bbmin = V3( TMIN( P1.x, TMIN( P2.x, P3.x ) ), TMIN( P1.y, TMIN( P2.y, P3.y ) ), TMIN( P1.z, TMIN( P2.z, P3.z ) ) ); out.bbmax = V3( TMAX( P1.x, TMAX( P2.x, P3.x ) ), TMAX( P1.y, TMAX( P2.y, P3.y ) ), TMAX( P1.z, TMAX( P2.z, P3.z ) ) ); } Vec3 GetNormal() const { return Vec3Cross( P3 - P1, P2 - P1 ).Normalized(); } }; typedef std::vector< Triangle > TriVector; struct BSPNode { BSPNode() : front_node( NULL ), back_node( NULL ){} ~BSPNode() { if( front_node ) delete front_node; if( back_node ) delete back_node; } void Split( int depth ); void AddTriangleSplit( Triangle* tri ); float IntersectRay( const Vec3& from, const Vec3& to, Vec3* outnormal ); bool PickSplitPlane(); void Dump( FILE* f, int lev = 0, const char* pfx = "" ) { for( int i = 0; i < lev; ++i ) fputc( ' ', f ); fprintf( f, "%sNODE [%g;%g;%g](%g), tris=%d\n", pfx, N.x, N.y, N.z, D, (int) triangles.size() ); fprintf( f, "{\n" ); for( size_t i = 0; i < triangles.size(); ++i ) { fprintf( f, " " ); triangles[i].P1.Dump( stdout ); fprintf( f, " " ); triangles[i].P2.Dump( stdout ); fprintf( f, " " ); triangles[i].P3.Dump( stdout ); } if( front_node ) front_node->Dump( f, lev + 1, "F " ); if( back_node ) back_node->Dump( f, lev + 1, "B " ); } Vec3 N; float D; BSPNode *front_node, *back_node; TriVector triangles; }; struct BSPTree { BSPTree() : root( new BSPNode() ){} ~BSPTree(){ delete root; } FORCEINLINE void SetTriangles( Triangle* tris, size_t count ) { root->triangles.resize( count ); TMEMCOPY( &root->triangles[0], tris, count ); root->Split( 0 ); } FORCEINLINE float IntersectRay( const Vec3& from, const Vec3& to, Vec3* outnormal = NULL ){ return root->IntersectRay( from, to, outnormal ); } BSPNode* root; }; struct BaseRayQuery { Vec3 ray_origin; float ray_len; Vec3 _ray_inv_dir; void SetRayDir( Vec3 dir ) { dir = dir.Normalized(); _ray_inv_dir = V3 ( safe_fdiv( 1, dir.x ), safe_fdiv( 1, dir.y ), safe_fdiv( 1, dir.z ) ); } void SetRay( const Vec3& r0, const Vec3& r1 ) { ray_origin = r0; ray_len = ( r1 - r0 ).Length(); SetRayDir( r1 - r0 ); } }; bool RayAABBTest( const Vec3& ro, const Vec3& inv_n, float len, const Vec3& bbmin, const Vec3& bbmax ); struct AABBTree { struct Node // size = 8(3+3+2) * 4(float/int32) { Vec3 bbmin; Vec3 bbmax; int32_t ch; // ch0 = node + 1, ch1 = ch int32_t ido; // item data offset }; // AABBs must be stored manually if necessary void SetAABBs( AABB3* aabbs, size_t count ); void _printdepth( int depth ) { for( int i = 0; i < depth; ++i ) printf( " " ); } void Dump( int32_t node = 0, int depth = 0 ) { AABBTree::Node& N = m_nodes[ node ]; _printdepth(depth); printf( "node #%d (%d items, %.2f;%.2f;%.2f -> %.2f;%.2f;%.2f)", int(node), N.ido != -1 ? int(m_itemidx[ N.ido ]) : 0, N.bbmin.x, N.bbmin.y, N.bbmin.z, N.bbmax.x, N.bbmax.y, N.bbmax.z ); if( N.ch != -1 ) { printf( " {\n" ); depth++; Dump( node + 1, depth ); Dump( N.ch, depth ); depth--; _printdepth(depth); printf( "}\n" ); } else printf( "\n" ); } template< class T > bool RayQuery( T& rq, int32_t node = 0 ) { AABBTree::Node& N = m_nodes[ node ]; if( RayAABBTest( rq.ray_origin, rq._ray_inv_dir, rq.ray_len, N.bbmin, N.bbmax ) == false ) return true; if( N.ido != -1 ) { if( rq( &m_itemidx[ N.ido + 1 ], m_itemidx[ N.ido ] ) == false ) return false; } // child nodes if( N.ch != -1 ) { if( RayQuery( rq, node + 1 ) == false ) return false; if( RayQuery( rq, N.ch ) == false ) return false; } return true; } template< class T > void DynBBQuery( T& bbq, int32_t node = 0 ) { AABBTree::Node& N = m_nodes[ node ]; if( bbq.bbmin.x > N.bbmax.x || bbq.bbmax.x < N.bbmin.x || bbq.bbmin.y > N.bbmax.y || bbq.bbmax.y < N.bbmin.y || bbq.bbmin.z > N.bbmax.z || bbq.bbmax.z < N.bbmin.z ) return; // items if( N.ido != -1 ) { bbq( &m_itemidx[ N.ido + 1 ], m_itemidx[ N.ido ] ); } // child nodes if( N.ch != -1 ) { DynBBQuery( bbq, node + 1 ); DynBBQuery( bbq, N.ch ); } } template< class T > void Query( const Vec3& qmin, const Vec3& qmax, T& out, int32_t node = 0 ) { AABBTree::Node& N = m_nodes[ node ]; if( qmin.x > N.bbmax.x || qmax.x < N.bbmin.x || qmin.y > N.bbmax.y || qmax.y < N.bbmin.y || qmin.z > N.bbmax.z || qmax.z < N.bbmin.z ) return; // items if( N.ido != -1 ) { out( &m_itemidx[ N.ido + 1 ], m_itemidx[ N.ido ] ); } // child nodes if( N.ch != -1 ) { Query( qmin, qmax, out, node + 1 ); Query( qmin, qmax, out, N.ch ); } } template< class T > void GetAll( T& out ) { for( size_t i = 0; i < m_itemidx.size(); i += 1 + m_itemidx[ i ] ) { out( &m_itemidx[ i + 1 ], m_itemidx[ i ] ); } } void _MakeNode( int32_t node, AABB3* aabbs, int32_t* sampidx_data, size_t sampidx_count, int depth ); // BVH std::vector< Node > m_nodes; std::vector< int32_t > m_itemidx; // format: <count> [ <item> x count ], ... }; struct TriTree { void SetTris( Triangle* tris, size_t count ); bool IntersectRay( const Vec3& from, const Vec3& to ); float IntersectRayDist( const Vec3& from, const Vec3& to, int32_t* outtid ); float GetDistance( const Vec3& p, float dist ); void OffsetSample( Vec3& P, const Vec3& N, float dist ); AABBTree m_bbTree; std::vector< Triangle > m_tris; }; struct ltr_MeshPart { u32 m_vertexCount; u32 m_vertexOffset; u32 m_indexCount; u32 m_indexOffset; int m_shadow; }; typedef std::vector< ltr_MeshPart > MeshPartVector; struct ltr_Mesh { ltr_Mesh( ltr_Scene* s ) : m_scene( s ){} ltr_Scene* m_scene; std::string m_ident; Vec3Vector m_vpos; Vec3Vector m_vnrm; Vec2Vector m_vtex1; Vec2Vector m_vtex2; U32Vector m_indices; MeshPartVector m_parts; }; typedef std::vector< ltr_Mesh* > MeshPtrVector; struct ltr_LightContribSample { Vec3 normal; int32_t sid; }; typedef std::vector< ltr_LightContribSample > LightContribVector; struct ltr_TmpContribSum { Vec3 normal; float mindot; int32_t count; }; struct ltr_MeshInstance { // input ltr_Mesh* mesh; std::string m_ident; float m_importance; Mat4 matrix; u32 lm_width; u32 lm_height; bool m_shadow; bool m_samplecont; // tmp Vec3Vector m_vpos; Vec3Vector m_vnrm; Vec2Vector m_vtex; Vec2Vector m_ltex; // output BSPTree m_bspTree; TriTree m_triTree; Vec3Vector m_samples_pos; Vec3Vector m_samples_nrm; U32Vector m_samples_loc; Vec4Vector m_samples_radinfo; Vec3Vector m_lightmap; LightContribVector m_contrib; }; typedef std::vector< ltr_MeshInstance* > MeshInstPtrVector; struct ltr_Light { void QueryMeshInsts( AABBTree& tree, std::vector< int32_t >& out ); u32 type; Vec3 position; Vec3 direction; Vec3 up_direction; Vec3 color_rgb; float range; float power; float light_radius; int shadow_sample_count; float spot_angle_out; float spot_angle_in; float spot_curve; // positions for point/spot, directions for directional lights std::vector< Vec3 > samples; }; typedef std::vector< ltr_Light > LightVector; FORCEINLINE float CalcBrightness( Vec3 color ){ return ( color.x + color.y + color.z ) * (1.0f/3.0f); } typedef std::vector< ltr_SampleInfo > SampleVector; struct ltr_RadSampleGeom { Vec3 pos; Vec3 normal; }; typedef std::vector< ltr_RadSampleGeom > RadSampleGeomVector; struct ltr_RadSampleColors { Vec3 diffuseColor; Vec3 totalLight; Vec3 outputEnergy; Vec3 inputEnergy; float area; }; typedef std::vector< ltr_RadSampleColors > RadSampleColorsVector; struct ltr_RadLink { uint32_t other; float factor; }; typedef std::vector< ltr_RadLink > RadLinkVector; struct dw_lmrender_data { std::vector<ltr_LightContribSample>* contribs; ltr_MeshInstance* mi; ltr_Light* light; float angle_out_rad; float angle_in_rad; float angle_diff; }; #define MAX_PENUMBRA_SIZE 2.0f // #define MAX_PENUMBRA_STEP 0.1f #define MAX_PENUMBRA_STEP 1.0f #define SAMPLE_SHADOW_OFFSET 0.005f struct ltr_Scene { ltr_Scene() : m_workStage( "not started" ), m_workCompletion(0), m_num_cpus( ltrnumcpus() ) { ltr_GetConfig( &config, NULL ); m_sampleMI.m_samplecont = true; m_sampleMI.mesh = NULL; m_sampleMI.m_importance = 0; m_sampleMI.lm_width = 0; m_sampleMI.lm_height = 0; m_meshInstances.push_back( &m_sampleMI ); } ~ltr_Scene() { for( size_t i = 1; i < m_meshInstances.size(); ++i ) delete m_meshInstances[i]; for( size_t i = 0; i < m_meshes.size(); ++i ) delete m_meshes[i]; for( size_t i = 0; i < m_workOutput.size(); ++i ) { delete [] m_workOutput[i].lightmap_rgb; if( m_workOutput[i].normals_xyzf ) delete [] m_workOutput[i].normals_xyzf; } } void Job_PreXForm_Inner( ltr_MeshInstance* mi ); static void Job_PreXForm( LTRWorker::IO* io ); void Job_ColInfo_Inner( ltr_MeshInstance* mi ); static void Job_ColInfo( LTRWorker::IO* io ); void Job_Samples_Inner( ltr_Scene* S, ltr_MeshInstance* mi ); static void Job_Samples( LTRWorker::IO* io ); void Job_LMRender_Point_Inner( size_t i, dw_lmrender_data* data ); void Job_LMRender_Spot_Inner( size_t i, dw_lmrender_data* data ); void Job_LMRender_Direct_Inner( size_t i, dw_lmrender_data* data ); static void Job_LMRender_Point( LTRWorker::IO* io ); static void Job_LMRender_Spot( LTRWorker::IO* io ); static void Job_LMRender_Direct( LTRWorker::IO* io ); void Int_LMRender( ltr_Light& light, ltr_MeshInstance* mi ); void Int_RDGenLinks(); void Int_RDBounce(); void Job_AORender_Inner( ltr_MeshInstance* mi, size_t i ); static void Job_AORender( LTRWorker::IO* io ); void Int_Finalize(); static void Job_MainProc( LTRWorker::IO* io ); bool VisibilityTest( const Vec3& A, const Vec3& B ); float Distance( const Vec3& p ); float CalcInvShadowFactor( const Vec3& from, const Vec3& to, float k ); // k = penumbra factor float DistanceTest( const Vec3& A, const Vec3& B, Vec3* outnormal = NULL ); float DistanceTestBBT( const Vec3& A, const Vec3& B ); ltr_Config config; MeshPtrVector m_meshes; MeshInstPtrVector m_meshInstances; LightVector m_lights; ltr_MeshInstance m_sampleMI; SampleVector m_samples; RadSampleGeomVector m_radSampleGeoms; RadSampleColorsVector m_radSampleColors; RadLinkVector m_radLinks; U32Vector m_radLinkMap; AABBTree m_instTree; WorkOutputVector m_workOutput; const char* m_workStage; float m_workCompletion; int m_num_cpus; LTRWorker m_worker; LTRWorker m_rootWorker; };
28.42315
160
0.629047
snake5
e9fc439729c3b1ac4817d0477d1e5c14bafa54f7
761
cpp
C++
hackerrank/problemSolving/caesarCipher.cpp
ravikiranmara/ProgrammingChallenges
dcd0e0b3997f05115fc1fab414818b7d9add54c4
[ "MIT" ]
null
null
null
hackerrank/problemSolving/caesarCipher.cpp
ravikiranmara/ProgrammingChallenges
dcd0e0b3997f05115fc1fab414818b7d9add54c4
[ "MIT" ]
null
null
null
hackerrank/problemSolving/caesarCipher.cpp
ravikiranmara/ProgrammingChallenges
dcd0e0b3997f05115fc1fab414818b7d9add54c4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // Complete the caesarCipher function below. string caesarCipher(string s, int k) { for (int i=0; i<s.size(); i++) { if (islower(s[i])) s[i] = 'a' + (k+s[i]-'a')%26; else if (isupper(s[i])) s[i] = 'A' + (k+s[i]-'A')%26; } return s; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int n; cin >> n; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string s; getline(cin, s); int k; cin >> k; cin.ignore(numeric_limits<streamsize>::max(), '\n'); string result = caesarCipher(s, k); fout << result << "\n"; fout.close(); return 0; } // https://www.hackerrank.com/challenges/caesar-cipher-1
17.697674
56
0.532194
ravikiranmara
e9fdb5b02e274f8866dd1289c472aa2e46358793
19,976
cpp
C++
src/input/InputManager.cpp
MicahMartin/asdf
d430777603a6906b7117e422885c949b539865cf
[ "MIT" ]
null
null
null
src/input/InputManager.cpp
MicahMartin/asdf
d430777603a6906b7117e422885c949b539865cf
[ "MIT" ]
null
null
null
src/input/InputManager.cpp
MicahMartin/asdf
d430777603a6906b7117e422885c949b539865cf
[ "MIT" ]
null
null
null
#include "input/InputManager.h" #include "input/VirtualController.h" #include <iostream> #include <fstream> #include <sstream> // input manager is gonna get all input events from SDL for all devices // keep a map with input keycodes as the key and tuple of player number actual 'button code' as the value // so lets say the map has {key: SDL_CODE, val: {playerNum:1, buttonVal: 0x1}} with the bits on the buttonVal byte corresponding to InputManager::Input void InputManager::init() { if( SDL_NumJoysticks() < 1 ) { printf( "Warning: No joysticks connected!\n" ); } else { //Load joystick p1SDLController = SDL_JoystickOpen( 0 ); p2SDLController = SDL_JoystickOpen( 1 ); if( p1SDLController == NULL ) { printf( "Warning: Unable to open game controller 1! SDL Error: %s\n", SDL_GetError() ); } else { printf("SDL Controller 1 initialized\n"); } if( p2SDLController == NULL ) { printf( "Warning: Unable to open game controller 2! SDL Error: %s\n", SDL_GetError() ); } else { printf("SDL Controller 2 initialized\n"); } } initConfig("../data/buttonconf.json", &bConf, &configJson); initConfig("../data/p1buttonconf.json", &p1bConf, &p1configJson); initConfig("../data/p2buttonconf.json", &p2bConf, &p2configJson); } void InputManager::initConfig(const char* fileName, ConfT* config, nlohmann::json* confJson) { // load the config(s) std::ifstream configFile(fileName); nlohmann::json newJson; configFile >> newJson; config->reserve(32); config->clear(); for(auto& item : newJson.items()){ // TODO: Check for too much configItems // the 'value' is gonna be the button value for corresponding device // std::cout << item.attribute("value").as_int() << std::endl; // the node text is gonna be the bit for said button // std::cout << std::bitset<16>(item.text().as_int()) << std::endl; ConfItem myItem; myItem.user = item.value()["user"].get<uint8_t>(); myItem.inputBit = (Input)std::stoi(item.value()["input"].get<std::string>(), 0 ,16); (*config)[std::stoi(item.key())] = myItem; } configFile.close(); *confJson = newJson; } void InputManager::update() { SDL_Event event; for (VirtualController* controller : controllers) { if (controller->playbackMode) { if (controllers[0]->copyModeSlot == 1) { InputFrameT currentFrame = controllers[0]->inputHistoryCopy[controller->playbackCounter]; controller->inputHistory.push_front(currentFrame); controller->currentState = controllers[0]->inputStateCopy[controller->playbackCounter]; controller->playbackCounter++; } else { InputFrameT currentFrame = controllers[0]->inputHistoryCopyTwo[controller->playbackCounter]; controller->inputHistory.push_front(currentFrame); controller->currentState = controllers[0]->inputStateCopyTwo[controller->playbackCounter]; controller->playbackCounter++; } } else { // controller->prevState = controller->currentState; controller->update(); } } while(SDL_PollEvent(&event) != 0){ if (!keySelectionMode) { // printf("got an event %d\n", event.type); switch (event.type) { case SDL_KEYDOWN: { if(event.key.repeat == 0){ if(bConf.find(event.key.keysym.sym) != bConf.end()){ ConfItem* item = &bConf.at(event.key.keysym.sym); VirtualController* controller = controllers.at(item->user - 1); Input* inputBit = &item->inputBit; if (!controller->playbackMode) { // is cardinal? if (*inputBit <= 8) { // printf("isCardinal!\n"); bool isXAxis = *inputBit <= 2; if (isXAxis) { *inputBit == RIGHT ? controller->xAxis++ : controller->xAxis--; } else { *inputBit == UP ? controller->yAxis++ : controller->yAxis--; } // this calls setBit controller->updateAxis(isXAxis); } else { controller->setBit(*inputBit); } } } else { // item not found } } break; } case SDL_KEYUP: { if (event.key.keysym.sym == SDLK_5) { controllers[0]->copyModeSlot = 1; controllers[0]->copyMode ? controllers[0]->stopCopyMode() : controllers[0]->startCopyMode(); printf("copyMode toggled to %d, copySize:%ld\n", controllers[0]->copyMode, controllers[0]->inputHistoryCopy.size()); }; if (event.key.keysym.sym == SDLK_6) { controllers[0]->copyModeSlot = 2; controllers[0]->copyMode ? controllers[0]->stopCopyMode() : controllers[0]->startCopyMode(); printf("copyMode slot 2 toggled to %d, copySize:%ld\n", controllers[0]->copyMode, controllers[0]->inputHistoryCopyTwo.size()); }; if (event.key.keysym.sym == SDLK_e) { notifyOne("game", "ADVANCE_STATE"); }; if (event.key.keysym.sym == SDLK_t) { notifyOne("game", "RESUME_REQUEST"); }; if (event.key.keysym.sym == SDLK_r) { notifyOne("game", "LOAD_STATE"); } if (event.key.keysym.sym == SDLK_1) { if (controllers[0]->copyMode) { controllers[0]->stopCopyMode(); } printf("setting input history to the copy %ld\n", controllers[0]->inputHistoryCopy.size()); controllers[0]->copyModeSlot = 1; controllers[1]->playbackMode = true; }; // if (event.key.keysym.sym == SDLK_2) { // if (controllers[0]->copyMode) { // controllers[0]->stopCopyMode(); // } // printf("setting input history to the copy %ld\n", controllers[0]->inputHistoryCopy.size()); // controllers[0]->copyModeSlot = 2; // controllers[1]->playbackMode = true; // }; // if (event.key.keysym.sym == SDLK_3) { // if (controllers[0]->copyMode) { // controllers[0]->stopCopyMode(); // } // srand (time(NULL)); // controllers[0]->copyModeSlot = rand() % 2 + 1; // printf("setting input history to randomly 1 or 2 %d\n", controllers[0]->copyModeSlot); // controllers[1]->playbackMode = true; // }; if (bConf.find(event.key.keysym.sym) != bConf.end()) { ConfItem* item = &bConf.at(event.key.keysym.sym); VirtualController* controller = controllers.at(item->user - 1); if (!controller->playbackMode) { Input* inputBit = &item->inputBit; // is cardinal? if (*inputBit <= 8) { // printf("isCardinal! clearing\n"); bool isXAxis = *inputBit <= 2; if (isXAxis) { *inputBit == RIGHT ? controller->xAxis-- : controller->xAxis++; } else { *inputBit == UP ? controller->yAxis-- : controller->yAxis++; } // this calls clearBit controller->updateAxis(isXAxis); } else { controller->clearBit(*inputBit); } } } if (event.key.keysym.sym == SDLK_ESCAPE) { notifyOne("game", "RESTART_REQUEST"); } if (event.key.keysym.sym == SDLK_v) { notifyOne("game", "VOLUME_DOWN_REQUEST"); } if (event.key.keysym.sym == SDLK_b) { notifyOne("game", "VOLUME_UP_REQUEST"); } if (event.key.keysym.sym == SDLK_c) { notifyOne("game", "VIEW_CBOXES_TOGGLE"); } if (event.key.keysym.sym == SDLK_q) { notifyOne("game", "PAUSE_REQUEST"); } if (event.key.keysym.sym == SDLK_w) { notifyOne("game", "SAVE_STATE"); } break; } case SDL_JOYBUTTONDOWN: { SDL_JoyHatEvent* jhatEvent = &event.jhat; printf("joy button down %d\n", &event.jbutton.button); SDL_Joystick* stick = SDL_JoystickFromInstanceID(jhatEvent->which); VirtualController* controller = stickToVC[stick]; if (!controller->playbackMode) { ConfT* conf; if(controller->controllerIndex == 1){ conf = &p1bConf; } else if(controller->controllerIndex == 2){ conf = &p2bConf; } if(conf != NULL && conf->count(event.jbutton.button)){ ConfItem* item = &conf->at(event.jbutton.button); Input* inputBit = &item->inputBit; printf("found item from jbutton %d with val: %d\n", event.jbutton.button, *inputBit); controller->setBit(*inputBit); } else if (conf != NULL && (event.jbutton.button >= 11 && event.jbutton.button <= 14)){ // UDLR int inputBit = event.jbutton.button - 10; printf("isCardinal! the inputBit:%d\n", inputBit); // printf("isCardinal!\n"); bool isXAxis = inputBit >= 3; if (isXAxis) { inputBit == CONTROLLER_RIGHT ? controller->xAxis++ : controller->xAxis--; } else { inputBit == CONTROLLER_UP ? controller->yAxis++ : controller->yAxis--; } // this calls setBit controller->updateAxis(isXAxis); } } break; } case SDL_JOYBUTTONUP: { SDL_JoyHatEvent* jhatEvent = &event.jhat; SDL_Joystick* stick = SDL_JoystickFromInstanceID(jhatEvent->which); VirtualController* controller = stickToVC[stick]; if (!controller->playbackMode) { ConfT* conf; if(controller->controllerIndex == 1){ conf = &p1bConf; } else if(controller->controllerIndex == 2){ conf = &p2bConf; } if(conf != NULL && conf->count(event.jbutton.button)){ ConfItem* item = &conf->at(event.jbutton.button); Input* inputBit = &item->inputBit; // printf("clearing item from jbutton %d with val: %d\n", event.jbutton.button, *inputBit); controller->clearBit(*inputBit); } else if (conf != NULL && (event.jbutton.button >= 11 && event.jbutton.button <= 14)){ // UDLR int inputBit = event.jbutton.button - 10; bool isXAxis = inputBit >= 3; if (isXAxis) { inputBit == CONTROLLER_RIGHT ? controller->xAxis-- : controller->xAxis++; } else { inputBit == CONTROLLER_UP ? controller->yAxis-- : controller->yAxis++; } // this calls setBit controller->updateAxis(isXAxis); } } break; } case SDL_JOYHATMOTION: { printf("hat motion\n"); SDL_JoyHatEvent* jhatEvent = &event.jhat; SDL_Joystick* stick = SDL_JoystickFromInstanceID(jhatEvent->which); VirtualController* controller = stickToVC[stick]; if (controller != NULL && !controller->playbackMode) { switch (jhatEvent->value) { case SDL_HAT_CENTERED: controller->setAxis(NOINPUT); printf("setting axis to noinput\n"); break; case SDL_HAT_RIGHT: controller->setAxis(RIGHT); printf("setting axis to right\n"); break; case SDL_HAT_LEFT: controller->setAxis(LEFT); printf("setting axis to left\n"); break; case SDL_HAT_UP: controller->setAxis(UP); printf("setting axis to up\n"); break; case SDL_HAT_DOWN: controller->setAxis(DOWN); printf("setting axis to down\n"); break; case SDL_HAT_RIGHTDOWN: controller->setAxis(DOWNRIGHT); printf("setting axis to downright\n"); break; case SDL_HAT_RIGHTUP: controller->setAxis(UPRIGHT); printf("setting axis to rightup\n"); break; case SDL_HAT_LEFTDOWN: controller->setAxis(DOWNLEFT); printf("setting axis to leftdown\n"); break; case SDL_HAT_LEFTUP: controller->setAxis(UPLEFT); printf("setting axis to leftup\n"); break; default: break; } } break; } case SDL_JOYAXISMOTION: { if (event.jaxis.value < 8000 || event.jaxis.value > 8000) { switch (event.jaxis.axis) { case 4: if (event.jaxis.value > 10000 && !leftTrigger) { printf("left trigger pressed\n"); leftTrigger = true; } else if (event.jaxis.value < 10000 && leftTrigger) { printf("left trigger released\n"); leftTrigger = false; } break; case 5: if (event.jaxis.value < 8000 && !rightTrigger) { printf("right trigger pressed\n"); rightTrigger = true; } else if (event.jaxis.value > 8000 && rightTrigger) { printf("right trigger released\n"); rightTrigger = false; } break; default: break; } } break; } case SDL_JOYBALLMOTION: { printf("joy ball motion\n"); break; } case SDL_QUIT: notifyOne("game", "QUIT_REQUEST"); break; default: break; } } else { switch (event.type) { case SDL_KEYDOWN: { if(event.key.repeat == 0){ printf("configuring item:%d, the sdl keycode for the thing just released : %d\n", configCounter, event.key.keysym.sym); if (bConf.find(event.key.keysym.sym) != bConf.end()) { configCounter++; ConfItem* item = &bConf.at(event.key.keysym.sym); Input* inputBit = &item->inputBit; if (*inputBit == MK) { keySelectionMode = false; configCounter = 0; } } break; } case SDL_KEYUP: { } break; } case SDL_JOYBUTTONDOWN: { printf("configuring item:%d, the button keycode for the thing just released : %d\n", configCounter, event.jbutton.button); buttonConfigArray[configCounter] = event.jbutton.button; configCounter++; if (configCounter == 4) { configCounter = 0; printf("writing button config\n"); keySelectionMode = false; writeButtonConfig(); } break; } case SDL_JOYBUTTONUP: { break; } case SDL_JOYAXISMOTION: { printf("joy axis motion\n"); break; } case SDL_JOYBALLMOTION: { printf("joy ball motion\n"); break; } case SDL_JOYHATMOTION: { break; } case SDL_QUIT: keySelectionMode = false; break; default: break; } } } if(controllers[0]->copyMode){ // printf("pushing input history to inputHistoryCopy\n"); if (controllers[0]->copyModeSlot == 1) { controllers[0]->inputHistoryCopy.push_back(controllers[0]->inputHistory.front()); controllers[0]->inputStateCopy.push_back(controllers[0]->currentState); } else if(controllers[0]->copyModeSlot == 2){ controllers[0]->inputHistoryCopyTwo.push_back(controllers[0]->inputHistory.front()); controllers[0]->inputStateCopyTwo.push_back(controllers[0]->currentState); } } if (controllers[1]->playbackMode) { int correctSize = controllers[0]->copyModeSlot == 1 ? controllers[0]->inputHistoryCopy.size() : controllers[0]->inputHistoryCopyTwo.size(); if (controllers[1]->playbackCounter == correctSize) { controllers[1]->playbackCounter = 0; controllers[1]->playbackMode = false; printf("stopping playback mode from slot %d\n", controllers[0]->copyModeSlot); } } } void InputManager::writeConfig(){ int itemCounter = 0; std::vector<std::string> removalKeys; for (auto i : configJson.items()) { int user = i.value().at("user"); std::string str = i.key(); const char* ptr = str.c_str(); printf("the key:%s the user for this item: %d\n", ptr, user); if(user == userBeingConfig){ removalKeys.push_back(i.key()); } } for (auto i : removalKeys) { configJson.erase(i); printf("removalKey:%s \n", i.c_str()); } for(auto input : inputTemplate){ nlohmann::json obj = nlohmann::json::object(); obj["user"] = userBeingConfig; std::stringstream stream; stream << std::hex << input; std::string result( stream.str() ); obj["input"] = "0x" + result; printf("the input:%x\n", input); configJson[std::to_string(configArray[itemCounter])] = obj; itemCounter++; if(itemCounter == 8){ break; } } std::ofstream newConfigFile("../data/buttonconf.json"); configJson >> newConfigFile; newConfigFile.close(); init(); } void InputManager::writeButtonConfig(){ int itemCounter = 0; nlohmann::json* currentConfig = userBeingConfig == 1 ? &p1configJson : &p2configJson; std::vector<std::string> removalKeys; for (auto i : currentConfig->items()) { std::string str = i.key(); const char* ptr = str.c_str(); printf("the key:%s the user for this item: %d\n", ptr, userBeingConfig); removalKeys.push_back(i.key()); } for (auto i : removalKeys) { currentConfig->erase(i); printf("removalKey:%s \n", i.c_str()); } for(auto input : buttonTemplate){ nlohmann::json obj = nlohmann::json::object(); obj["user"] = userBeingConfig; std::stringstream stream; stream << std::hex << input; std::string result( stream.str() ); obj["input"] = "0x" + result; printf("the input:%x\n", input); (*currentConfig)[std::to_string(buttonConfigArray[itemCounter])] = obj; itemCounter++; if(itemCounter == 4){ printf("breaking button conf\n"); break; } } const char* confPath = userBeingConfig == 1 ? "../data/p1buttonconf.json" : "../data/p2buttonconf.json"; std::ofstream newConfigFile(confPath); (*currentConfig) >> newConfigFile; newConfigFile.close(); init(); } // Subject void InputManager::addObserver(const char* observerName, Observer* observer){ printf("Observer added to inputManager \n"); observerList.insert(std::make_pair(observerName, observer)); }; void InputManager::removeObserver(const char* observerName){ observerList.erase(observerName); }; void InputManager::notifyAll(const char* eventName){ for( const auto& [key, observer] : observerList ){ observer->onNotify(eventName); } }; void InputManager::addVirtualController(VirtualController* controller){ controllers.push_back(controller); } VirtualController* InputManager::getVirtualController(int index){ return controllers.at(index); } void InputManager::notifyOne(const char* observerName, const char* eventName){ Observer* observer = observerList.at(observerName); observer->onNotify(eventName); }
36.720588
151
0.550511
MicahMartin
e9ffd7f0dd51dd1290181cd72dcd37c847186388
4,617
cpp
C++
apps/visualizer.cpp
aquibrash87/RecoridingTool
1af39f7e6eb5bea2c649157003d7848b1f9cf4d8
[ "Apache-2.0" ]
null
null
null
apps/visualizer.cpp
aquibrash87/RecoridingTool
1af39f7e6eb5bea2c649157003d7848b1f9cf4d8
[ "Apache-2.0" ]
null
null
null
apps/visualizer.cpp
aquibrash87/RecoridingTool
1af39f7e6eb5bea2c649157003d7848b1f9cf4d8
[ "Apache-2.0" ]
null
null
null
/**************************************************************** ** ** ** Copyright(C) 2016 Quanergy Systems. All Rights Reserved. ** ** Contact: http://www.quanergy.com ** ** ** ****************************************************************/ // visualization module #include "visualizer_module.h" #include "filesave_module.h" // console parser #include <pcl/console/parse.h> #include <quanergy/client/sensor_client.h> // parsers for the data packets we want to support #include <quanergy/parsers/data_packet_parser_00.h> #include <quanergy/parsers/data_packet_parser_01.h> #include <quanergy/parsers/data_packet_parser_04.h> #include <quanergy/parsers/variadic_packet_parser.h> // module to apply encoder correction #include <quanergy/modules/encoder_angle_calibration.h> // conversion module from polar to Cartesian #include <quanergy/modules/polar_to_cart_converter.h> namespace { static const std::string MANUAL_CORRECT{"--manual-correct"}; static const std::string CALIBRATE_STR{"--calibrate"}; static const std::string AMPLITUDE_STR{"--amplitude"}; static const std::string PHASE_STR{"--phase"}; } void usage(char** argv) { std::cout << "usage: " << argv[0] << " --host <host> [-h | --help] [" << CALIBRATE_STR << "][" << MANUAL_CORRECT << " " << AMPLITUDE_STR << " <value> " << PHASE_STR << " <value>]" << std::endl << std::endl << " --host hostname or IP address of the sensor" << std::endl << "-h, --help show this help and exit" << std::endl; return; } typedef quanergy::client::SensorClient ClientType; typedef quanergy::client::VariadicPacketParser<quanergy::PointCloudHVDIRPtr, // return type quanergy::client::DataPacketParser00, // PARSER_00_INDEX quanergy::client::DataPacketParser01, // PARSER_00_INDEX quanergy::client::DataPacketParser04> ParserType; // PARSER_04_INDEX enum { PARSER_00_INDEX = 0, PARSER_01_INDEX = 1, PARSER_04_INDEX = 2 }; typedef quanergy::client::PacketParserModule<ParserType> ParserModuleType; typedef quanergy::calibration::EncoderAngleCalibration CalibrationType; typedef quanergy::client::PolarToCartConverter ConverterType; int main(int argc, char** argv) { int max_num_args = 8; // get host if (argc < 2 || argc > max_num_args || pcl::console::find_switch(argc, argv, "-h") || pcl::console::find_switch(argc, argv, "--help") || !pcl::console::find_switch(argc, argv, "--host")) { usage (argv); return (0); } std::string host; std::string port = "4141"; pcl::console::parse_argument(argc, argv, "--host", host); // create modules ClientType client(host, port, 100); ParserModuleType parser; ConverterType converter; VisualizerModule visualizer; FilesaveModule filesaver(FilesaveModule::DataType::Binary, "pcldata", FilesaveModule::TimestampType::System); //Binary oder Text CalibrationType calibrator; // setup modules parser.get<PARSER_00_INDEX>().setFrameId("quanergy"); parser.get<PARSER_00_INDEX>().setReturnSelection(0); parser.get<PARSER_00_INDEX>().setDegreesOfSweepPerCloud(360.0); parser.get<PARSER_01_INDEX>().setFrameId("quanergy"); parser.get<PARSER_04_INDEX>().setFrameId("quanergy"); // connect modules std::vector<boost::signals2::connection> connections; connections.push_back(client.connect([&parser](const ClientType::ResultType& pc){ parser.slot(pc); })); connections.push_back(parser.connect([&converter](const ParserModuleType::ResultType& pc){ converter.slot(pc); })); connections.push_back(converter.connect([&visualizer](const ConverterType::ResultType& pc){ visualizer.slot(pc); })); connections.push_back(converter.connect([&filesaver](const ConverterType::ResultType& pc){ filesaver.slot(pc);})); // run the client with the calibrator and wait for a signal from the // calibrator that a successful calibration has been performed std::thread client_thread([&client, &visualizer] { try { client.run(); } catch (std::exception& e) { std::cerr << "Terminating after catching exception: " << e.what() << std::endl; visualizer.stop(); } }); // start visualizer (blocks until stopped) visualizer.run(); // clean up client.stop(); connections.clear(); client_thread.join(); return (0); }
35.790698
177
0.635911
aquibrash87
1802e73bc9e102d64403cb942ccd1d9490c89b66
1,548
cpp
C++
io2d/src/device.cpp
cristianadam/N3888_RefImpl
d7975633ad0e66e32c2dea70b0952d48ed777e9b
[ "MIT" ]
52
2016-02-28T23:00:45.000Z
2021-11-28T06:13:02.000Z
io2d/src/device.cpp
cristianadam/N3888_RefImpl
d7975633ad0e66e32c2dea70b0952d48ed777e9b
[ "MIT" ]
null
null
null
io2d/src/device.cpp
cristianadam/N3888_RefImpl
d7975633ad0e66e32c2dea70b0952d48ed777e9b
[ "MIT" ]
6
2018-01-08T08:21:11.000Z
2022-03-11T03:18:54.000Z
#include "io2d.h" #include "xio2dhelpers.h" #include "xcairoenumhelpers.h" using namespace std; using namespace std::experimental::io2d; device::native_handle_type device::native_handle() const noexcept { return _Device.get(); } device::device(device::native_handle_type nh) : _Device() { _Device = shared_ptr<cairo_device_t>(nh, &cairo_device_destroy); _Throw_if_failed_cairo_status_t(cairo_device_status(_Device.get())); } device::device(device::native_handle_type nh, error_code& ec) noexcept : _Device() { _Device = shared_ptr<cairo_device_t>(nh, &cairo_device_destroy); if (cairo_device_status(_Device.get()) != CAIRO_STATUS_SUCCESS) { ec = _Cairo_status_t_to_std_error_code(CAIRO_STATUS_DEVICE_ERROR); } else { ec.clear(); } } device::device(device&& other) noexcept { _Device = move(other._Device); other._Device = nullptr; } device& device::operator=(device&& other) noexcept { if (this != &other) { _Device = move(other._Device); other._Device = nullptr; } return *this; } void device::flush() noexcept { cairo_device_flush(_Device.get()); } void device::lock() { _Throw_if_failed_cairo_status_t(cairo_device_acquire(_Device.get())); } void device::lock(error_code& ec) noexcept { if (cairo_device_acquire(_Device.get()) != CAIRO_STATUS_SUCCESS) { ec = make_error_code(errc::resource_unavailable_try_again); } else { ec.clear(); } } void device::unlock() { cairo_device_release(_Device.get()); } void device::unlock(error_code& ec) noexcept { cairo_device_release(_Device.get()); ec.clear(); }
23.815385
84
0.739664
cristianadam
18070b669def585ee9fa55b3d2a3fc5333c9f3ef
1,158
cpp
C++
Bridge/Cpp/main.cpp
john29917958/Design-Patterns
86b0139d67769552a9b97d1d436b9915a513871c
[ "MIT" ]
null
null
null
Bridge/Cpp/main.cpp
john29917958/Design-Patterns
86b0139d67769552a9b97d1d436b9915a513871c
[ "MIT" ]
null
null
null
Bridge/Cpp/main.cpp
john29917958/Design-Patterns
86b0139d67769552a9b97d1d436b9915a513871c
[ "MIT" ]
null
null
null
#include "character.h" int main() { std::unique_ptr<character> character = std::make_unique<human>(0, "Jack", 100, 100); character->cast_spell(); character->set_spell(std::make_shared<fire_spell>(30, 100, 20)); character->cast_spell(); character->set_spell(std::make_shared<ice_spell>(30, 50, 20)); character->cast_spell(); character->set_spell(std::make_shared<curse_spell>(40, 60, 20)); character->cast_spell(); character = std::make_unique<orc>(1, "Gary", 100, 100); character->cast_spell(); character->set_spell(std::make_shared<fire_spell>(30, 100, 20)); character->cast_spell(); character->set_spell(std::make_shared<ice_spell>(30, 50, 20)); character->cast_spell(); character->set_spell(std::make_shared<curse_spell>(40, 60, 20)); character->cast_spell(); character = std::make_unique<vampire>(3, "Prince", 100, 100); character->cast_spell(); character->set_spell(std::make_shared<fire_spell>(30, 100, 20)); character->cast_spell(); character->set_spell(std::make_shared<ice_spell>(30, 50, 20)); character->cast_spell(); character->set_spell(std::make_shared<curse_spell>(40, 60, 20)); character->cast_spell(); return 0; }
35.090909
85
0.721071
john29917958
1807818d667d2cbb291b49973ad6412d87550fc6
490
cpp
C++
Sphere_Online_Judge_soj/Classical/math_is_love.cpp
mushahadur/Competitive-Programming-Problem-Solving-Online-Judge
66b49ee2564b85d7b42d91a977f3d57d437e43d5
[ "Apache-2.0" ]
1
2021-08-25T06:49:16.000Z
2021-08-25T06:49:16.000Z
Sphere_Online_Judge_soj/Classical/math_is_love.cpp
mushahadur/Competitive-Programming-Problem-Solving-Online-Judge
66b49ee2564b85d7b42d91a977f3d57d437e43d5
[ "Apache-2.0" ]
null
null
null
Sphere_Online_Judge_soj/Classical/math_is_love.cpp
mushahadur/Competitive-Programming-Problem-Solving-Online-Judge
66b49ee2564b85d7b42d91a977f3d57d437e43d5
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int main() { int t; long long int y,sum=0,i,arr[100],arry[1000]; for(i=0; i<10; i++) { sum=sum+i; arr[i]=sum; arry[sum]=i; } cout<<"check : "<<arr[6]<<endl; cout<<"check 2 : "<<arry[21]<<endl; cin>>t; while(t--) { cin>>y; if(arry[y]!=0){ cout<<arry[y]<<endl; } else { cout<<"NUL"<<endl; } } return 0; }
16.333333
48
0.408163
mushahadur
18079d3658ce78314386c430ddb2cf88e2c3866b
1,234
inl
C++
LibImagics/Images/Wm5Lattice.inl
CRIMSONCardiovascularModelling/WildMagic5
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
[ "BSL-1.0" ]
1
2021-02-18T10:25:42.000Z
2021-02-18T10:25:42.000Z
LibImagics/Images/Wm5Lattice.inl
CRIMSONCardiovascularModelling/WildMagic5
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
[ "BSL-1.0" ]
null
null
null
LibImagics/Images/Wm5Lattice.inl
CRIMSONCardiovascularModelling/WildMagic5
fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c
[ "BSL-1.0" ]
null
null
null
// Geometric Tools, LLC // Copyright (c) 1998-2014 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 5.0.0 (2010/01/01) //---------------------------------------------------------------------------- inline int Lattice::GetDimensions () const { return mNumDimensions; } //---------------------------------------------------------------------------- inline const int* Lattice::GetBounds () const { return mBounds; } //---------------------------------------------------------------------------- inline int Lattice::GetBound (int i) const { return mBounds[i]; } //---------------------------------------------------------------------------- inline int Lattice::GetQuantity () const { return mQuantity; } //---------------------------------------------------------------------------- inline const int* Lattice::GetOffsets () const { return mOffsets; } //---------------------------------------------------------------------------- inline int Lattice::GetOffset (int i) const { return mOffsets[i]; } //----------------------------------------------------------------------------
30.85
78
0.388169
CRIMSONCardiovascularModelling
18121f2661b46c9ef94060e23bf73aa36410076e
14,098
cpp
C++
src/terminal_renderer/DecorationRenderer.cpp
christianparpart/libterminal
0e6d75a2042437084c9f9880a5c8b5661a02da07
[ "Apache-2.0" ]
4
2019-08-14T22:29:57.000Z
2019-09-19T08:57:15.000Z
src/terminal_renderer/DecorationRenderer.cpp
christianparpart/libterminal
0e6d75a2042437084c9f9880a5c8b5661a02da07
[ "Apache-2.0" ]
69
2019-08-17T18:57:16.000Z
2019-09-22T23:25:49.000Z
src/terminal_renderer/DecorationRenderer.cpp
christianparpart/libterminal
0e6d75a2042437084c9f9880a5c8b5661a02da07
[ "Apache-2.0" ]
null
null
null
/** * This file is part of the "contour" project. * Copyright (c) 2020 Christian Parpart <christian@parpart.family> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 <terminal_renderer/DecorationRenderer.h> #include <terminal_renderer/GridMetrics.h> #include <terminal_renderer/Pixmap.h> #include <terminal_renderer/shared_defines.h> #include <crispy/times.h> #include <crispy/utils.h> #include <array> #include <cmath> #include <iostream> #include <optional> #include <utility> using crispy::each_element; using crispy::Size; using std::array; using std::ceil; using std::clamp; using std::floor; using std::get; using std::max; using std::min; using std::move; using std::nullopt; using std::optional; using std::pair; using std::string; namespace terminal::renderer { namespace { auto constexpr CellFlagDecorationMappings = array { pair { CellFlags::Underline, Decorator::Underline }, pair { CellFlags::DoublyUnderlined, Decorator::DoubleUnderline }, pair { CellFlags::CurlyUnderlined, Decorator::CurlyUnderline }, pair { CellFlags::DottedUnderline, Decorator::DottedUnderline }, pair { CellFlags::DashedUnderline, Decorator::DashedUnderline }, pair { CellFlags::Overline, Decorator::Overline }, pair { CellFlags::CrossedOut, Decorator::CrossedOut }, pair { CellFlags::Framed, Decorator::Framed }, pair { CellFlags::Encircled, Decorator::Encircle }, }; } DecorationRenderer::DecorationRenderer(GridMetrics const& _gridMetrics, Decorator _hyperlinkNormal, Decorator _hyperlinkHover): Renderable { _gridMetrics }, hyperlinkNormal_ { _hyperlinkNormal }, hyperlinkHover_ { _hyperlinkHover } { } constexpr inline uint32_t DirectMappedDecorationCount = std::numeric_limits<Decorator>::count(); void DecorationRenderer::setRenderTarget(RenderTarget& renderTarget, DirectMappingAllocator& directMappingAllocator) { Renderable::setRenderTarget(renderTarget, directMappingAllocator); _directMapping = directMappingAllocator.allocate(DirectMappedDecorationCount); clearCache(); } void DecorationRenderer::setTextureAtlas(TextureAtlas& atlas) { Renderable::setTextureAtlas(atlas); initializeDirectMapping(); } void DecorationRenderer::clearCache() { } void DecorationRenderer::initializeDirectMapping() { Require(_textureAtlas); for (Decorator const decoration: each_element<Decorator>()) { auto const tileIndex = _directMapping.toTileIndex(static_cast<uint32_t>(decoration)); auto const tileLocation = _textureAtlas->tileLocation(tileIndex); TextureAtlas::TileCreateData tileData = createTileData(decoration, tileLocation); _textureAtlas->setDirectMapping(tileIndex, move(tileData)); } } void DecorationRenderer::inspect(std::ostream& /*output*/) const { } void DecorationRenderer::renderLine(RenderLine const& line) { for (auto const& mapping: CellFlagDecorationMappings) if (line.textAttributes.flags & mapping.first) renderDecoration(mapping.second, _gridMetrics.map(CellLocation { line.lineOffset }), line.usedColumns, line.textAttributes.decorationColor); } void DecorationRenderer::renderCell(RenderCell const& _cell) { for (auto const& mapping: CellFlagDecorationMappings) if (_cell.attributes.flags & mapping.first) renderDecoration(mapping.second, _gridMetrics.map(_cell.position), ColumnCount(1), _cell.attributes.decorationColor); } auto DecorationRenderer::createTileData(Decorator decoration, atlas::TileLocation tileLocation) -> TextureAtlas::TileCreateData { auto const width = _gridMetrics.cellSize.width; auto tileData = TextureAtlas::TileCreateData {}; // NB: To be filled below: bitmapSize, bitmap. tileData.bitmapFormat = atlas::Format::Red; tileData.metadata.x = {}; tileData.metadata.y = {}; auto const create = [this, tileLocation](ImageSize bitmapSize, auto createBitmap) -> TextureAtlas::TileCreateData { return createTileData(tileLocation, createBitmap(), atlas::Format::Red, bitmapSize, RenderTileAttributes::X { 0 }, RenderTileAttributes::Y { 0 }, FRAGMENT_SELECTOR_GLYPH_ALPHA); }; switch (decoration) { case Decorator::Encircle: // TODO (default to Underline for now) [[fallthrough]]; case Decorator::Underline: { auto const thickness_half = max(1u, unsigned(ceil(underlineThickness() / 2.0))); auto const thickness = thickness_half * 2; auto const y0 = max(0u, unsigned(underlinePosition()) - thickness_half); auto const height = Height(y0 + thickness); auto const imageSize = ImageSize { width, height }; return create(imageSize, [&]() -> atlas::Buffer { auto image = atlas::Buffer(imageSize.area(), 0); for (unsigned y = 1; y <= thickness; ++y) for (unsigned x = 0; x < unbox<unsigned>(width); ++x) image[(*height - y0 - y) * *width + x] = 0xFF; return image; }); } case Decorator::DoubleUnderline: { auto const thickness = max(1u, unsigned(ceil(double(underlineThickness()) * 2.0) / 3.0)); auto const y1 = max(0u, unsigned(underlinePosition()) + thickness); auto const y0 = max(0u, y1 - 3 * thickness); auto const height = Height(y1 + thickness); auto const imageSize = ImageSize { width, height }; return create(imageSize, [&]() -> atlas::Buffer { auto image = atlas::Buffer(imageSize.area(), 0); for (unsigned y = 1; y <= thickness; ++y) { for (unsigned x = 0; x < unbox<unsigned>(width); ++x) { image[(*height - y1 - y) * *width + x] = 0xFF; // top line image[(*height - y0 - y) * *width + x] = 0xFF; // bottom line } } return image; }); } case Decorator::CurlyUnderline: { auto const height = Height::cast_from(_gridMetrics.baseline); auto const h2 = max(unbox<int>(height) / 2, 1); auto const yScalar = h2 - 1; auto const xScalar = 2 * M_PI / *width; auto const yBase = h2; auto const imageSize = ImageSize { width, height }; auto block = blockElement(imageSize); return create(block.downsampledSize(), [&]() -> atlas::Buffer { auto const thickness_half = max(1, int(ceil(underlineThickness() / 2.0))); for (int x = 0; x < unbox<int>(width); ++x) { // Using Wu's antialiasing algorithm to paint the curved line. // See: https://www-users.mat.umk.pl//~gruby/teaching/lgim/1_wu.pdf auto const y = yScalar * cos(xScalar * x); auto const y1 = static_cast<int>(floor(y)); auto const y2 = static_cast<int>(ceil(y)); auto const intensity = static_cast<uint8_t>(255 * fabs(y - y1)); // block.paintOver(x, yBase + y1, 255 - intensity); // block.paintOver(x, yBase + y2, intensity); block.paintOverThick(x, yBase + y1, uint8_t(255 - intensity), thickness_half, 0); block.paintOverThick(x, yBase + y2, intensity, thickness_half, 0); } return block.take(); }); } case Decorator::DottedUnderline: { auto const dotHeight = (unsigned) _gridMetrics.underline.thickness; auto const dotWidth = dotHeight; auto const height = Height::cast_from((unsigned) _gridMetrics.underline.position + dotHeight); auto const y0 = (unsigned) _gridMetrics.underline.position - dotHeight; auto const x0 = 0u; auto const x1 = unbox<unsigned>(width) / 2; auto block = blockElement(ImageSize { width, height }); return create(block.downsampledSize(), [&]() -> atlas::Buffer { for (unsigned y = 0; y < dotHeight; ++y) { for (unsigned x = 0; x < dotWidth; ++x) { block.paint(int(x + x0), int(y + y0)); block.paint(int(x + x1), int(y + y0)); } } return block.take(); }); } case Decorator::DashedUnderline: { // Devides a grid cell's underline in three sub-ranges and only renders first and third one, // whereas the middle one is being skipped. auto const thickness_half = max(1u, unsigned(ceil(underlineThickness() / 2.0))); auto const thickness = max(1u, thickness_half * 2); auto const y0 = max(0u, unsigned(underlinePosition()) - thickness_half); auto const height = Height(y0 + thickness); auto const imageSize = ImageSize { width, height }; return create(imageSize, [&]() -> atlas::Buffer { auto image = atlas::Buffer(unbox<size_t>(width) * unbox<size_t>(height), 0); for (unsigned y = 1; y <= thickness; ++y) for (unsigned x = 0; x < unbox<unsigned>(width); ++x) if (fabsf(float(x) / float(*width) - 0.5f) >= 0.25f) image[(*height - y0 - y) * *width + x] = 0xFF; return image; }); } case Decorator::Framed: { auto const cellHeight = _gridMetrics.cellSize.height; auto const thickness = max(1u, unsigned(underlineThickness()) / 2); auto const imageSize = ImageSize { width, cellHeight }; return create(imageSize, [&]() -> atlas::Buffer { auto image = atlas::Buffer(unbox<size_t>(width) * unbox<size_t>(cellHeight), 0); auto const gap = 0; // thickness; // Draws the top and bottom horizontal lines for (unsigned y = gap; y < thickness + gap; ++y) for (unsigned x = gap; x < unbox<unsigned>(width) - gap; ++x) { image[y * *width + x] = 0xFF; image[(*cellHeight - 1 - y) * *width + x] = 0xFF; } // Draws the left and right vertical lines for (unsigned y = gap; y < unbox<unsigned>(cellHeight) - gap; y++) for (unsigned x = gap; x < thickness + gap; ++x) { image[y * *width + x] = 0xFF; image[y * *width + (*width - 1 - x)] = 0xFF; } return image; }); } case Decorator::Overline: { auto const cellHeight = _gridMetrics.cellSize.height; auto const thickness = (unsigned) underlineThickness(); auto const imageSize = ImageSize { width, cellHeight }; return create(imageSize, [&]() -> atlas::Buffer { auto image = atlas::Buffer(unbox<size_t>(width) * unbox<size_t>(cellHeight), 0); for (unsigned y = 0; y < thickness; ++y) for (unsigned x = 0; x < unbox<unsigned>(width); ++x) image[(*cellHeight - y - 1) * *width + x] = 0xFF; return image; }); } case Decorator::CrossedOut: { auto const height = Height(*_gridMetrics.cellSize.height / 2); auto const thickness = (unsigned) underlineThickness(); auto const imageSize = ImageSize { width, height }; return create(imageSize, [&]() -> atlas::Buffer { auto image = atlas::Buffer(unbox<size_t>(width) * unbox<size_t>(height), 0); for (unsigned y = 1; y <= thickness; ++y) for (unsigned x = 0; x < unbox<unsigned>(width); ++x) image[(*height - y) * *width + x] = 0xFF; return image; }); } } Require(false && "Unhandled case."); return {}; } void DecorationRenderer::renderDecoration(Decorator decoration, crispy::Point pos, ColumnCount columnCount, RGBColor const& color) { for (auto i = ColumnCount(0); i < columnCount; ++i) { auto const tileIndex = _directMapping.toTileIndex(static_cast<uint32_t>(decoration)); auto const tileLocation = _textureAtlas->tileLocation(tileIndex); TextureAtlas::TileCreateData tileData = createTileData(decoration, tileLocation); AtlasTileAttributes const& tileAttributes = _textureAtlas->directMapped(tileIndex); renderTile({ pos.x + unbox<int>(i) * unbox<int>(_gridMetrics.cellSize.width) }, { pos.y }, color, tileAttributes); } } } // namespace terminal::renderer
43.782609
107
0.563839
christianparpart
1812243c839f98ba54f28bd5d6e08ccbd812977c
4,280
cc
C++
libfabric/prov/sstmac/src/sstmac_wait.cc
sstsimulator/sst-transports
6561e1ab001b3ee8ece1b97ee89360258cd4c75c
[ "BSD-3-Clause" ]
null
null
null
libfabric/prov/sstmac/src/sstmac_wait.cc
sstsimulator/sst-transports
6561e1ab001b3ee8ece1b97ee89360258cd4c75c
[ "BSD-3-Clause" ]
1
2021-08-05T17:24:36.000Z
2021-08-05T17:24:36.000Z
libfabric/prov/sstmac/src/sstmac_wait.cc
sstsimulator/sst-transports
6561e1ab001b3ee8ece1b97ee89360258cd4c75c
[ "BSD-3-Clause" ]
2
2021-08-05T17:25:14.000Z
2021-11-10T02:48:04.000Z
/** Copyright 2009-2020 National Technology and Engineering Solutions of Sandia, LLC (NTESS). Under the terms of Contract DE-NA-0003525, the U.S. Government retains certain rights in this software. Sandia National Laboratories is a multimission laboratory managed and operated by National Technology and Engineering Solutions of Sandia, LLC., a wholly owned subsidiary of Honeywell International, Inc., for the U.S. Department of Energy's National Nuclear Security Administration under contract DE-NA0003525. Copyright (c) 2009-2020, NTESS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder 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. Questions? Contact sst-macro-help@sandia.gov */ #include <stdlib.h> #include <signal.h> #include "sstmac.h" #include "sstmac_wait.h" #include <sprockit/errors.h> #include <vector> static int sstmac_wait_control(struct fid *wait, int command, void *arg); extern "C" int sstmac_wait_close(struct fid *wait); extern "C" DIRECT_FN int sstmac_wait_wait(struct fid_wait *wait, int timeout); extern "C" DIRECT_FN int sstmac_wait_open(struct fid_fabric *fabric, struct fi_wait_attr *attr, struct fid_wait **waitset); static struct fi_ops sstmac_fi_ops = { .size = sizeof(struct fi_ops), .close = sstmac_wait_close, .bind = fi_no_bind, .control = sstmac_wait_control, .ops_open = fi_no_ops_open }; static struct fi_ops_wait sstmac_wait_ops = { .size = sizeof(struct fi_ops_wait), .wait = sstmac_wait_wait }; struct sstmac_fid_wait_obj { }; struct sstmac_fid_wait_set { struct fid_wait wait; struct fid_fabric *fabric; enum fi_cq_wait_cond cond_type; enum fi_wait_obj type; std::vector<fid*> listeners; }; static int sstmac_wait_control(struct fid *wait, int command, void *arg) { /* struct fid_wait *wait_fid_priv; SSTMAC_TRACE(WAIT_SUB, "\n"); wait_fid_priv = container_of(wait, struct fid_wait, fid); */ switch (command) { case FI_GETWAIT: return -FI_ENOSYS; default: return -FI_EINVAL; } } extern "C" void sstmaci_add_wait(struct fid_wait *wait, struct fid *wait_obj) { sstmac_fid_wait_set* waitset = (sstmac_fid_wait_set*) wait; waitset->listeners.push_back(wait_obj); } extern "C" DIRECT_FN int sstmac_wait_wait(struct fid_wait *wait, int timeout) { int err = 0, ret; char c; spkt_abort_printf("unimplemented: sstmac_wait_wait for wait set"); return FI_SUCCESS; } extern "C" int sstmac_wait_close(struct fid *wait) { free(wait); return FI_SUCCESS; } DIRECT_FN int sstmac_wait_open(struct fid_fabric *fabric, struct fi_wait_attr *attr, struct fid_wait **waitset) { struct sstmac_fid_wait_set* waiter = (struct sstmac_fid_wait_set*) calloc(1,sizeof(struct sstmac_fid_wait_set)); waiter->wait.fid.fclass = FI_CLASS_WAIT; waiter->wait.fid.ops = &sstmac_fi_ops; waiter->fabric = fabric; *waitset = (fid_wait*) waiter; return FI_SUCCESS; }
31.703704
114
0.764953
sstsimulator
181290adcdcadb00e1457986b03d3982e0cbba0f
5,759
hpp
C++
include/cadence/async/streamsocket.hpp
abbyssoul/libcadence
c9a49d95df608497e9551f7d62169d0c78a48737
[ "Apache-2.0" ]
2
2020-04-24T15:07:33.000Z
2020-06-12T07:01:53.000Z
include/cadence/async/streamsocket.hpp
abbyssoul/libcadence
c9a49d95df608497e9551f7d62169d0c78a48737
[ "Apache-2.0" ]
null
null
null
include/cadence/async/streamsocket.hpp
abbyssoul/libcadence
c9a49d95df608497e9551f7d62169d0c78a48737
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) Ivan Ryabov - All Rights Reserved * * Unauthorized copying of this file, via any medium is strictly prohibited. * Proprietary and confidential. * * Written by Ivan Ryabov <abbyssoul@gmail.com> */ /******************************************************************************* * libcadence: Async Stream Sockets * @file cadence/async/streamsocket.hpp * @author $LastChangedBy$ * @date $LastChangedDate$ * ID: $Id$ ******************************************************************************/ #pragma once #ifndef CADENCE_ASYNC_STREAMSOCKET_HPP #define CADENCE_ASYNC_STREAMSOCKET_HPP #include "cadence/async/channel.hpp" #include "cadence/networkEndpoint.hpp" namespace cadence { namespace async { /** * Base class for stream-oriented sockets */ class StreamSocket : public Channel { public: using Channel::size_type; ~StreamSocket() override; StreamSocket(StreamSocket const &) = delete; StreamSocket& operator= (StreamSocket const& ) = delete; StreamSocket(StreamSocket&& rhs) = default; StreamSocket& operator= (StreamSocket&& rhs) noexcept = default; StreamSocket& swap(StreamSocket& rhs) noexcept { using std::swap; swap(_pimpl, rhs._pimpl); return *this; } using Channel::asyncRead; using Channel::asyncWrite; using Channel::read; using Channel::write; /** * Post an async read request to read specified amount of data from this IO object into the given buffer. * * @param dest The provided destination buffer to read data into. * @param bytesToRead Amount of data (in bytes) to read from this IO object. * @return A future that will be resolved one the scpecified number of bytes has been read. * * @note If the provided destination buffer is too small to hold requested amount of data - an exception is raised. */ Solace::Future<void> asyncRead(Solace::ByteWriter& dest, size_type bytesToRead) override; /** * Post an async write request to write specified amount of data into this IO object. * * @param src The provided source buffer to read data from. * @param bytesToWrite Amount of data (in bytes) to write from the buffer into this IO object. * @return A future that will be resolved one the scpecified number of bytes has been written into the IO object. * * @note If the provided source buffer does not have requested amount of data - an exception is raised. */ Solace::Future<void> asyncWrite(Solace::ByteReader& src, size_type bytesToWrite) override; /** @see Channel::cancel */ void cancel() override; /** @see Channel::close */ void close() override; /** @see Channel::isOpen */ bool isOpen() const override; /** @see Channel::isClosed */ bool isClosed() const override; /** @see Channel::read */ Solace::Result<void, Solace::Error> read(Solace::ByteWriter& dest, size_type bytesToRead) override; /** @see Channel::write */ Solace::Result<void, Solace::Error> write(Solace::ByteReader& src, size_type bytesToWrite) override; /** * Get the local endpoint of the socket. * @return Local endpoint this socket is bound to. */ NetworkEndpoint getLocalEndpoint() const; /** * Get the remote endpoint of the socket. * @return Remote endpoint this socket is connected to if any. */ NetworkEndpoint getRemoteEndpoint() const; /** * Disable sends or receives on the socket. */ void shutdown(); /** * Start an syncronous connection to the given endpoint. * This call will block until a connection is complete (either successfully or in an error) * @param endpoint An endpoint to connect to. */ Solace::Result<void, Solace::Error> connect(NetworkEndpoint const& endpoint); /** * Start an asynchronous connection to the given endpoint. * @param endpoint An endpoint to connect to. * @return Future that is resolved when connection is establised or an error occured. */ Solace::Future<void> asyncConnect(NetworkEndpoint const& endpoint); public: class StreamSocketImpl { public: virtual ~StreamSocketImpl(); virtual Solace::Future<void> asyncRead(Solace::ByteWriter& dest, size_type bytesToRead) = 0; virtual Solace::Future<void> asyncWrite(Solace::ByteReader& src, size_type bytesToWrite) = 0; virtual Solace::Result<void, Solace::Error> read(Solace::ByteWriter& dest, size_type bytesToRead) = 0; virtual Solace::Result<void, Solace::Error> write(Solace::ByteReader& src, size_type bytesToWrite) = 0; virtual void cancel() = 0; virtual void close() = 0; virtual bool isOpen() const = 0; virtual bool isClosed() const = 0; virtual NetworkEndpoint getLocalEndpoint() const = 0; virtual NetworkEndpoint getRemoteEndpoint() const = 0; virtual void shutdown() = 0; virtual Solace::Future<void> asyncConnect(NetworkEndpoint const& endpoint) = 0; virtual Solace::Result<void, Solace::Error> connect(NetworkEndpoint const& endpoint) = 0; }; StreamSocket(EventLoop& ioContext, std::unique_ptr<StreamSocketImpl> impl); private: std::unique_ptr<StreamSocketImpl> _pimpl; }; inline void swap(StreamSocket& lhs, StreamSocket& rhs) noexcept { lhs.swap(rhs); } StreamSocket createTCPSocket(EventLoop& loop); StreamSocket createUnixSocket(EventLoop& loop); } // End of namespace async } // End of namespace cadence #endif // CADENCE_ASYNC_STREAMSOCKET_HPP
28.092683
119
0.650113
abbyssoul
181c4ea39274ab564324aa2056b36512a31cec36
6,911
cpp
C++
addjobdiag.cpp
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
addjobdiag.cpp
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
addjobdiag.cpp
dayuanyuan1989/RemoteBinder
6c07896828187bbb890115fa1326f9db4fbd7b68
[ "MIT" ]
null
null
null
#include "addjobdiag.h" #include "ui_addjobdiag.h" #include <QSize> #include <QString> #include <QStringList> #include <QTime> #include <QDate> #include <QColor> #include <QFontDatabase> #include <QDebug> AddJobDiag::AddJobDiag(QWidget *parent) : QWidget(parent), ui(new Ui::AddJobDiag) { ui->setupUi(this); init(); m_sizeMap["1280 × 720"] = QSize(1280, 720); m_sizeMap["1280 × 960"] = QSize(1280, 960); m_sizeMap["1920 × 1080"] = QSize(1920, 1080); m_sizeMap["1920 × 1200"] = QSize(1920, 1200); m_sizeMap["2048 × 1748"] = QSize(2048, 1748); m_sizeMap["2560 × 1600"] = QSize(2560, 1600); m_sizeMap["3840 × 2160"] = QSize(3840, 2160); m_sizeMap["4960 × 2790"] = QSize(4960, 2790); m_sizeMap["4960 × 3508"] = QSize(4960, 3508); m_sizeMap["7680 × 4320"] = QSize(7680, 4320); m_sizeMap["7680 × 4800"] = QSize(7680, 4800); ui->comboBox->clear(); QStringList items; items.append(m_sizeMap.keys()); ui->comboBox->addItems(items); ui->fontsizecombox->setCurrentText("36"); ui->textedit->clear(); ui->textedit->setPlainText("Sample Text"); } AddJobDiag::~AddJobDiag() { final(); delete ui; } void AddJobDiag::init() { SetFontSizeCombox(QFont()); // connect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SIGNAL(fontFamilyChanged(QFont))); connect(ui->fontboldbtn, SIGNAL(toggled(bool)), this, SIGNAL(BoldStateChanged(bool))); connect(ui->fontitalicbtn, SIGNAL(toggled(bool)), this, SIGNAL(ItalyStateChanged(bool))); connect(ui->watermarkchkbox, SIGNAL(toggled(bool)), this, SIGNAL(WaterMarkVisibleChanged(bool))); } void AddJobDiag::final() { // disconnect(ui->fontComboBox, SIGNAL(currentFontChanged(QFont)), this, SIGNAL(fontFamilyChanged(QFont))); disconnect(ui->fontboldbtn, SIGNAL(toggled(bool)), this, SIGNAL(BoldStateChanged(bool))); disconnect(ui->fontitalicbtn, SIGNAL(toggled(bool)), this, SIGNAL(ItalyStateChanged(bool))); disconnect(ui->watermarkchkbox, SIGNAL(toggled(bool)), this, SIGNAL(WaterMarkVisibleChanged(bool))); } QByteArray AddJobDiag::GetAddRenderTaskString() { RenderData data; QString fileName; data.size = m_sizeMap[ui->comboBox->currentText()]; if(ui->mediumBtn->isChecked()) { fileName.append("MEDIUM"); data.quality = 0; } else if (ui->highBtn->isChecked()) { fileName.append("HIGH"); data.quality = 1; } else if (ui->veryHighBtn->isChecked()) { fileName.append("VERY HIGH"); data.quality = 2; } else { fileName.append("MEDIUM"); data.quality = 0; } fileName.append("_"); fileName.append(QString::number(data.size.width())); fileName.append("_"); fileName.append(QString::number(data.size.height())); fileName.append("_"); fileName.append(QDateTime::currentDateTime().date().toString("yyyyMMdd")); fileName.append("_"); fileName.append(QDateTime::currentDateTime().time().toString("hhmmsszzz")); if(ui->jpgBtn->isChecked()) { data.format = 0; fileName.append(".jpg"); } else if(ui->tifBtn->isChecked()) { fileName.append(".tif"); data.format = 1; } else if(ui->pngBtn->isChecked()){ fileName.append(".png"); data.format = 2; } else { fileName.append(".jpg"); data.format = 0; } qDebug() << fileName; data.fileName = fileName; QByteArray str("AddRenderTask:"); unsigned uSize = 0x00; uSize = data.size.width(); uSize = uSize << 16; uSize |= data.size.height(); str.append(QString("FileName:%1;").arg(data.fileName)); str.append(QString("SIZE:%1;").arg(uSize)); str.append(QString("FORMAT:%1;").arg(data.format)); str.append(QString("QUALITY:%1;").arg(data.quality)); return str; } void AddJobDiag::on_addTaskBtn_clicked() { RenderData data; QString fileName; data.size = m_sizeMap[ui->comboBox->currentText()]; if(ui->mediumBtn->isChecked()) { fileName.append("MEDIUM"); data.quality = 0; } else if (ui->highBtn->isChecked()) { fileName.append("HIGH"); data.quality = 1; } else if (ui->veryHighBtn->isChecked()) { fileName.append("VERY HIGH"); data.quality = 2; } else { fileName.append("MEDIUM"); data.quality = 0; } fileName.append("_"); fileName.append(QString::number(data.size.width())); fileName.append("_"); fileName.append(QString::number(data.size.height())); fileName.append("_"); fileName.append(QDateTime::currentDateTime().date().toString("yyyyMMdd")); fileName.append("_"); fileName.append(QDateTime::currentDateTime().time().toString("hhmmsszzz")); if(ui->jpgBtn->isChecked()) { data.format = 0; fileName.append(".jpg"); } else if(ui->tifBtn->isChecked()) { fileName.append(".tif"); data.format = 1; } else if(ui->pngBtn->isChecked()){ fileName.append(".png"); data.format = 2; } else { fileName.append(".jpg"); data.format = 0; } data.fileName = fileName; unsigned uSize = 0x00; uSize = data.size.width(); uSize = uSize << 16; uSize |= data.size.height(); emit AddNewTask(data); } void AddJobDiag::on_colorlineEdit_editingFinished() { QString colorStr = ui->colorlineEdit->text(); if(colorStr.startsWith("#")) { QString colorDataStr = colorStr.mid(1, 6); bool ok = false; uint ucolordata = colorDataStr.toUInt(&ok, 16); if(ok) { QColor color(ucolordata); ui->colorbglabel->setStyleSheet(QString("background-color: rgba(%1, %2, %3, %4);").arg(color.red()).arg(color.green()).arg(color.blue()).arg(color.alpha())); emit TextColorChanged(color); } } } void AddJobDiag::on_fontsizecombox_currentIndexChanged(const QString &arg1) { bool ok = false; uint size = arg1.toUInt(&ok); if(ok) { emit fontSizeChanged(size); } } void AddJobDiag::on_textedit_textChanged() { emit TextChanged(ui->textedit->toPlainText()); } void AddJobDiag::on_fontComboBox_currentFontChanged(const QFont &f) { SetFontSizeCombox(f); ui->fontboldbtn->setChecked(false); ui->fontitalicbtn->setChecked(false); ui->fontsizecombox->setCurrentText("36"); emit fontFamilyChanged(f); emit fontSizeChanged(36); } void AddJobDiag::SetFontSizeCombox(const QFont& f) { QFontDatabase database; QList<int> list = database.pointSizes(f.family()); ui->fontsizecombox->clear(); foreach(int size, list) { ui->fontsizecombox->addItem(QString::number(size)); } }
30.444934
170
0.610476
dayuanyuan1989
181c70421b6c0598ec588002242307255ecf1f7f
12,521
cc
C++
modules/perception/obstacle/camera/visualizer/frame_content.cc
fukatani/apollo
8677d8fd9d74e625c9dfaf184775d9e7cd24c8e2
[ "Apache-2.0" ]
1
2021-11-27T02:45:38.000Z
2021-11-27T02:45:38.000Z
modules/perception/obstacle/camera/visualizer/frame_content.cc
LiuGuoJiang/apollo
ca0e14af13c06bc5ff9cc5b3200c06351a07ee1d
[ "Apache-2.0" ]
null
null
null
modules/perception/obstacle/camera/visualizer/frame_content.cc
LiuGuoJiang/apollo
ca0e14af13c06bc5ff9cc5b3200c06351a07ee1d
[ "Apache-2.0" ]
1
2021-03-30T07:50:50.000Z
2021-03-30T07:50:50.000Z
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "modules/perception/obstacle/camera/visualizer/frame_content.h" #include <Eigen/LU> #include <map> #include "modules/common/log.h" namespace apollo { namespace perception { FrameContent::FrameContent() : _global_offset_initialized(false) { _continuous_type = PC_CONTINUOUS; } FrameContent::~FrameContent() {} void FrameContent::set_image_content(double timestamp, cv::Mat image) { ImageContent image_content; image_content._timestamp = timestamp; image_content._image_mat_src = image; _image_caches[timestamp] = image_content; } void FrameContent::set_motion_content(double timestamp, MotionBufferPtr motion_buffer) { MotionContent motion_content; motion_content._motion_frame_content = *motion_buffer; _motion_caches[timestamp] = motion_content; } void FrameContent::set_camera_content(double timestamp, Eigen::Matrix4d pose_c2w, const std::vector<ObjectPtr>& objects, const CameraFrameSupplement& supplement) { if (_camera_caches.find(timestamp) != _camera_caches.end()) return; CameraContent content; content._timestamp = timestamp; content._pose_c2w = pose_c2w; content._camera_objects.resize(objects.size()); for (size_t i = 0; i < objects.size(); ++i) { content._camera_objects[i].reset(new Object); content._camera_objects[i]->clone(*objects[i]); // offset_object(content._camera_objects[i], _global_offset); } content._camera_frame_supplement->clone(supplement); _camera_caches[timestamp] = content; } void FrameContent::set_camera_content(double timestamp, Eigen::Matrix4d pose_c2w, const std::vector<ObjectPtr>& objects) { if (_camera_caches.find(timestamp) != _camera_caches.end()) return; CameraContent content; content._timestamp = timestamp; if (!_global_offset_initialized) { _global_offset[0] = -pose_c2w(0, 3); _global_offset[1] = -pose_c2w(1, 3); _global_offset[2] = -pose_c2w(2, 3); _global_offset_initialized = true; AINFO << "initial pose " << pose_c2w; AINFO << "offset = " << _global_offset[0] << " " << _global_offset[1] << " " << _global_offset[2] << "\n"; } content._pose_c2w = pose_c2w; // content._pose_c2w(0, 3) += _global_offset[0]; // content._pose_c2w(1, 3) += _global_offset[1]; // content._pose_c2w(2, 3) += _global_offset[2]; content._camera_objects.resize(objects.size()); for (size_t i = 0; i < objects.size(); ++i) { content._camera_objects[i].reset(new Object); content._camera_objects[i]->clone(*objects[i]); offset_object(content._camera_objects[i], _global_offset); } _camera_caches[timestamp] = content; } void FrameContent::set_radar_content(double timestamp, const std::vector<ObjectPtr>& objects) { RadarContent content; content._timestamp = timestamp; content._radar_objects.resize(objects.size()); for (size_t i = 0; i < objects.size(); ++i) { content._radar_objects[i].reset(new Object); content._radar_objects[i]->clone(*objects[i]); offset_object(content._radar_objects[i], _global_offset); } _radar_caches[timestamp] = content; } void FrameContent::set_fusion_content(double timestamp, const std::vector<ObjectPtr>& objects) { FusionContent content; content._timestamp = timestamp; content._fused_objects.resize(objects.size()); for (size_t i = 0; i < objects.size(); ++i) { content._fused_objects[i].reset(new Object); content._fused_objects[i]->clone(*objects[i]); offset_object(content._fused_objects[i], _global_offset); } _fusion_caches[timestamp] = content; } void FrameContent::set_gt_content(double timestamp, const std::vector<ObjectPtr>& objects) { GroundTruthContent content; content._timestamp = timestamp; content._gt_objects.resize(objects.size()); for (size_t i = 0; i < objects.size(); ++i) { content._gt_objects[i].reset(new Object); content._gt_objects[i]->clone(*objects[i]); offset_object(content._gt_objects[i], _global_offset); } _gt_caches[timestamp] = content; } void FrameContent::update_timestamp(double ref) { double best_delta = FLT_MAX; double best_ts = -1; if (_continuous_type == IMAGE_CONTINUOUS) { if (_image_caches.empty()) { return; } best_ts = FLT_MAX; for (std::map<double, ImageContent>::iterator it = _image_caches.begin(); it != _image_caches.end(); it++) { double it_ts = it->first; if (it_ts < best_ts && _current_image_timestamp != it_ts) { best_ts = it_ts; } } ref = best_ts; _current_image_timestamp = ref; } for (std::map<double, ImageContent>::iterator it = _image_caches.begin(); it != _image_caches.end();) { if (it->first < _current_image_timestamp) { _image_caches.erase(it++); } else { it++; } } std::string ts_string = std::to_string(ref); AINFO << "cur time: " << ts_string << " | radar caches num: " << _radar_caches.size() << " | camera caches num: " << _camera_caches.size() << " | fusion caches num: " << _fusion_caches.size() << " | image caches num: " << _image_caches.size(); best_delta = FLT_MAX; best_ts = -1; for (std::map<double, RadarContent>::iterator it = _radar_caches.begin(); it != _radar_caches.end(); it++) { double it_ts = it->first; double delta = fabs(it_ts - ref); if (delta < best_delta) { best_delta = delta; best_ts = it_ts; } } _current_radar_timestamp = best_ts; for (std::map<double, RadarContent>::iterator it = _radar_caches.begin(); it != _radar_caches.end();) { if (it->first < best_ts) { _radar_caches.erase(it++); } else { it++; } } best_delta = FLT_MAX; best_ts = -1; for (std::map<double, FusionContent>::iterator it = _fusion_caches.begin(); it != _fusion_caches.end(); it++) { double it_ts = it->first; double delta = fabs(it_ts - ref); if (delta < best_delta) { best_delta = delta; best_ts = it_ts; } } _current_fusion_timestamp = best_ts; for (std::map<double, FusionContent>::iterator it = _fusion_caches.begin(); it != _fusion_caches.end();) { if (it->first < best_ts) { _fusion_caches.erase(it++); } else { it++; } } // find camera tracked best ts best_delta = FLT_MAX; best_ts = -1; for (std::map<double, CameraContent>::iterator it = _camera_caches.begin(); it != _camera_caches.end(); it++) { double it_ts = it->first; double delta = fabs(it_ts - ref); if (delta < best_delta) { best_delta = delta; best_ts = it_ts; } } _current_camera_timestamp = best_ts; for (std::map<double, CameraContent>::iterator it = _camera_caches.begin(); it != _camera_caches.end();) { if (it->first < best_ts) { _camera_caches.erase(it++); } else { it++; } } best_delta = FLT_MAX; best_ts = -1; for (std::map<double, GroundTruthContent>::iterator it = _gt_caches.begin(); it != _gt_caches.end(); it++) { double it_ts = it->first; double delta = fabs(it_ts - ref); if (delta < best_delta) { best_delta = delta; best_ts = it_ts; } } _current_gt_timestamp = best_ts; for (std::map<double, GroundTruthContent>::iterator it = _gt_caches.begin(); it != _gt_caches.end();) { if (it->first < best_ts) { _gt_caches.erase(it++); } else { it++; } } // get motion timestamp best_delta = FLT_MAX; best_ts = -1; for (std::map<double, MotionContent>::iterator it = _motion_caches.begin(); it != _motion_caches.end(); it++) { double it_ts = it->first; double delta = fabs(it_ts - ref); if (delta < best_delta) { best_delta = delta; best_ts = it_ts; } } _current_motion_timestamp = best_ts; for (std::map<double, MotionContent>::iterator it = _motion_caches.begin(); it != _motion_caches.end();) { if (it->first < best_ts) { _motion_caches.erase(it++); } else { it++; } } } Eigen::Matrix4d FrameContent::get_camera_to_world_pose() { std::map<double, CameraContent>::iterator it = _camera_caches.find(_current_camera_timestamp); if (it == _camera_caches.end()) { return Eigen::Matrix4d::Identity(); } CameraContent content = it->second; return content._pose_c2w; } cv::Mat FrameContent::get_camera_image() { std::map<double, ImageContent>::iterator it = _image_caches.find(_current_image_timestamp); if (it == _image_caches.end()) { cv::Mat mat = cv::Mat::zeros(1080, 1920, CV_8UC3); return mat; } ImageContent content = it->second; return content._image_mat_src; } const MotionBuffer FrameContent::get_motion_buffer() { std::map<double, MotionContent>::iterator it = _motion_caches.find(_current_motion_timestamp); if (it == _motion_caches.end()) { return MotionBuffer(0); } MotionContent content = it->second; return content._motion_frame_content; } void FrameContent::set_camera2car_pose(Eigen::Matrix4d pose_velo2cam) { _pose_camera2velo = pose_velo2cam.inverse(); } Eigen::Matrix4d FrameContent::get_opengl_camera_system_pose() { Eigen::Matrix4d pose = Eigen::Matrix4d::Identity(); if (_continuous_type == IMAGE_CONTINUOUS) { pose = get_camera_to_world_pose() * _pose_camera2velo; } return pose; } std::vector<ObjectPtr> FrameContent::get_radar_objects() { std::map<double, RadarContent>::iterator it = _radar_caches.find(_current_radar_timestamp); if (it == _radar_caches.end()) { return std::vector<ObjectPtr>(); } RadarContent content = it->second; return content._radar_objects; } std::vector<ObjectPtr> FrameContent::get_camera_objects() { std::map<double, CameraContent>::iterator it = _camera_caches.find(_current_camera_timestamp); if (it == _camera_caches.end()) { return std::vector<ObjectPtr>(); } CameraContent content = it->second; return content._camera_objects; } CameraFrameSupplementPtr FrameContent::get_camera_frame_supplement() { std::map<double, CameraContent>::iterator it = _camera_caches.find(_current_camera_timestamp); if (it == _camera_caches.end()) { CameraFrameSupplementPtr supplement_ptr; supplement_ptr.reset(new CameraFrameSupplement); return supplement_ptr; } CameraContent content = it->second; return content._camera_frame_supplement; } double FrameContent::get_visualization_timestamp() { double timestamp = 0; if (_continuous_type == IMAGE_CONTINUOUS) { timestamp = _current_image_timestamp; } return timestamp; } std::vector<ObjectPtr> FrameContent::get_fused_objects() { std::map<double, FusionContent>::iterator it = _fusion_caches.find(_current_fusion_timestamp); if (it == _fusion_caches.end()) { return std::vector<ObjectPtr>(); } FusionContent content = it->second; return content._fused_objects; } std::vector<ObjectPtr> FrameContent::get_gt_objects() { std::map<double, GroundTruthContent>::iterator it = _gt_caches.find(_current_gt_timestamp); if (it == _gt_caches.end()) { return std::vector<ObjectPtr>(); } GroundTruthContent content = it->second; return content._gt_objects; } void FrameContent::offset_object(ObjectPtr object, const Eigen::Vector3d& offset) { object->center[0] += offset[0]; object->center[1] += offset[1]; object->center[2] += offset[2]; } } // namespace perception } // namespace apollo
31.698734
80
0.654101
fukatani
181fa7bc68e2ce079f2550f5cb168e0e9e8ceb6f
1,625
cpp
C++
cpgf/src/metadata/irrlicht/meta_irrlicht_S3DVertex.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
187
2015-01-19T06:05:30.000Z
2022-03-27T14:28:21.000Z
cpgf/src/metadata/irrlicht/meta_irrlicht_S3DVertex.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
37
2015-01-16T04:15:11.000Z
2020-03-31T23:42:55.000Z
cpgf/src/metadata/irrlicht/meta_irrlicht_S3DVertex.cpp
mousepawmedia/libdeps
b004d58d5b395ceaf9fdc993cfb00e91334a5d36
[ "BSD-3-Clause" ]
50
2015-01-13T13:50:10.000Z
2022-01-25T17:16:51.000Z
// Auto generated file, don't modify. #include "irrlicht.h" #include "S3DVertex.h" #include "cpgf/metadata/irrlicht/meta_irrlicht_S3DVertex.h" using namespace cpgf; namespace meta_irrlicht { GDefineMetaInfo createMetaClass_Global_s3dvertex() { GDefineMetaGlobalDangle _d = GDefineMetaGlobalDangle::dangle(); buildMetaClass_Global_s3dvertex(0, _d); return _d.getMetaInfo(); } GDefineMetaInfo createMetaClass_S3DVertex() { GDefineMetaGlobalDangle _d = GDefineMetaGlobalDangle::dangle(); { GDefineMetaClass<irr::video::S3DVertex> _nd = GDefineMetaClass<irr::video::S3DVertex>::declare("S3DVertex"); buildMetaClass_S3DVertex(0, _nd); _d._class(_nd); } return _d.getMetaInfo(); } GDefineMetaInfo createMetaClass_S3DVertex2TCoords() { GDefineMetaGlobalDangle _d = GDefineMetaGlobalDangle::dangle(); { GDefineMetaClass<irr::video::S3DVertex2TCoords, irr::video::S3DVertex> _nd = GDefineMetaClass<irr::video::S3DVertex2TCoords, irr::video::S3DVertex>::declare("S3DVertex2TCoords"); buildMetaClass_S3DVertex2TCoords(0, _nd); _d._class(_nd); } return _d.getMetaInfo(); } GDefineMetaInfo createMetaClass_S3DVertexTangents() { GDefineMetaGlobalDangle _d = GDefineMetaGlobalDangle::dangle(); { GDefineMetaClass<irr::video::S3DVertexTangents, irr::video::S3DVertex> _nd = GDefineMetaClass<irr::video::S3DVertexTangents, irr::video::S3DVertex>::declare("S3DVertexTangents"); buildMetaClass_S3DVertexTangents(0, _nd); _d._class(_nd); } return _d.getMetaInfo(); } } // namespace meta_irrlicht
27.083333
186
0.729846
mousepawmedia
1820eb9ae60047891661d8c8f9e02f9470c2d92a
1,520
hpp
C++
zooTycoon.hpp
bolym/C-ZooGame
33a66a4e7e3cccc731520471c2641cd8f901ae02
[ "MIT" ]
null
null
null
zooTycoon.hpp
bolym/C-ZooGame
33a66a4e7e3cccc731520471c2641cd8f901ae02
[ "MIT" ]
null
null
null
zooTycoon.hpp
bolym/C-ZooGame
33a66a4e7e3cccc731520471c2641cd8f901ae02
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> #include <stdio.h> /* printf, scanf, puts, NULL */ #include <stdlib.h> /* srand, rand */ #include <time.h> /* time */ using namespace std; class Animal{ protected: int age; int price; int numBabies; int foodCost; int revenue; public: Animal(); int getAge(); int getPrice(); int getNumBabies(); int getFoodCost(); int getRevenue(); void incrementAge(); }; class Sloth : public Animal { protected: public: Sloth(); Sloth(int days); }; class SeaOtter : public Animal { protected: public: SeaOtter(); SeaOtter(int days); }; class Monkey : public Animal { protected: public: Monkey(); Monkey(int days); }; class Zoo{ protected: int bankAccount; int numAnimals; int numMonkey; Monkey* monkeys; int numSeaOtter; SeaOtter* seaOtters; int numSloth; Sloth* sloths; int baseFoodCost; bool bankrupt; public: Zoo(); ~Zoo(); void displayGame(); void ageAnimals(); int checkInput(string question, string valid); void buyAnimal(); void addMonkey(int age); void addSeaOtter(int age); void addSloth(int age); void feedAnimals(); Animal* getRandAnimal(); void specialEvent(); void makeSick(); void makeBirth(); void makeBoom(); void makeRevenue(); void beginGame(); };
17.882353
56
0.576974
bolym
18218a4cb185430f140c18184eeea8088d3aea79
2,013
cpp
C++
torch/csrc/distributed/c10d/Ops.cpp
qqaatw/pytorch
44764f131b040a41a6dcf1304bb635c574bf5a3b
[ "Intel" ]
null
null
null
torch/csrc/distributed/c10d/Ops.cpp
qqaatw/pytorch
44764f131b040a41a6dcf1304bb635c574bf5a3b
[ "Intel" ]
null
null
null
torch/csrc/distributed/c10d/Ops.cpp
qqaatw/pytorch
44764f131b040a41a6dcf1304bb635c574bf5a3b
[ "Intel" ]
null
null
null
#include <torch/csrc/distributed/c10d/Ops.hpp> #include <ATen/core/dispatch/Dispatcher.h> #include <torch/library.h> namespace c10d { namespace { c10::intrusive_ptr<ProcessGroup::Work> broadcast( const c10::intrusive_ptr<ProcessGroup>& process_group, at::TensorList tensors, int64_t root_rank = 0, int64_t root_tensor = 0, int64_t timeout = -1) { auto tensor_vec = tensors.vec(); return process_group->broadcast( tensor_vec, BroadcastOptions{ root_rank, root_tensor, std::chrono::milliseconds(timeout)}); } TORCH_LIBRARY(c10d, m) { // The following ProcessGroup and Work definations are more like declarations. // They don't expose the details of the two classes into TorchScript. m.class_<ProcessGroup>("ProcessGroup").def(torch::init<int64_t, int64_t>()); m.class_<ProcessGroup::Work>("Work").def(torch::init<>()); // It's important to register the op to the CompositeExplicitAutograd key to // enable // __torch_dispatch__. m.def( "broadcast", dispatch(c10::DispatchKey::CompositeExplicitAutograd, broadcast)); } } // namespace namespace ops { c10::intrusive_ptr<ProcessGroup::Work> broadcast( const c10::intrusive_ptr<ProcessGroup>& process_group, at::TensorList tensors, const BroadcastOptions& opts) { auto op = c10::Dispatcher::singleton() .findSchemaOrThrow("c10d::broadcast", "") .typed<c10::intrusive_ptr<::c10d::ProcessGroup::Work>( const c10::intrusive_ptr<::c10d::ProcessGroup>&, at::TensorList, int64_t, int64_t, int64_t)>(); // It's awakward to unbox the opts here and box them again in the custom C++ // op. But it's also complicated to make opts as a CustomClassHolder. Leave it // as it is now. return op.call( process_group, tensors, opts.rootRank, opts.rootTensor, opts.timeout.count()); } } // namespace ops } // namespace c10d
32.467742
80
0.660209
qqaatw
18228eca0c71619b74e7395225bdc2da6e71e6d8
11,390
cpp
C++
src/stringarray.cpp
Sneedd/rush
a07eef74d1757f1995ea4f6ceafb7c328719f08d
[ "MIT" ]
null
null
null
src/stringarray.cpp
Sneedd/rush
a07eef74d1757f1995ea4f6ceafb7c328719f08d
[ "MIT" ]
null
null
null
src/stringarray.cpp
Sneedd/rush
a07eef74d1757f1995ea4f6ceafb7c328719f08d
[ "MIT" ]
null
null
null
/* * stringarray.cpp - Implementation of StringArray class * * This file is part of the rush utility library. * Licenced unter the terms of Lesser GPL v3.0 (see licence.txt). * Copyright 2011-2012 - Steffen Ott * */ #include <rush/stringarray.h> #include <rush/log.h> #include <rush/buildinexpect.h> #include <rush/macros.h> namespace rush { //----------------------------------------------------------------------------- StringArray::StringArray() /** * \brief Standardconstructor, initializes the StringArray object. * Initialcapacity is 16 strings. **/ { m_capacity = 16; m_count = 0; m_items = new String*[m_capacity]; memset(m_items, 0, m_capacity*sizeof(String*)); } //----------------------------------------------------------------------------- StringArray::StringArray(size_t capacity) /** * \brief Constructor, initializes the StringArray object with the * given capacity. * \param capacity Initial capacity of the array. **/ { if (unlikely(capacity < 4)) { capacity = 4; } m_capacity = capacity; m_count = 0; m_items = new String*[m_capacity]; memset(m_items, 0, m_capacity*sizeof(String*)); } //----------------------------------------------------------------------------- StringArray::StringArray(const StringArray& array) /** * \brief Copyconstructor, shallow copies the given array to this. * Note, that the copy will not contain copied strings, if you want a * full or deep copy, use Copy(). **/ { m_capacity = array.m_count; m_count = array.m_count; m_items = new String*[m_capacity]; m_items = (String**)memcpy(m_items, array.m_items, sizeof(String*)*m_capacity); } //----------------------------------------------------------------------------- StringArray::~StringArray() /** * \brief Destructor. Frees all allocated memory. **/ { if (likely(m_items != NULL)) { for (size_t i=0; i<m_count; ++i) { if (m_items[i] != NULL) { delete m_items[i]; } } delete [] m_items; } } //----------------------------------------------------------------------------- StringArray& StringArray::operator=(const StringArray& array) /** * \brief Assigment operator, copies the given array to this. * \param array String array to copy into this array. * \return This array. **/ { if (likely(m_items != NULL)) { for (size_t i=0; i<m_count; ++i) { if (m_items[i] != NULL) { delete m_items[i]; m_items[i] = NULL; } } delete [] m_items; } m_capacity = array.m_count; m_count = array.m_count; m_items = new String*[m_capacity]; for (size_t i=0; i<m_capacity; ++i) { m_items[i] = new String(*(array.m_items[i])); } return (*this); } //----------------------------------------------------------------------------- String& StringArray::operator[](size_t index) /** * \brief Returns the string at the given index. * \param index Index. * \return String at the index. **/ { if (unlikely(index >= m_count)) { Log::Error(_T("[StringArray::operator[]] Index out of range.")); return (*m_items[index]); } return (*m_items[index]); } //----------------------------------------------------------------------------- const String& StringArray::operator[](size_t index) const /** * \brief Returns the string at the given index. * \param index Index. * \return String at the index. **/ { if (unlikely(index >= m_count)) { Log::Error(_T("[StringArray::operator[]] Index out of range.")); return (*m_items[index]); } return (*m_items[index]); } //----------------------------------------------------------------------------- String& StringArray::Item(size_t index) /** * \brief Returns the string at the given index. * \param index Index. * \return String at the index. **/ { if (unlikely(index >= m_count)) { Log::Error(_T("[StringArray::operator[]] Index out of range.")); return (*m_items[index]); } return (*m_items[index]); } //----------------------------------------------------------------------------- const String& StringArray::Item(size_t index) const /** * \brief Returns the string at the given index. * \param index Index. * \return String at the index. **/ { if (unlikely(index >= m_count)) { Log::Error(_T("[StringArray::operator[]] Index out of range.")); return (*m_items[index]); } return (*m_items[index]); } //----------------------------------------------------------------------------- int StringArray::IndexOf(const String& strg) const /** * \brief Searches for a string in the array and returning its index. * \param strg String to search for. * \return Index in the array or -1 if the string is not in the array. **/ { for (size_t i=0; i<m_count; ++i) { if (m_items[i] != NULL) { if (*(m_items[i]) == strg) { return (i); } } } return (-1); } //----------------------------------------------------------------------------- StringArray& StringArray::Add(const String& strg) /** * \brief Adds a string to the array. * \param strg String. * \return This array. **/ { if (unlikely(m_count >= m_capacity)) { this->Alloc(m_capacity*2); } m_items[m_count] = new String(strg); m_count++; return (*this); } //----------------------------------------------------------------------------- StringArray& StringArray::AddFormat(const String& format, ...) /** * \brief Adds a formated string to the array. See printf() for format options. * \param format Format string. * \return This array. **/ { va_list args; va_start(args,format); this->Add(String::FormatV(format, args)); return (*this); } //----------------------------------------------------------------------------- bool StringArray::Insert(size_t index, const String& strg) /** * \brief Inserts a string at the given index. * \param index Index. * \param strg String. * \return True, if string was successful inserted; otherwise false. **/ { if (unlikely(index > m_count)) { Log::Error(_T("[PrimitiveArray::Insert] Index out of range.")); return (false); } if (unlikely(index == m_count)) { this->Add(strg); return (true); } if (unlikely(m_capacity <= m_count)) { this->Alloc(m_capacity*2); } memmove(m_items+index+1, m_items+index, (m_count-index)*sizeof(String*)); m_items[index] = new String(strg); m_count++; return (true); } //----------------------------------------------------------------------------- bool StringArray::Remove(size_t index) /** * \brief Removes a string from the given index. * \param index Index. * \return True, if string was successful removed; otherwise false. **/ { if (unlikely(index >= m_count)) { Log::Error(_T("[PrimitiveArray::Remove] Index out of range.")); return (false); } if (m_items[index] != NULL) { delete m_items[index]; } m_items[index] = NULL; memmove(m_items+index, m_items+index+1, (m_count-index)*sizeof(String*)); m_count--; return (true); } //----------------------------------------------------------------------------- void StringArray::Clear() /** * \brief Clears the array and eventually reduces capacity. * Reduces capacity only if the current capacity is bigger than 64. **/ { // Shrinks the array if capacity is to big if (unlikely(m_capacity > 64)) { this->Alloc(64); } // Free allocated memory for (size_t i=0; i<m_count; ++i) { if (m_items[i] != NULL) { delete m_items[i]; m_items[i] = NULL; } } // Empties array m_count = 0; } //----------------------------------------------------------------------------- void StringArray::Shrink() /** * \brief Shrinks the capacity to the number of strings in the array. **/ { this->Alloc(m_count); } //----------------------------------------------------------------------------- void StringArray::Alloc(size_t capacity) /** * \brief Allocates the array capacity, can extend or shrink the array. * \param capacity Capacity. **/ { if (unlikely(capacity < 4)) { capacity = 4; } if (likely(capacity > m_capacity)) { // Extend array String** temp = new String*[capacity]; temp = (String**)memcpy(temp, m_items, m_capacity*sizeof(String*)); delete [] m_items; m_items = temp; m_capacity = capacity; } else { if (likely(capacity != m_capacity)) { // Shrink array String** temp = new String*[capacity]; memcpy(temp, m_items, capacity*sizeof(String*)); for (size_t i=capacity; i<m_count; ++i) { if (m_items[i] != NULL) { delete m_items[i]; // Free dropping objects } } delete [] m_items; m_items = temp; m_capacity = capacity; m_count = ((m_count < capacity) ? m_count:capacity); } } } //----------------------------------------------------------------------------- StringArray* StringArray::Split(const String& strg, const String& separator, StringSplitOptions options) /** * \brief Splits a string with the given separator by the given options. * Note: The returning string array must be destroyed by the caller. * \param strg The string which should be splitted. * \param separator The separator string. * \param options The split options. * \return String array with the splitted strings. **/ { StringArray* array = new StringArray(); String split = _T(""); for (size_t index=0; index<strg.Length(); ++index) { if (strg[index] == separator[0]) { bool endString = true; for (size_t i=1; i<separator.Length(); ++i) { if (strg[index+i] != separator[i]) { endString = false; break; } if (separator.Length()-1 <= i) { break; } } if (endString) { index += separator.Length()-1; if ((options & StringSplitOptions::Trim) == StringSplitOptions::Trim) { split.Trim(); } if ((options & StringSplitOptions::RemoveEmptyEntries) == StringSplitOptions::RemoveEmptyEntries) { if (split.Length() > 0) array->Add(split); } else { array->Add(split); } split.Clear(); } else { split.Append(strg[index]); } } else { split.Append(strg[index]); } } if ((options & StringSplitOptions::Trim) == StringSplitOptions::Trim) { split.Trim(); } if ((options & StringSplitOptions::RemoveEmptyEntries) == StringSplitOptions::RemoveEmptyEntries) { if (split.Length() > 0) array->Add(split); } else { array->Add(split); } array->Shrink(); return (array); } } // namespace rush
25.311111
115
0.502809
Sneedd
182c4afc4644b7470626e4dda738c6446a7e2cd2
4,547
cpp
C++
C/Lista03.cpp
IzaacBaptista/ads-senac
2a2fe89a88e2ac5a776302f464695e2537c2cd69
[ "MIT" ]
2
2021-03-14T13:27:28.000Z
2021-09-29T19:09:37.000Z
C/Lista03.cpp
IzaacBaptista/ads-senac
2a2fe89a88e2ac5a776302f464695e2537c2cd69
[ "MIT" ]
null
null
null
C/Lista03.cpp
IzaacBaptista/ads-senac
2a2fe89a88e2ac5a776302f464695e2537c2cd69
[ "MIT" ]
null
null
null
// ************************************************************ // // Exemplo de Estruturas Encadeadas // // ************************************************************ #include <stdio.h> #include <string.h> #include <conio.h> #include <stdlib.h> // define a estrutura do nodo typedef struct Temp { int info; struct Temp *prox; }TNODO; // cria o inicio da lista TNODO *inicio=NULL; //-------------------------------------------------------- // Funcao que define a lista como vazia. void CriaLista() { inicio = NULL; } //-------------------------------------------------------- // Funcao que insere um elemento do inicio da lista. // Retorna: // 0 - se nao ha' memoria para inserir // 1 - se conseguiu inserir int Insere(int dado) { TNODO *p; p = (TNODO *) malloc(sizeof(TNODO)); if (p==NULL) { printf("Erro de alocacao\n"); return 0; } p->info = dado; p->prox = NULL; if (inicio==NULL) inicio = p; else { p->prox = inicio; inicio = p; } return 1; } //-------------------------------------------------------- // Funcao que remove um elemento do inicio da lista. // Retorna: // 0 - se a lista ja' estava vazia // 1 - se conseguiu remover int RemoveDoInicio() { TNODO *ptr; if (inicio==NULL) return 0; else { ptr = inicio; inicio = inicio->prox; free(ptr); return 1; } } //-------------------------------------------------------- // Funcao que imprime toda a lista. // void Imprime() { TNODO *ptr; if (inicio == NULL) { printf("--- fim da lista ---\n\n"); return; } // Caso a lista nao esteja vazia ptr = inicio; while (ptr !=NULL) { printf("Info = %d\n",ptr->info); ptr = ptr->prox; } printf("--- fim da lista ---\n\n"); } //-------------------------------------------------------- // Funcao que busca um elemento na lista. // Retorna: // - NULL caso nao encontre // - ponteiro para o NODO onde esta' o dado, se conseguir encontrar TNODO *BuscaDado(int dado) { TNODO *ptr; if (inicio == NULL) { return NULL; // Lista Vazia } // Caso a lista nao esteja vazia ptr = inicio; while (ptr !=NULL) { if (ptr->info == dado) // achou !! return (ptr); // retorna um ponteiro para //o inicio da lista else ptr = ptr->prox; } return NULL; } //-------------------------------------------------------- // Funcao que remove um elemento especificado por 'dado' // Retorna: // 0 - se nao conseguiu achar // 1 - se conseguiu remover int RemoveDado(int dado) { TNODO *ptr, *antes; if (inicio==NULL) { return 0; // Lista vazia !!! } else { // Caso a lista nao esteja vazia ptr = inicio; antes = inicio; while (ptr !=NULL) { if (ptr->info == dado) // achou !! { if (ptr == inicio) // se esta removendo o primeiro da lista { inicio = inicio->prox; free(ptr); return 1; // removeu !! } else // esta removendo do meio da lista { antes->prox = ptr->prox; // Refaz o encadeamento free(ptr); // Libera a area do nodo return 1; // removeu !! } } else // continua procurando no prox. nodo { antes = ptr; ptr = ptr->prox; } } return 0; // Nao achou !!! } } //-------------------------------------------------- main() { int i, ret; TNODO *aux; CriaLista(); // Insere na lista os numeros 2, 4, 6, 8, 10, 12, 14, 16, 18 e 20 for (i=1; i<=10;i++) Insere(i*2); Imprime(); getch(); // Busca dados de -2 a 25 for (i=-2; i<=25;i++) { aux = BuscaDado(i); if (aux != NULL) printf("+++Achou o %d\n", aux->info); else printf("---Nao achou o %d\n", i); } getch(); printf("Antes da remocao do primeiro nodo\n"); Imprime(); printf("Apos a remocao dos dois primeiros nodos\n"); // Remove os dois primeiros nodos RemoveDoInicio(); RemoveDoInicio(); Imprime(); getch(); // Remove um elemento do meio da lista // Tenta remover -3, 0, 3, 6, 9, 12, 15, 18, 21 printf("Remocao no meio da lista\n"); for (i=-3; i<=21;i+=3) { ret = RemoveDado(i); if (ret == 1) printf("+++Removeu o %d\n",i); else printf("---Nao achou o %d\n", i); } printf("Apos a remocao\n"); Imprime(); getch(); // Remove Toda a Lista ret = 1; while (ret == 1) { ret = RemoveDoInicio(); } printf("Apos a remocao de todos os nodos\n"); Imprime(); getch(); }
22.509901
68
0.485155
IzaacBaptista
1836e4e72fea2754d0112fa86bd8af8e9ab6e35b
13,095
hpp
C++
sources/SceneGraph/spSceneLight.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/SceneGraph/spSceneLight.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/SceneGraph/spSceneLight.hpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2016-10-31T06:08:44.000Z
2019-08-02T16:12:33.000Z
/* * Light scene node header * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #ifndef __SP_SCENE_LIGHT_H__ #define __SP_SCENE_LIGHT_H__ #include "Base/spStandard.hpp" #include "Base/spDimensionMatrix4.hpp" #include "SceneGraph/spRenderNode.hpp" namespace sp { namespace scene { /* * Macros */ static const s32 MAX_COUNT_OF_SCENELIGHTS = 0x0D31; class SceneGraph; /* * Structures */ /* Light attenuation configuration structure. \since Version 3.3 */ struct SLightAttenuation { SLightAttenuation(f32 Cnst = 1.0f, f32 Lin = 0.1f, f32 Quad = 0.4f) : Constant (Cnst ), Linear (Lin ), Quadratic (Quad ) { } ~SLightAttenuation() { } /* Functions */ inline void setRadius(f32 Radius) { if (Radius > math::ROUNDING_ERROR) { Constant = 1.0f; Linear = 1.0f / Radius; Quadratic = 1.0f / Radius; } } inline f32 getRadius() const { return 1.0f / Linear; } /* Members */ f32 Constant; f32 Linear; f32 Quadratic; }; /** Spot light cone structure. It contains the inner and outer cone angles. \since Version 3.3 */ struct SP_EXPORT SLightCone { SLightCone(f32 Inner = 30.0f, f32 Outer = 60.0f) : InnerAngle(Inner), OuterAngle(Outer) { } ~SLightCone() { } /* Members */ f32 InnerAngle; f32 OuterAngle; }; /** Light color structured. It contains an ambient, a diffuse and a specular color. \since Version 3.3 */ struct SLightColor { SLightColor( const video::color &Ambt = 255, const video::color &Diff = 200, const video::color Spec = 0) : Ambient (Ambt), Diffuse (Diff), Specular(Spec) { } ~SLightColor() { } /* Members */ video::color Ambient; video::color Diffuse; video::color Specular; }; /** Lights can be created for dynamic lighting and shading technics. But you will only see a maximum of 8 lights because more are not supported by the current graphics cards! But you can create much more then 8. But be aware of that you will only see 8 of them ;-). The engine is able to manage the lighting system good enough that these ones who are near by the camera will be visible. Directional lights (scene::LIGHT_DIRECTIONAL) have a priority in this sort process because they are never volumetric but endless visible. */ class SP_EXPORT Light : public SceneNode { public: Light(const ELightModels Type = LIGHT_DIRECTIONAL); virtual ~Light(); /* === Functions === */ /** Sets the new light color. \see SLightColor \since Version 3.3 */ void setColor(const SLightColor &Color); /** Sets the light's colors. \param Diffuse: Diffuse color. This is the 'main' lighting color which is multiplied by each vertex's color. \param Ambient: Ambient color. This is the darkest color. Also if the color is full bright it will not let the object be complete white. \param Specular: Specular color. If this color is not bright enough each shininess value for the Entity objects will not cause any shine. \depreacted Use setColor instead. */ void setLightingColor(const video::color &Diffuse, const video::color &Ambient = 255, const video::color &Specular = 0); //! \deprecated Use "getColor" instead. void getLightingColor(video::color &Diffuse, video::color &Ambient, video::color &Specular) const; //! \deprecated Use the new "setSpotCone" function instead. void setSpotCone(const f32 InnerConeAngle, const f32 OuterConeAngle); //! \deprecated Use the new "getSpotCone" function instead. void getSpotCone(f32 &InnerConeAngle, f32 &OuterConeAngle) const; void setSpotConeInner(f32 Angle); void setSpotConeOuter(f32 Angle); /** Sets the new spot light cone angles. \see SLightCone \since Version 3.3 */ void setSpotCone(const SLightCone &SpotCone); /** Returns a view frustum if this is a spot light. \param[out] Frustum Specifies the resulting view frustum. Although the spot light is actual a cone, the resulting model is a frustum which can be used to render a shadow map from the light's point of view. \param[out] GlobalPosition Specifies the global position which can be computed on the fly. This can be used for frustum/frustum culling tests. \return True if the frustum could be computed. This requires that this light is a spot light. Otherwise false. */ bool getSpotFrustum(scene::ViewFrustum &Frustum, dim::vector3df &GlobalPosition) const; /** Enables or disables the volumetric technic for lighting. This technic is only usable when the light is a Point or a Spot light. Three parameters called "Attenuation" are used for this computation. */ void setVolumetric(bool IsVolumetric); /** Sets the volumetric radius. This function computes the threee attenuation parameters automatically by only one value: the Radius. */ void setVolumetricRadius(f32 Radius); f32 getVolumetricRadius() const; /** Sets the volumetric range or the three attenuation values. Here you have to compute your own attenuations. \deprecated Use "setAttenuation" instead. */ void setVolumetricRange(f32 Constant, f32 Linear, f32 Quadratic); //! \deprecated Use "getAttenuation" instead. void getVolumetricRange(f32 &Constant, f32 &Linear, f32 &Quadratic) const; //! Sets the light's direction. Only usable for Directional or Spot lights. void setDirection(const dim::vector3df &Direction); void setDirection(const dim::matrix4f &Matrix); //! Enables or disables the light void setVisible(bool isVisible); //! Copies the light objects and returns the pointer to the new instance. Don't forget to delete this object! Light* copy() const; /** Updates the light. This function is called in the "renderScene" function of the SceneManager class. You do not have to call this function. */ virtual void render(); /* === Static functions === */ /** Sets the render-context usage for fixed-function light sources. \param[in] UseAllRCs Specifies whether all render-contexts are to be used or only the active one. By default all render contexts are affected. \note Disable this state when you change light states (color, visiblity etc.) every frame and you have several render contexts! */ static void setRCUsage(bool UseAllRCs); /* === Inline functions === */ //! Sets the light shading model. inline void setLightModel(const ELightModels Type) { LightModel_ = Type; } //! Returns the light shading model. inline ELightModels getLightModel() const { return LightModel_; } //! Sets the diffuse light color. inline void setDiffuseColor(const video::color &Color) { setLightingColor(Color, Color_.Ambient, Color_.Specular); } //! Returns the diffuse light color. inline const video::color& getDiffuseColor() const { return Color_.Diffuse; } //! Sets the ambient light color. inline void setAmbientColor(const video::color &Color) { setLightingColor(Color_.Diffuse, Color, Color_.Specular); } //! Returns the ambient light color. inline const video::color& getAmbientColor() const { return Color_.Ambient; } //! Sets the specular light color. inline void setSpecularColor(const video::color &Color) { setLightingColor(Color_.Diffuse, Color_.Ambient, Color); } //! Returns the specular light color. inline const video::color& getSpecularColor() const { return Color_.Specular; } /** Returns the light color \see SLightColor \since Version 3.3 */ inline const SLightColor& getColor() const { return Color_; } /** Sets the new light attenuation settings. \see SLightAttenuation \since Version 3.3 */ inline void setAttenuation(const SLightAttenuation &Attn) { Attn_ = Attn; } /** Returns the light attenuation settings \see SLightAttenuation \since Version 3.3 */ inline const SLightAttenuation& getAttenuation() const { return Attn_; } /** Returns the spot light cone angles. \see SLightCone \since Version 3.3 */ inline const SLightCone& getSpotCone() const { return SpotCone_; } /** Returns the inner spot cone angle (in degrees). \deprecated Use getSpotCone() instead. */ inline f32 getSpotConeInner() const { return SpotCone_.InnerAngle; } /** Returns the outer spot cone angle (in degrees). \deprecated Use getSpotCone() instead. */ inline f32 getSpotConeOuter() const { return SpotCone_.OuterAngle; } //! Returns true if this is a volumetric light. By default false. inline bool getVolumetric() const { return IsVolumetric_; } /** Enables or disables shadow mapping. \param[in] Enable Specifies whether shadow mapping is to be enabled or disabled for this light source. By default false. \note This can only be used in combination with the integrated advanced-renderer. \see video::AdvancedRenderer \since Version 3.2 */ inline void setShadow(bool Enable) { IsShadowMapping_ = Enable; } /** Returns true if shadow mapping is enabled for this light source. \since Version 3.2 */ inline bool getShadow() const { return IsShadowMapping_; } /** Enables or disables global illumiation. \param[in] Enable Specifies whether global illumination is to be enabled or disabled for this light source. By default false. \note This can only be used in combination with the integrated advanced-renderer. \see video::AdvancedRenderer \since Version 3.3 */ inline void setGlobalIllumination(bool Enable) { IsGlobalIllumination_ = Enable; } //! Returns true if global illumination is enabled for this light source. inline bool getGlobalIllumination() const { return IsGlobalIllumination_; } //! Returns the light's direction. This is only used for spot- and directional lights (LIGHT_SPOT, LIGHT_DIRECTIONAL). inline dim::vector3df getDirection() const { return Direction_; } //! Returns the projection matrix. This is only used for spot-lights (LIGHT_SPOT). inline dim::matrix4f getProjectionMatrix() const { return ProjectionMatrix_; } protected: friend class SceneGraph; /* === Members ===*/ u32 LightID_; //!< Renderer ID number for this light. ELightModels LightModel_; //!< Lighting model: Directional, Point, Spot. SLightColor Color_; //!< Light color (ambient, diffuse, specular). dim::vector3df Direction_; //!< Spot- and directional light direction. SLightCone SpotCone_; //!< Spot light cone angles. dim::matrix4f ProjectionMatrix_; bool IsVolumetric_; bool IsShadowMapping_; bool IsGlobalIllumination_; SLightAttenuation Attn_; private: /* === Functions === */ void registerLight(); void updateProjectionMatrix(); /* === Members === */ static bool UseAllRCs_; }; } // /namespace scene } // /namespace sp #endif // ================================================================================
30.524476
133
0.590302
rontrek
183c6be741a29cfb8f63fcca438f17b13b8c0a19
5,340
cpp
C++
src/chrono_sensor/ChDynamicsManager.cpp
zzhou292/chrono-collision
c2a20e171bb0eb8819636d370887aa32d68547c6
[ "BSD-3-Clause" ]
3
2019-01-15T07:40:33.000Z
2019-01-15T09:16:45.000Z
src/chrono_sensor/ChDynamicsManager.cpp
zzhou292/chrono-collision
c2a20e171bb0eb8819636d370887aa32d68547c6
[ "BSD-3-Clause" ]
7
2021-10-20T04:43:35.000Z
2021-12-24T08:44:31.000Z
src/chrono_sensor/ChDynamicsManager.cpp
zzhou292/chrono-collision
c2a20e171bb0eb8819636d370887aa32d68547c6
[ "BSD-3-Clause" ]
2
2021-12-09T05:32:31.000Z
2021-12-12T17:31:18.000Z
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2019 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Asher Elmquist // ============================================================================= // // Class for managing the Optix rendering system // // ============================================================================= #include "chrono_sensor/ChDynamicsManager.h" #include <iomanip> #include <iostream> namespace chrono { namespace sensor { CH_SENSOR_API ChDynamicsManager::ChDynamicsManager(ChSystem* chrono_system) { // save the chrono system handle m_system = chrono_system; } CH_SENSOR_API ChDynamicsManager::~ChDynamicsManager() {} CH_SENSOR_API void ChDynamicsManager::UpdateSensors() { // update the GPS sensors (sometimes perform the update, but always pack the keyframe) for (int i = 0; i < m_gps_list.size(); i++) { auto pGPS = m_gps_list[i]; if (m_system->GetChTime() > pGPS->GetNumLaunches() / pGPS->GetUpdateRate() - 1e-7) { ChVector<double> pos_data = pGPS->GetParent()->TransformPointLocalToParent(pGPS->GetOffsetPose().GetPos()); m_gps_collection_data[i].push_back( std::make_tuple((float)pGPS->GetParent()->GetSystem()->GetChTime(), pos_data)); if (m_system->GetChTime() > pGPS->GetNumLaunches() / pGPS->GetUpdateRate() + pGPS->GetCollectionWindow() - 1e-7) { pGPS->gps_key_frames = m_gps_collection_data[i]; std::shared_ptr<SensorBuffer> buffer; pGPS->IncrementNumLaunches(); // step through the filter list, applying each filter for (auto filter : pGPS->GetFilterList()) { filter->Apply(pGPS, buffer); } // clear the keyframes for this gps m_gps_collection_data[i].clear(); } } } // update the IMU sensors (sometimes perform the update, but always pack the keyframe) for (int i = 0; i < m_imu_list.size(); i++) { auto pIMU = m_imu_list[i]; if (m_system->GetChTime() > pIMU->GetNumLaunches() / pIMU->GetUpdateRate() - 1e-7) { ChVector<float> tran_acc_no_offset = pIMU->GetParent()->PointAccelerationLocalToParent(pIMU->GetOffsetPose().GetPos()); ChVector<float> tran_acc_offset = -pIMU->GetParent()->GetSystem()->Get_G_acc(); tran_acc_offset = pIMU->GetParent()->GetRot().Rotate(tran_acc_offset); ChVector<float> tran_acc = tran_acc_no_offset + tran_acc_offset; ChVector<float> ang_vel = pIMU->GetParent()->GetWvel_loc(); m_imu_collection_data[i].push_back(std::make_tuple(ang_vel, tran_acc)); if (m_system->GetChTime() > pIMU->GetNumLaunches() / pIMU->GetUpdateRate() + pIMU->GetCollectionWindow() - 1e-7) { pIMU->imu_key_frames = m_imu_collection_data[i]; std::shared_ptr<SensorBuffer> buffer; pIMU->IncrementNumLaunches(); // step through the filter list, applying each filter for (auto filter : pIMU->GetFilterList()) { filter->Apply(pIMU, buffer); } // clear the keyframes for this gps m_imu_collection_data[i].clear(); } } } } CH_SENSOR_API void ChDynamicsManager::AssignSensor(std::shared_ptr<ChSensor> sensor) { if (auto gps = std::dynamic_pointer_cast<ChGPSSensor>(sensor)) { // check if sensor is already in sensor list if (std::find(m_gps_list.begin(), m_gps_list.end(), gps) != m_gps_list.end()) { std::cerr << "WARNING: This GPS Sensor already exists in manager. Ignoring this addition\n"; return; } // add a GPS sensor m_gps_list.push_back(gps); for (auto f : gps->GetFilterList()) { f->Initialize(gps); } gps->LockFilterList(); m_gps_collection_data.push_back(std::vector<std::tuple<float, ChVector<double>>>()); } else if (auto imu = std::dynamic_pointer_cast<ChIMUSensor>(sensor)) { // check if sensor is already in sensor list if (std::find(m_imu_list.begin(), m_imu_list.end(), imu) != m_imu_list.end()) { std::cerr << "WARNING: This IMU Sensor already exists in manager. Ignoring this addition\n"; return; } // add an IMU sensor m_imu_list.push_back(imu); for (auto f : imu->GetFilterList()) { f->Initialize(imu); } imu->LockFilterList(); m_imu_collection_data.push_back(std::vector<std::tuple<ChVector<float>, ChVector<float>>>()); // m_imu_collection_data.push_back(std::vector<ChVector>()); } else { std::cerr << "WARNING: unsupported sensor type found in the dynamic sensor manager. Ignoring...\n"; } } } // namespace sensor } // namespace chrono
42.047244
119
0.578464
zzhou292
183e2f5aa8fd7cc021abe41fa99f9a56e5d21454
8,822
cc
C++
chrome/browser/sync/glue/bookmark_model_worker_unittest.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
chrome/browser/sync/glue/bookmark_model_worker_unittest.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/sync/glue/bookmark_model_worker_unittest.cc
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/thread.h" #include "chrome/browser/sync/engine/syncapi.h" #include "chrome/browser/sync/glue/bookmark_model_worker.h" #include "testing/gtest/include/gtest/gtest.h" using browser_sync::BookmarkModelWorker; using namespace sync_api; // Various boilerplate, primarily for the StopWithPendingWork test. class BookmarkModelWorkerVisitor : public ModelSafeWorkerInterface::Visitor { public: BookmarkModelWorkerVisitor(MessageLoop* faux_ui_loop, base::WaitableEvent* was_run, bool quit_loop) : faux_ui_loop_(faux_ui_loop), quit_loop_when_run_(quit_loop), was_run_(was_run) { } virtual ~BookmarkModelWorkerVisitor() { } virtual void DoWork() { EXPECT_EQ(MessageLoop::current(), faux_ui_loop_); was_run_->Signal(); if (quit_loop_when_run_) MessageLoop::current()->Quit(); } private: MessageLoop* faux_ui_loop_; bool quit_loop_when_run_; base::WaitableEvent* was_run_; DISALLOW_COPY_AND_ASSIGN(BookmarkModelWorkerVisitor); }; // A faux-syncer that only interacts with its model safe worker. class Syncer { public: explicit Syncer(BookmarkModelWorker* worker) : worker_(worker) {} ~Syncer() {} void SyncShare(BookmarkModelWorkerVisitor* visitor) { worker_->CallDoWorkFromModelSafeThreadAndWait(visitor); } private: BookmarkModelWorker* worker_; DISALLOW_COPY_AND_ASSIGN(Syncer); }; // A task run from the SyncerThread to "sync share", ie tell the Syncer to // ask it's ModelSafeWorker to do something. class FakeSyncShareTask : public Task { public: FakeSyncShareTask(Syncer* syncer, BookmarkModelWorkerVisitor* visitor) : syncer_(syncer), visitor_(visitor) { } virtual void Run() { syncer_->SyncShare(visitor_); } private: Syncer* syncer_; BookmarkModelWorkerVisitor* visitor_; DISALLOW_COPY_AND_ASSIGN(FakeSyncShareTask); }; // A task run from the CoreThread to simulate terminating syncapi. class FakeSyncapiShutdownTask : public Task { public: FakeSyncapiShutdownTask(base::Thread* syncer_thread, BookmarkModelWorker* worker, base::WaitableEvent** jobs, size_t job_count) : syncer_thread_(syncer_thread), worker_(worker), jobs_(jobs), job_count_(job_count), all_jobs_done_(false, false) { } virtual void Run() { // In real life, we would try and close a sync directory, which would // result in the syncer calling it's own destructor, which results in // the SyncerThread::HaltSyncer being called, which sets the // syncer in RequestEarlyExit mode and waits until the Syncer finishes // SyncShare to remove the syncer from it's watch. Here we just manually // wait until all outstanding jobs are done to simulate what happens in // SyncerThread::HaltSyncer. all_jobs_done_.WaitMany(jobs_, job_count_); // These two calls are made from SyncBackendHost::Core::DoShutdown. syncer_thread_->Stop(); worker_->OnSyncerShutdownComplete(); } private: base::Thread* syncer_thread_; BookmarkModelWorker* worker_; base::WaitableEvent** jobs_; size_t job_count_; base::WaitableEvent all_jobs_done_; DISALLOW_COPY_AND_ASSIGN(FakeSyncapiShutdownTask); }; class BookmarkModelWorkerTest : public testing::Test { public: BookmarkModelWorkerTest() : faux_syncer_thread_("FauxSyncerThread"), faux_core_thread_("FauxCoreThread") { } virtual void SetUp() { faux_syncer_thread_.Start(); bmw_.reset(new BookmarkModelWorker(&faux_ui_loop_)); syncer_.reset(new Syncer(bmw_.get())); } Syncer* syncer() { return syncer_.get(); } BookmarkModelWorker* bmw() { return bmw_.get(); } base::Thread* core_thread() { return &faux_core_thread_; } base::Thread* syncer_thread() { return &faux_syncer_thread_; } MessageLoop* ui_loop() { return &faux_ui_loop_; } private: MessageLoop faux_ui_loop_; base::Thread faux_syncer_thread_; base::Thread faux_core_thread_; scoped_ptr<BookmarkModelWorker> bmw_; scoped_ptr<Syncer> syncer_; }; TEST_F(BookmarkModelWorkerTest, ScheduledWorkRunsOnUILoop) { base::WaitableEvent v_was_run(false, false); scoped_ptr<BookmarkModelWorkerVisitor> v( new BookmarkModelWorkerVisitor(ui_loop(), &v_was_run, true)); syncer_thread()->message_loop()->PostTask(FROM_HERE, new FakeSyncShareTask(syncer(), v.get())); // We are on the UI thread, so run our loop to process the // (hopefully) scheduled task from a SyncShare invocation. MessageLoop::current()->Run(); bmw()->OnSyncerShutdownComplete(); bmw()->Stop(); syncer_thread()->Stop(); } TEST_F(BookmarkModelWorkerTest, StopWithPendingWork) { // What we want to set up is the following: // ("ui_thread" is the thread we are currently executing on) // 1 - simulate the user shutting down the browser, and the ui thread needing // to terminate the core thread. // 2 - the core thread is where the syncapi is accessed from, and so it needs // to shut down the SyncerThread. // 3 - the syncer is waiting on the BookmarkModelWorker to // perform a task for it. // The BookmarkModelWorker's manual shutdown pump will save the day, as the // UI thread is not actually trying to join() the core thread, it is merely // waiting for the SyncerThread to give it work or to finish. After that, it // will join the core thread which should succeed as the SyncerThread has left // the building. Unfortunately this test as written is not provably decidable, // as it will always halt on success, but it may not on failure (namely if // the task scheduled by the Syncer is _never_ run). core_thread()->Start(); base::WaitableEvent v_ran(false, false); scoped_ptr<BookmarkModelWorkerVisitor> v(new BookmarkModelWorkerVisitor( ui_loop(), &v_ran, false)); base::WaitableEvent* jobs[] = { &v_ran }; // The current message loop is not running, so queue a task to cause // BookmarkModelWorker::Stop() to play a crucial role. See comment below. syncer_thread()->message_loop()->PostTask(FROM_HERE, new FakeSyncShareTask(syncer(), v.get())); // This is what gets the core_thread blocked on the syncer_thread. core_thread()->message_loop()->PostTask(FROM_HERE, new FakeSyncapiShutdownTask(syncer_thread(), bmw(), jobs, 1)); // This is what gets the UI thread blocked until NotifyExitRequested, // which is called when FakeSyncapiShutdownTask runs and deletes the syncer. bmw()->Stop(); EXPECT_FALSE(syncer_thread()->IsRunning()); core_thread()->Stop(); } TEST_F(BookmarkModelWorkerTest, HypotheticalManualPumpFlooding) { // This situation should not happen in real life because the Syncer should // never send more than one CallDoWork notification after early_exit_requested // has been set, but our BookmarkModelWorker is built to handle this case // nonetheless. It may be needed in the future, and since we support it and // it is not actually exercised in the wild this test is essential. // It is identical to above except we schedule more than one visitor. core_thread()->Start(); // Our ammunition. base::WaitableEvent fox1_ran(false, false); scoped_ptr<BookmarkModelWorkerVisitor> fox1(new BookmarkModelWorkerVisitor( ui_loop(), &fox1_ran, false)); base::WaitableEvent fox2_ran(false, false); scoped_ptr<BookmarkModelWorkerVisitor> fox2(new BookmarkModelWorkerVisitor( ui_loop(), &fox2_ran, false)); base::WaitableEvent fox3_ran(false, false); scoped_ptr<BookmarkModelWorkerVisitor> fox3(new BookmarkModelWorkerVisitor( ui_loop(), &fox3_ran, false)); base::WaitableEvent* jobs[] = { &fox1_ran, &fox2_ran, &fox3_ran }; // The current message loop is not running, so queue a task to cause // BookmarkModelWorker::Stop() to play a crucial role. See comment below. syncer_thread()->message_loop()->PostTask(FROM_HERE, new FakeSyncShareTask(syncer(), fox1.get())); syncer_thread()->message_loop()->PostTask(FROM_HERE, new FakeSyncShareTask(syncer(), fox2.get())); // This is what gets the core_thread blocked on the syncer_thread. core_thread()->message_loop()->PostTask(FROM_HERE, new FakeSyncapiShutdownTask(syncer_thread(), bmw(), jobs, 3)); syncer_thread()->message_loop()->PostTask(FROM_HERE, new FakeSyncShareTask(syncer(), fox3.get())); // This is what gets the UI thread blocked until NotifyExitRequested, // which is called when FakeSyncapiShutdownTask runs and deletes the syncer. bmw()->Stop(); // Was the thread killed? EXPECT_FALSE(syncer_thread()->IsRunning()); core_thread()->Stop(); }
39.738739
80
0.726026
rwatson
1842df48aab0e75398e4ea449f3a5329268189d3
388
cpp
C++
if.cpp
yanfeng1012/CPlusPlusProgramList
16dae9ece99407e2213b82bf6910202f07a4b6a3
[ "Apache-2.0" ]
null
null
null
if.cpp
yanfeng1012/CPlusPlusProgramList
16dae9ece99407e2213b82bf6910202f07a4b6a3
[ "Apache-2.0" ]
null
null
null
if.cpp
yanfeng1012/CPlusPlusProgramList
16dae9ece99407e2213b82bf6910202f07a4b6a3
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main() { char ch; int spaces, total = 0; cin.get(ch); while (ch != '.') { if (ch == ' ') { ++spaces; } else { cout << ++ch; } ++total; cin.get(ch); } cout << spaces << " spaces, " << total; cout << " characters total in sentence\n"; return 0; }
17.636364
46
0.427835
yanfeng1012
18438247f174c44472273c761c39deea66195cb4
538
cpp
C++
Splendor/Splendor/Randomizer.cpp
TFphoenix/splendor
0fcf1fef69e8b85dae542636bf0ea3d682f0f142
[ "Apache-2.0" ]
null
null
null
Splendor/Splendor/Randomizer.cpp
TFphoenix/splendor
0fcf1fef69e8b85dae542636bf0ea3d682f0f142
[ "Apache-2.0" ]
null
null
null
Splendor/Splendor/Randomizer.cpp
TFphoenix/splendor
0fcf1fef69e8b85dae542636bf0ea3d682f0f142
[ "Apache-2.0" ]
null
null
null
#include "Randomizer.h" Randomizer::Randomizer() { m_MTwister.seed(randomDevice()); } uint16_t Randomizer::Generate(uint16_t minim, uint16_t maxim) { const std::uniform_int_distribution<uint16_t> dist(minim, maxim); return dist(m_MTwister); } int Randomizer::Generate(int minim, int maxim) { const std::uniform_int_distribution<int> dist(minim, maxim); return dist(m_MTwister); } float Randomizer::Generate(float minim, float maxim) { const std::uniform_real_distribution<float> dist(minim, maxim); return dist(m_MTwister); }
20.692308
66
0.763941
TFphoenix
18460dd8a23bad1b4e94b484815a94caa2881627
5,443
cc
C++
bench/add.cc
ajtulloch/XNNPACK
7e955979fd57fff70b9208b82b3bb13d971b182d
[ "BSD-3-Clause" ]
1
2019-11-26T06:26:29.000Z
2019-11-26T06:26:29.000Z
bench/add.cc
Maratyszcza/XNNPACK
791d01da82cecbc259eb396a19822f8f6a8b8219
[ "BSD-3-Clause" ]
null
null
null
bench/add.cc
Maratyszcza/XNNPACK
791d01da82cecbc259eb396a19822f8f6a8b8219
[ "BSD-3-Clause" ]
1
2019-10-10T00:49:20.000Z
2019-10-10T00:49:20.000Z
// Copyright (c) Facebook, Inc. and its affiliates. // All rights reserved. // // Copyright 2019 Google LLC // // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. #include <algorithm> #include <cmath> #include <functional> #include <random> #include <vector> #include <xnnpack.h> #include <benchmark/benchmark.h> #include "bench/utils.h" static void add_nc_q8(benchmark::State& state) { const size_t batch_size = static_cast<size_t>(state.range(0)); const size_t channels = static_cast<size_t>(state.range(1)); std::random_device random_device; auto rng = std::mt19937(random_device()); auto u8rng = std::bind(std::uniform_int_distribution<uint8_t>(), rng); std::vector<uint8_t> a(batch_size * channels); std::vector<uint8_t> b(batch_size * channels); std::vector<uint8_t> y(batch_size * channels); std::generate(a.begin(), a.end(), std::ref(u8rng)); std::generate(b.begin(), b.end(), std::ref(u8rng)); xnn_status status = xnn_initialize(); if (status != xnn_status_success) { state.SkipWithError("failed to initialize XNNPACK"); return; } xnn_operator_t add_op = nullptr; status = xnn_create_add_nc_q8( channels, channels /* a_stride */, channels /* b_stride */, channels /* sum_stride */, 127 /* a:zero point */, 1.0f /* a:scale */, 127 /* b:zero point */, 1.0f /* b:scale */, 127 /* y:zero point */, 1.0f /* y:scale */, 1 /* y:min */, 254 /* y:max */, 0 /* flags */, &add_op); if (status != xnn_status_success || add_op == nullptr) { state.SkipWithError("failed to create Q8 Add operator"); return; } status = xnn_setup_add_nc_q8( add_op, batch_size, a.data(), b.data(), y.data(), nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to setup Q8 Add operator"); return; } for (auto _ : state) { status = xnn_run_operator(add_op, nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to run Q8 Add operator"); return; } } status = xnn_delete_operator(add_op); if (status != xnn_status_success) { state.SkipWithError("failed to delete Q8 Add operator"); return; } state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency(); const size_t elements_per_iteration = batch_size * channels; state.counters["elements"] = benchmark::Counter(uint64_t(state.iterations()) * elements_per_iteration, benchmark::Counter::kIsRate); const size_t bytes_per_iteration = 3 * elements_per_iteration * sizeof(uint8_t); state.counters["bytes"] = benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate); } static void add_nc_q8_inplace(benchmark::State& state) { const size_t batch_size = static_cast<size_t>(state.range(0)); const size_t channels = static_cast<size_t>(state.range(1)); std::random_device random_device; auto rng = std::mt19937(random_device()); auto u8rng = std::bind(std::uniform_int_distribution<uint8_t>(), rng); std::vector<uint8_t> a(batch_size * channels); std::vector<uint8_t> y(batch_size * channels); std::generate(a.begin(), a.end(), std::ref(u8rng)); xnn_status status = xnn_initialize(); if (status != xnn_status_success) { state.SkipWithError("failed to initialize XNNPACK"); return; } xnn_operator_t add_op = nullptr; status = xnn_create_add_nc_q8( channels, channels /* a_stride */, channels /* b_stride */, channels /* sum_stride */, 127 /* a:zero point */, 1.0f /* a:scale */, 127 /* b:zero point */, 1.0f /* b:scale */, 127 /* y:zero point */, 1.0f /* y:scale */, 1 /* y:min */, 254 /* y:max */, 0 /* flags */, &add_op); if (status != xnn_status_success || add_op == nullptr) { state.SkipWithError("failed to create Q8 Add operator"); return; } status = xnn_setup_add_nc_q8( add_op, batch_size, a.data(), y.data(), y.data(), nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to setup Q8 Add operator"); return; } for (auto _ : state) { status = xnn_run_operator(add_op, nullptr /* thread pool */); if (status != xnn_status_success) { state.SkipWithError("failed to run Q8 Add operator"); return; } } status = xnn_delete_operator(add_op); if (status != xnn_status_success) { state.SkipWithError("failed to delete Q8 Add operator"); return; } state.counters["Freq"] = benchmark::utils::GetCurrentCpuFrequency(); const size_t elements_per_iteration = batch_size * channels; state.counters["elements"] = benchmark::Counter(uint64_t(state.iterations()) * elements_per_iteration, benchmark::Counter::kIsRate); const size_t bytes_per_iteration = 3 * elements_per_iteration * sizeof(uint8_t); state.counters["bytes"] = benchmark::Counter(uint64_t(state.iterations()) * bytes_per_iteration, benchmark::Counter::kIsRate); } static void CharacteristicArguments(benchmark::internal::Benchmark* b) { b->ArgNames({"N", "C"}); int32_t c = 16; for (int32_t n = 224; n >= 7; n /= 2) { b->Args({n * n, c}); c *= 2; } } BENCHMARK(add_nc_q8)->Apply(CharacteristicArguments)->UseRealTime(); BENCHMARK(add_nc_q8_inplace)->Apply(CharacteristicArguments)->UseRealTime(); #ifndef XNNPACK_BENCHMARK_NO_MAIN BENCHMARK_MAIN(); #endif
31.645349
107
0.67573
ajtulloch
184778e301bbd85ff50db12d846587406413f17e
207
cpp
C++
win64/w_pch.cpp
Fjellstedt/dk30
b9fea347620fafe2d9994b4be6e20be0b2cee6f2
[ "MIT" ]
null
null
null
win64/w_pch.cpp
Fjellstedt/dk30
b9fea347620fafe2d9994b4be6e20be0b2cee6f2
[ "MIT" ]
null
null
null
win64/w_pch.cpp
Fjellstedt/dk30
b9fea347620fafe2d9994b4be6e20be0b2cee6f2
[ "MIT" ]
null
null
null
/* ======================================================================== $Creator: Patrik Fjellstedt $ ======================================================================== */ #include "w_pch.h"
41.4
78
0.173913
Fjellstedt
1849760999870dc0707935ebcab042f096c822fe
458
cc
C++
test/main_expr.cc
CHChang810716/libsimdpp
669bbffb9a94660f83c1c2e46af6098a8e993caa
[ "BSL-1.0" ]
975
2015-01-08T08:30:17.000Z
2022-03-30T02:57:58.000Z
test/main_expr.cc
abique/libsimdpp
a42deb7e3ca75c5ebaca0a334f18f1ab9822db02
[ "BSL-1.0" ]
125
2015-05-06T09:25:14.000Z
2022-03-23T01:07:07.000Z
test/main_expr.cc
abique/libsimdpp
a42deb7e3ca75c5ebaca0a334f18f1ab9822db02
[ "BSL-1.0" ]
140
2015-05-03T18:56:00.000Z
2022-03-22T07:14:46.000Z
/* Copyright (C) 2014 Povilas Kanapickas <povilas@radix.lt> 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) */ #include "expr/tests.h" #include <iostream> #include <cstdlib> int main() { TestReporter ts(std::cerr); main_test_function(ts); ts.report_summary(); return ts.success() ? EXIT_SUCCESS : EXIT_FAILURE; }
22.9
62
0.681223
CHChang810716
184cfe058c3c3d71170ebad1942e2f05f49a85f1
20,162
cpp
C++
XRADGUI/Sources/GUI/MathFunctionGUI.cpp
Center-of-Diagnostics-and-Telemedicine/xrad
ec2dd3f1dcd164787e2a192cd1f2b78c3217f9ed
[ "BSD-3-Clause" ]
1
2021-04-02T16:47:00.000Z
2021-04-02T16:47:00.000Z
XRADGUI/Sources/GUI/MathFunctionGUI.cpp
Center-of-Diagnostics-and-Telemedicine/xrad
ec2dd3f1dcd164787e2a192cd1f2b78c3217f9ed
[ "BSD-3-Clause" ]
null
null
null
XRADGUI/Sources/GUI/MathFunctionGUI.cpp
Center-of-Diagnostics-and-Telemedicine/xrad
ec2dd3f1dcd164787e2a192cd1f2b78c3217f9ed
[ "BSD-3-Clause" ]
3
2021-08-30T11:26:23.000Z
2021-09-23T09:39:56.000Z
/* Copyright (c) 2021, Moscow Center for Diagnostics & Telemedicine All rights reserved. This file is licensed under BSD-3-Clause license. See LICENSE file for details. */ #include "pre.h" #include "MathFunctionGUI.h" #include "XRADGUI.h" #include "GraphSet.h" #include <XRADBasic/Sources/SampleTypes/HLSColorSample.h> #include <XRADBasic/FFT1D.h> #include <XRADGUI/Sources/GUI/DynamicDialog.h> XRAD_BEGIN namespace NS_DisplayMathFunctionHelpers { // вспомогательные процедуры получения режимов отображения complex_function_oscillation AskOscillation() { return Decide(L"Choose oscillation type", { MakeButton(L"None", no_oscillation), MakeButton(L"Positive", positive_oscillation), MakeButton(L"Negative", negative_oscillation) }); } vector<Button<window_function_e>> CreateWindowFunctionsButtons() { auto window_types = { e_constant_window, e_triangular_window, e_cos2_window, e_hamming_window, e_nuttall_window, e_blackman_harris_window, e_blackman_nuttall_window, e_flat_top_window }; vector<Button<window_function_e>> buttons; for(auto type: window_types) { buttons.push_back(MakeButton(GetWindowFunctionName(type), type)); } return buttons; } //! Поворот массива с нечетным числом отсчетов считается по-разному в зависимости от того, оригинал это или спектр. const bool preferred_data_roll_direction = false; const bool preferred_spectrum_roll_direction = true; void ShowWindowFunction(size_t n, window_function_e wfe, bool roll_before) { SafeExecute([&]() { ComplexFunctionF32 window_function(n, complexF32(1)); ApplyWindowFunction(window_function, wfe); DisplayMathFunction(window_function, 0, 1, ssprintf("Window function: %s", EnsureType<const char*>(GetWindowFunctionName(wfe).c_str()))); if(roll_before) { window_function.roll_half(preferred_data_roll_direction); DisplayMathFunction(window_function, 0, 1, ssprintf("Window function rolled: %s", EnsureType<const char*>(GetWindowFunctionName(wfe).c_str()))); } }); } // вспомогательные процедуры получения компонентов комплексной функции ComplexFunctionF64 Derivative(const ComplexFunctionF64 &f, complex_function_oscillation osc) { ComplexFunctionF64 result(f.size()); for(size_t i=0; i<f.size(); ++i) result[i] = f.d_dx(i, osc); return result; } RealFunctionF64 PhaseDerivative(const ComplexFunctionF64 &f, complex_function_oscillation osc) { size_t s = f.size(); size_t interpolation_factor = 128; RealFunctionF64 buffer(interpolation_factor); complexF64 previous = f.in(0, osc); RealFunctionF64 result(s); for(size_t i = 0; i < s; ++i) { for(size_t j = 0; j < interpolation_factor; ++j) { double x = i + double(j)/interpolation_factor; complexF64 current = f.in(x, osc); buffer[j] = arg(current%previous); previous=current; } result[i] = AverageValue(buffer)*interpolation_factor; } return result; } RealFunctionF64 LinearMagnitude(const ComplexFunctionF64 &f) { RealFunctionF64 result(f.size()); CopyData(result, f, Functors::assign_f1(Functors::absolute_value())); return result; } RealFunctionF64 LogMagnitude(const ComplexFunctionF64 &f, double minDB) { RealFunctionF64 result(f.size()); CopyData(result, f, [](double &r, const complexF64 &v) { r = cabs2(v); }); // double max_value = MaxValue(result); auto it = result.begin(); for(size_t i=0; i<f.size(); ++it, ++i) // normalized dB's { double value = *it; if(value) { // делалась нормировка, максимальное значение устанавливалось в 0 дБ. неинформативно. // отменено, показывается логарифм как есть. 2016_04_11 KNS // *it = max(10.0*log10(value/max_value), -minDB); *it = max(10.0*log10(value), -minDB); } else { *it = -minDB; } } return result; } // RealFunctionF64 LogMagnitudeAbs(const ComplexFunctionF64 &f, double dynamic_range_min, double dynamic_range_max) // { // RealFunctionF64 result(f.size()); // CopyData(result, f, cabs_functor<double, complexF64>()); // // for(size_t i=0; i<f.size(); i++) // { // if(!result[i]) // result[i] = dynamic_range_min; // else // { // result[i] = range(20.0*log10(result[i]), dynamic_range_min, dynamic_range_max); // } // } // return result; // } RealFunctionF64 PhaseContinued(const ComplexFunctionF64 &f, complex_function_oscillation osc) { RealFunctionF64 result(PhaseDerivative(f, osc)); result[0] = arg(f[0]); for(size_t i=1; i<f.size(); i++) { result[i] += result[i-1]; } return result; } RealFunctionF64 PhaseCut(const ComplexFunctionF64 &f) { RealFunctionF64 result(f.size()); CopyData(result, f, [](double &r, const complexF64 &v) { r = arg(v); }); return result; } void grafreal(const RealFunctionF64 &mf, const wstring &title, const value_legend &vlegend, const axis_legend & xlegend, bool b_is_stopped) { DataArray<double> buffer; MakeCopy(buffer, mf, get_display_value()); GraphSet gs(title, vlegend.label, xlegend.label); gs.AddGraphUniform(buffer, xlegend.min_value, xlegend.step, title); gs.Display(b_is_stopped); } void grafc(const ComplexFunctionF64 &data, const wstring &data_title, const value_legend &vlegend, const axis_legend &xlegend, bool) { bool upsample_fragment = false; bool phase_radians = true; bool phase_continuous = true; bool log_magnitude = true; static const double log_magnitude_dynamic_range = 2000; bool derivative_per_samples = false; wstring option_title = ssprintf(L"Display '%Ls'", data_title.c_str()); for (;;) { enum display_options { linear_magnitude_option, real_option, log_magnitude_option, phase_cut_option, phase_deriv_option, roll_option, cancel_phase_option, spectrum_option, polar_option, real_imag_option, imag_option, magnitude_phase_option, phase_continued_option, derivative_option, flip_phase_option, cancel_magnitude_option, fragment_option, cancel_option }; auto option = GetButtonDecision(option_title, { MakeButton(L"Linear magnitude", linear_magnitude_option), MakeButton(L"Real part", real_option), MakeButton(L"Log. magnitude", log_magnitude_option), MakeButton(L"Phase cut", phase_cut_option), MakeButton(L"Phase derivative", phase_deriv_option), MakeButton(L"Roll data ->", roll_option), MakeButton(L"Cancel phase ->", cancel_phase_option), MakeButton(L"Spectrum ->", spectrum_option), MakeButton(L"Real/Imaginary (polar)", polar_option), MakeButton(L"Real/Imaginary", real_imag_option), MakeButton(L"Imaginary part", imag_option), MakeButton(L"Magnitude/Phase", magnitude_phase_option), MakeButton(L"Phase continued", phase_continued_option), MakeButton(L"Derivative ->", derivative_option), MakeButton(L"Flip phase ->", flip_phase_option), MakeButton(L"Cancel magnitude ->", cancel_magnitude_option), MakeButton(L"Fragment ->", fragment_option), MakeButton(L"Exit display", cancel_option) }); if (option == cancel_option) break; SafeExecute([&]() { complex_function_oscillation phase_oscillation = no_oscillation; switch(option) { case log_magnitude_option: log_magnitude = true; break; case linear_magnitude_option: log_magnitude = false; break; case magnitude_phase_option: case cancel_phase_option: log_magnitude = Decide2("Magnitude display mode", "Linear", "Log", log_magnitude? 1: 0) == 1; break; } if(option == magnitude_phase_option || option == phase_cut_option || option == phase_continued_option || option == cancel_magnitude_option || option == phase_deriv_option) { switch(option) { case magnitude_phase_option: case cancel_magnitude_option: phase_continuous = Decide2("Phase compute algorithm", "Cut", "Continuous", phase_continuous? 1: 0) == 1; break; case phase_cut_option: phase_continuous = false; break; case phase_continued_option: phase_continuous = true; break; case phase_deriv_option: derivative_per_samples = Decide2("Derivative argument", "Natural", "Sample", derivative_per_samples? 1: 0) == 1; phase_continuous = true; break; }; phase_oscillation = phase_continuous ? AskOscillation() : no_oscillation; phase_radians = Decide2("Phase units", "Degrees", "Radians", phase_radians? 1: 0) == 1; } if(option==derivative_option) { phase_oscillation = AskOscillation(); derivative_per_samples = Decide2("Derivative argument", "Natural", "Sample", derivative_per_samples? 1: 0) == 1; } wstring derivative_divisor_label = derivative_per_samples ? L"/sample" : wstring(L"/") + (xlegend.label.size() ? xlegend.label:L"x unit"); wstring phase_unit_label = phase_radians ? L"radians" : L"degrees"; double phase_factor = phase_radians ? 1. : 180./pi(); wstring magnitude_unit_label = log_magnitude ? L"dB" : vlegend.label; RealFunctionF64 phase = (phase_continuous ? PhaseContinued(data, phase_oscillation) : PhaseCut(data)) * phase_factor; RealFunctionF64 magnitude = log_magnitude ? LogMagnitude(data, log_magnitude_dynamic_range) : LinearMagnitude(data); switch(option) { case magnitude_phase_option: { GraphSet gs(data_title, L"", xlegend.label); gs.AddGraphUniform(phase, xlegend.min_value, xlegend.step, ssprintf(L"phase(%Ls)", phase_unit_label.c_str())); gs.AddGraphUniform(magnitude, xlegend.min_value, xlegend.step, (magnitude_unit_label.size() ? ssprintf(L"magnitude(%Ls)", magnitude_unit_label.c_str()) : L"magnitude(linear)")); gs.Display(); } break; case real_option: { DisplayMathFunction(real(data), xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Real part>", data_title.c_str()), vlegend.label, xlegend.label); } break; case imag_option: { DisplayMathFunction(imag(data), xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Imaginary part>", data_title.c_str()), vlegend.label, xlegend.label); } break; case linear_magnitude_option: case log_magnitude_option: { wstring magnitude_title = log_magnitude ? ssprintf(L"%Ls <Log. magnitude>", data_title.c_str()) : ssprintf(L"%Ls <Linear magnitude>", data_title.c_str()); DisplayMathFunction(magnitude, xlegend.min_value, xlegend.step, magnitude_title, magnitude_unit_label, xlegend.label); } break; case phase_continued_option: case phase_cut_option: { DisplayMathFunction(phase, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Phase>", data_title.c_str()), phase_unit_label, xlegend.label); } break; case phase_deriv_option: { RealFunctionF64 phase_derivative = PhaseDerivative(data, phase_oscillation) * phase_factor; if(!derivative_per_samples) { phase_derivative /= xlegend.step; } DisplayMathFunction(phase_derivative, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Phase derivative>", data_title.c_str()), phase_unit_label + derivative_divisor_label, xlegend.label); } break; case roll_option: { ComplexFunctionF64 rolled_data(data); rolled_data.roll_half(preferred_data_roll_direction); DisplayMathFunction(rolled_data, xlegend.min_value-xlegend.step*data.size()/2., xlegend.step, ssprintf(L"%Ls <Rolled>", data_title.c_str()), vlegend.label, xlegend.label); } break; case spectrum_option: { auto dialog = DynamicDialog::OKCancelDialog::Create(L"Display spectrum options"); bool inverse_ft_direction = false; bool roll_data_before_ft = false; bool roll_spectrum_after_ft = false; bool view_window_function = false; window_function_e wfe = e_constant_window; auto window_selection = DynamicDialog::EnumRadioButtonChoice::Create(L"Window function", CreateWindowFunctionsButtons(), MakeGUIValue(&wfe, saved_default_value)); auto fft_options = make_shared<DynamicDialog::ControlContainer>(DynamicDialog::Layout::Vertical); fft_options->AddControl(make_shared<DynamicDialog::ValueCheckBox>(L"Inverse FT", SavedGUIValue(&inverse_ft_direction))); fft_options->AddControl(make_shared<DynamicDialog::ValueCheckBox>(L"Roll before FT", SavedGUIValue(&roll_data_before_ft))); fft_options->AddControl(make_shared<DynamicDialog::ValueCheckBox>(L"Roll after FT", SavedGUIValue(&roll_spectrum_after_ft))); fft_options->AddControl(make_shared<DynamicDialog::ValueCheckBox>(L"View window function", SavedGUIValue(&view_window_function))); auto layout = make_shared<DynamicDialog::ControlContainer>(DynamicDialog::Layout::Horizontal); layout->AddControl(fft_options); layout->AddControl(window_selection); dialog->AddControl(layout); dialog->Show(); if(dialog->Choice() != DynamicDialog::OKCancelDialog::Result::OK) throw canceled_operation("Show spectrum canceled"); if(view_window_function)ShowWindowFunction(data.size(), wfe, roll_data_before_ft); ComplexFunctionF64 spectrum(data); ApplyWindowFunction(spectrum, wfe); if(roll_data_before_ft) spectrum.roll_half(preferred_data_roll_direction); if(!inverse_ft_direction) FT(spectrum, ftForward); else FT(spectrum, ftReverse); if(roll_spectrum_after_ft) spectrum.roll_half(preferred_spectrum_roll_direction); double dx = 2.*pi()/(xlegend.step*data.size()); double x0 = roll_spectrum_after_ft ? -dx*(data.size()/2): 0; wstring frequency_label(L""); if(xlegend.label.size()) { frequency_label = ssprintf(L"2*pi/(%Ls)", xlegend.label.c_str()); } DisplayMathFunction(spectrum, x0, dx, ssprintf(L"%Ls <Spectrum>", data_title.c_str()), vlegend.label, frequency_label); // 2*PI } break; case polar_option: { GraphSet gs(data_title, vlegend.label + L"<imag>", vlegend.label + L" <real>"); gs.AddGraphParametric(imag(data), real(data), ssprintf(L"%Ls <Polar>", data_title.c_str())); gs.Display(); } break; case real_imag_option: { GraphSet gs(data_title, vlegend.label, xlegend.label); gs.AddGraphUniform(real(data), xlegend.min_value, xlegend.step, "Real part"); gs.AddGraphUniform(imag(data), xlegend.min_value, xlegend.step, "Imag part"); gs.Display(); } break; case flip_phase_option: { ComplexFunctionF64 flipped_phase(data.size()); for(size_t i=0; i<data.size(); ++i) { flipped_phase[i] = i%2 ? -data[i] : data[i]; } DisplayMathFunction(flipped_phase, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Flip phase>", data_title.c_str()), vlegend.label, xlegend.label); } break; case cancel_phase_option: { ComplexFunctionF64 magnitude_c(magnitude); DisplayMathFunction(magnitude_c, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Magnitude>", data_title.c_str()), vlegend.label, xlegend.label); } break; case cancel_magnitude_option: { ComplexFunctionF64 phase_c(data.size()); for(size_t i=0; i<data.size(); i++) { phase_c[i] = polar(1., phase[i]); } DisplayMathFunction(phase_c, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Phase only>", data_title.c_str()), L"", xlegend.label); } break; case derivative_option: { ComplexFunctionF64 derivative = Derivative(data, phase_oscillation); if(!derivative_per_samples) { derivative /= xlegend.step; } wstring y_label_derivative = vlegend.label.size() ? vlegend.label + derivative_divisor_label : L"y unit" + derivative_divisor_label; DisplayMathFunction(derivative, xlegend.min_value, xlegend.step, ssprintf(L"%Ls <Derivative>", data_title.c_str()), y_label_derivative, xlegend.label); } break; case fragment_option: { double x_max = xlegend.min_value + xlegend.step*data.size(); double x_min = GetFloating("Fragment start", xlegend.min_value, xlegend.min_value, x_max); x_max = GetFloating("Fragment end", x_max, x_min, x_max); upsample_fragment = YesOrNo("Upsample fragment?", false); size_t fragment_size = (x_max - x_min)/xlegend.step; size_t fragment_start = (x_min - xlegend.min_value)/xlegend.step; if(fragment_start + fragment_size > data.size()-1) fragment_size = data.size() - fragment_start; if(fragment_size < 2) break; printf("\n fragment_start = %du, fragEnd = %du, size = %du", int(fragment_start), int(fragment_start + fragment_size), int(data.size())); ComplexFunctionF64 fragment; size_t upsample_ratio; if(upsample_fragment) { upsample_ratio = GetUnsigned("Upsample ratio", 2, 1, 1024); complex_function_oscillation oscillation = AskOscillation(); fragment.realloc(fragment_size*upsample_ratio); for(size_t i = 0; i < fragment_size*upsample_ratio; i++) { fragment[i] = data.in(fragment_start + double(i)/upsample_ratio, oscillation); } } else { upsample_ratio = 1; fragment.realloc(fragment_size); std::copy(data.begin() + fragment_start, data.begin() + fragment_start+fragment_size, fragment.begin()); } DisplayMathFunction(fragment, x_min, xlegend.step/upsample_ratio, ssprintf(L"%Ls <Fragment %g--%g>", data_title.c_str(), x_min, x_max), vlegend.label, xlegend.label); } break; default: break; } }); } } void grafrgb(const ColorFunctionF64 &data, const wstring &data_title, const value_legend &vlegend, const axis_legend &xlegend, bool stop) { wstring option_title = ssprintf(L"Display '%Ls'", EnsureType<const wchar_t*>(data_title.c_str())); for (;;) { enum display_options { rgb, red, green, blue, hue, lightness, saturation, cancel_option }; auto answer = GetButtonDecision(convert_to_string(option_title), { MakeButton(L"RGB graph", rgb), MakeButton(L"Red graph", red), MakeButton(L"Green graph", green), MakeButton(L"Blue graph", blue), MakeButton(L"Hue graph", hue), MakeButton(L"Lightness graph", lightness), MakeButton(L"Saturation graph", saturation), MakeButton(L"Exit display", cancel_option) }); if (answer == cancel_option) break; switch(answer) { case rgb: { GraphSet gs(data_title, vlegend.label, xlegend.label); gs.AddGraphUniform(data.green(), xlegend.min_value, xlegend.step, "green"); gs.AddGraphUniform(data.blue(), xlegend.min_value, xlegend.step, "blue"); gs.AddGraphUniform(data.red(), xlegend.min_value, xlegend.step, "red"); gs.Display(stop); } break; case red: DisplayMathFunction(data.red(), xlegend.min_value, xlegend.step, data_title + L" red", vlegend.label, xlegend.label, stop); break; case green: DisplayMathFunction(data.green(), xlegend.min_value, xlegend.step, data_title + L" green", vlegend.label, xlegend.label, stop); break; case blue: DisplayMathFunction(data.blue(), xlegend.min_value, xlegend.step, data_title + L" blue", vlegend.label, xlegend.label, stop); break; case hue: { RealFunctionF32 H; H.MakeCopy(data, [](float &x, const HLSColorSample &s){return x=s.H;}); DisplayMathFunction(H, xlegend.min_value, xlegend.step, data_title + L" 'hue'", vlegend.label, xlegend.label, stop); } break; case lightness: { RealFunctionF32 L; L.MakeCopy(data, [](float &x, const HLSColorSample &s){return x=s.L;}); DisplayMathFunction(L, xlegend.min_value, xlegend.step, data_title + L" 'lightness'", vlegend.label, xlegend.label, stop); } break; case saturation: { RealFunctionF32 S; S.MakeCopy(data, [](float &x, const HLSColorSample &s){return x=s.S;}); DisplayMathFunction(S, xlegend.min_value, xlegend.step, data_title + L" 'saturation'", vlegend.label, xlegend.label, stop); } break; } } } }//namespace NS_DisplayMathFunctionHelpers XRAD_END
30.828746
194
0.694624
Center-of-Diagnostics-and-Telemedicine
184e07ea0495ab0b128ff5034b7c8da951c262d2
1,060
cpp
C++
YorozuyaGSLib/source/_chat_lock_inform_zoclDetail.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/_chat_lock_inform_zoclDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/_chat_lock_inform_zoclDetail.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <_chat_lock_inform_zoclDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace Detail { Info::_chat_lock_inform_zoclsize2_ptr _chat_lock_inform_zoclsize2_next(nullptr); Info::_chat_lock_inform_zoclsize2_clbk _chat_lock_inform_zoclsize2_user(nullptr); int _chat_lock_inform_zoclsize2_wrapper(struct _chat_lock_inform_zocl* _this) { return _chat_lock_inform_zoclsize2_user(_this, _chat_lock_inform_zoclsize2_next); }; ::std::array<hook_record, 1> _chat_lock_inform_zocl_functions = { _hook_record { (LPVOID)0x14011f1f0L, (LPVOID *)&_chat_lock_inform_zoclsize2_user, (LPVOID *)&_chat_lock_inform_zoclsize2_next, (LPVOID)cast_pointer_function(_chat_lock_inform_zoclsize2_wrapper), (LPVOID)cast_pointer_function((int(_chat_lock_inform_zocl::*)())&_chat_lock_inform_zocl::size) }, }; }; // end namespace Detail END_ATF_NAMESPACE
37.857143
110
0.682075
lemkova
184fea8bfef2f72570a06334c56751cda187a273
2,949
cpp
C++
NAS2D/Xml/XmlMemoryBuffer.cpp
Brett208/nas2d-core
f9506540f32d34f3c60bc83b87b34460d582ae81
[ "Zlib" ]
null
null
null
NAS2D/Xml/XmlMemoryBuffer.cpp
Brett208/nas2d-core
f9506540f32d34f3c60bc83b87b34460d582ae81
[ "Zlib" ]
null
null
null
NAS2D/Xml/XmlMemoryBuffer.cpp
Brett208/nas2d-core
f9506540f32d34f3c60bc83b87b34460d582ae81
[ "Zlib" ]
null
null
null
// ================================================================================== // = NAS2D // = Copyright © 2008 - 2020 New Age Software // ================================================================================== // = NAS2D is distributed under the terms of the zlib license. You are free to copy, // = modify and distribute the software under the terms of the zlib license. // = // = Acknowledgement of your use of NAS2D is appriciated but is not required. // ================================================================================== // = Originally based on TinyXML. See Xml.h for additional details. // ================================================================================== #include "XmlMemoryBuffer.h" #include "XmlAttribute.h" #include "XmlAttributeSet.h" #include "XmlComment.h" #include "XmlDocument.h" #include "XmlElement.h" #include "XmlText.h" #include "XmlUnknown.h" using namespace NAS2D::Xml; inline void indent(int depth, const std::string& indent, std::string& buffer) { for (int i = 0; i < depth; ++i) { buffer += indent; } } inline void line_break(const std::string& linebreak, std::string& buffer) { buffer += linebreak; } XmlMemoryBuffer::XmlMemoryBuffer() : depth(0), _indent("\t"), _lineBreak("\n") {} bool XmlMemoryBuffer::visitEnter(const XmlElement& element, const XmlAttribute* firstAttribute) { indent(depth, _indent, _buffer); _buffer += "<"; _buffer += element.value(); for (const XmlAttribute* attrib = firstAttribute; attrib; attrib = attrib->next()) { _buffer += " "; attrib->write(_buffer, 0); } if (!element.firstChild()) { _buffer += " />"; line_break(_lineBreak, _buffer); } else { _buffer += ">"; line_break(_lineBreak, _buffer); } ++depth; return true; } bool XmlMemoryBuffer::visitExit(const XmlElement& element) { --depth; if (element.firstChild()) { indent(depth, _indent, _buffer); _buffer += "</"; _buffer += element.value(); _buffer += ">"; line_break(_lineBreak, _buffer); } return true; } bool XmlMemoryBuffer::visit(const XmlText& text) { if (text.CDATA()) { indent(depth, _indent, _buffer); _buffer += "<![CDATA["; _buffer += text.value(); _buffer += "]]>"; line_break(_lineBreak, _buffer); } else { indent(depth, _indent, _buffer); std::string str; _buffer += text.value(); line_break(_lineBreak, _buffer); } return true; } bool XmlMemoryBuffer::visit(const XmlComment& comment) { indent(depth, _indent, _buffer); _buffer += "<!--"; _buffer += comment.value(); _buffer += "-->"; line_break(_lineBreak, _buffer); return true; } bool XmlMemoryBuffer::visit(const XmlUnknown& unknown) { indent(depth, _indent, _buffer); _buffer += "<"; _buffer += unknown.value(); _buffer += ">"; line_break(_lineBreak, _buffer); return true; } std::size_t XmlMemoryBuffer::size() { return _buffer.size(); } const std::string& XmlMemoryBuffer::buffer() { return _buffer; }
21.215827
95
0.597491
Brett208
18510d8907f8dee50b3fec59d629ad531ad02c5a
8,449
hpp
C++
examples/pppbayestree/gpstk/FFTextStream.hpp
shaolinbit/minisam_lib
e2e904d1b6753976de1dee102f0b53e778c0f880
[ "BSD-3-Clause" ]
104
2019-06-23T14:45:20.000Z
2022-03-20T12:45:29.000Z
examples/pppbayestree/gpstk/FFTextStream.hpp
shaolinbit/minisam_lib
e2e904d1b6753976de1dee102f0b53e778c0f880
[ "BSD-3-Clause" ]
2
2019-06-28T08:23:23.000Z
2019-07-17T02:37:08.000Z
examples/pppbayestree/gpstk/FFTextStream.hpp
shaolinbit/minisam_lib
e2e904d1b6753976de1dee102f0b53e778c0f880
[ "BSD-3-Clause" ]
28
2019-06-23T14:45:19.000Z
2022-03-20T12:45:24.000Z
#pragma ident "$Id$" /** * @file FFTextStream.hpp * An FFStream for text files */ #ifndef GPSTK_FFTEXTSTREAM_HPP #define GPSTK_FFTEXTSTREAM_HPP //============================================================================ // // This file is part of GPSTk, the GPS Toolkit. // // The GPSTk is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published // by the Free Software Foundation; either version 2.1 of the License, or // any later version. // // The GPSTk 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with GPSTk; if not, write to the Free Software Foundation, // Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA // // Copyright 2004, The University of Texas at Austin // //============================================================================ //============================================================================ // //This software developed by Applied Research Laboratories at the University of //Texas at Austin, under contract to an agency or agencies within the U.S. //Department of Defense. The U.S. Government retains all rights to use, //duplicate, distribute, disclose, or release this software. // //Pursuant to DoD Directive 523024 // // DISTRIBUTION STATEMENT A: This software has been approved for public // release, distribution is unlimited. // //============================================================================= #include "FFStream.hpp" namespace gpstk { /** @addtogroup formattedfile */ //@{ /** * An FFStream is meant for reading text. This also includes an * internal line count and a read line method. When reading and * using the formattedGetLine() call, the lineNumber automatically * increments. However, any other read and all write calls do not * update the line number - the derived class or programmer * needs to make sure that the reader or writer increments * lineNumber in these cases. */ class FFTextStream : public FFStream { public: /// Destructor virtual ~FFTextStream() {}; /// Default constructor FFTextStream() : lineNumber(0) {}; /** Common constructor. * * @param fn file name. * @param mode file open mode (std::ios) */ FFTextStream( const char* fn, std::ios::openmode mode=std::ios::in ) : FFStream(fn, mode), lineNumber(0) {}; /** Common constructor. * * @param fn file name. * @param mode file open mode (std::ios) */ FFTextStream( const std::string& fn, std::ios::openmode mode=std::ios::in ) : FFStream( fn.c_str(), mode ), lineNumber(0) {}; /// Overrides open to reset the line number. virtual void open( const char* fn, std::ios::openmode mode ) { FFStream::open(fn, mode); lineNumber = 0; }; /// Overrides open to reset the line number. virtual void open( const std::string& fn, std::ios::openmode mode ) { open(fn.c_str(), mode); }; /// The internal line count. When writing, make sure /// to increment this. unsigned int lineNumber; /** * Like std::istream::getline but checks for EOF and removes '/r'. * Also increments lineNumber. When \a expectEOF is true and EOF * is found, an gpstk::EndOfFile exception is thrown. If * \a expectEOF is false and an EOF is encountered, an * gpstk::FFStreamError is thrown. * @param line is set to the value of the line read from the file. * @param expectEOF set true if finding EOF on this read is acceptable. * @throw EndOfFile if \a expectEOF is true and an EOF is encountered. * @throw FFStreamError if EOF is found and \a expectEOF is false * @throw gpstk::StringUtils::StringException when a string error occurs * or if any other error happens. * @warning There is a maximum line length of 1500 characters when * using this function. */ inline void formattedGetLine( std::string& line, const bool expectEOF = false ) throw(EndOfFile, FFStreamError, gpstk::StringUtils::StringException); protected: /// calls FFStream::tryFFStreamGet and adds line number information virtual void tryFFStreamGet(FFData& rec) throw(FFStreamError, gpstk::StringUtils::StringException) { unsigned int initialLineNumber = lineNumber; try { FFStream::tryFFStreamGet(rec); } catch(gpstk::Exception& e) { e.addText( std::string("Near file line ") + gpstk::StringUtils::asString(lineNumber) ); lineNumber = initialLineNumber; mostRecentException = e; conditionalThrow(); } }; /// calls FFStream::tryFFStreamPut and adds line number information virtual void tryFFStreamPut(const FFData& rec) throw(FFStreamError, gpstk::StringUtils::StringException) { unsigned int initialLineNumber = lineNumber; try { FFStream::tryFFStreamPut(rec); } catch(gpstk::Exception& e) { e.addText( std::string("Near file line ") + gpstk::StringUtils::asString(lineNumber) ); lineNumber = initialLineNumber; mostRecentException = e; conditionalThrow(); } } }; // End of class 'FFTextStream' // the reason for checking ffs.eof() in the try AND catch block is // because if the user enabled exceptions on the stream with exceptions() // then eof could throw an exception, in which case we need to catch it // and rethrow an EOF or FFStream exception. In any event, EndOfFile // gets thrown whenever there's an EOF and expectEOF is true void FFTextStream::formattedGetLine( std::string& line, const bool expectEOF ) throw(EndOfFile, FFStreamError, gpstk::StringUtils::StringException) { try { // The following constant used to be 256, but with the change to // RINEX3 formats the possible length of a line increased // considerably. A RINEX3 observation file line for Galileo may // be 1277 characters long (taking into account all the possible // types of observations available, plus the end of line // characters), so this constant was conservatively set to // 1500 characters. Dagoberto Salazar. const int MAX_LINE_LENGTH = 1500; char templine[MAX_LINE_LENGTH + 1]; getline(templine, MAX_LINE_LENGTH); lineNumber++; //check if line was longer than 256 characters, if so error if(fail() && !eof()) { FFStreamError err("Line too long"); GPSTK_THROW(err); } line = templine; gpstk::StringUtils::stripTrailing(line, '\r'); // catch EOF when stream exceptions are disabled if ((gcount() == 0) && eof()) { if (expectEOF) { EndOfFile err("EOF encountered"); GPSTK_THROW(err); } else { FFStreamError err("Unexpected EOF encountered"); GPSTK_THROW(err); } } } catch(std::exception &e) { // catch EOF when exceptions are enabled if ( (gcount() == 0) && eof()) { if (expectEOF) { EndOfFile err("EOF encountered"); GPSTK_THROW(err); } else { FFStreamError err("Unexpected EOF"); GPSTK_THROW(err); } } else { FFStreamError err("Critical file error: " + std::string(e.what())); GPSTK_THROW(err); } // End of 'if ( (gcount() == 0) && eof())' } // End of 'try-catch' block } // End of method 'FFTextStream::formattedGetLine()' //@} } // End of namespace gpstk #endif // GPSTK_FFTEXTSTREAM_HPP
30.835766
79
0.586578
shaolinbit
4c757cadf9f87fcd5866150038316d3a5d1b37db
159
cpp
C++
source/ThreadControl.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,315
2015-01-07T02:03:15.000Z
2022-03-30T09:48:17.000Z
source/ThreadControl.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
1,429
2015-01-08T00:09:17.000Z
2022-03-31T08:12:14.000Z
source/ThreadControl.cpp
Gavin-Lijy/STAR
4571190968fc134aa4bd0d4d7065490253b1a4c5
[ "MIT" ]
495
2015-01-23T20:00:45.000Z
2022-03-31T13:24:50.000Z
#include "ThreadControl.h" ThreadControl::ThreadControl() { chunkInN=0; chunkOutN=0; // chunkOutBAMposition=new uint [MAX_chunkOutBAMposition]; };
22.714286
62
0.72327
Gavin-Lijy
4c762507c5a648221606a37bed8ab1360f98ec9b
15,886
cpp
C++
src/det/scope.cpp
alta-lang/alta-core
290ebcd94b4b2956fd34f5cd0e516e756d4fc219
[ "MIT" ]
null
null
null
src/det/scope.cpp
alta-lang/alta-core
290ebcd94b4b2956fd34f5cd0e516e756d4fc219
[ "MIT" ]
6
2019-03-04T01:37:27.000Z
2019-09-07T20:12:36.000Z
src/det/scope.cpp
alta-lang/alta-core
290ebcd94b4b2956fd34f5cd0e516e756d4fc219
[ "MIT" ]
null
null
null
#include "../../include/altacore/det/scope.hpp" #include "../../include/altacore/det/function.hpp" #include "../../include/altacore/det/module.hpp" #include "../../include/altacore/det/alias.hpp" #include "../../include/altacore/det/namespace.hpp" #include "../../include/altacore/det/variable.hpp" #include "../../include/altacore/det/class.hpp" #include "../../include/altacore/util.hpp" const AltaCore::DET::NodeType AltaCore::DET::Scope::nodeType() { return NodeType::Scope; }; std::shared_ptr<AltaCore::DET::Node> AltaCore::DET::Scope::clone() { return std::make_shared<Scope>(*this); }; std::shared_ptr<AltaCore::DET::Node> AltaCore::DET::Scope::deepClone() { auto self = std::dynamic_pointer_cast<Scope>(clone()); self->items.clear(); for (auto& item: items) { auto newItem = std::dynamic_pointer_cast<ScopeItem>(item->deepClone()); newItem->parentScope = self; self->items.push_back(newItem); } return self; }; auto AltaCore::DET::Scope::makeWithParentScope(std::shared_ptr<Scope> parent) -> std::shared_ptr<Scope> { auto scope = std::make_shared<Scope>(parent); parent->childScopes.push_back(scope); return scope; }; AltaCore::DET::Scope::Scope() {}; AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Scope> _parent): parent(_parent), relativeID(_parent->nextChildID) { _parent->nextChildID++; noRuntime = _parent->noRuntime; }; AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Module> _parentModule): parentModule(_parentModule) {}; AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Function> _parentFunction): parentFunction(_parentFunction) { if (auto parent = parentFunction.lock()->parentScope.lock()) { noRuntime = parent->noRuntime; } }; AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Namespace> _parentNamespace): parentNamespace(_parentNamespace) { if (auto parent = parentNamespace.lock()->parentScope.lock()) { noRuntime = parent->noRuntime; } }; AltaCore::DET::Scope::Scope(std::shared_ptr<AltaCore::DET::Class> _parentClass): parentClass(_parentClass) { if (auto parent = parentClass.lock()->parentScope.lock()) { noRuntime = parent->noRuntime; } }; std::vector<std::shared_ptr<AltaCore::DET::ScopeItem>> AltaCore::DET::Scope::findAll(std::string name, std::vector<std::shared_ptr<Type>> excludeTypes, bool searchParents, std::shared_ptr<Scope> originScope) { std::vector<std::shared_ptr<ScopeItem>> results; std::vector<std::shared_ptr<Type>> funcTypes; std::shared_ptr<ScopeItem> first = nullptr; bool allFunctions = true; for (auto& item: items) { if (item->name == name) { if (originScope && !originScope->canSee(item)) { continue; } auto trueItem = item; while (trueItem->nodeType() == NodeType::Alias) { trueItem = std::dynamic_pointer_cast<Alias>(item)->target; } if (trueItem->nodeType() != NodeType::Function || std::dynamic_pointer_cast<Function>(trueItem)->isAccessor) { if (allFunctions && first) { // we've already found a non-function scope item with that name throw std::runtime_error("found non-function scope item with same name as another scope item; this is a conflict"); } else if (allFunctions && results.size() == 0) { // we don't have a first item yet, and allFunctions is still true and there's no functions found. // this means we found the first (and hopefully only) item first = trueItem; } else if (allFunctions) { // we've found functions with that name (since `results.size() > 0` here) throw std::runtime_error("found non-function scope item with same name as a function; this is a conflict"); } allFunctions = false; } else if (!allFunctions) { // it is a function, but we already found a non-function item with that name throw std::runtime_error("found function scope item with same name as a non-function scope item; this is a conflict"); } else { auto type = Type::getUnderlyingType(trueItem); bool ok = true; if (type && excludeTypes.size() > 0) { for (auto& excl: excludeTypes) { if (type->isExactlyCompatibleWith(*excl)) { ok = false; break; } } } if (ok) { results.push_back(trueItem); funcTypes.push_back(type); } } } } std::shared_ptr<Scope> parentScope = nullptr; if (!parent.expired()) { parentScope = parent.lock(); } else if (!parentFunction.expired() && !parentFunction.lock()->parentScope.expired()) { parentScope = parentFunction.lock()->parentScope.lock(); } else if (!parentNamespace.expired() && !parentNamespace.lock()->parentScope.expired()) { parentScope = parentNamespace.lock()->parentScope.lock(); } else if (!parentClass.expired() && !parentClass.lock()->parentScope.expired()) { parentScope = parentClass.lock()->parentScope.lock(); } if (searchParents && parentScope != nullptr && (allFunctions || !first)) { // here, allFunctions being true means that either all the scope items found were functions // (in which case, we're free to search for overloads in parent scopes) // OR no items were found (which is fine, too, since we can also search parent scopes in that case) funcTypes.insert(funcTypes.end(), excludeTypes.begin(), excludeTypes.end()); auto otherResults = parentScope->findAll(name, funcTypes); if (otherResults.size() == 1) { if (otherResults[0]->nodeType() == NodeType::Function) { results.push_back(otherResults[0]); } else if (!first) { first = otherResults[0]; } // otherwise, ignore the result if it's not a function } else { results.insert(results.end(), otherResults.begin(), otherResults.end()); } } if (first) { return { first }; } else { return results; } }; void AltaCore::DET::Scope::hoist(std::shared_ptr<AltaCore::DET::ScopeItem> item) { if (auto ns = std::dynamic_pointer_cast<DET::Namespace>(item)) { if (!ns->underlyingEnumerationType) return; } if (item->nodeType() == NodeType::Type) { auto type = std::dynamic_pointer_cast<DET::Type>(item); if (type->name.empty()) { if (type->isFunction) { for (auto& param: type->parameters) { hoist(std::get<1>(param)); } hoist(type->returnType); } else if (type->isUnion()) { for (auto& member: type->unionOf) { hoist(member); } } else if (type->isOptional) { hoist(type->optionalTarget); } else { if (type->klass) { hoist(type->klass); } return; } } } if (item->nodeType() == NodeType::Variable) { if (auto parent = item->parentScope.lock()) { if (auto func = Util::getFunction(parent).lock()) { return; } if (auto klass = parent->parentClass.lock()) { return; } } } // this is weird, we shouldn't need this but it covers some functions being weird if (auto func = std::dynamic_pointer_cast<Function>(item)) { for (auto& param: func->parameters) { if (auto type = std::get<1>(param)) { hoist(type); } } if (func->returnType) { hoist(func->returnType); } } if (auto mod = parentModule.lock()) { mod->hoistedItems.push_back(item); } else if (auto func = parentFunction.lock()) { func->privateHoistedItems.push_back(item); } else if (auto klass = parentClass.lock()) { klass->privateHoistedItems.push_back(item); } else if (auto ns = parentNamespace.lock()) { if (auto scope = ns->parentScope.lock()) { scope->hoist(item); } else { throw std::runtime_error("failed to hoist item anywhere"); } } else if (auto scope = parent.lock()) { scope->hoist(item); } else { throw std::runtime_error("failed to hoist item anywhere"); } if (auto mod = Util::getModule(this).lock()) { if (auto otherMod = Util::getModule(item->parentScope.lock().get()).lock()) { otherMod->dependents.push_back(mod); if (item->genericParameterCount > 0) { mod->genericsUsed.push_back(item); } } } }; void AltaCore::DET::Scope::unhoist(std::shared_ptr<AltaCore::DET::ScopeItem> item) { if (item->nodeType() == NodeType::Namespace) return; if (auto mod = parentModule.lock()) { for (size_t i = 0; i < mod->hoistedItems.size(); i++) { if (mod->hoistedItems[i]->id == item->id) { mod->hoistedItems.erase(mod->hoistedItems.begin() + i); break; } } } else if (auto func = parentFunction.lock()) { for (size_t i = 0; i < func->privateHoistedItems.size(); i++) { if (func->privateHoistedItems[i]->id == item->id) { func->privateHoistedItems.erase(func->privateHoistedItems.begin() + i); break; } } } else if (auto klass = parentClass.lock()) { for (size_t i = 0; i < klass->privateHoistedItems.size(); i++) { if (klass->privateHoistedItems[i]->id == item->id) { klass->privateHoistedItems.erase(klass->privateHoistedItems.begin() + i); break; } } } else if (auto ns = parentNamespace.lock()) { if (auto scope = ns->parentScope.lock()) { scope->unhoist(item); } } else if (auto scope = parent.lock()) { scope->unhoist(item); } if (item->genericParameterCount > 0) { if (auto mod = Util::getModule(this).lock()) { for (size_t i = 0; i < mod->genericsUsed.size(); i++) { if (mod->genericsUsed[i]->id == item->id) { mod->genericsUsed.erase(mod->genericsUsed.begin() + i); break; } } } } }; std::shared_ptr<AltaCore::DET::Scope> AltaCore::DET::Scope::getMemberScope(std::shared_ptr<AltaCore::DET::ScopeItem> item) { auto detType = item->nodeType(); if (detType == NodeType::Namespace) { auto ns = std::dynamic_pointer_cast<Namespace>(item); return ns->scope; } else if (detType == NodeType::Function) { auto func = std::dynamic_pointer_cast<Function>(item); return func->scope; } else if (detType == NodeType::Variable) { auto var = std::dynamic_pointer_cast<Variable>(item); if (var->type->bitfield) return var->type->bitfield->scope; if (var->type->isNative || var->type->isUnion()) return nullptr; return var->type->klass->scope; } return nullptr; }; bool AltaCore::DET::Scope::hasParent(std::shared_ptr<Scope> lookup) const { // `s` for `strong` (i.e. locked) if (auto sParent = parent.lock()) { if (sParent->id == lookup->id) return true; return sParent->hasParent(lookup); } else if (auto sModule = parentModule.lock()) { return false; } else if (auto sFunction = parentFunction.lock()) { if (auto sParent = sFunction->parentScope.lock()) { if (sParent->id == lookup->id) return true; return sParent->hasParent(lookup); } } else if (auto sNamespace = parentNamespace.lock()) { if (auto sParent = sNamespace->parentScope.lock()) { if (sParent->id == lookup->id) return true; return sParent->hasParent(lookup); } } else if (auto sClass = parentClass.lock()) { if (auto sParent = sClass->parentScope.lock()) { if (sParent->id == lookup->id) return true; return sParent->hasParent(lookup); } } return false; }; bool AltaCore::DET::Scope::canSee(std::shared_ptr<ScopeItem> item) const { if (item->visibility == Visibility::Private) { auto itemScope = item->parentScope.lock(); if (itemScope && id != itemScope->id && !hasParent(itemScope)) { return false; } } else if (item->visibility == Visibility::Protected) { auto itemClass = Util::getClass(item->parentScope.lock()).lock(); auto thisClass = Util::getClass(shared_from_this()).lock(); if (!itemClass || !thisClass) { return false; } if (thisClass->id != itemClass->id && !thisClass->hasParent(itemClass)) { return false; } } else if (item->visibility == Visibility::Module) { auto itemModule = Util::getModule(item->parentScope.lock().get()).lock(); auto thisModule = Util::getModule(this).lock(); if (!itemModule || !thisModule) { return false; } if (itemModule->id != thisModule->id) { return false; } } else if (item->visibility == Visibility::Package) { auto itemModule = Util::getModule(item->parentScope.lock().get()).lock(); auto thisModule = Util::getModule(this).lock(); if (!itemModule || !thisModule) { return false; } if (!(itemModule->packageInfo.root == thisModule->packageInfo.root)) { return false; } } return true; }; std::weak_ptr<AltaCore::DET::Scope> AltaCore::DET::Scope::findTry() { std::weak_ptr<AltaCore::DET::Scope> result; if (auto scope = parent.lock()) { if (auto func = scope->parentFunction.lock()) { func->throws(true); scope->isTry = true; } if (scope->isTry) { result = scope; return result; } return scope->findTry(); } return result; }; void AltaCore::DET::Scope::addPossibleError(std::shared_ptr<Type> errorType) { if (isTry) { typesThrown.insert(errorType); } else if (auto func = parentFunction.lock()) { func->throws(true); isTry = true; typesThrown.insert(errorType); } else { auto tgt = findTry().lock(); if (tgt) { tgt->addPossibleError(errorType); } else { throw std::runtime_error("Couldn't annotate error anywhere!"); } } }; bool AltaCore::DET::Scope::contains(std::shared_ptr<ScopeItem> item) { auto lockedParent = item->parentScope.lock(); if (!lockedParent) return false; if (id == lockedParent->id) return true; return lockedParent->hasParent(shared_from_this()); }; std::shared_ptr<AltaCore::DET::Function> AltaCore::DET::Scope::findParentLambda() { if (auto func = parentFunction.lock()) { if (func->isLambda) { return func; } } else if (auto scope = parent.lock()) { return scope->findParentLambda(); } return nullptr; }; std::string AltaCore::DET::Scope::toString() const { std::string result; result = "<scope#" + std::to_string(relativeID) + '>'; if (auto pScope = parent.lock()) { result = pScope->toString() + result; } if (auto pMod = parentModule.lock()) { result = '[' + pMod->toString() + "]." + result; } else if (auto pFunc = parentFunction.lock()) { auto str = pFunc->toString(); auto pos = str.find_last_of('.'); result = str.substr(0, pos) + ".[" + str.substr(pos + 1) + "]." + result; } else if (auto pClass = parentClass.lock()) { result = pClass->toString() + '.' + result; } else if (auto pNamespace = parentNamespace.lock()) { result = pNamespace->toString() + '.' + result; } return result; }; std::shared_ptr<AltaCore::DET::Class> AltaCore::DET::Scope::findParentCaptureClass() { if (auto klass = parentClass.lock()) { if (klass->isCaptureClass()) { return klass; } } else if (auto scope = parent.lock()) { return scope->findParentCaptureClass(); } else if (auto func = parentFunction.lock()) { if (auto scope = func->parentScope.lock()) { return scope->findParentCaptureClass(); } } return nullptr; }; auto AltaCore::DET::Scope::findClosestParentScope() -> std::shared_ptr<Scope> { if (auto sParent = parent.lock()) { return sParent; } else if (auto sFunction = parentFunction.lock()) { if (auto sParent = sFunction->parentScope.lock()) { return sParent; } } else if (auto sNamespace = parentNamespace.lock()) { if (auto sParent = sNamespace->parentScope.lock()) { return sParent; } } else if (auto sClass = parentClass.lock()) { if (auto sParent = sClass->parentScope.lock()) { return sParent; } } return nullptr; };
34.534783
209
0.629422
alta-lang
4c7a81b9d3eaa16f1706ee832b9fc83d2f3c63d3
709
cpp
C++
Dev/asd_cpp/core/IO/StaticFile/asd.AsyncStaticFileFactory.cpp
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
37
2015-07-12T14:21:03.000Z
2020-10-17T03:08:17.000Z
Dev/asd_cpp/core/IO/StaticFile/asd.AsyncStaticFileFactory.cpp
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
91
2015-06-14T10:47:22.000Z
2020-06-29T18:05:21.000Z
Dev/asd_cpp/core/IO/StaticFile/asd.AsyncStaticFileFactory.cpp
GCLemon/Altseed
b525740d64001aaed673552eb4ba3e98a321fcdf
[ "FTL" ]
14
2015-07-13T04:15:20.000Z
2021-09-30T01:34:51.000Z
#include "asd.AsyncStaticFileFactory.h" #include "../asd.StaticFile_Imp.h" namespace asd { AsyncStaticFileFactory::AsyncStaticFileFactory(File_Imp * file, Synchronizer::Ptr sync) : file(file) , sync(sync) { } StaticFile_Imp * AsyncStaticFileFactory::LoadFromBaseFile( BaseFile::Ptr & baseFile, const astring & cacheKey) { return new StaticFile_Imp(file, sync, cacheKey, baseFile); } StaticFile_Imp * AsyncStaticFileFactory::LoadFromPackedFile( const astring & cacheKey, const BaseFile::Ptr & packedFile, PackFileInternalHeader & internalHeader, std::shared_ptr<Decryptor> decryptor) { return new StaticFile_Imp(file, sync, cacheKey, packedFile, internalHeader, decryptor); } }
26.259259
89
0.758815
GCLemon
4c81875806e2ac936f9db43c67ac6ff124a06eba
7,709
cxx
C++
PWGLF/STRANGENESS/Lifetimes/selectors/MiniV0efficiency.cxx
Tingchenxi/AliPhysics
16ea676341c0d417efa849673baa54bed717cd54
[ "BSD-3-Clause" ]
null
null
null
PWGLF/STRANGENESS/Lifetimes/selectors/MiniV0efficiency.cxx
Tingchenxi/AliPhysics
16ea676341c0d417efa849673baa54bed717cd54
[ "BSD-3-Clause" ]
null
null
null
PWGLF/STRANGENESS/Lifetimes/selectors/MiniV0efficiency.cxx
Tingchenxi/AliPhysics
16ea676341c0d417efa849673baa54bed717cd54
[ "BSD-3-Clause" ]
1
2018-09-22T01:09:25.000Z
2018-09-22T01:09:25.000Z
#define MiniV0efficiency_cxx #include <TGraph.h> #include "MiniV0efficiency.h" #include <TH2.h> #include <TAxis.h> #include <TStyle.h> #include <TF1.h> #include <AliPDG.h> #include "MiniV0.h" #include "MCparticle.h" #include "HyperTriton2Body.h" #include "Riostream.h" using namespace Lifetimes; using namespace std; MiniV0efficiency::MiniV0efficiency(TTree *) : fChain{nullptr}, fOutputFileName{"MiniV0efficiency_Acceptance.root"} {} void MiniV0efficiency::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); } void MiniV0efficiency::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). //////////////////////////////////////// TString option = GetOption(); //// ////Kaon fHistV0ptData[0] = new TH1D("fHistV0ptDataK", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 4.); fHistV0ptMC[0] = new TH1D("fHistV0ptMCK", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 4.); fHistV0ctData[0] = new TH1D("fHistV0ctDataK", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 20.); fHistV0ctMC[0] = new TH1D("fHistV0ctMCK", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 20.); ctAnalysis[0]=new TH2D("ctAnalysisK","K_ct_Analysis",40,-1.,1.,40,0.,20.); ctAnalysis[0]->SetXTitle("ctRec-ctGen(#it{cm})"); ctAnalysis[0]->SetYTitle("ctGen(#it{cm})"); ////Lambda fHistV0ptData[1] = new TH1D("fHistV0ptDataL", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 4.); fHistV0ptMC[1] = new TH1D("fHistV0ptMCL", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 4.); fHistV0ctData[1] = new TH1D("fHistV0ctDataL", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 40.); fHistV0ctMC[1] = new TH1D("fHistV0ctMCL", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 40.); ctAnalysis[1]=new TH2D("ctAnalysisL","L_ct_Analysis",40,-1.,1.,40,0.,40.); ctAnalysis[1]->SetXTitle("ctRec-ctGen(#it{cm})"); ctAnalysis[1]->SetYTitle("ctGen(#it{cm})"); ///Hypertriton fHistV0ptData[2] = new TH1D("fHistV0ptDataH", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 10.); fHistV0ptMC[2] = new TH1D("fHistV0ptMCH", ";V0 #it{p}_{T} (GeV/#it{c}); Counts", 40, 0., 10.); fHistV0ctData[2] = new TH1D("fHistV0ctDataH", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 40.); fHistV0ctMC[2] = new TH1D("fHistV0ctMCH", ";V0 #it{ct} (#it{cm}); Counts", 40, 0., 40.); ptAnalysisH = new TH2D("ptAnalysisH","H_pt_Analysis",40,-1.,1.,40,0.,10.); ctAnalysis[2]=new TH2D("ctAnalysisH","H_ct_Analysis",40,-2.,2.,40,0.,40.); ctAnalysis[2]->SetXTitle("ctRec-ctGen(#it{cm})"); ctAnalysis[2]->SetYTitle("ctGen(#it{cm})"); AliPDG::AddParticlesToPdgDataBase(); //// } Bool_t MiniV0efficiency::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // When processing keyed objects with PROOF, the object is already loaded // and is available via the fObject pointer. // // This function should contain the \"body\" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. fReader.SetEntry(entry); int p_vec[3]={310,3122,1010010030}; for(int i=0;i<(static_cast<int>(MCparticles.GetSize()));i++){ auto& miniMC=MCparticles[i]; if(miniMC.IsPrimary()){ int part=miniMC.GetPDGcode(); int ind=miniMC.GetRecoIndex(); for (int j=0;j<3;j++){ if(p_vec[j]==part){ float MCmass=miniMC.GetMass(); if(miniMC.GetNBodies()==2 || part!=p_vec[2]){ fHistV0ptMC[j]->Fill(miniMC.GetPt()); fHistV0ctMC[j]->Fill(MCmass*(miniMC.GetDistOverP())); } if(ind>=0){ if(miniMC.GetNBodies()==2 && part==p_vec[2] && miniMC.IsHyperCandidate()==true){ auto& minihyper= V0Hyper[ind]; if(minihyper.GetCandidateInvMass()!=-1){ fHistV0ptData[2]->Fill(minihyper.GetV0pt()); fHistV0ctData[2]->Fill(MCmass*(minihyper.GetDistOverP())); ctAnalysis[2]->Fill(MCmass*(minihyper.GetDistOverP())-MCmass*(miniMC.GetDistOverP()),MCmass*(miniMC.GetDistOverP())); ptAnalysisH->Fill(miniMC.GetPt()-minihyper.GetV0pt(),miniMC.GetPt()); } } else if(part!=p_vec[2] && miniMC.IsHyperCandidate()==false ){ auto& minidata= V0s[ind]; fHistV0ptData[j]->Fill(minidata.GetV0pt()); fHistV0ctData[j]->Fill(MCmass*(minidata.GetDistOverP())); ctAnalysis[j]->Fill(MCmass*(minidata.GetDistOverP())-MCmass*(miniMC.GetDistOverP()),MCmass*(miniMC.GetDistOverP())); } } } } } } return kTRUE; } void MiniV0efficiency::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } void MiniV0efficiency::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. string vec[]={"K","L","H"}; for(int j=0;j<3;j++){ GetOutputList()->Add(fHistV0ptData[j]); GetOutputList()->Add(fHistV0ptMC[j]); GetOutputList()->Add(fHistV0ctData[j]); GetOutputList()->Add(fHistV0ctMC[j]); EffvsPt[j]=(TH1D*)fHistV0ptData[j]->Clone(Form("EffvsPt%s",vec[j].data())); EffvsPt[j]->Divide(fHistV0ptMC[j]); EffvsPt[j]->SetTitle(Form("%s",vec[j].data())); EffvsPt[j]->SetYTitle("MiniV0efficiency x Acceptance"); GetOutputList()->Add(EffvsPt[j]); Effvsct[j]=(TH1D*)fHistV0ctData[j]->Clone(Form("Effvsct%s",vec[j].data())); Effvsct[j]->SetTitle(Form("%s",vec[j].data())); Effvsct[j]->Divide(fHistV0ctMC[j]); Effvsct[j]->SetYTitle("MiniV0efficiency x Acceptance"); GetOutputList()->Add(Effvsct[j]); GetOutputList()->Add(ctAnalysis[j]); } GetOutputList()->Add(ptAnalysisH); TFile output(Form("results/%s", fOutputFileName.data()),"RECREATE"); GetOutputList()->Write(); output.Close(); } void MiniV0efficiency::Init(TTree *tree) { // The Init() function is called when the selector needs to initialize // a new tree or chain. Typically here the reader is initialized. // It is normally not necessary to make changes to the generated // code, but the routine can be extended by the user if needed. // Init() will be called many times when running on PROOF // (once per file to be processed). fReader.SetTree(tree); } Bool_t MiniV0efficiency::Notify() { // The Notify() function is called when a new file is opened. This // can be either for a new TTree in a TChain or when when a new TTree // is started when using PROOF. It is normally not necessary to make changes // to the generated code, but the routine can be extended by the // user if needed. The return value is currently not used. return kTRUE; }
35.200913
133
0.632767
Tingchenxi
4c85e55dade9c7d499fe842c2a549f220afc6849
13,690
hpp
C++
src/inference/include/openvino/runtime/infer_request.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1
2022-03-25T10:35:59.000Z
2022-03-25T10:35:59.000Z
src/inference/include/openvino/runtime/infer_request.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
2
2022-03-28T13:18:55.000Z
2022-03-28T13:18:57.000Z
src/inference/include/openvino/runtime/infer_request.hpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // /** * @brief A header file that provides InferRequest. * * @file openvino/runtime/infer_request.hpp */ #pragma once #include <map> #include <memory> #include <string> #include "openvino/core/node_output.hpp" #include "openvino/runtime/common.hpp" #include "openvino/runtime/profiling_info.hpp" #include "openvino/runtime/tensor.hpp" #include "openvino/runtime/variable_state.hpp" namespace InferenceEngine { class IInferRequestInternal; } // namespace InferenceEngine namespace ov { class CompiledModel; /** * @brief This is a class of infer request that can be run in asynchronous or synchronous manners. */ class OPENVINO_RUNTIME_API InferRequest { std::shared_ptr<InferenceEngine::IInferRequestInternal> _impl; std::shared_ptr<void> _so; /** * @brief Constructs InferRequest from the initialized std::shared_ptr. * @param impl Initialized shared pointer. * @param so Plugin to use. This is required to ensure that InferRequest can work properly even if a plugin object * is destroyed. */ InferRequest(const std::shared_ptr<InferenceEngine::IInferRequestInternal>& impl, const std::shared_ptr<void>& so); friend class ov::CompiledModel; public: /** * @brief Default constructor. */ InferRequest() = default; /** * @brief Default copy constructor. * @param other Another InferRequest object. */ InferRequest(const InferRequest& other) = default; /** * @brief Default copy assignment operator. * @param other Another InferRequest object. * @return Reference to the current object. */ InferRequest& operator=(const InferRequest& other) = default; /** * @brief Default move constructor. * @param other Another InferRequest object. */ InferRequest(InferRequest&& other) = default; /** * @brief Default move assignment operator. * @param other Another InferRequest object. * @return Reference to the current object. */ InferRequest& operator=(InferRequest&& other) = default; /** * @brief Destructor that preserves unloading order of implementation object and reference to the library. * @note To preserve destruction order inside the default generated assignment operator, `_impl` is stored before * `_so`. Use the destructor to remove implementation object before referencing to the library explicitly. */ ~InferRequest(); /** * @brief Sets an input/output tensor to infer on. * * @param tensor_name Name of the input or output tensor. * @param tensor Reference to the tensor. The element_type and shape of the tensor must match * the model's input/output element_type and size. */ void set_tensor(const std::string& tensor_name, const Tensor& tensor); /** * @brief Sets an input/output tensor to infer. * @param port Port of the input or output tensor. Use the following methods to get the ports: * - ov::Model::input() * - ov::Model::inputs() * - ov::Model::outputs() * - ov::Model::outputs() * - ov::CompiledModel::input() * - ov::CompiledModel::inputs() * - ov::CompiledModel::outputs() * - ov::CompiledModel::outputs() * @param tensor Reference to a tensor. The element_type and shape of a tensor must match * the model's input/output element_type and size. */ void set_tensor(const ov::Output<const ov::Node>& port, const Tensor& tensor); /** * @brief Sets an input/output tensor to infer. * @param port Port of the input or output tensor. Use the following methods to get the ports: * - ov::Model::input() * - ov::Model::inputs() * - ov::Model::outputs() * - ov::Model::outputs() * - ov::CompiledModel::input() * - ov::CompiledModel::inputs() * - ov::CompiledModel::outputs() * - ov::CompiledModel::outputs() * @param tensor Reference to a tensor. The element_type and shape of a tensor must match * the model's input/output element_type and size. */ void set_tensor(const ov::Output<ov::Node>& port, const Tensor& tensor); /** * @brief Sets a batch of tensors for input data to infer by tensor name. * Model input must have batch dimension, and the number of @p tensors must match the batch size. * The current version supports setting tensors to model inputs only. If @p tensor_name is associated * with output (or any other non-input node), an exception is thrown. * * @param tensor_name Name of the input tensor. * @param tensors Input tensors for batched infer request. The type of each tensor must match the model * input element type and shape (except batch dimension). Total size of tensors must match the input size. */ void set_tensors(const std::string& tensor_name, const std::vector<Tensor>& tensors); /** * @brief Sets a batch of tensors for input data to infer by input port. * Model input must have batch dimension, and the number of @p tensors must match the batch size. * The current version supports setting tensors to model inputs only. If @p port is associated * with output (or any other non-input node), an exception is thrown. * * @param port Port of the input tensor. * @param tensors Input tensors for batched infer request. The type of each tensor must match the model * input element type and shape (except batch dimension). Total size of tensors must match the input size. */ void set_tensors(const ov::Output<const ov::Node>& port, const std::vector<Tensor>& tensors); /** * @brief Sets an input tensor to infer. * * @param idx Index of the input tensor. If @p idx is greater than the number of model inputs, an exception * is thrown. * @param tensor Reference to the tensor. The element_type and shape of the tensor must match * the model's input/output element_type and size. */ void set_input_tensor(size_t idx, const Tensor& tensor); /** * @brief Sets an input tensor to infer models with single input. * @note If model has several inputs, an exception is thrown. * @param tensor Reference to the input tensor. */ void set_input_tensor(const Tensor& tensor); /** * @brief Sets a batch of tensors for single input data. * Model input must have batch dimension, and the number of @p tensors must match the batch size. * * @param tensors Input tensors for batched infer request. The type of each tensor must match the model * input element type and shape (except batch dimension). Total size of tensors must match the input size. */ void set_input_tensors(const std::vector<Tensor>& tensors); /** * @brief Sets a batch of tensors for input data to infer by input name. * Model input must have batch dimension, and number of @p tensors must match the batch size. * * @param idx Name of the input tensor. * @param tensors Input tensors for batched infer request. The type of each tensor must match the model * input element type and shape (except batch dimension). Total size of tensors must match the input size. */ void set_input_tensors(size_t idx, const std::vector<Tensor>& tensors); /** * @brief Sets an output tensor to infer. * @note Index of the input preserved accross ov::Model, ov::CompiledModel, and ov::InferRequest. * @param idx Index of the output tensor. * @param tensor Reference to the output tensor. The type of the tensor must match the model output element type and * shape. */ void set_output_tensor(size_t idx, const Tensor& tensor); /** * @brief Sets an output tensor to infer models with single output. * @note If model has several outputs, an exception is thrown. * @param tensor Reference to the output tensor. */ void set_output_tensor(const Tensor& tensor); /** * @brief Gets an input/output tensor for inference by tensor name. * @param tensor_name Name of a tensor to get. * @return The tensor with name @p tensor_name. If the tensor is not found, an exception is thrown. */ Tensor get_tensor(const std::string& tensor_name); /** * @brief Gets an input/output tensor for inference. * @note If the tensor with the specified @p port is not found, an exception is thrown. * @param port Port of the tensor to get. * @return Tensor for the port @p port. */ Tensor get_tensor(const ov::Output<const ov::Node>& port); /** * @brief Gets an input/output tensor for inference. * @note If the tensor with the specified @p port is not found, an exception is thrown. * @param port Port of the tensor to get. * @return Tensor for the port @p port. */ Tensor get_tensor(const ov::Output<ov::Node>& port); /** * @brief Gets an input tensor for inference. * * @param idx Index of the tensor to get. * @return Tensor with the input index @p idx. If the tensor with the specified @p idx is not found, an exception * is thrown. */ Tensor get_input_tensor(size_t idx); /** * @brief Gets an input tensor for inference. * * @return The input tensor for the model. If model has several inputs, an exception is thrown. */ Tensor get_input_tensor(); /** * @brief Gets an output tensor for inference. * * @param idx Index of the tensor to get. * @return Tensor with the output index @p idx. If the tensor with the specified @p idx is not found, an exception * is thrown. */ Tensor get_output_tensor(size_t idx); /** * @brief Gets an output tensor for inference. * * @return Output tensor for the model. If model has several outputs, an exception is thrown. */ Tensor get_output_tensor(); /** * @brief Infers specified input(s) in synchronous mode. * @note It blocks all methods of InferRequest while request is ongoing (running or waiting in a queue). * Calling any method leads to throwning the ov::Busy exception. */ void infer(); /** * @brief Cancels inference request. */ void cancel(); /** * @brief Queries performance measures per layer to identify the most time consuming operation. * @note Not all plugins provide meaningful data. * @return Vector of profiling information for operations in a model. */ std::vector<ProfilingInfo> get_profiling_info() const; /** * @brief Starts inference of specified input(s) in asynchronous mode. * @note It returns immediately. Inference starts also immediately. * Calling any method while the request in a running state leads to throwning the ov::Busy exception. */ void start_async(); /** * @brief Waits for the result to become available. Blocks until the result * becomes available. */ void wait(); /** * @brief Waits for the result to become available. Blocks until the specified timeout has elapsed or the result * becomes available, whichever comes first. * * @param timeout Maximum duration, in milliseconds, to block for. * @return True if inference request is ready and false, otherwise. */ bool wait_for(const std::chrono::milliseconds timeout); /** * @brief Sets a callback std::function that is called on success or failure of an asynchronous request. * @param callback callback object which will be called on when inference finish. * @warning Do not capture strong references to OpenVINO runtime objects into callback. * Following objects should not be captured like: * - ov::InferRequest * - ov::ExecutableNetwork * - ov::Core * As specified objects implement shared reference concept do not capture this objects by value. * It can lead to memory leaks or undefined behaviour! * Try to use weak references or pointers. */ void set_callback(std::function<void(std::exception_ptr)> callback); /** * @brief Gets state control interface for the given infer request. * * State control essential for recurrent models. * @return Vector of Variable State objects. */ std::vector<VariableState> query_state(); /** * @brief Returns a compiled model that creates this inference request. * @return Compiled model object. */ CompiledModel get_compiled_model(); /** * @brief Checks if the current InferRequest object is not initialized. * @return True if the current InferRequest object is not initialized; false, otherwise. */ bool operator!() const noexcept; /** * @brief Checks if the current InferRequest object is initialized. * @return True if the current InferRequest object is initialized; false, otherwise. */ explicit operator bool() const noexcept; /** * @brief Compares whether this request wraps the same impl underneath. * @param other Another inference request. * @return True if the current InferRequest object does not wrap the same impl as the operator's arg. */ bool operator!=(const InferRequest& other) const noexcept; /** * @brief Compares whether this request wraps the same impl underneath. * @param other Another inference request. * @return True if the current InferRequest object wraps the same impl as the operator's arg. */ bool operator==(const InferRequest& other) const noexcept; }; } // namespace ov
38.672316
120
0.676991
ryanloney
4c85f35e4c49fdb180f8827821bb25dcaa73bc6a
357
cpp
C++
src/sim/missile/flight.cpp
Terebinth/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
117
2015-01-13T14:48:49.000Z
2022-03-16T01:38:19.000Z
src/sim/missile/flight.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
4
2015-05-01T13:09:53.000Z
2017-07-22T09:11:06.000Z
src/sim/missile/flight.cpp
darongE/freefalcon-central
c28d807183ab447ef6a801068aa3769527d55deb
[ "BSD-2-Clause" ]
78
2015-01-13T09:27:47.000Z
2022-03-18T14:39:09.000Z
#include "stdhdr.h" #include "missile.h" #include "drawable.h" void MissileClass::Flight(void) { if (inputData->displayType not_eq DisplayHTS and display) { display->DisplayExit(); display = NULL; } Atmosphere(); FlightControlSystem(); Aerodynamics(); Engine(); Accelerometers(); EquationsOfMotion(); }
17.85
61
0.633053
Terebinth
4c869658add13503aa2fb39346360ba3bc499304
1,329
cpp
C++
20_Sources/IpcAdapter/Core/src/SimplePipelineFrame.cpp
ssproessig/ipc-adapter
466b9c12aa15561e75742b61b88ce5732eb505af
[ "MIT" ]
1
2019-12-04T08:06:52.000Z
2019-12-04T08:06:52.000Z
20_Sources/IpcAdapter/Core/src/SimplePipelineFrame.cpp
ssproessig/ipc-adapter
466b9c12aa15561e75742b61b88ce5732eb505af
[ "MIT" ]
16
2019-09-06T18:38:21.000Z
2019-10-20T18:34:38.000Z
20_Sources/IpcAdapter/Core/src/SimplePipelineFrame.cpp
ssproessig/ipc-adapter
466b9c12aa15561e75742b61b88ce5732eb505af
[ "MIT" ]
null
null
null
#include "Core/api/SimplePipelineFrame.h" #include <QByteArray> #include <QMap> #include <QString> #include <QVariant> using IpcAdapter::Core::IPipelineFrame; using IpcAdapter::Core::SimplePipelineFrame; struct SimplePipelineFrame::Data { IPipelineFrame::MetaDataMap metaData; IPipelineFrame::RawData rawData; }; SimplePipelineFrame::SimplePipelineFrame(): d(std::make_unique<Data>()) {} SimplePipelineFrame::SimplePipelineFrame(IPipelineFrame::RawData const& anInitialDataBuffer) : d(std::make_unique<Data>()) { d->rawData = anInitialDataBuffer; } SimplePipelineFrame::SimplePipelineFrame (std::shared_ptr<IPipelineFrame> const& anotherPipelineFrame) : d(std::make_unique<Data>()) { d->rawData = anotherPipelineFrame->getData(); d->metaData = anotherPipelineFrame->getMetaData(); } SimplePipelineFrame::~SimplePipelineFrame() = default; IPipelineFrame::RawData const& SimplePipelineFrame::getData() const { return d->rawData; } IPipelineFrame::MetaDataMap const& SimplePipelineFrame::getMetaData() const { return d->metaData; } void SimplePipelineFrame::setData(IPipelineFrame::RawData const& aRawDataBuffer) { d->rawData = aRawDataBuffer; } void SimplePipelineFrame::updateMetaData(QString const& aKey, QVariant const& aValue) { d->metaData[aKey] = aValue; }
19.835821
92
0.753198
ssproessig
4c86ca90553a4d08102547fef689eff05b0c9280
10,225
hpp
C++
src/libraries/dynamicMesh/dynamicMesh/polyTopoChange/polyTopoChange/addObject/polyAddFace.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/dynamicMesh/dynamicMesh/polyTopoChange/polyTopoChange/addObject/polyAddFace.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
src/libraries/dynamicMesh/dynamicMesh/polyTopoChange/polyTopoChange/addObject/polyAddFace.hpp
MrAwesomeRocks/caelus-cml
55b6dc5ba47d0e95c07412d9446ac72ac11d7fd7
[ "mpich2" ]
null
null
null
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS 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. CAELUS 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 CAELUS. If not, see <http://www.gnu.org/licenses/>. Class CML::polyAddFace Description A face addition data class. A face can be inflated either from a point or from another face and can either be in internal or a boundary face. \*---------------------------------------------------------------------------*/ #ifndef polyAddFace_H #define polyAddFace_H // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #include "label.hpp" #include "face.hpp" #include "topoAction.hpp" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace CML { /*---------------------------------------------------------------------------*\ Class polyAddFace Declaration \*---------------------------------------------------------------------------*/ class polyAddFace : public topoAction { // Private data //- Face identifier face face_; //- Face owner label owner_; //- Face neighbour label neighbour_; //- Master point ID for faces blown up from points label masterPointID_; //- Master edge ID for faces blown up from edges label masterEdgeID_; //- Master face ID for faces blown up from faces label masterFaceID_; //- Does the face flux need to be flipped bool flipFaceFlux_; //- Boundary patch ID label patchID_; //- Face zone ID label zoneID_; //- Face zone flip bool zoneFlip_; public: // Static data members //- Runtime type information TypeName("addFace"); // Constructors //- Construct null. Used for constructing lists polyAddFace() : face_(0), owner_(-1), neighbour_(-1), masterPointID_(-1), masterEdgeID_(-1), masterFaceID_(-1), flipFaceFlux_(false), patchID_(-1), zoneID_(-1), zoneFlip_(false) {} //- Construct from components polyAddFace ( const face& f, const label owner, const label neighbour, const label masterPointID, const label masterEdgeID, const label masterFaceID, const bool flipFaceFlux, const label patchID, const label zoneID, const bool zoneFlip ) : face_(f), owner_(owner), neighbour_(neighbour), masterPointID_(masterPointID), masterEdgeID_(masterEdgeID), masterFaceID_(masterFaceID), flipFaceFlux_(flipFaceFlux), patchID_(patchID), zoneID_(zoneID), zoneFlip_(zoneFlip) { if (face_.size() < 3) { FatalErrorInFunction << "Invalid face: less than 3 points. " << "This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (min(face_) < 0) { FatalErrorInFunction << "Face contains invalid vertex ID: " << face_ << ". " << "This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (min(owner_, neighbour_) >= 0 && owner_ == neighbour_) { FatalErrorInFunction << "Face owner and neighbour are identical. " << "This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (neighbour_ >= 0 && patchID >= 0) { FatalErrorInFunction << "Patch face has got a neighbour. Patch ID: " << patchID << ". This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (owner_ < 0 && zoneID < 0) { FatalErrorInFunction << "Face has no owner and is not in a zone. " << "This is not allowed.\n" << "Face: " << face_ << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } if (zoneID_ == -1 && zoneFlip) { FatalErrorInFunction << "Specified zone flip for a face that does not " << "belong to zone. This is not allowed.\n" << "Face: " << face_ << " masterPointID:" << masterPointID_ << " masterEdgeID:" << masterEdgeID_ << " masterFaceID:" << masterFaceID_ << " patchID:" << patchID_ << " owner:" << owner_ << " neighbour:" << neighbour_ << abort(FatalError); } } //- Construct and return a clone virtual autoPtr<topoAction> clone() const { return autoPtr<topoAction>(new polyAddFace(*this)); } // Default Destructor // Member Functions //- Return face const face& newFace() const { return face_; } //- Return owner cell label owner() const { return owner_; } //- Return neighour cell label neighbour() const { return neighbour_; } //- Is the face mastered by a point bool isPointMaster() const { return masterPointID_ >= 0; } //- Is the face mastered by an edge bool isEdgeMaster() const { return masterEdgeID_ >= 0; } //- Is the face mastered by another face bool isFaceMaster() const { return masterFaceID_ >= 0; } //- Is the face appended with no master bool appended() const { return !isPointMaster() && !isEdgeMaster() && !isFaceMaster(); } //- Return master point ID label masterPointID() const { return masterPointID_; } //- Return master edge ID label masterEdgeID() const { return masterEdgeID_; } //- Return master face ID label masterFaceID() const { return masterFaceID_; } //- Does the face flux need to be flipped bool flipFaceFlux() const { return flipFaceFlux_; } //- Does the face belong to a boundary patch? bool isInPatch() const { return patchID_ >= 0; } //- Boundary patch ID label patchID() const { return patchID_; } //- Does the face belong to a zone? bool isInZone() const { return zoneID_ >= 0; } //- Is the face only a zone face (i.e. not belonging to a cell) bool onlyInZone() const { return zoneID_ >= 0 && owner_ < 0 && neighbour_ < 0; } //- Face zone ID label zoneID() const { return zoneID_; } //- Face zone flip label zoneFlip() const { return zoneFlip_; } }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace CML // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
28.966006
79
0.434523
MrAwesomeRocks
4c8842c49ecfa8362ef045f676e4899280e94206
4,443
cpp
C++
src/libtextmode/textmode.cpp
joelpob/ansilove-term
2842c41bc2429a98d51e02e2d6eb55254afa79bb
[ "BSD-3-Clause" ]
null
null
null
src/libtextmode/textmode.cpp
joelpob/ansilove-term
2842c41bc2429a98d51e02e2d6eb55254afa79bb
[ "BSD-3-Clause" ]
null
null
null
src/libtextmode/textmode.cpp
joelpob/ansilove-term
2842c41bc2429a98d51e02e2d6eb55254afa79bb
[ "BSD-3-Clause" ]
null
null
null
#include "textmode.h" #include "file_formats/ansi.h" #include "file_formats/ansiedit.h" #include "file_formats/artworx.h" #include "file_formats/ascii.h" #include "file_formats/binary_text.h" #include "file_formats/ice_draw.h" #include "file_formats/pc_board.h" #include "file_formats/tundra_draw.h" #include "file_formats/xbin.h" #include <cstring> textmode_t::textmode_t(const std::string& filename) : sauce(filename) { this->filename = filename; options = sauce.get_options(); if(!sauce.title.empty()) { title = sauce.title; } if(!sauce.author.empty()) { author = sauce.author; } if(!sauce.group.empty()) { group = sauce.group; } } inline bool extension_test(std::string& extension, const char* extension_suffix) { return strcasecmp(extension.c_str(), extension_suffix) == 0; } textmode_type_t check_extension(const std::string& filename) { size_t pos = filename.rfind("."); if(pos == std::string::npos) { return textmode_type_t::undefined; } std::string extension = filename.substr(pos + 1); if(extension_test(extension, "ans")) { return textmode_type_t::ansi; } else if(extension_test(extension, "ansiedit")) { return textmode_type_t::ansiedit; } else if(extension_test(extension, "adf")) { return textmode_type_t::artworx; } else if(extension_test(extension, "asc") || extension_test(extension, "diz") || extension_test(extension, "nfo") || extension_test(extension, "txt")) { return textmode_type_t::ascii; } else if(extension_test(extension, "bin")) { return textmode_type_t::binary_text; } else if(extension_test(extension, "idf")) { return textmode_type_t::ice_draw; } else if(extension_test(extension, "pcb")) { return textmode_type_t::pc_board; } else if(extension_test(extension, "tnd")) { return textmode_type_t::tundra_draw; } else if(extension_test(extension, "xb")) { return textmode_type_t::xbin; } return textmode_type_t::undefined; } textmode_t load_artwork(std::string filename) { auto textmode_type = check_extension(filename); switch(textmode_type) { case textmode_type_t::ansiedit: return ansiedit_t(filename); case textmode_type_t::artworx: return artworx_t(filename); case textmode_type_t::binary_text: return binary_text_t(filename); case textmode_type_t::ice_draw: return ice_draw_t(filename); case textmode_type_t::pc_board: return pc_board_t(filename); case textmode_type_t::tundra_draw: return tundra_draw_t(filename); case textmode_type_t::xbin: return xbin_t(filename); case textmode_type_t::ansi: return ansi_t(filename); case textmode_type_t::ascii: return ascii_t(filename); case textmode_type_t::undefined: default: throw file_format_not_recognized_t(); } } std::ostream& operator<<(std::ostream& ostream, const textmode_type_t& type) { switch(type) { case textmode_type_t::ansi: ostream << "ANSi"; break; case textmode_type_t::ansiedit: ostream << "AnsiEdit"; break; case textmode_type_t::artworx: ostream << "Artworx"; break; case textmode_type_t::ascii: ostream << "ASCii (8-Bit)"; break; case textmode_type_t::binary_text: ostream << "Binary Text"; break; case textmode_type_t::ice_draw: ostream << "Ice Draw"; break; case textmode_type_t::pc_board: ostream << "PC Board"; break; case textmode_type_t::tundra_draw: ostream << "Tundra Draw"; break; case textmode_type_t::xbin: ostream << "XBIN"; break; case textmode_type_t::undefined: ostream << "Undefined"; break; } return ostream; } std::ostream& operator<<(std::ostream& ostream, textmode_t& artwork) { ostream << " Columns: " << artwork.image_data.columns << std::endl; ostream << " Rows: " << artwork.image_data.rows << std::endl; ostream << " Type: " << artwork.type << std::endl; ostream << " Title: " << artwork.title << std::endl; ostream << " Author: " << artwork.author << std::endl; ostream << " Group: " << artwork.group << std::endl; return ostream; }
30.854167
80
0.635607
joelpob
4c889cd5d67439f9e8986c192c2f06c0adc81485
26
cpp
C++
source/pch/stdafx.cpp
chillpert/renderer
9c953cef10ebec7a2c8fe5763a2c10105729deab
[ "Zlib" ]
2
2020-11-18T18:20:12.000Z
2020-12-18T19:24:00.000Z
source/pch/stdafx.cpp
chillpert/rayex
9c953cef10ebec7a2c8fe5763a2c10105729deab
[ "Zlib" ]
null
null
null
source/pch/stdafx.cpp
chillpert/rayex
9c953cef10ebec7a2c8fe5763a2c10105729deab
[ "Zlib" ]
null
null
null
#include "pch/stdafx.hpp"
13
25
0.730769
chillpert
4c8a8af00e7ffcf623871fa7014b9910b9d993cf
3,716
hpp
C++
src/util/intervalrunner.hpp
kit-algo/TCPSPSuite
01499b4fb0f28bda72115a699cd762c70d7fff63
[ "MIT" ]
3
2018-05-02T11:45:57.000Z
2020-09-14T08:35:43.000Z
src/util/intervalrunner.hpp
kit-algo/TCPSPSuite
01499b4fb0f28bda72115a699cd762c70d7fff63
[ "MIT" ]
null
null
null
src/util/intervalrunner.hpp
kit-algo/TCPSPSuite
01499b4fb0f28bda72115a699cd762c70d7fff63
[ "MIT" ]
null
null
null
#ifndef INTERVALRUNNER_HPP #define INTERVALRUNNER_HPP #include "../datastructures/maybe.hpp" template<class It1, class It2, class Point, class PointGetter, class EventHandler, class DataGetter, class Data> void process_intervals(It1 start_a, It1 end_a, It2 start_b, It2 end_b, PointGetter &pg, EventHandler &handler, DataGetter &dg) { using CbData = Maybe<Data>; Point last_point = Point(); if ((start_a != end_a) && ((start_b == end_b) || (pg(start_a, true) < pg(start_b, true)))) { last_point = pg(start_a, true); } bool event_a; bool event_b; if ((start_a != end_a) && (pg(start_a, true) == last_point)) { event_a = true; } else { event_a = false; } if ((start_b != end_b) && (pg(start_b, true) == last_point)) { event_b = true; } else { event_b = false; } handler(last_point, event_a ? CbData(dg(start_a)) : CbData(), CbData(), event_b ? CbData(dg(start_b)) : CbData(), CbData() ); while ((start_a != end_a) || (start_b != end_b)) { Point next_point = last_point; bool a_ends = false; bool a_starts = false; bool b_ends = false; bool b_starts = false; if (start_a != end_a) { if (pg(start_a, true) > last_point) { a_starts = true; next_point = pg(start_a, true); } else { #ifdef ENABLE_ASSERTIONS assert(pg(start_a, false) > last_point); #endif a_ends = true; next_point = pg(start_a, false); if ((start_a + 1) != end_a) { if (pg((start_a + 1), true) == next_point) { a_starts = true; } } } } if (start_b != end_b) { //std::cout << "Comparing for B: " << pg(start_b, true) << " vs " << last_point << "\n"; if (pg(start_b, true) > last_point) { //std::cout << "Taking B's lower point\n"; if ((next_point == last_point) || (pg(start_b, true) < next_point)) { b_starts = true; a_starts = false; a_ends = false; next_point = pg(start_b, true); } else if (pg(start_b, true) == next_point) { b_starts = true; } } else { #ifdef ENABLE_ASSERTIONS assert(pg(start_b, false) > last_point); #endif if ((next_point == last_point) || (pg(start_b, false) < next_point)) { b_starts = false; b_ends = true; a_starts = false; a_ends = false; next_point = pg(start_b, false); } else if (pg(start_b, false) == next_point) { b_ends = true; } if ((b_ends) && ((start_b + 1) != end_b) && (pg((start_b + 1), true) == next_point)) { b_starts = true; } } } //std::cout << "A Starts: " << a_starts << " / A Ends: " << a_ends ; //std::cout << "B Starts: " << b_starts << " / B Ends: " << b_ends ; //std::cout << "Next point: " << next_point ; handler(next_point, // start data in A: start_a starts here a_starts && (!a_ends) ? CbData(dg(start_a)) : // Start data in A: (start_a + 1) starts here a_starts && a_ends ? CbData(dg(start_a + 1)) : // Start data in A: nothing starts here CbData(), a_ends ? CbData(dg(start_a)) : CbData(), // start data in B: start_b starts here b_starts && (!b_ends) ? CbData(dg(start_b)) : // Start data in B: (start_b + 1) starts here b_starts && b_ends ? CbData(dg(start_b + 1)) : // Start data in B: nothing starts here CbData(), b_ends ? CbData(dg(start_b)) : CbData() ); last_point = next_point; if (a_ends) { start_a++; } if (b_ends) { start_b++; } } } #endif
28.366412
128
0.541981
kit-algo
4c8b9d079e7f32b39542a62dabd82a51c6b2739e
5,603
cpp
C++
third_party/WebKit/Source/platform/animation/AnimationTranslationUtil.cpp
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
third_party/WebKit/Source/platform/animation/AnimationTranslationUtil.cpp
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/animation/AnimationTranslationUtil.cpp
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
/* * Copyright (C) 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "platform/animation/AnimationTranslationUtil.h" #include "platform/animation/CompositorTransformOperations.h" #include "platform/transforms/InterpolatedTransformOperation.h" #include "platform/transforms/Matrix3DTransformOperation.h" #include "platform/transforms/MatrixTransformOperation.h" #include "platform/transforms/PerspectiveTransformOperation.h" #include "platform/transforms/RotateTransformOperation.h" #include "platform/transforms/ScaleTransformOperation.h" #include "platform/transforms/SkewTransformOperation.h" #include "platform/transforms/TransformOperations.h" #include "platform/transforms/TransformationMatrix.h" #include "platform/transforms/TranslateTransformOperation.h" namespace blink { void toCompositorTransformOperations( const TransformOperations& transformOperations, CompositorTransformOperations* outTransformOperations) { // We need to do a deep copy the transformOperations may contain ref pointers // to TransformOperation objects. for (const auto& operation : transformOperations.operations()) { switch (operation->type()) { case TransformOperation::ScaleX: case TransformOperation::ScaleY: case TransformOperation::ScaleZ: case TransformOperation::Scale3D: case TransformOperation::Scale: { auto transform = static_cast<const ScaleTransformOperation*>(operation.get()); outTransformOperations->appendScale(transform->x(), transform->y(), transform->z()); break; } case TransformOperation::TranslateX: case TransformOperation::TranslateY: case TransformOperation::TranslateZ: case TransformOperation::Translate3D: case TransformOperation::Translate: { auto transform = static_cast<const TranslateTransformOperation*>(operation.get()); DCHECK(transform->x().isFixed() && transform->y().isFixed()); outTransformOperations->appendTranslate( transform->x().value(), transform->y().value(), transform->z()); break; } case TransformOperation::RotateX: case TransformOperation::RotateY: case TransformOperation::Rotate3D: case TransformOperation::Rotate: { auto transform = static_cast<const RotateTransformOperation*>(operation.get()); outTransformOperations->appendRotate( transform->x(), transform->y(), transform->z(), transform->angle()); break; } case TransformOperation::SkewX: case TransformOperation::SkewY: case TransformOperation::Skew: { auto transform = static_cast<const SkewTransformOperation*>(operation.get()); outTransformOperations->appendSkew(transform->angleX(), transform->angleY()); break; } case TransformOperation::Matrix: { auto transform = static_cast<const MatrixTransformOperation*>(operation.get()); TransformationMatrix m = transform->matrix(); outTransformOperations->appendMatrix( TransformationMatrix::toSkMatrix44(m)); break; } case TransformOperation::Matrix3D: { auto transform = static_cast<const Matrix3DTransformOperation*>(operation.get()); TransformationMatrix m = transform->matrix(); outTransformOperations->appendMatrix( TransformationMatrix::toSkMatrix44(m)); break; } case TransformOperation::Perspective: { auto transform = static_cast<const PerspectiveTransformOperation*>(operation.get()); outTransformOperations->appendPerspective(transform->perspective()); break; } case TransformOperation::Interpolated: { TransformationMatrix m; operation->apply(m, FloatSize()); outTransformOperations->appendMatrix( TransformationMatrix::toSkMatrix44(m)); break; } case TransformOperation::Identity: outTransformOperations->appendIdentity(); break; case TransformOperation::None: // Do nothing. break; } // switch } // for each operation } } // namespace blink
43.1
80
0.698197
xzhan96
4c8bbaf097e4c8fad91a90bf07dc5236a213b0d7
8,009
hpp
C++
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_BlockEncrypt.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
216
2019-03-09T06:41:28.000Z
2022-02-25T16:27:19.000Z
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_BlockEncrypt.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
9
2020-09-27T08:00:52.000Z
2021-07-02T14:27:31.000Z
Source/AllProjects/SecureUtils/CIDCrypto/CIDCrypto_BlockEncrypt.hpp
MarkStega/CIDLib
82014e064eef51cad998bf2c694ed9c1c8cceac6
[ "MIT" ]
29
2019-03-09T10:12:24.000Z
2021-03-03T22:25:29.000Z
// // FILE NAME: CIDCrypto_BlockEncrypt.hpp // // AUTHOR: Dean Roddey // // CREATED: 10/21/1997 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the abstract base class TBlockEncrypter, which is // the base abstraction for all block based encryption schemes. This allows // many different block encryption schemes to be manipulated via this basic // interface. // // Actually most of the work is done here. The derived classes just have // to provide the basic ability to encrypt/decrypt blocks of data upon our // request. We handle the various block encryption modes for them. This is // slower, but drastically reduces the likelihood of error. // // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once #pragma CIDLIB_PACK(CIDLIBPACK) // --------------------------------------------------------------------------- // CLASS: TBlockEncrypter // PREFIX: cryp // --------------------------------------------------------------------------- class CIDCRYPTEXP TBlockEncrypter : public TObject { public : // ------------------------------------------------------------------- // Constructors and Destructor // ------------------------------------------------------------------- TBlockEncrypter() = delete; TBlockEncrypter(const TBlockEncrypter&) = delete; ~TBlockEncrypter(); // ------------------------------------------------------------------- // Public operators // ------------------------------------------------------------------- TBlockEncrypter& operator=(const TBlockEncrypter&) = delete; // ------------------------------------------------------------------- // Public, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TCard4 c4BlockSize() const { return m_c4BlockSize; } tCIDLib::TCard4 c4Decrypt ( const TMemBuf& mbufCypher , TMemBuf& mbufPlain , const tCIDLib::TCard4 c4CypherBytes , const tCIDLib::TCard1* const pc1IV = nullptr ); tCIDLib::TCard4 c4Decrypt ( const tCIDLib::TCard1* const pc1Cypher , TMemBuf& mbufPlain , const tCIDLib::TCard4 c4CypherBytes , const tCIDLib::TCard1* const pc1IV = nullptr ); tCIDLib::TCard4 c4Decrypt ( const TMemBuf& mbufCypher , TString& strPlain , const tCIDLib::TCard4 c4CypherBytes , const tCIDLib::TCard1* const pc1IV = nullptr ); tCIDLib::TCard4 c4Decrypt ( const tCIDLib::TCard1* const pc1Cypher , tCIDLib::TCard1* const pc1Plain , const tCIDLib::TCard4 c4CypherBytes , const tCIDLib::TCard4 c4MaxOutBytes , const tCIDLib::TCard1* const pc1IV = nullptr ); tCIDLib::TCard4 c4Encrypt ( const TMemBuf& mbufPlain , TMemBuf& mbufCypher , const tCIDLib::TCard4 c4PlainBytes , const tCIDLib::TCard1* const pc1IV = nullptr ); tCIDLib::TCard4 c4Encrypt ( const tCIDLib::TCard1* const pc1Plain , TMemBuf& mbufCypher , const tCIDLib::TCard4 c4PlainBytes , const tCIDLib::TCard1* const pc1IV = nullptr ); tCIDLib::TCard4 c4Encrypt ( const TString& strPlain , TMemBuf& mbufCypher , const tCIDLib::TCard1* const pc1IV = nullptr ); tCIDLib::TCard4 c4Encrypt ( const tCIDLib::TCard1* const pc1Plain , tCIDLib::TCard1* const pc1Cypher , const tCIDLib::TCard4 c4PlainBytes , const tCIDLib::TCard4 c4MaxOutBytes , const tCIDLib::TCard1* const pc1IV = nullptr ); tCIDCrypto::EBlockModes eMode() const; tCIDCrypto::EBlockModes eMode ( const tCIDCrypto::EBlockModes eNewMode ); tCIDLib::TVoid Reset(); protected : // ------------------------------------------------------------------- // Hidden constructors and operators // ------------------------------------------------------------------- TBlockEncrypter ( const tCIDLib::TCard4 c4BlockSize , const tCIDCrypto::EBlockModes eMode ); // ------------------------------------------------------------------- // Protected, virtual methods // ------------------------------------------------------------------- virtual tCIDLib::TVoid DecryptImpl ( const tCIDLib::TCard1* const pc1Cypher , tCIDLib::TCard1* const pc1Plain ) = 0; virtual tCIDLib::TVoid EncryptImpl ( const tCIDLib::TCard1* const pc1Plain , tCIDLib::TCard1* const pc1CypherBuf ) = 0; virtual tCIDLib::TVoid ResetImpl() = 0; // ------------------------------------------------------------------- // Protected, non-virtual methods // ------------------------------------------------------------------- tCIDLib::TCard4 c4ECBDecrypt ( const tCIDLib::TCard1* const pc1Cypher , const tCIDLib::TCard4 c4CypherBytes , TMemBuf& mbufPlainBuf ); tCIDLib::TCard4 c4ECBEncrypt ( const tCIDLib::TCard1* const pc1Plain , const tCIDLib::TCard4 c4PlainBytes , TMemBuf& mbufCypherBuf ); tCIDLib::TCard4 c4CBCDecrypt ( const tCIDLib::TCard1* const pc1Cypher , const tCIDLib::TCard4 c4CypherBytes , TMemBuf& mbufPlainBuf , const tCIDLib::TCard1* const pac1IV ); tCIDLib::TCard4 c4CBCEncrypt ( const tCIDLib::TCard1* const pc1Plain , const tCIDLib::TCard4 c4PlainBytes , TMemBuf& mbufCypherBuf , const tCIDLib::TCard1* const pc1IV ); tCIDLib::TCard4 c4OFBProcess ( const tCIDLib::TCard1* const pc1Input , const tCIDLib::TCard4 c4InputBytes , TMemBuf& mbufOut , const tCIDLib::TCard1* const pc1IV ); private : // ------------------------------------------------------------------- // Private data members // // m_c4BlockSize // The block size used by the derived class. It is passed to the // protected constructor by the derived class and we just store // it and provide access to it. // // m_eMode // The block encryption mode to use. // ------------------------------------------------------------------- tCIDLib::TCard4 m_c4BlockSize; tCIDCrypto::EBlockModes m_eMode; // ------------------------------------------------------------------- // Do any needed magic macros // ------------------------------------------------------------------- RTTIDefs(TBlockEncrypter,TObject) }; #pragma CIDLIB_POPPACK
33.095041
78
0.443251
MarkStega
4c8c3eacfd4266cf60ba08a480bd518f47e422ac
266
hpp
C++
Code/Class_headers/Collision.hpp
EnderRayquaza/DeltaEngine
1f1c456d221c27e1a6e49095fe2819dca7994f13
[ "MIT" ]
2
2021-10-16T22:37:03.000Z
2021-11-08T21:46:27.000Z
Code/Class_headers/Collision.hpp
EnderRayquaza/DeltaEngine
1f1c456d221c27e1a6e49095fe2819dca7994f13
[ "MIT" ]
null
null
null
Code/Class_headers/Collision.hpp
EnderRayquaza/DeltaEngine
1f1c456d221c27e1a6e49095fe2819dca7994f13
[ "MIT" ]
2
2021-11-13T10:48:38.000Z
2021-11-13T10:50:14.000Z
#pragma once #include "../config.hpp" namespace DeltaEngine { enum class moveType { Static, Kinematic, Dynamic }; enum class collisionType { Nothing, Decor, Ground, ObjectA, ObjectB }; typedef std::vector<collisionType> collisionTargets; }
11.083333
53
0.691729
EnderRayquaza
4c8cf098b8628b570079b11ae7da2495560f2084
2,336
cpp
C++
GenesisX/dsa1Engine/Bullet.cpp
mray2014/GenesisX
5bede0340c4c44f7217d4ffe1bde7e879aedfe2d
[ "MIT" ]
null
null
null
GenesisX/dsa1Engine/Bullet.cpp
mray2014/GenesisX
5bede0340c4c44f7217d4ffe1bde7e879aedfe2d
[ "MIT" ]
null
null
null
GenesisX/dsa1Engine/Bullet.cpp
mray2014/GenesisX
5bede0340c4c44f7217d4ffe1bde7e879aedfe2d
[ "MIT" ]
null
null
null
#include "Bullet.h" #include "Renderer.h" Bullet::Bullet() { } Bullet::Bullet(float s, std::string file, Renderer* r) { speed = s; glm::vec3 camPos = ((Renderer*)r)->cam->camCenter; glm::vec3 foward = ((Renderer*)r)->cam->foward; glm::vec4 color = glm::vec4(glm::normalize(glm::vec3(Engine::Random(), Engine::Random(), Engine::Random())), 1); bulletTime = 0.0f; bulletLifeSpan = 3.0f; bulletModel = new GameEntity("my bullet",file,Mesh::SingleMesh, "",r); bulletLight = new Light("my bullet light", 1.0, camPos, glm::vec3(0, 0, 0), r); r->RemoveFromRenderer(bulletLight->sphere->rendID); bulletLight->myLight.color = color; bulletModel->SetTag("Bullet"); bulletModel->Translate(camPos); bulletModel->color = color; bulletModel->applyGrav = true; bulletModel->ApplyForce(foward * (glm::vec3(1)*speed)); } Bullet::Bullet(float s, Mesh &myMesh, Renderer* r) { speed = s; glm::vec3 camPos = ((Renderer*)r)->cam->camCenter; glm::vec3 foward = ((Renderer*)r)->cam->foward; glm::vec4 color = glm::vec4(glm::normalize(glm::vec3(Engine::Random(), Engine::Random(), Engine::Random())), 1); bulletTime = 0.0f; bulletLifeSpan = 3.0f; bulletModel = new GameEntity("my bullet", myMesh, r); bulletLight = new Light("my bullet light", 1.0, camPos, glm::vec3(0, 0, 0), r); r->RemoveFromRenderer(bulletLight->sphere->rendID); bulletLight->myLight.color = color; bulletModel->SetTag("Bullet"); bulletModel->Translate(camPos + foward); //bulletModel->ridgidBody.mass = 0.5f; bulletModel->color = color; //bulletModel->applyGrav = true; bulletModel->ApplyForce(foward * (glm::vec3(1)*speed)); } Bullet::~Bullet() { //if (bulletModel != nullptr) { delete bulletModel; bulletModel = nullptr; } //if (bulletLight != nullptr) { delete bulletLight; bulletLight = nullptr; } } void Bullet::Update() { bulletModel->Update(); //printf("x: %.3f, y: %.3f, z: %.3f\n", bulletModel->ridgidBody.velocity.x, bulletModel->ridgidBody.velocity.y, bulletModel->ridgidBody.velocity.z); //bulletLight->myLight.lightPos = bulletModel->transform.position; //bulletLight->sphere->transform.position = bulletModel->transform.position; //bulletLight->sphere->SetWorldPos(); bulletLight->Move(bulletModel->ridgidBody.velocity); bulletTime += Engine::time.dt; if (bulletTime > bulletLifeSpan) { destroyBullet = true; } }
29.948718
149
0.693065
mray2014
4c923e6a432823beda6c4a28a439b548a343fbeb
514
hpp
C++
code/src/mupen64plus-rsp-paraLLEl/debug_jit.hpp
OotinnyoO1/N64Wasm
1cc12b643e5f4a3ea8f499d21f08723cdf1d6c4b
[ "MIT" ]
335
2021-10-16T14:56:14.000Z
2022-03-31T15:50:11.000Z
code/src/mupen64plus-rsp-paraLLEl/debug_jit.hpp
OotinnyoO1/N64Wasm
1cc12b643e5f4a3ea8f499d21f08723cdf1d6c4b
[ "MIT" ]
10
2021-11-09T19:20:34.000Z
2022-03-14T13:17:47.000Z
code/src/mupen64plus-rsp-paraLLEl/debug_jit.hpp
OotinnyoO1/N64Wasm
1cc12b643e5f4a3ea8f499d21f08723cdf1d6c4b
[ "MIT" ]
29
2021-10-19T00:38:18.000Z
2022-03-31T19:03:47.000Z
#ifndef DEBUG_JIT_HPP__ #define DEBUG_JIT_HPP__ #include <memory> #include <stdint.h> #include <string> #include <unordered_map> namespace JIT { using Func = void (*)(void *, void *); class DebugBlock { public: DebugBlock(const std::unordered_map<std::string, uint64_t> &symbol_table); ~DebugBlock(); bool compile(uint64_t hash, const std::string &source); Func get_func() const { return block; } private: struct Impl; std::unique_ptr<Impl> impl; Func block = nullptr; }; } // namespace JIT #endif
16.0625
75
0.715953
OotinnyoO1
4c939bb2b360c229b878d7b926ea07537fea21c6
1,751
hpp
C++
test_conformance/clcpp/utils_common/scalar_type.hpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
1
2019-12-05T03:45:31.000Z
2019-12-05T03:45:31.000Z
test_conformance/clcpp/utils_common/scalar_type.hpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
3
2020-03-25T07:42:27.000Z
2020-04-02T13:23:42.000Z
test_conformance/clcpp/utils_common/scalar_type.hpp
jainvikas8/OpenCL-CTS
b7e7a3eb65d80d6847bd522f66f876fd5f6fe938
[ "Apache-2.0" ]
3
2020-10-26T02:53:08.000Z
2021-02-12T14:59:41.000Z
// // Copyright (c) 2017 The Khronos Group Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef TEST_CONFORMANCE_CLCPP_UTILS_COMMON_SCALAR_TYPE_HPP #define TEST_CONFORMANCE_CLCPP_UTILS_COMMON_SCALAR_TYPE_HPP #include "../common.hpp" // scalar_type<Type>::type returns scalar type of Type. // // Examples: // * scalar_type<cl_float>::type is cl_float // * scalar_type<cl_float4>::types is cl_float template<class Type> struct scalar_type { typedef void type; }; #define ADD_VECTOR_TYPE(Type, n) \ template<> \ struct scalar_type<Type ## n> \ { \ typedef Type type; \ }; #define ADD_VECTOR_TYPES(Type) \ template<> \ struct scalar_type<Type> \ { \ typedef Type type; \ }; \ ADD_VECTOR_TYPE(Type, 2) \ ADD_VECTOR_TYPE(Type, 4) \ ADD_VECTOR_TYPE(Type, 8) \ ADD_VECTOR_TYPE(Type, 16) ADD_VECTOR_TYPES(cl_char) ADD_VECTOR_TYPES(cl_uchar) ADD_VECTOR_TYPES(cl_short) ADD_VECTOR_TYPES(cl_ushort) ADD_VECTOR_TYPES(cl_int) ADD_VECTOR_TYPES(cl_uint) ADD_VECTOR_TYPES(cl_long) ADD_VECTOR_TYPES(cl_ulong) ADD_VECTOR_TYPES(cl_float) ADD_VECTOR_TYPES(cl_double) #undef ADD_VECTOR_TYPES #undef ADD_VECTOR_TYPE #endif // TEST_CONFORMANCE_CLCPP_UTILS_COMMON_SCALAR_TYPE_HPP
26.938462
75
0.743004
jainvikas8
4c94a5851eaf7f12aba8316d5fa94c19056a780c
2,074
cpp
C++
Gogaman/src/Platform/Vulkan/RenderHardwareInterface/VulkanDescriptorGroupLayout.cpp
FeodorVolguine/Gogaman
fb29d7f7924fecb5a31b04e8187689ecef46d347
[ "Apache-2.0" ]
null
null
null
Gogaman/src/Platform/Vulkan/RenderHardwareInterface/VulkanDescriptorGroupLayout.cpp
FeodorVolguine/Gogaman
fb29d7f7924fecb5a31b04e8187689ecef46d347
[ "Apache-2.0" ]
null
null
null
Gogaman/src/Platform/Vulkan/RenderHardwareInterface/VulkanDescriptorGroupLayout.cpp
FeodorVolguine/Gogaman
fb29d7f7924fecb5a31b04e8187689ecef46d347
[ "Apache-2.0" ]
1
2020-05-02T19:25:44.000Z
2020-05-02T19:25:44.000Z
#include "pch.h" #include "VulkanDescriptorGroupLayout.h" #include "Gogaman/RenderHardwareInterface/Device.h" namespace Gogaman { namespace RHI { DescriptorGroupLayout::DescriptorGroupLayout(const uint32_t bindingCount, Binding *bindings, const Shader::StageFlag shaderVisibilityFlags) : AbstractDescriptorGroupLayout(bindingCount, bindings, shaderVisibilityFlags) { GM_DEBUG_ASSERT(m_BindingCount, "Failed to construct descriptor group layout | Invalid bindings"); VkDescriptorSetLayoutBinding *descriptorSetLayoutBindingDescriptors = new VkDescriptorSetLayoutBinding[m_BindingCount]; for(uint32_t i = 0; i < m_BindingCount; i++) { const auto &binding = m_Bindings[i]; descriptorSetLayoutBindingDescriptors[i] = {}; descriptorSetLayoutBindingDescriptors[i].binding = i; descriptorSetLayoutBindingDescriptors[i].descriptorType = DescriptorHeap::GetNativeType(binding.type); descriptorSetLayoutBindingDescriptors[i].descriptorCount = binding.descriptorCount; descriptorSetLayoutBindingDescriptors[i].stageFlags = Shader::GetNativeStageFlags(m_ShaderVisibilityFlags); descriptorSetLayoutBindingDescriptors[i].pImmutableSamplers = nullptr; } VkDescriptorSetLayoutCreateInfo descriptorSetLayoutDescriptor = {}; descriptorSetLayoutDescriptor.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO; descriptorSetLayoutDescriptor.bindingCount = m_BindingCount; descriptorSetLayoutDescriptor.pBindings = descriptorSetLayoutBindingDescriptors; if(vkCreateDescriptorSetLayout(g_Device->GetNativeData().vulkanDevice, &descriptorSetLayoutDescriptor, nullptr, &m_NativeData.vulkanDescriptorSetLayout) != VK_SUCCESS) GM_DEBUG_ASSERT(false, "Failed to construct descriptor group layout | Failed to create Vulkan descriptor set"); delete[] descriptorSetLayoutBindingDescriptors; } DescriptorGroupLayout::~DescriptorGroupLayout() { vkDestroyDescriptorSetLayout(g_Device->GetNativeData().vulkanDevice, m_NativeData.vulkanDescriptorSetLayout, nullptr); } } }
47.136364
170
0.804243
FeodorVolguine
4c95648303f2179b04954a5e1c895d5c1869a44f
509
cpp
C++
Cplus/FriendsOfAppropriateAges.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
1
2018-01-22T12:06:28.000Z
2018-01-22T12:06:28.000Z
Cplus/FriendsOfAppropriateAges.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
Cplus/FriendsOfAppropriateAges.cpp
JumHorn/leetcode
1447237ae8fc3920b19f60b30c71a84b088cc200
[ "MIT" ]
null
null
null
#include <unordered_map> #include <vector> using namespace std; class Solution { public: int numFriendRequests(vector<int> &ages) { unordered_map<int, int> count; for (int &age : ages) ++count[age]; int res = 0; for (auto &a : count) { for (auto &b : count) { if (request(a.first, b.first)) res += a.second * (b.second - (a.first == b.first ? 1 : 0)); } } return res; } bool request(int a, int b) { return !(b <= 0.5 * a + 7 || b > a || (b > 100 && a < 100)); } };
17.551724
65
0.552063
JumHorn
4c983eb39f3003249805a1b1ba90e527c274b912
10,405
cpp
C++
src/cruxhom.cpp
Junology/khover
1970689d4505ddd0887ec4f44888f91af816eae0
[ "BSD-2-Clause" ]
2
2021-05-19T06:48:04.000Z
2021-05-19T06:50:39.000Z
src/cruxhom.cpp
Junology/khover
1970689d4505ddd0887ec4f44888f91af816eae0
[ "BSD-2-Clause" ]
null
null
null
src/cruxhom.cpp
Junology/khover
1970689d4505ddd0887ec4f44888f91af816eae0
[ "BSD-2-Clause" ]
null
null
null
/*! * \file cruxhom.hpp * \author Jun Yoshida * \copyright (c) 2020 Jun Yoshida. * The project is released under the 2-clause BSD License. * \date August, 2020: created */ #include <thread> #include "states.hpp" #include "khovanov.hpp" #include "enhancements.hpp" #include "debug/debug.hpp" using namespace khover; using matrix_t = ChainIntegral::matrix_t; //! Provide zero map for cubes //! \param cube_dom The domain cube. //! \param cube_cod The codomain cube. //! \pre cube_dom.dim() == cube_cod.dim() template <template <class...> class C1, template <class...> class C2> static std::vector<matrix_t> zero_on_cubes( Cube<C1> const& cube_dom, std::vector<EnhancementProperty> enhprop_dom, Cube<C2> const& cube_cod, std::vector<EnhancementProperty> enhprop_cod ) noexcept { auto mindeg = std::min(cube_dom.mincohdeg(), cube_cod.mincohdeg()); auto maxdeg = std::max(cube_dom.maxcohdeg(), cube_cod.maxcohdeg()); std::vector<matrix_t> homs{}; for(auto i = maxdeg; i >= mindeg; --i) { std::size_t rk_cod, rk_dom; if(i >= cube_dom.mincohdeg() && i <= cube_dom.maxcohdeg()) { std::size_t maxst_dom = cube_dom.maxState( i-cube_dom.mincohdeg()).to_ulong(); rk_dom = enhprop_dom[maxst_dom].headidx + binom(cube_dom[maxst_dom].ncomp, enhprop_dom[maxst_dom].xcnt); } else rk_dom = 0; if(i >= cube_cod.mincohdeg() && i <= cube_cod.maxcohdeg()) { std::size_t maxst_cod = cube_cod.maxState( i-cube_cod.mincohdeg()).to_ulong(); rk_cod = enhprop_cod[maxst_cod].headidx + binom(cube_cod[maxst_cod].ncomp, enhprop_cod[maxst_cod].xcnt); } else rk_cod = 0; homs.push_back(matrix_t::Zero(rk_cod, rk_dom)); } return homs; } /***************** *** Morphisms *** *****************/ //! The chain contratcion theta template<template <class...> class C1, template <class...> class C2> static ChainIntegral::Hom theta( LinkDiagram diagram, std::size_t dblpt, Cube<C1> const& cube_dom, std::vector<EnhancementProperty> enhprop_dom, Cube<C2> const& cube_cod, std::vector<EnhancementProperty> enhprop_cod ) noexcept { std::vector<matrix_t> homs = zero_on_cubes( cube_dom, enhprop_dom, cube_cod, enhprop_cod); for(std::size_t st = 0; st < cube_dom.size(); ++st) { auto urcomp_dom = cube_dom[st].arccomp[diagram.getURArc(dblpt)]; auto dlcomp_dom = cube_dom[st].arccomp[diagram.getDLArc(dblpt)]; auto urcomp_cod = cube_cod[st].arccomp[diagram.getURArc(dblpt)]; auto dlcomp_cod = cube_cod[st].arccomp[diagram.getDLArc(dblpt)]; auto rk = binom(cube_dom[st].ncomp, enhprop_dom[st].xcnt); for(std::size_t e = 0; e < rk; ++e) { auto enh = std::make_optional<enhancement_t>( bitsWithPop<max_components>( enhprop_dom[st].xcnt, e) ); // eta \circ epsilon if(urcomp_dom != dlcomp_dom && urcomp_cod != dlcomp_cod) { if (enh->test(urcomp_dom)) enh->set(urcomp_dom,false); else enh.reset(); } // eta else if (urcomp_dom == dlcomp_dom && urcomp_cod != dlcomp_cod) { bool aux = enh->test(urcomp_dom); *enh = insertBit( *enh, urcomp_dom == urcomp_cod ? dlcomp_cod : urcomp_cod, false); enh->set(dlcomp_cod, aux); enh->set(urcomp_cod, false); } // epsilon else if (urcomp_dom != dlcomp_dom && urcomp_cod == dlcomp_cod) { if (enh->test(urcomp_dom)) *enh = purgeBit( *enh, urcomp_dom == urcomp_cod ? dlcomp_cod : urcomp_cod ); else enh.reset(); } // Write if(enh) { auto e_cod = bitsIndex(*enh); homs[state_t{st}.count()].coeffRef( enhprop_cod[st].headidx + e_cod, enhprop_dom[st].headidx + e ) = 1; } } } return ChainIntegral::Hom(-1,std::move(homs)); } // Compute the morphism PhiHat. std::optional<ChainIntegral::Hom> khover::crossPhiHat( LinkDiagram const& diagram, std::size_t crossing, SmoothCube const& cube_neg, std::vector<EnhancementProperty> const& enhprop_neg, SmoothCube const& cube_pos, std::vector<EnhancementProperty> const& enhprop_pos ) noexcept { std::vector<matrix_t> homs = zero_on_cubes(cube_neg, enhprop_neg, cube_pos, enhprop_pos); std::size_t nstates = 1u << (cube_neg.dim()-1); for(std::size_t st = 0; st < nstates; ++st) { auto stbit_neg = insertBit(state_t{st}, crossing, true); auto stbit_pos = insertBit(state_t{st}, crossing, false); std::size_t st_neg = stbit_neg.to_ulong(); std::size_t st_pos = stbit_pos.to_ulong(); auto urcomp_neg = cube_neg[st_neg].arccomp[diagram.getURArc(crossing)]; auto dlcomp_neg = cube_neg[st_neg].arccomp[diagram.getDLArc(crossing)]; // Skip the cases where the double point is adjacent to a single component. if (urcomp_neg == dlcomp_neg) continue; // Compute the coefficients of the matrix. auto rk = binom(cube_neg[st_neg].ncomp, enhprop_neg[st_neg].xcnt); for(std::size_t e = 0; e < rk; ++e) { auto enh = bitsWithPop<max_components>(enhprop_neg[st_neg].xcnt, e); // 1⊗1 -> 1⊗x - x⊗1 if(!enh.test(urcomp_neg) && !enh.test(dlcomp_neg)) { // 1*x enh.set(urcomp_neg); homs[cube_pos.dim()-stbit_pos.count()].coeffRef( enhprop_pos[st_pos].headidx + bitsIndex(enh), enhprop_neg[st_neg].headidx + e ) = 1; enh.set(urcomp_neg, false); enh.set(dlcomp_neg); // -x⊗1 enh.set(dlcomp_neg); homs[cube_pos.dim()-stbit_pos.count()].coeffRef( enhprop_pos[st_pos].headidx + bitsIndex(enh), enhprop_neg[st_neg].headidx + e ) = -1; } // x⊗1 -> x⊗x else if(!enh.test(urcomp_neg)) { enh.set(urcomp_neg); homs[cube_pos.dim()-stbit_pos.count()].coeffRef( enhprop_pos[st_pos].headidx + bitsIndex(enh), enhprop_neg[st_neg].headidx + e ) = 1; } // 1⊗x -> -x⊗x else if(!enh.test(dlcomp_neg)) { enh.set(dlcomp_neg); homs[cube_pos.dim()-stbit_pos.count()].coeffRef( enhprop_pos[st_pos].headidx + bitsIndex(enh), enhprop_neg[st_neg].headidx + e ) = -1; } // x*x -> 0; omitted. } } return ChainIntegral::Hom( -cube_pos.maxcohdeg(), std::move(homs)); } std::optional<ChainIntegral::Hom> khover::cruxXi( LinkDiagram const& diagram, CruxCube const& cubeCrx, LinkDiagram const& diagV, SmoothCube const& cubeV, LinkDiagram const& diagW, SmoothCube const& cubeW, std::size_t dblpt, int qdeg ) noexcept { std::optional<ChainIntegral> chV_neg, chV_pos, chW_neg, chW_pos; std::optional<std::vector<EnhancementProperty>> propC_dom, propC_cod; std::optional<std::vector<EnhancementProperty>> propV_neg, propV_pos; std::optional<std::vector<EnhancementProperty>> propW_neg, propW_pos; // Compute Khovanov homologies. { std::thread thC( [&diagram, &cubeCrx, &propC_dom, &propC_cod, dblpt, q=qdeg]() { propC_dom = get_enhancement_prop( diagram, cubeCrx, diagram.getSign(dblpt) > 0 ? q-2 : q-4); propC_cod = get_enhancement_prop( diagram, cubeCrx, diagram.getSign(dblpt) > 0 ? q+4 : q+2); }); std::thread thV_neg( [&diagV, &cubeV, &chV_neg, &propV_neg, q=qdeg]() { propV_neg = get_enhancement_prop(diagV, cubeV, q+1); if(propV_neg) chV_neg = khChain(diagV, cubeV, *propV_neg); }); std::thread thV_pos( [&diagV, &cubeV, &chV_pos, &propV_pos, q=qdeg]() { propV_pos = get_enhancement_prop(diagV, cubeV, q-1); if(propV_pos) chV_pos = khChain(diagV, cubeV, *propV_pos); }); std::thread thW_neg( [&diagW, &cubeW, &chW_neg, &propW_neg, q=qdeg]() { propW_neg = get_enhancement_prop(diagW, cubeW, q+2); if(propW_neg) chW_neg = khChain(diagW, cubeW, *propW_neg); }); std::thread thW_pos( [&diagW, &cubeW, &chW_pos, &propW_pos, q=qdeg]() { propW_pos = get_enhancement_prop(diagW, cubeW, q-2); if(propW_pos) chW_pos = khChain(diagW, cubeW, *propW_pos); }); thC.join(); thV_neg.join(); thV_pos.join(); thW_neg.join(); thW_pos.join(); } if(!propC_dom || !propC_cod || !propV_neg || !chV_neg || !propV_pos || !chV_pos || !propW_neg || !chW_neg || !propW_pos || !chW_pos ) { return std::nullopt; } ChainIntegral::Hom result = theta( diagram, dblpt, cubeW, *propW_neg, cubeCrx, *propC_cod) << 3; result *= chW_neg->diffAsHom() << 2; result *= theta(diagram, dblpt, cubeV, *propV_neg, cubeW, *propW_neg) << 2; result *= chV_neg->diffAsHom() << 1; result *= theta(diagram, dblpt, cubeV, *propV_pos, cubeV, *propV_neg) << 1; result *= chV_pos->diffAsHom(); result *= theta(diagram, dblpt, cubeW, *propW_pos, cubeV, *propV_pos); result *= chW_pos->diffAsHom() << -1; result *= theta(diagram, dblpt, cubeCrx, *propC_dom, cubeW, *propW_pos) << -1; return std::make_optional(std::move(result)); }
34.916107
83
0.547525
Junology
4c9a87344fbb7166a3209ccf49e0a1471e9dc3ce
282
cpp
C++
problems/baekjoon/p10871.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
problems/baekjoon/p10871.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
problems/baekjoon/p10871.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
/** * (210929) X보다 작은 수 * https://www.acmicpc.net/problem/10871 */ #include <cstdio> int main() { int N, X; scanf("%d %d", &N, &X); int buf; for (int i=0; i<N; i++) { scanf("%d",&buf); if (buf < X) printf("%d ", buf); } printf("\n"); return 0; }
12.26087
40
0.468085
yejun614
4c9c3e8cc01a154e7ed32f1279c0b721dd58cb7b
38,428
cc
C++
ion/remote/resourcehandler.cc
mdemoret/Snapshot
987b3d45532f3644d35d858e036542d5691953ce
[ "Apache-2.0" ]
null
null
null
ion/remote/resourcehandler.cc
mdemoret/Snapshot
987b3d45532f3644d35d858e036542d5691953ce
[ "Apache-2.0" ]
null
null
null
ion/remote/resourcehandler.cc
mdemoret/Snapshot
987b3d45532f3644d35d858e036542d5691953ce
[ "Apache-2.0" ]
null
null
null
/** Copyright 2016 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #if !ION_PRODUCTION #include "ion/remote/resourcehandler.h" #include <sstream> #include <string> #include <vector> #include "ion/base/allocator.h" #include "ion/base/invalid.h" #include "ion/base/stringutils.h" #include "ion/base/zipassetmanager.h" #include "ion/base/zipassetmanagermacros.h" #include "ion/gfx/image.h" #include "ion/gfx/resourcemanager.h" #include "ion/gfx/tracinghelper.h" #include "ion/gfxutils/resourcecallback.h" #include "ion/image/conversionutils.h" #include "ion/image/renderutils.h" ION_REGISTER_ASSETS(IonRemoteResourcesRoot); namespace ion { namespace remote { namespace { using gfx::AttributeArray; using gfx::BufferObject; using gfx::CubeMapTexture; using gfx::CubeMapTexturePtr; using gfx::FramebufferObject; using gfx::Image; using gfx::ImagePtr; using gfx::Renderer; using gfx::RendererPtr; using gfx::ResourceManager; using gfx::Sampler; using gfx::Shader; using gfx::ShaderProgram; using gfx::TextureBase; using gfx::Texture; using gfx::TexturePtr; using gfxutils::ArrayCallback; using gfxutils::BufferCallback; using gfxutils::FramebufferCallback; using gfxutils::PlatformCallback; using gfxutils::ProgramCallback; using gfxutils::SamplerCallback; using gfxutils::ShaderCallback; using gfxutils::TextureCallback; using gfxutils::TextureImageCallback; using std::bind; using std::placeholders::_1; typedef ResourceManager::ArrayInfo ArrayInfo; typedef ResourceManager::BufferInfo BufferInfo; typedef ResourceManager::FramebufferInfo FramebufferInfo; typedef ResourceManager::RenderbufferInfo RenderbufferInfo; typedef ResourceManager::PlatformInfo PlatformInfo; typedef ResourceManager::ProgramInfo ProgramInfo; typedef ResourceManager::SamplerInfo SamplerInfo; typedef ResourceManager::ShaderInfo ShaderInfo; typedef ResourceManager::TextureImageInfo TextureImageInfo; typedef ResourceManager::TextureInfo TextureInfo; //----------------------------------------------------------------------------- // // Helper class for consistent indentation. // //----------------------------------------------------------------------------- class Indent { public: explicit Indent(size_t spaces) : indent_(spaces, ' '), spaces_(spaces) {} // Outputs the indentation held by this indent to the stream. friend std::ostream& operator<<(std::ostream& out, const Indent& indent) { out << indent.indent_; return out; } // The + operator increases the indentation. friend const Indent operator+(const Indent& indent, size_t spaces) { return Indent(indent.spaces_ + spaces); } private: const std::string indent_; const size_t spaces_; }; // Escapes ", \, and \n. static const std::string EscapeJson(const std::string& str) { std::string ret = base::ReplaceString(str, "\\", "\\\\"); ret = base::ReplaceString(ret, "\"", "\\\""); ret = base::EscapeNewlines(ret); return ret; } //----------------------------------------------------------------------------- // // Helper class derived from TextureImageCallback that first renders textures // into images so that the images show up correctly regardless of whether the // textures' images had data wiped. // //----------------------------------------------------------------------------- class RenderTextureCallback : public TextureImageCallback { public: typedef base::ReferentPtr<RenderTextureCallback>::Type RefPtr; RenderTextureCallback(const RendererPtr& renderer, bool do_wait) : TextureImageCallback(do_wait), renderer_(renderer) {} // Renders texture images and then calls the version in the base class. void Callback(const std::vector<TextureImageInfo>& data); private: // The constructor is private because this class is derived from Referent. ~RenderTextureCallback() override {} // Each of these uses the renderer to render images from a Texture or // CubeMapTexture in the passed TextureImageInfo, replacing the images in it. void RenderTextureImage(const RendererPtr& renderer, TextureImageInfo* info); void RenderCubeMapTextureImages(const RendererPtr& renderer, TextureImageInfo* info); // Renderer used to render images. const RendererPtr& renderer_; }; void RenderTextureCallback::Callback( const std::vector<TextureImageInfo>& data) { // Keep this instance from being deleted when Callback() finishes. RefPtr holder(this); // Make sure the Renderer doesn't try to process this (unfinished) // request before rendering the image. const bool flag_was_set = renderer_->GetFlags().test(Renderer::kProcessInfoRequests); renderer_->ClearFlag(Renderer::kProcessInfoRequests); // If any of the returned images is missing data, render it into an image. std::vector<TextureImageInfo> new_data = data; const size_t data_count = new_data.size(); for (size_t i = 0; i < data_count; ++i) { TextureImageInfo* info = &new_data[i]; if (info->texture.Get()) { if (info->texture->GetTextureType() == TextureBase::kTexture) RenderTextureImage(renderer_, info); else RenderCubeMapTextureImages(renderer_, info); } } if (flag_was_set) renderer_->SetFlag(Renderer::kProcessInfoRequests); // Let the base class do its work. TextureImageCallback::Callback(new_data); } void RenderTextureCallback::RenderTextureImage( const RendererPtr& renderer, TextureImageInfo* info) { DCHECK(info); DCHECK_EQ(info->texture->GetTextureType(), TextureBase::kTexture); DCHECK_EQ(info->images.size(), 1U); const ImagePtr& input_image = info->images[0]; if (input_image.Get()) { TexturePtr tex(static_cast<Texture*>(info->texture.Get())); const base::AllocatorPtr& sta = tex->GetAllocator()->GetAllocatorForLifetime(base::kShortTerm); ImagePtr output_image = image::RenderTextureImage( tex, input_image->GetWidth(), input_image->GetHeight(), renderer, sta); if (output_image.Get()) info->images[0] = output_image; } } void RenderTextureCallback::RenderCubeMapTextureImages( const RendererPtr& renderer, TextureImageInfo* info) { DCHECK(info); DCHECK_EQ(info->texture->GetTextureType(), TextureBase::kCubeMapTexture); DCHECK_EQ(info->images.size(), 6U); CubeMapTexturePtr tex(static_cast<CubeMapTexture*>(info->texture.Get())); const base::AllocatorPtr& sta = tex->GetAllocator()->GetAllocatorForLifetime(base::kShortTerm); for (int i = 0; i < 6; ++i) { const ImagePtr& input_image = info->images[i]; const CubeMapTexture::CubeFace face = static_cast<CubeMapTexture::CubeFace>(i); ImagePtr output_image = image::RenderCubeMapTextureFaceImage( tex, face, input_image->GetWidth(), input_image->GetHeight(), renderer, sta); if (output_image.Get()) info->images[i] = output_image; } } //----------------------------------------------------------------------------- // // Helper functions. // //----------------------------------------------------------------------------- // Returns a JSON string representation of a FramebufferInfo::Attachment. static const std::string ConvertAttachmentToJson( const Indent& indent, const FramebufferInfo::Attachment& info, const RenderbufferInfo& rb_info) { gfx::TracingHelper helper; std::ostringstream str; const Indent indent2 = indent + 2; str << indent << "\"type\": \"" << (info.type ? helper.ToString("GLenum", info.type) : "GL_NONE") << "\",\n"; str << indent; if (info.type == GL_TEXTURE) str << "\"texture_glid\": " << info.value << ",\n"; else str << "\"value\": " << info.value << ",\n"; str << indent << "\"mipmap_level\": " << info.level << ",\n"; str << indent << "\"cube_face\": \"" << (info.cube_face ? helper.ToString("GLenum", info.cube_face) : "GL_NONE") << "\",\n"; str << indent << "\"renderbuffer\": {\n"; str << indent2 << "\"object_id\": " << rb_info.id << ",\n"; str << indent2 << "\"label\": " << "\"" << rb_info.label << "\",\n"; str << indent2 << "\"width\": " << rb_info.width << ",\n"; str << indent2 << "\"height\": " << rb_info.height << ",\n"; str << indent2 << "\"internal_format\": \"" << helper.ToString("GLenum", rb_info.internal_format) << "\",\n"; str << indent2 << "\"red_size\": " << rb_info.red_size << ",\n"; str << indent2 << "\"green_size\": " << rb_info.green_size << ",\n"; str << indent2 << "\"blue_size\": " << rb_info.blue_size << ",\n"; str << indent2 << "\"alpha_size\": " << rb_info.alpha_size << ",\n"; str << indent2 << "\"depth_size\": " << rb_info.depth_size << ",\n"; str << indent2 << "\"stencil_size\": " << rb_info.stencil_size << "\n"; str << indent << "}\n"; return str.str(); } const std::string ConvertEnumVectorToJson(const std::vector<GLenum>& vec) { gfx::TracingHelper helper; std::ostringstream str; const size_t count = vec.size(); for (size_t i = 0; i < count; ++i) { if (i) str << ", "; str << helper.ToString("GLenum", vec[i]); } return str.str(); } // Returns a JSON string representation of a ProgramInfo shader input. template <typename T> static const std::string ConvertShaderInputToJson(const Indent& indent, const T& input) { gfx::TracingHelper helper; std::ostringstream str; str << indent << "\"name\": \"" << input.name << "\",\n"; str << indent << "\"index\": " << input.index << ",\n"; str << indent << "\"size\": " << input.size << ",\n"; str << indent << "\"type\": \"" << helper.ToString("GLenum", input.type) << "\"\n"; return str.str(); } // Returns a JSON string representation of a ProgramInfo::Attribute. static const std::string ConvertProgramAttributesToJson( const Indent& indent, const std::vector<ProgramInfo::Attribute>& attrs) { gfx::TracingHelper helper; std::ostringstream str; const size_t count = attrs.size(); for (size_t i = 0; i < count; ++i) { str << indent << "{\n"; str << ConvertShaderInputToJson(indent + 2, attrs[i]); str << indent << "}" << (i < count - 1U ? "," : "") << "\n"; } return str.str(); } // Outputs the passed uniform to a stream. template <typename T> static void StreamProgramUniform(const ProgramInfo::Uniform& uniform, std::ostream& str) { // NOLINT str << "\""; if (uniform.size > 1) { str << "["; for (GLint i = 0; i < uniform.size; i++) { if (i) str << ", "; str << uniform.value.GetValueAt<T>(i); } str << "]"; } else { str << uniform.value.Get<T>(); } str << "\""; } // Outputs the passed uniform vector to a stream. template <typename T> static void StreamProgramUniformVector(const ProgramInfo::Uniform& uniform, std::ostream& str) { // NOLINT str << "\""; if (uniform.size > 1) { str << "["; for (GLint i = 0; i < uniform.size; i++) { if (i) str << ", "; uniform.value.GetValueAt<T>(i).Print(str, 'V'); } str << "]"; } else { uniform.value.Get<T>().Print(str, 'V'); } str << "\""; } // Returns a JSON string representation of a ProgramInfo::Uniform. static const std::string ConvertProgramUniformsToJson( const Indent& indent, const std::vector<ProgramInfo::Uniform>& uniforms) { gfx::TracingHelper helper; std::ostringstream str; const Indent indent2 = indent + 2; const size_t count = uniforms.size(); for (size_t i = 0; i < count; ++i) { const ProgramInfo::Uniform& u = uniforms[i]; str << indent << "{\n"; str << indent2 << "\"value\": "; switch (u.type) { case GL_FLOAT: StreamProgramUniform<float>(u, str); break; case GL_FLOAT_VEC2: StreamProgramUniformVector<math::VectorBase2f>(u, str); break; case GL_FLOAT_VEC3: StreamProgramUniformVector<math::VectorBase3f>(u, str); break; case GL_FLOAT_VEC4: StreamProgramUniformVector<math::VectorBase4f>(u, str); break; case GL_INT: case GL_INT_SAMPLER_1D: case GL_INT_SAMPLER_1D_ARRAY: case GL_INT_SAMPLER_2D: case GL_INT_SAMPLER_2D_ARRAY: case GL_INT_SAMPLER_3D: case GL_INT_SAMPLER_CUBE: case GL_INT_SAMPLER_CUBE_MAP_ARRAY: case GL_SAMPLER_1D: case GL_SAMPLER_1D_ARRAY: case GL_SAMPLER_1D_ARRAY_SHADOW: case GL_SAMPLER_1D_SHADOW: case GL_SAMPLER_2D: case GL_SAMPLER_2D_ARRAY: case GL_SAMPLER_2D_ARRAY_SHADOW: case GL_SAMPLER_2D_MULTISAMPLE: case GL_SAMPLER_2D_MULTISAMPLE_ARRAY: case GL_SAMPLER_2D_SHADOW: case GL_SAMPLER_3D: case GL_SAMPLER_CUBE: case GL_SAMPLER_CUBE_MAP_ARRAY: case GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW: case GL_SAMPLER_CUBE_SHADOW: case GL_SAMPLER_EXTERNAL_OES: case GL_UNSIGNED_INT_SAMPLER_1D: case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_2D: case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY: case GL_UNSIGNED_INT_SAMPLER_3D: case GL_UNSIGNED_INT_SAMPLER_CUBE: case GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY: StreamProgramUniform<int>(u, str); break; case GL_INT_VEC2: StreamProgramUniformVector<math::VectorBase2i>(u, str); break; case GL_INT_VEC3: StreamProgramUniformVector<math::VectorBase3i>(u, str); break; case GL_INT_VEC4: StreamProgramUniformVector<math::VectorBase4i>(u, str); break; case GL_UNSIGNED_INT: StreamProgramUniform<uint32>(u, str); break; case GL_UNSIGNED_INT_VEC2: StreamProgramUniformVector<math::VectorBase2ui>(u, str); break; case GL_UNSIGNED_INT_VEC3: StreamProgramUniformVector<math::VectorBase3ui>(u, str); break; case GL_UNSIGNED_INT_VEC4: StreamProgramUniformVector<math::VectorBase4ui>(u, str); break; case GL_FLOAT_MAT2: StreamProgramUniform<math::Matrix2f>(u, str); break; case GL_FLOAT_MAT3: StreamProgramUniform<math::Matrix3f>(u, str); break; case GL_FLOAT_MAT4: StreamProgramUniform<math::Matrix4f>(u, str); break; #if !defined(ION_COVERAGE) // COV_NF_START default: break; #endif // COV_NF_END } str << ",\n"; str << ConvertShaderInputToJson(indent + 2, u); str << indent << "}" << (i < count - 1U ? "," : "") << "\n"; } return str.str(); } // The below functions convert various structs into JSON parseable strings // suitable for reconstruction by a web browser. // // Default unspecialized version which should never be called. template <typename InfoType> static const std::string ConvertInfoToJson(const Indent& indent, const InfoType& info) { CHECK(false) << "Unspecialized ConvertInfoToJson() called."; return std::string(); } template <> const std::string ConvertInfoToJson(const Indent& indent, const PlatformInfo& info) { std::ostringstream str; const Indent indent2 = indent + 2; const Indent indent4 = indent + 4; str << indent << "\"renderer\": \"" << info.renderer << "\",\n"; str << indent << "\"vendor\": \"" << info.vendor << "\",\n"; str << indent << "\"version_string\": \"" << info.version_string << "\",\n"; str << indent << "\"gl_version\": " << info.major_version << "." << info.minor_version << ",\n"; str << indent << "\"glsl_version\": " << info.glsl_version << ",\n"; str << indent << "\"aliased_line_width_range\": \"" << info.aliased_line_width_range[0] << " - " << info.aliased_line_width_range[1] << "\",\n"; str << indent << "\"aliased_point_size_range\": \"" << info.aliased_point_size_range[0] << " - " << info.aliased_point_size_range[1] << "\",\n"; str << indent << "\"max_color_attachments\": " << info.max_color_attachments << ",\n"; str << indent << "\"max_combined_texture_image_units\": " << info.max_combined_texture_image_units << ",\n"; str << indent << "\"max_cube_map_texture_size\": " << info.max_cube_map_texture_size << ",\n"; str << indent << "\"max_draw_buffers\": " << info.max_draw_buffers << ",\n"; str << indent << "\"max_fragment_uniform_vectors\": " << info.max_fragment_uniform_vectors << ",\n"; str << indent << "\"max_renderbuffer_size\": " << info.max_renderbuffer_size << ",\n"; str << indent << "\"max_texture_image_units\": " << info.max_texture_image_units << ",\n"; str << indent << "\"max_texture_size\": " << info.max_texture_size << ",\n"; str << indent << "\"max_transform_feedback_buffers\": " << info.max_transform_feedback_buffers << ",\n"; str << indent << "\"max_transform_feedback_interleaved_components\": " << info.max_transform_feedback_interleaved_components << ",\n"; str << indent << "\"max_transform_feedback_separate_attribs\": " << info.max_transform_feedback_separate_attribs << ",\n"; str << indent << "\"max_transform_feedback_separate_components\": " << info.max_transform_feedback_separate_components << ",\n"; str << indent << "\"max_varying_vectors\": " << info.max_varying_vectors << ",\n"; str << indent << "\"max_vertex_attribs\": " << info.max_vertex_attribs << ",\n"; str << indent << "\"max_vertex_texture_image_units\": " << info.max_vertex_texture_image_units << ",\n"; str << indent << "\"max_vertex_uniform_vectors\": " << info.max_vertex_uniform_vectors << ",\n"; str << indent << "\"max_viewport_dims\": \"" << info.max_viewport_dims[0] << " x " << info.max_viewport_dims[1] << "\",\n"; str << indent << "\"transform_feedback_varying_max_length\": " << info.transform_feedback_varying_max_length << ",\n"; str << indent << "\"compressed_texture_formats\": \"" << ConvertEnumVectorToJson(info.compressed_texture_formats) << "\",\n"; str << indent << "\"shader_binary_formats\": \"" << ConvertEnumVectorToJson(info.shader_binary_formats) << "\",\n"; str << indent << "\"extensions\": \"" << info.extensions << "\"\n"; return str.str(); } template <> const std::string ConvertInfoToJson(const Indent& indent, const ArrayInfo& info) { gfx::TracingHelper helper; std::ostringstream str; const Indent indent2 = indent + 2; const Indent indent4 = indent + 4; str << indent << "\"object_id\": " << info.id << ",\n"; str << indent << "\"label\": " << "\"" << info.label << "\",\n"; str << indent << "\"vertex_count\": " << info.vertex_count << ",\n"; str << indent << "\"attributes\": [\n"; const size_t count = info.attributes.size(); for (size_t i = 0; i < count; ++i) { str << indent2 << "{\n"; str << indent4 << "\"buffer_glid\": " << info.attributes[i].buffer << ",\n"; str << indent4 << "\"enabled\": \"" << helper.ToString("GLboolean", info.attributes[i].enabled) << "\",\n"; str << indent4 << "\"size\": " << info.attributes[i].size << ",\n"; str << indent4 << "\"stride\": " << info.attributes[i].stride << ",\n"; str << indent4 << "\"type\": \"" << helper.ToString("GLenum", info.attributes[i].type) << "\",\n"; str << indent4 << "\"normalized\": \"" << helper.ToString("GLboolean", info.attributes[i].normalized) << "\",\n"; str << indent4 << "\"pointer_or_offset\": \"" << helper.ToString("GLvoid*", info.attributes[i].pointer) << "\",\n"; str << indent4 << "\"value\": \"" << info.attributes[i].value << "\"\n"; str << indent2 << "}" << (i < count - 1U ? "," : "") << "\n"; } str << indent << "]\n"; return str.str(); } template <> const std::string ConvertInfoToJson(const Indent& indent, const BufferInfo& info) { gfx::TracingHelper helper; std::ostringstream str; str << indent << "\"object_id\": " << info.id << ",\n"; str << indent << "\"label\": " << "\"" << info.label << "\",\n"; str << indent << "\"size\": " << info.size << ",\n"; str << indent << "\"usage\": \"" << helper.ToString("GLenum", info.usage) << "\",\n"; str << indent << "\"mapped_pointer\": \"" << helper.ToString("GLvoid*", info.mapped_data) << "\",\n"; str << indent << "\"target\": \"" << helper.ToString("GLenum", info.target) << "\"\n"; return str.str(); } template <> const std::string ConvertInfoToJson(const Indent& indent, const FramebufferInfo& info) { std::ostringstream str; const Indent indent2 = indent + 2; str << indent << "\"object_id\": " << info.id << ",\n"; str << indent << "\"label\": " << "\"" << info.label << "\",\n"; str << indent << "\"attachment_color0\": {\n"; str << ConvertAttachmentToJson( indent2, info.color0, info.color0_renderbuffer); str << indent << "},\n"; str << indent << "\"attachment_depth\": {\n"; str << ConvertAttachmentToJson(indent2, info.depth, info.depth_renderbuffer); str << indent << "},\n"; str << indent << "\"attachment_stencil\": {\n"; str << ConvertAttachmentToJson( indent2, info.stencil, info.stencil_renderbuffer); str << indent << "}\n"; return str.str(); } template <> const std::string ConvertInfoToJson(const Indent& indent, const ProgramInfo& info) { gfx::TracingHelper helper; std::ostringstream str; const Indent indent2 = indent + 2; str << indent << "\"object_id\": " << info.id << ",\n"; str << indent << "\"label\": " << "\"" << info.label << "\",\n"; str << indent << "\"vertex_shader_glid\": " << info.vertex_shader << ",\n"; str << indent << "\"fragment_shader_glid\": " << info.fragment_shader << ",\n"; str << indent << "\"delete_status\": \"" << helper.ToString("GLboolean", info.delete_status) << "\",\n"; str << indent << "\"link_status\": \"" << helper.ToString("GLboolean", info.link_status) << "\",\n"; str << indent << "\"validate_status\": \"" << helper.ToString("GLboolean", info.validate_status) << "\",\n"; str << indent << "\"attributes\": [\n"; str << ConvertProgramAttributesToJson(indent2, info.attributes); str << indent << "],\n"; str << indent << "\"uniforms\": [\n"; str << ConvertProgramUniformsToJson(indent2, info.uniforms); str << indent << "],\n"; str << indent << "\"info_log\": \"" << EscapeJson(info.info_log) << "\"\n"; return str.str(); } template <> const std::string ConvertInfoToJson(const Indent& indent, const SamplerInfo& info) { gfx::TracingHelper helper; std::ostringstream str; str << indent << "\"object_id\": " << info.id << ",\n"; str << indent << "\"label\": " << "\"" << info.label << "\",\n"; str << indent << "\"compare_function\": \"" << helper.ToString("GLtextureenum", info.compare_func) << "\",\n"; str << indent << "\"compare_mode\": \"" << helper.ToString("GLtextureenum", info.compare_mode) << "\",\n"; str << indent << "\"max_anisotropy\": " << info.max_anisotropy << ",\n"; str << indent << "\"min_lod\": " << info.min_lod << ",\n"; str << indent << "\"max_lod\": " << info.max_lod << ",\n"; str << indent << "\"min_filter\": \"" << helper.ToString("GLenum", info.min_filter) << "\",\n"; str << indent << "\"mag_filter\": \"" << helper.ToString("GLenum", info.mag_filter) << "\",\n"; str << indent << "\"wrap_r\": \"" << helper.ToString("GLenum", info.wrap_r) << "\",\n"; str << indent << "\"wrap_s\": \"" << helper.ToString("GLenum", info.wrap_s) << "\",\n"; str << indent << "\"wrap_t\": \"" << helper.ToString("GLenum", info.wrap_t) << "\"\n"; return str.str(); } template <> const std::string ConvertInfoToJson(const Indent& indent, const ShaderInfo& info) { gfx::TracingHelper helper; std::ostringstream str; str << indent << "\"object_id\": " << info.id << ",\n"; str << indent << "\"label\": " << "\"" << info.label << "\",\n"; str << indent << "\"type\": \"" << helper.ToString("GLenum", info.type) << "\",\n"; str << indent << "\"delete_status\": \"" << helper.ToString("GLboolean", info.delete_status) << "\",\n"; str << indent << "\"compile_status\": \"" << helper.ToString("GLboolean", info.compile_status) << "\",\n"; str << indent << "\"source\": \"" << base::MimeBase64EncodeString("<pre><code>" + info.source + "</code></pre>") << "\",\n"; str << indent << "\"info_log\": \"" << EscapeJson(info.info_log) << "\"\n"; return str.str(); } template <> const std::string ConvertInfoToJson(const Indent& indent, const TextureInfo& info) { gfx::TracingHelper helper; std::ostringstream str; str << indent << "\"object_id\": " << info.id << ",\n"; str << indent << "\"label\": " << "\"" << info.label << "\",\n"; str << indent << "\"width\": " << info.width << ",\n"; str << indent << "\"height\": " << info.height<< ",\n"; str << indent << "\"format\": \"" << Image::GetFormatString(info.format) << "\",\n"; str << indent << "\"sampler_glid\": " << info.sampler << ",\n"; str << indent << "\"base_level\": " << info.base_level << ",\n"; str << indent << "\"max_level\": " << info.max_level << ",\n"; str << indent << "\"compare_function\": \"" << helper.ToString("GLtextureenum", info.compare_func) << "\",\n"; str << indent << "\"compare_mode\": \"" << helper.ToString("GLtextureenum", info.compare_mode) << "\",\n"; str << indent << "\"max_anisotropy\": " << info.max_anisotropy << ",\n"; str << indent << "\"min_lod\": " << info.min_lod << ",\n"; str << indent << "\"max_lod\": " << info.max_lod << ",\n"; str << indent << "\"min_filter\": \"" << helper.ToString("GLenum", info.min_filter) << "\",\n"; str << indent << "\"mag_filter\": \"" << helper.ToString("GLenum", info.mag_filter) << "\",\n"; str << indent << "\"swizzle_red\": \"" << helper.ToString("GLtextureenum", info.swizzle_r) << "\",\n"; str << indent << "\"swizzle_green\": \"" << helper.ToString("GLtextureenum", info.swizzle_g) << "\",\n"; str << indent << "\"swizzle_blue\": \"" << helper.ToString("GLtextureenum", info.swizzle_b) << "\",\n"; str << indent << "\"swizzle_alpha\": \"" << helper.ToString("GLtextureenum", info.swizzle_a) << "\",\n"; str << indent << "\"wrap_r\": \"" << helper.ToString("GLenum", info.wrap_r) << "\",\n"; str << indent << "\"wrap_s\": \"" << helper.ToString("GLenum", info.wrap_s) << "\",\n"; str << indent << "\"wrap_t\": \"" << helper.ToString("GLenum", info.wrap_t) << "\",\n"; str << indent << "\"target\": \"" << helper.ToString("GLenum", info.target) << "\",\n"; str << indent << "\"last_image_unit\": \"" << helper.ToString("GLenum", info.unit) << "\"\n"; return str.str(); } // Uses the passed ResourceManager to request information about OpenGL // resources. template <typename ResourceType, typename InfoType> void RequestInfo( ResourceManager* manager, const typename gfxutils::ResourceCallback<InfoType>::RefPtr& callback) { manager->RequestAllResourceInfos<ResourceType, InfoType>(std::bind( &gfxutils::ResourceCallback<InfoType>::Callback, callback.Get(), _1)); } // Specialization for PlatformInfo, which does not require a ResourceType and // has a different function signature in the ResourceManager. template <> void RequestInfo<PlatformInfo, PlatformInfo>( ResourceManager* manager, const gfxutils::ResourceCallback<PlatformInfo>::RefPtr& callback) { manager->RequestPlatformInfo(std::bind( &gfxutils::ResourceCallback<PlatformInfo>::Callback, callback.Get(), _1)); } // Builds and returns a JSOn struct for the named resource type. template <typename ResourceType, typename InfoType> const std::string BuildJsonStruct(const RendererPtr& renderer, const std::string& name, const Indent& indent, const bool wait_for_completion) { // Get resource information out of the Renderer's ResourceManager. ResourceManager* manager = renderer->GetResourceManager(); typedef gfxutils::ResourceCallback<InfoType> Callback; typename Callback::RefPtr callback(new Callback(wait_for_completion)); RequestInfo<ResourceType, InfoType>(manager, callback); // Only explicitly ask the renderer to process the requests if we are not // willing to block. This should only be used for tests, since the handler // will be executed on a thread other than the Renderer's. if (!wait_for_completion) renderer->ProcessResourceInfoRequests(); std::vector<InfoType> infos; callback->WaitForCompletion(&infos); std::ostringstream str; const Indent indent2 = indent + 2; const Indent indent4 = indent + 4; // Start the array. str << indent << "\"" << name << "\": [\n"; const size_t count = infos.size(); for (size_t i = 0; i < count; ++i) { str << indent2 << "{\n"; str << ConvertInfoToJson<InfoType>(indent4, infos[i]); str << indent2 << "}" << (i < count - 1U ? "," : "") << "\n"; } // End the array. str << indent << "]"; return str.str(); } // Returns a string containing a JSON object containing lists of JSON structs // for the types queried in the "types" argument in args. static const std::string GetResourceList(const RendererPtr& renderer, const HttpServer::QueryMap& args) { const bool wait_for_completion = args.find("nonblocking") == args.end(); HttpServer::QueryMap::const_iterator it = args.find("types"); std::ostringstream str; if (it != args.end()) { str << "{\n"; const Indent indent(2); const std::vector<std::string> types = base::SplitString(it->second, ","); const size_t count = types.size(); for (size_t i = 0; i < count; ++i) { if (types[i] == "platform") { str << BuildJsonStruct<PlatformInfo, PlatformInfo>( renderer, "platform", indent, wait_for_completion); } else if (types[i] == "buffers") { str << BuildJsonStruct<BufferObject, BufferInfo>( renderer, "buffers", indent, wait_for_completion); } else if (types[i] == "framebuffers") { str << BuildJsonStruct<FramebufferObject, FramebufferInfo>( renderer, "framebuffers", indent, wait_for_completion); } else if (types[i] == "programs") { str << BuildJsonStruct<ShaderProgram, ProgramInfo>( renderer, "programs", indent, wait_for_completion); } else if (types[i] == "samplers") { str << BuildJsonStruct<Sampler, SamplerInfo>( renderer, "samplers", indent, wait_for_completion); } else if (types[i] == "shaders") { str << BuildJsonStruct<Shader, ShaderInfo>(renderer, "shaders", indent, wait_for_completion); } else if (types[i] == "textures") { str << BuildJsonStruct<TextureBase, TextureInfo>( renderer, "textures", indent, wait_for_completion); } else if (types[i] == "vertex_arrays") { str << BuildJsonStruct<AttributeArray, ArrayInfo>( renderer, "vertex_arrays", indent, wait_for_completion); } else { // Ignore invalid labels. continue; } // Every struct but the last requires a trailing comma. if (i < count - 1) str << ",\n"; else str << "\n"; } str << "}\n"; } return str.str(); } static const std::string GetBufferData(const RendererPtr& renderer, const HttpServer::QueryMap& args) { // TODO(user): Map the buffer read-only given only the id, and return the // data. return std::string(); } // Writes a face of a cube map into the map at the passed offsets. This inverts // the Y coordinate to counteract OpenGL rendering. static void WriteFaceIntoCubeMap(uint32 x_offset, uint32 y_offset, const ImagePtr& face, const ImagePtr& cubemap) { const uint32 x_offset_bytes = x_offset * 3; const uint32 face_height = face->GetHeight(); const uint32 face_row_bytes = face->GetWidth() * 3; const uint32 cube_row_bytes = cubemap->GetWidth() * 3; const uint8* in = face->GetData()->GetData<uint8>(); uint8* out = cubemap->GetData()->GetMutableData<uint8>(); DCHECK(in); DCHECK(out); for (uint32 row = 0; row < face_height; ++row) { const uint32 y = face_height - row - 1; memcpy(&out[(y_offset + y) * cube_row_bytes + x_offset_bytes], &in[y * face_row_bytes], face_row_bytes); } } // Returns a string that contains PNG data for the ID passed as a query arg. static const std::string GetTextureData(const RendererPtr& renderer, const HttpServer::QueryMap& args, bool wait_for_completion) { std::string data; HttpServer::QueryMap::const_iterator id_it = args.find("id"); if (id_it != args.end()) { if (GLuint id = static_cast<GLuint>(base::StringToInt32(id_it->second))) { // Request the info. ResourceManager* manager = renderer->GetResourceManager(); RenderTextureCallback::RefPtr callback( new RenderTextureCallback(renderer, wait_for_completion)); manager->RequestTextureImage( id, std::bind(&RenderTextureCallback::Callback, callback.Get(), _1)); if (!wait_for_completion) renderer->ProcessResourceInfoRequests(); // Wait for the callback to be triggered. std::vector<TextureImageInfo> infos; callback->WaitForCompletion(&infos); // There should only be one info, and it contains the texture image. if (infos.size() && infos[0].images.size()) { if (infos[0].images.size() == 1U) { // Convert the image to png. Flip Y to counteract OpenGL rendering. const std::vector<uint8> png_data = image::ConvertToExternalImageData( infos[0].images[0], image::kPng, true); data = base::MimeBase64EncodeString( std::string(png_data.begin(), png_data.end())); } else { // Make a vertical cube map cross image. DCHECK_EQ(6U, infos[0].images.size()); uint32 face_width = 0; uint32 face_height = 0; for (int i = 0; i < 6; ++i) { face_width = std::max(face_width, infos[0].images[0]->GetWidth()); face_height = std::max(face_height, infos[0].images[0]->GetHeight()); } // Allocate the data. ImagePtr cubemap(new Image); const uint32 num_bytes = face_width * 3U * face_height * 4U * 3U; base::DataContainerPtr cubemap_data = base::DataContainer::CreateOverAllocated<uint8>( num_bytes, NULL, cubemap->GetAllocator()); cubemap->Set( Image::kRgb888, face_width * 3U, face_height * 4U, cubemap_data); memset(cubemap_data->GetMutableData<uint8>(), 0, num_bytes); // Copy the images into the cubemap. The output map should look like: // ---- // |+Y| // ---------- // |-X|+Z|+X| // ---------- // |-Y| // ---- // |-Z| // ---- WriteFaceIntoCubeMap(face_width, 0U, infos[0].images[4], cubemap); WriteFaceIntoCubeMap(0U, face_height, infos[0].images[0], cubemap); WriteFaceIntoCubeMap( face_width, face_height, infos[0].images[5], cubemap); WriteFaceIntoCubeMap( face_width * 2U, face_height, infos[0].images[3], cubemap); WriteFaceIntoCubeMap( face_width, face_height * 2U, infos[0].images[1], cubemap); WriteFaceIntoCubeMap( face_width, face_height * 3U, infos[0].images[2], cubemap); // Send the image back. const std::vector<uint8> png_data = image::ConvertToExternalImageData(cubemap, image::kPng, false); data = base::MimeBase64EncodeString( std::string(png_data.begin(), png_data.end())); } } } } return data; } } // anonymous namespace //----------------------------------------------------------------------------- // // ResourceHandler functions. // //----------------------------------------------------------------------------- ResourceHandler::ResourceHandler(const gfx::RendererPtr& renderer) : HttpServer::RequestHandler("/ion/resources"), renderer_(renderer) { IonRemoteResourcesRoot::RegisterAssetsOnce(); } ResourceHandler::~ResourceHandler() {} const std::string ResourceHandler::HandleRequest( const std::string& path_in, const HttpServer::QueryMap& args, std::string* content_type) { const std::string path = path_in.empty() ? "index.html" : path_in; if (path == "buffer_data") { return GetBufferData(renderer_, args); } else if (path == "resources_by_type") { *content_type = "application/json"; return GetResourceList(renderer_, args); } else if (path == "texture_data") { *content_type = "image/png"; return GetTextureData( renderer_, args, args.find("nonblocking") == args.end()); } else { const std::string& data = base::ZipAssetManager::GetFileData( "ion/resources/" + path); if (base::IsInvalidReference(data)) { return std::string(); } else { // Ensure the content type is set if the editor HTML is requested. if (base::EndsWith(path, "html")) *content_type = "text/html"; return data; } } } } // namespace remote } // namespace ion #endif
38.934144
80
0.605496
mdemoret
4c9d960feb65756eb35282dde7b24bdf61bb3e8b
9,492
cpp
C++
platforms/linux/TTYLib.cpp
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
2
2021-05-06T19:56:26.000Z
2021-05-27T16:41:56.000Z
platforms/linux/TTYLib.cpp
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
54
2021-03-30T18:45:12.000Z
2022-03-17T20:13:04.000Z
platforms/linux/TTYLib.cpp
ICESat2-SlideRule/sliderule
90776d7e174e151c5806077001f5f9c21ef81f48
[ "BSD-3-Clause" ]
1
2021-05-14T16:34:08.000Z
2021-05-14T16:34:08.000Z
/* * Copyright (c) 2021, University of Washington * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the University of Washington 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 UNIVERSITY OF WASHINGTON 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 UNIVERSITY OF WASHINGTON 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. */ /****************************************************************************** * INCLUDES ******************************************************************************/ #include "OsApi.h" #include <stdlib.h> #include <stdio.h> #include <stdarg.h> #include <string.h> #include <time.h> #include <limits.h> #include <assert.h> #include <unistd.h> #include <signal.h> #include <ctype.h> #include <fcntl.h> #include <errno.h> #include <poll.h> #include <termios.h> #include <sys/sysinfo.h> /****************************************************************************** * PUBLIC METHODS ******************************************************************************/ /*---------------------------------------------------------------------------- * init *----------------------------------------------------------------------------*/ void TTYLib::init() { } /*---------------------------------------------------------------------------- * deinit *----------------------------------------------------------------------------*/ void TTYLib::deinit(void) { } /*---------------------------------------------------------------------------- * ttyopen *----------------------------------------------------------------------------*/ int TTYLib::ttyopen(const char* _device, int _baud, char _parity) { int fd = INVALID_RC; int baud = 0; int parity = 0; /* Set Parity */ if(_parity == 'N' || _parity == 'n') { parity = 0; // no parity } else if(_parity == 'O' || _parity == 'o') { parity = PARENB | PARODD; // odd parity } else if(_parity == 'E' || _parity == 'e') { parity = PARENB; // event parity } /* Set Baud */ switch(_baud) { case 50: baud = B50; break; case 75: baud = B75; break; case 110: baud = B110; break; case 134: baud = B134; break; case 150: baud = B150; break; case 200: baud = B200; break; case 300: baud = B300; break; case 600: baud = B600; break; case 1200: baud = B1200; break; case 1800: baud = B1800; break; case 2400: baud = B2400; break; case 4800: baud = B4800; break; case 9600: baud = B9600; break; case 19200: baud = B19200; break; case 38400: baud = B38400; break; case 115200: baud = B115200; break; case 230400: baud = B230400; break; case 460800: baud = B460800; break; case 500000: baud = B500000; break; case 576000: baud = B576000; break; case 921600: baud = B921600; break; case 1000000: baud = B1000000; break; case 1152000: baud = B1152000; break; default: baud = B0; break; } /* Set Device */ if(_device) { /* Set File Descriptor */ fd = open(_device, O_RDWR | O_NOCTTY | O_NDELAY); if(fd < 0) { dlog("Failed (%d) to open %s: %s", errno, _device, strerror(errno)); fd = INVALID_RC; } else { struct termios tty; memset(&tty, 0, sizeof(tty)); if(tcgetattr (fd, &tty) != 0) { dlog("Failed (%d) tcgetattr for %s: %s", errno, _device, strerror(errno)); fd = INVALID_RC; } else { cfsetospeed (&tty, baud); cfsetispeed (&tty, baud); tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars tty.c_iflag &= ~IGNBRK; // disable break processing tty.c_iflag &= ~(INLCR | ICRNL | IUCLC); // no remapping on input tty.c_lflag = 0; // no signaling chars, no echo tty.c_oflag = 0; // no remapping, no delays tty.c_cc[VMIN] = 0; // read is non-blocking tty.c_cc[VTIME] = 0; // no read timeout tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl tty.c_cflag |= (CLOCAL | CREAD); // ignore modem controls tty.c_cflag &= ~(PARENB | PARODD); // initialize parity to off tty.c_cflag |= parity; // set parity tty.c_cflag &= ~CSTOPB; // send one stop bit tty.c_cflag &= ~CRTSCTS; // no hardware flow control if(tcsetattr (fd, TCSANOW, &tty) != 0) { dlog("Failed (%d) tcsetattr for %s: %s", errno, _device, strerror(errno)); fd = INVALID_RC; } } } } /* Return Descriptor */ return fd; } /*---------------------------------------------------------------------------- * ttyclose *----------------------------------------------------------------------------*/ void TTYLib::ttyclose(int fd) { close(fd); } /*---------------------------------------------------------------------------- * ttywrite *----------------------------------------------------------------------------*/ int TTYLib::ttywrite(int fd, const void* buf, int size, int timeout) { unsigned char* cbuf = (unsigned char*)buf; int activity = 1; int revents = POLLOUT; /* Check Device */ if(fd == INVALID_RC) { if(timeout != IO_CHECK) LocalLib::performIOTimeout(); return TIMEOUT_RC; } /* Send Data */ int c = 0; while(c >= 0 && c < size) { /* Perform Poll if not Checking */ if(timeout != IO_CHECK) { /* Build Poll Structure */ struct pollfd polllist[1]; polllist[0].fd = fd; polllist[0].events = POLLOUT | POLLHUP; polllist[0].revents = 0; /* Poll */ do activity = poll(polllist, 1, timeout); while(activity == -1 && (errno == EINTR || errno == EAGAIN)); /* Check Activity */ if(activity <= 0) break; revents = polllist[0].revents; } /* Perform Send */ if(revents & POLLHUP) { c = SHUTDOWN_RC; } else if(revents & POLLOUT) { int ret = write(fd, &cbuf[c], size - c); if(ret > 0) c += ret; else if(ret <= 0) c = TTY_ERR_RC; } } /* Return Results */ return c; } /*---------------------------------------------------------------------------- * ttyread *----------------------------------------------------------------------------*/ int TTYLib::ttyread(int fd, void* buf, int size, int timeout) { int c = TIMEOUT_RC; int revents = POLLIN; /* Check Device */ if(fd == INVALID_RC) { if(timeout != IO_CHECK) LocalLib::performIOTimeout(); return TIMEOUT_RC; } /* Perform Poll if not Checking */ if(timeout != IO_CHECK) { struct pollfd polllist[1]; polllist[0].fd = fd; polllist[0].events = POLLIN | POLLHUP; polllist[0].revents = 0; int activity = 1; do activity = poll(polllist, 1, timeout); while(activity == -1 && (errno == EINTR || errno == EAGAIN)); revents = polllist[0].revents; } /* Perform Receive */ if(revents & POLLIN) { c = read(fd, buf, size); if(c <= 0) c = TTY_ERR_RC; } else if(revents & POLLHUP) { c = SHUTDOWN_RC; } /* Return Results*/ return c; }
33.659574
98
0.455225
ICESat2-SlideRule