hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
a747a9d7989b49408a74654685190a1643c9d0cc
860
hpp
C++
src/View/Palette.hpp
qzerrty/graphics-editor
af76f1466bac3b3ba7363272af74ab04e6ee44ae
[ "MIT" ]
null
null
null
src/View/Palette.hpp
qzerrty/graphics-editor
af76f1466bac3b3ba7363272af74ab04e6ee44ae
[ "MIT" ]
null
null
null
src/View/Palette.hpp
qzerrty/graphics-editor
af76f1466bac3b3ba7363272af74ab04e6ee44ae
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <istream> #include "main/graphicsEditor.hpp" #include "Interfaces/Window.hpp" #include "ColorInput.hpp" #include "ChoosenColor.hpp" #include "TextInput.hpp" class Palette : public Window { private: std::vector<ColorInput *> colors; std::vector<TextInput *> textInputs; ChoosenColor* m_choosenColor; public: Palette(int,int,int,int,const style_s *); ~Palette(); bool clicked(SDL_Event *) override; bool hovered(SDL_Event *) override; void draw(SDL_Surface *) override; void addColorInput(int,int,int,int,const style_s *,Uint32,char *,ComponentName); void addTextInput(int,int,int,int,const style_s *,char *,std::string,ComponentName); void setChoosenColor(int,int,int,int,const style_s *,Uint32,char *,ComponentName); ChoosenColor * getChoosenColor(); TextInput * getTextInput(size_t index); };
30.714286
86
0.748837
[ "vector" ]
a747b9379b58d9310c3235715fd75faa43fc3708
44,663
cpp
C++
src/backend/gporca/server/src/unittest/gpopt/operators/CExpressionTest.cpp
saschasch76/gpdb
83e217407e8d431f97144c5233e6b93aa4db26c7
[ "PostgreSQL", "Apache-2.0" ]
4
2017-11-28T08:12:58.000Z
2020-10-28T04:15:52.000Z
src/backend/gporca/server/src/unittest/gpopt/operators/CExpressionTest.cpp
wjzeng/gpdb
42ed049b7d7dfd21127cfffaf7aa9be862570828
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
src/backend/gporca/server/src/unittest/gpopt/operators/CExpressionTest.cpp
wjzeng/gpdb
42ed049b7d7dfd21127cfffaf7aa9be862570828
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2009 Greenplum, Inc. // // @filename: // CExpressionTest.cpp // // @doc: // Test for CExpression //--------------------------------------------------------------------------- #include "unittest/gpopt/operators/CExpressionTest.h" #include "gpos/error/CAutoTrace.h" #include "gpos/io/COstreamString.h" #include "gpos/string/CWStringDynamic.h" #include "gpopt/base/CCTEReq.h" #include "gpopt/base/CDrvdPropCtxtPlan.h" #include "gpopt/base/CUtils.h" #include "gpopt/engine/CEngine.h" #include "gpopt/eval/CConstExprEvaluatorDefault.h" #include "gpopt/mdcache/CAutoMDAccessor.h" #include "gpopt/metadata/CIndexDescriptor.h" #include "gpopt/operators/CLogicalBitmapTableGet.h" #include "gpopt/operators/CLogicalDynamicGetBase.h" #include "gpopt/operators/CLogicalInnerJoin.h" #include "gpopt/operators/CLogicalLeftAntiSemiJoin.h" #include "gpopt/operators/CLogicalLeftAntiSemiJoinNotIn.h" #include "gpopt/operators/CLogicalLeftOuterJoin.h" #include "gpopt/operators/CLogicalLeftSemiJoin.h" #include "gpopt/operators/CLogicalUnion.h" #include "gpopt/operators/CScalarBitmapBoolOp.h" #include "gpopt/operators/CScalarBitmapIndexProbe.h" #include "naucrates/base/CDatumInt8GPDB.h" #include "naucrates/md/CMDIdGPDB.h" #include "naucrates/md/IMDScalarOp.h" #include "unittest/base.h" #include "unittest/gpopt/CTestUtils.h" using namespace gpos; //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest // // @doc: // Create required properties which are empty, except for required column set, given by 'pcrs'. // Caller takes ownership of returned pointer. // //--------------------------------------------------------------------------- CReqdPropPlan * CExpressionTest::PrppCreateRequiredProperties(CMemoryPool *mp, CColRefSet *pcrs) { COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp); CDistributionSpec *pds = GPOS_NEW(mp) CDistributionSpecSingleton(CDistributionSpecSingleton::EstMaster); CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec( CRewindabilitySpec::ErtNone, CRewindabilitySpec::EmhtNoMotion); CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy); CEnfdDistribution *ped = GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmSatisfy); CEnfdRewindability *per = GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy); CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp); return GPOS_NEW(mp) CReqdPropPlan(pcrs, peo, ped, per, pcter); } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest // // @doc: // Creates a logical GroupBy and a Get as its child. The columns in the // Get follow the format wszColNameFormat. // Caller takes ownership of returned pointer. // //--------------------------------------------------------------------------- CExpression * CExpressionTest::PexprCreateGbyWithColumnFormat(CMemoryPool *mp, const WCHAR *wszColNameFormat) { CWStringConst strRelName(GPOS_WSZ_LIT("Rel1")); CMDIdGPDB *rel_mdid = GPOS_NEW(mp) CMDIdGPDB(GPOPT_TEST_REL_OID1, 1, 1); CTableDescriptor *ptabdesc = CTestUtils::PtabdescPlainWithColNameFormat( mp, 3, rel_mdid, wszColNameFormat, CName(&strRelName), false); CWStringConst strRelAlias(GPOS_WSZ_LIT("Rel1")); CExpression *pexprGet = CTestUtils::PexprLogicalGet(mp, ptabdesc, &strRelAlias); return CTestUtils::PexprLogicalGbAggWithInput(mp, pexprGet); } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest // // @doc: // Unittest for expressions // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest() { CUnittest rgut[] = { GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_SimpleOps), GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_Union), GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_BitmapGet), GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_Const), #ifdef GPOS_DEBUG GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_ComparisonTypes), #endif // GPOS_DEBUG GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_FValidPlan), GPOS_UNITTEST_FUNC( CExpressionTest::EresUnittest_FValidPlan_InvalidOrder), GPOS_UNITTEST_FUNC( CExpressionTest::EresUnittest_FValidPlan_InvalidDistribution), GPOS_UNITTEST_FUNC( CExpressionTest::EresUnittest_FValidPlan_InvalidRewindability), GPOS_UNITTEST_FUNC( CExpressionTest::EresUnittest_FValidPlan_InvalidCTEs), #ifdef GPOS_DEBUG GPOS_UNITTEST_FUNC(CExpressionTest::EresUnittest_FValidPlanError), #endif // GPOS_DEBUG GPOS_UNITTEST_FUNC(EresUnittest_ReqdCols), #ifdef GPOS_DEBUG GPOS_UNITTEST_FUNC_ASSERT(CExpressionTest::EresUnittest_InvalidSetOp), #endif // GPOS_DEBUG }; return CUnittest::EresExecute(rgut, GPOS_ARRAY_SIZE(rgut)); } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_SimpleOps // // @doc: // Basic tree builder test // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_SimpleOps() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); typedef CExpression *(*Pfpexpr)(CMemoryPool *); Pfpexpr rgpf[] = { CTestUtils::PexprLogicalGet, CTestUtils::PexprLogicalExternalGet, CTestUtils::PexprLogicalGetPartitioned, CTestUtils::PexprLogicalSelect, CTestUtils::PexprLogicalSelectCmpToConst, CTestUtils::PexprLogicalSelectArrayCmp, CTestUtils::PexprLogicalSelectPartitioned, CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>, CTestUtils::PexprLogicalJoin<CLogicalLeftOuterJoin>, CTestUtils::PexprLogicalJoin<CLogicalLeftSemiJoin>, CTestUtils::PexprLogicalJoin<CLogicalLeftAntiSemiJoin>, CTestUtils::PexprLogicalJoin<CLogicalLeftAntiSemiJoinNotIn>, CTestUtils::PexprLogicalGbAgg, CTestUtils::PexprLogicalGbAggOverJoin, CTestUtils::PexprLogicalGbAggWithSum, CTestUtils::PexprLogicalLimit, CTestUtils::PexprLogicalNAryJoin, CTestUtils::PexprLogicalProject, CTestUtils::PexprConstTableGet5, CTestUtils::PexprLogicalDynamicGet, CTestUtils::PexprLogicalSequence, CTestUtils::PexprLogicalTVFTwoArgs, CTestUtils::PexprLogicalAssert, PexprComplexJoinTree}; #ifdef GPOS_DEBUG // misestimation risk for the roots of the plans in rgpf ULONG rgulRisk[] = {1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 1, 2, 1, 1, 1, 1, 1, 1, 6}; #endif // GPOS_DEBUG for (ULONG i = 0; i < GPOS_ARRAY_SIZE(rgpf); i++) { // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); // generate simple expression CExpression *pexpr = rgpf[i](mp); CLogicalGet *popGet = dynamic_cast<CLogicalGet *>(pexpr->Pop()); CLogicalDynamicGetBase *popDynGet = dynamic_cast<CLogicalDynamicGetBase *>(pexpr->Pop()); CColRefArray *colrefs = nullptr; if (nullptr != popGet) { colrefs = popGet->PdrgpcrOutput(); } else if (nullptr != popDynGet) { colrefs = popDynGet->PdrgpcrOutput(); } if (nullptr != colrefs) { for (ULONG ul = 0; ul < colrefs->Size(); ul++) { (*colrefs)[ul]->MarkAsUsed(); } } // self-match GPOS_ASSERT(pexpr->FMatchDebug(pexpr)); // debug print CWStringDynamic str(mp, GPOS_WSZ_LIT("\n")); COstreamString oss(&str); oss << "EXPR:" << std::endl << *pexpr << std::endl; GPOS_TRACE(str.GetBuffer()); str.Reset(); #ifdef GPOS_DEBUG oss << std::endl << "DERIVED PROPS:" << std::endl; GPOS_TRACE(str.GetBuffer()); str.Reset(); pexpr->DbgPrint(); // copy expression CColRef *pcrOld = pexpr->DeriveOutputColumns()->PcrAny(); CColRef *new_colref = COptCtxt::PoctxtFromTLS()->Pcf()->PcrCreate(pcrOld); UlongToColRefMap *colref_mapping = GPOS_NEW(mp) UlongToColRefMap(mp); BOOL result = colref_mapping->Insert(GPOS_NEW(mp) ULONG(pcrOld->Id()), new_colref); GPOS_ASSERT(result); CExpression *pexprCopy = pexpr->PexprCopyWithRemappedColumns( mp, colref_mapping, true /*must_exist*/); colref_mapping->Release(); oss << std::endl << "COPIED EXPRESSION (AFTER MAPPING " << *pcrOld << " TO " << *new_colref << "):" << std::endl; GPOS_TRACE(str.GetBuffer()); str.Reset(); pexprCopy->DbgPrint(); pexprCopy->Release(); // derive stats on expression CReqdPropRelational *prprel = GPOS_NEW(mp) CReqdPropRelational(GPOS_NEW(mp) CColRefSet(mp)); IStatisticsArray *stats_ctxt = GPOS_NEW(mp) IStatisticsArray(mp); IStatistics *stats = pexpr->PstatsDerive(prprel, stats_ctxt); GPOS_ASSERT(nullptr != stats); oss << "Expected risk: " << rgulRisk[i] << std::endl; oss << std::endl << "STATS:" << *stats << std::endl; GPOS_TRACE(str.GetBuffer()); GPOS_ASSERT(rgulRisk[i] == stats->StatsEstimationRisk()); prprel->Release(); stats_ctxt->Release(); #endif // GPOS_DEBUG // cleanup pexpr->Release(); } return GPOS_OK; } //--------------------------------------------------------------------------- // CExpressionTest::EresUnittest_Union // // @doc: // Basic tree builder test w/ Unions // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_Union() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); // build union tree of depth 2 CExpression *pexpr = CTestUtils::PexprLogicalUnion(mp, 2); // debug print CWStringDynamic str(mp); COstreamString oss(&str); pexpr->OsPrint(oss); GPOS_TRACE(str.GetBuffer()); // derive properties on expression (void) pexpr->PdpDerive(); #ifdef GPOS_DEBUG CReqdPropRelational *prprel = GPOS_NEW(mp) CReqdPropRelational(GPOS_NEW(mp) CColRefSet(mp)); IStatisticsArray *stats_ctxt = GPOS_NEW(mp) IStatisticsArray(mp); IStatistics *stats = pexpr->PstatsDerive(prprel, stats_ctxt); GPOS_ASSERT(nullptr != stats); // We expect a risk of 3 because every Union increments the risk. GPOS_ASSERT(3 == stats->StatsEstimationRisk()); stats_ctxt->Release(); prprel->Release(); #endif // GPOS_DEBUG // cleanup pexpr->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // CExpressionTest::EresUnittest_BitmapScan // // @doc: // Basic tree builder test with bitmap index and table get. // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_BitmapGet() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); CWStringConst strRelName(GPOS_WSZ_LIT("MyTable")); CWStringConst strRelAlias(GPOS_WSZ_LIT("T")); CMDIdGPDB *rel_mdid = GPOS_NEW(mp) CMDIdGPDB(GPOPT_MDCACHE_TEST_OID, 1, 1); const WCHAR *wszColNameFormat = GPOS_WSZ_LIT("column_%04d"); CTableDescriptor *ptabdesc = CTestUtils::PtabdescPlainWithColNameFormat( mp, 3, rel_mdid, wszColNameFormat, CName(&strRelName), false); // get the index associated with the table const IMDRelation *pmdrel = mda.RetrieveRel(ptabdesc->MDId()); GPOS_ASSERT(0 < pmdrel->IndexCount()); // create an index descriptor IMDId *pmdidIndex = pmdrel->IndexMDidAt(0 /*pos*/); const IMDIndex *pmdindex = mda.RetrieveIndex(pmdidIndex); CColumnFactory *col_factory = COptCtxt::PoctxtFromTLS()->Pcf(); const ULONG num_cols = pmdrel->ColumnCount(); GPOS_ASSERT(2 < num_cols); // create an index on the first column const IMDColumn *pmdcol = pmdrel->GetMdCol(0); const IMDType *pmdtype = mda.RetrieveType(pmdcol->MdidType()); CColRef *pcrFirst = col_factory->PcrCreate(pmdtype, pmdcol->TypeModifier()); CExpression *pexprIndexCond = CUtils::PexprScalarEqCmp( mp, pcrFirst, CUtils::PexprScalarConstInt4(mp, 20 /*val*/)); CMDIdGPDB *mdid = GPOS_NEW(mp) CMDIdGPDB(CMDIdGPDB::m_mdid_unknown); CIndexDescriptor *pindexdesc = CIndexDescriptor::Pindexdesc(mp, ptabdesc, pmdindex); CExpression *pexprBitmapIndex = GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CScalarBitmapIndexProbe(mp, pindexdesc, mdid), pexprIndexCond); CColRefArray *pdrgpcrTable = GPOS_NEW(mp) CColRefArray(mp); for (ULONG ul = 0; ul < num_cols; ++ul) { const IMDColumn *pmdcol = pmdrel->GetMdCol(ul); const IMDType *pmdtype = mda.RetrieveType(pmdcol->MdidType()); CColRef *colref = col_factory->PcrCreate(pmdtype, pmdcol->TypeModifier()); pdrgpcrTable->Append(colref); } CExpression *pexprTableCond = CUtils::PexprScalarEqCmp( mp, pcrFirst, CUtils::PexprScalarConstInt4(mp, 20 /*val*/)); CExpression *pexprBitmapTableGet = GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CLogicalBitmapTableGet( mp, ptabdesc, gpos::ulong_max, // pgexprOrigin GPOS_NEW(mp) CName(mp, CName(&strRelAlias)), pdrgpcrTable), pexprTableCond, pexprBitmapIndex); // debug print CWStringDynamic str(mp); COstreamString oss(&str); pexprBitmapTableGet->OsPrint(oss); CWStringConst strExpectedDebugPrint(GPOS_WSZ_LIT( "+--CLogicalBitmapTableGet , Table Name: (\"MyTable\"), Columns: [\"ColRef_0001\" (1), \"ColRef_0002\" (2), \"ColRef_0003\" (3)]\n" " |--CScalarCmp (=)\n" " | |--CScalarIdent \"ColRef_0000\" (0)\n" " | +--CScalarConst (20)\n" " +--CScalarBitmapIndexProbe Bitmap Index Name: (\"T_a\")\n" " +--CScalarCmp (=)\n" " |--CScalarIdent \"ColRef_0000\" (0)\n" " +--CScalarConst (20)\n")); GPOS_ASSERT(str.Equals(&strExpectedDebugPrint)); // derive properties on expression (void) pexprBitmapTableGet->PdpDerive(); // test matching of bitmap index probe expressions CMDIdGPDB *pmdid2 = GPOS_NEW(mp) CMDIdGPDB(CMDIdGPDB::m_mdid_unknown); CIndexDescriptor *pindexdesc2 = CIndexDescriptor::Pindexdesc(mp, ptabdesc, pmdindex); CExpression *pexprIndexCond2 = CUtils::PexprScalarEqCmp( mp, pcrFirst, CUtils::PexprScalarConstInt4(mp, 20 /*val*/)); CExpression *pexprBitmapIndex2 = GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CScalarBitmapIndexProbe(mp, pindexdesc2, pmdid2), pexprIndexCond2); CWStringDynamic strIndex2(mp); COstreamString ossIndex2(&strIndex2); pexprBitmapIndex2->OsPrint(ossIndex2); CWStringConst strExpectedDebugPrintIndex2(GPOS_WSZ_LIT( // clang-format off "+--CScalarBitmapIndexProbe Bitmap Index Name: (\"T_a\")\n" " +--CScalarCmp (=)\n" " |--CScalarIdent \"ColRef_0000\" (0)\n" " +--CScalarConst (20)\n" // clang-format on )); GPOS_ASSERT(strIndex2.Equals(&strExpectedDebugPrintIndex2)); GPOS_ASSERT(pexprBitmapIndex2->Matches(pexprBitmapIndex)); mdid->AddRef(); pexprBitmapIndex->AddRef(); pexprBitmapIndex2->AddRef(); CExpression *pexprBitmapBoolOp1 = GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CScalarBitmapBoolOp(mp, CScalarBitmapBoolOp::EbitmapboolAnd, mdid), pexprBitmapIndex, pexprBitmapIndex2); mdid->AddRef(); pexprBitmapIndex->AddRef(); CExpression *pexprBitmapBoolOp2 = GPOS_NEW(mp) CExpression( mp, GPOS_NEW(mp) CScalarBitmapBoolOp(mp, CScalarBitmapBoolOp::EbitmapboolAnd, mdid), pexprBitmapIndex, pexprBitmapIndex2); GPOS_ASSERT(pexprBitmapBoolOp2->Matches(pexprBitmapBoolOp1)); // cleanup pexprBitmapBoolOp2->Release(); pexprBitmapBoolOp1->Release(); pexprBitmapTableGet->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_Const // // @doc: // Test of scalar constant expressions // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_Const() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); BOOL value = true; CExpression *pexprTrue = CUtils::PexprScalarConstBool(mp, value); value = false; CExpression *pexprFalse = CUtils::PexprScalarConstBool(mp, value); ULONG ulVal = 123456; CExpression *pexprUl = CUtils::PexprScalarConstInt4(mp, ulVal); CExpression *pexprUl2nd = CUtils::PexprScalarConstInt4(mp, ulVal); ulVal = 1; CExpression *pexprUlOne = CUtils::PexprScalarConstInt4(mp, ulVal); CWStringDynamic str(mp); COstreamString oss(&str); oss << std::endl; pexprTrue->OsPrint(oss); pexprFalse->OsPrint(oss); pexprUl->OsPrint(oss); pexprUl2nd->OsPrint(oss); pexprUlOne->OsPrint(oss); #ifdef GPOS_DEBUG CScalarConst *pscalarconstTrue = CScalarConst::PopConvert(pexprTrue->Pop()); CScalarConst *pscalarconstFalse = CScalarConst::PopConvert(pexprFalse->Pop()); CScalarConst *pscalarconstUl = CScalarConst::PopConvert(pexprUl->Pop()); CScalarConst *pscalarconstUl2nd = CScalarConst::PopConvert(pexprUl2nd->Pop()); CScalarConst *pscalarconstUlOne = CScalarConst::PopConvert(pexprUlOne->Pop()); #endif // GPOS_DEBUG GPOS_ASSERT(pscalarconstUl->HashValue() == pscalarconstUl2nd->HashValue()); GPOS_ASSERT(!pscalarconstTrue->Matches(pscalarconstFalse)); GPOS_ASSERT(!pscalarconstTrue->Matches(pscalarconstUlOne)); pexprTrue->Release(); pexprFalse->Release(); pexprUl->Release(); pexprUl2nd->Release(); pexprUlOne->Release(); GPOS_TRACE(str.GetBuffer()); return GPOS_OK; } #ifdef GPOS_DEBUG //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_ComparisonTypes // // @doc: // Test of scalar comparison types // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_ComparisonTypes() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache()); mda.RegisterProvider(CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); const IMDType *pmdtype = mda.PtMDType<IMDTypeInt4>(); GPOS_ASSERT( IMDType::EcmptEq == CUtils::ParseCmpType(pmdtype->GetMdidForCmpType(IMDType::EcmptEq))); GPOS_ASSERT( IMDType::EcmptL == CUtils::ParseCmpType(pmdtype->GetMdidForCmpType(IMDType::EcmptL))); GPOS_ASSERT( IMDType::EcmptG == CUtils::ParseCmpType(pmdtype->GetMdidForCmpType(IMDType::EcmptG))); const IMDScalarOp *pmdscopEq = mda.RetrieveScOp(pmdtype->GetMdidForCmpType(IMDType::EcmptEq)); const IMDScalarOp *pmdscopLT = mda.RetrieveScOp(pmdtype->GetMdidForCmpType(IMDType::EcmptL)); const IMDScalarOp *pmdscopGT = mda.RetrieveScOp(pmdtype->GetMdidForCmpType(IMDType::EcmptG)); GPOS_ASSERT(IMDType::EcmptNEq == CUtils::ParseCmpType(pmdscopEq->GetInverseOpMdid())); GPOS_ASSERT(IMDType::EcmptLEq == CUtils::ParseCmpType(pmdscopGT->GetInverseOpMdid())); GPOS_ASSERT(IMDType::EcmptGEq == CUtils::ParseCmpType(pmdscopLT->GetInverseOpMdid())); return GPOS_OK; } #endif // GPOS_DEBUG //--------------------------------------------------------------------------- // @function: // CExpressionTest::SetupPlanForFValidPlanTest // // @doc: // Helper function for the FValidPlan tests // //--------------------------------------------------------------------------- void CExpressionTest::SetupPlanForFValidPlanTest(CMemoryPool *mp, CExpression **ppexprGby, CColRefSet **ppcrs, CExpression **ppexprPlan, CReqdPropPlan **pprpp) { *ppexprGby = PexprCreateGbyWithColumnFormat(mp, GPOS_WSZ_LIT("Test Column%d")); // Create a column requirement using the first output column of the group by. CColRefSet *pcrsGby = (*ppexprGby)->DeriveOutputColumns(); *ppcrs = GPOS_NEW(mp) CColRefSet(mp); (*ppcrs)->Include(pcrsGby->PcrFirst()); *pprpp = PrppCreateRequiredProperties(mp, *ppcrs); CExpressionHandle exprhdl(mp); exprhdl.Attach(*ppexprGby); exprhdl.InitReqdProps(*pprpp); // Optimize the logical plan under default required properties, which are always satisfied. CEngine eng(mp); CAutoP<CQueryContext> pqc; pqc = CTestUtils::PqcGenerate(mp, *ppexprGby); eng.Init(pqc.Value(), nullptr /*search_stage_array*/); eng.Optimize(); *ppexprPlan = eng.PexprExtractPlan(); } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_FValidPlan // // @doc: // Test for CExpression::FValidPlan // Test now just very basic cases. More complex cases are covered by minidump tests // in CEnumeratorTest. // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_FValidPlan() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); const IMDType *pmdtype = mda.PtMDType<IMDTypeInt4>(); // Create a group-by with a get child. Properties required contain one of the columns in the group by. // Test that the plan is valid. { CExpression *pexprGby = nullptr; CColRefSet *pcrs = nullptr; CExpression *pexprPlan = nullptr; CReqdPropPlan *prpp = nullptr; SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp); CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp); // Test that prpp is actually satisfied. GPOS_ASSERT(pexprPlan->FValidPlan(prpp, pdpctxtplan)); pdpctxtplan->Release(); pexprPlan->Release(); prpp->Release(); pexprGby->Release(); } // Create a group-by with a get child. Properties required contain one column that doesn't exist. // Test that the plan is NOT valid. { CExpression *pexprGby = PexprCreateGbyWithColumnFormat(mp, GPOS_WSZ_LIT("Test Column%d")); (void) pexprGby->PdpDerive(); CColRefSet *pcrsInvalid = GPOS_NEW(mp) CColRefSet(mp); CColumnFactory *col_factory = COptCtxt::PoctxtFromTLS()->Pcf(); // Creating the column reference with the column factory ensures that it's a brand new column. CColRef *pcrComputed = col_factory->PcrCreate(pmdtype, default_type_modifier); pcrsInvalid->Include(pcrComputed); CReqdPropPlan *prpp = PrppCreateRequiredProperties(mp, pcrsInvalid); CExpressionHandle exprhdl(mp); exprhdl.Attach(pexprGby); exprhdl.InitReqdProps(prpp); // Optimize the logical plan, but under default required properties, which are always satisfied. CEngine eng(mp); CAutoP<CQueryContext> pqc; pqc = CTestUtils::PqcGenerate(mp, pexprGby); eng.Init(pqc.Value(), nullptr /*search_stage_array*/); eng.Optimize(); CExpression *pexprPlan = eng.PexprExtractPlan(); CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp); // Test that prpp is actually unsatisfied. GPOS_ASSERT(!pexprPlan->FValidPlan(prpp, pdpctxtplan)); pdpctxtplan->Release(); pexprPlan->Release(); prpp->Release(); pexprGby->Release(); } return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_FValidPlan_InvalidOrder // // @doc: // Test for CExpression::FValidPlan with incompatible order properties // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_FValidPlan_InvalidOrder() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); CExpression *pexprGby = nullptr; CColRefSet *pcrs = nullptr; CExpression *pexprPlan = nullptr; CReqdPropPlan *prpp = nullptr; SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp); CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp); // Create similar requirements, but // add an order requirement using a couple of output columns of a Get CExpression *pexprGet = CTestUtils::PexprLogicalGet(mp); CColRefSet *pcrsGet = pexprGet->DeriveOutputColumns(); CColRefSet *pcrsGetCopy = GPOS_NEW(mp) CColRefSet(mp, *pcrsGet); CColRefArray *pdrgpcrGet = pcrsGetCopy->Pdrgpcr(mp); GPOS_ASSERT(2 <= pdrgpcrGet->Size()); COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp); const IMDType *pmdtypeint4 = mda.PtMDType<IMDTypeInt4>(); IMDId *pmdidInt4LT = pmdtypeint4->GetMdidForCmpType(IMDType::EcmptL); pmdidInt4LT->AddRef(); pos->Append(pmdidInt4LT, (*pdrgpcrGet)[1], COrderSpec::EntFirst); CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy); CDistributionSpec *pds = GPOS_NEW(mp) CDistributionSpecSingleton(CDistributionSpecSingleton::EstMaster); CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec( CRewindabilitySpec::ErtNone, CRewindabilitySpec::EmhtNoMotion); CEnfdDistribution *ped = GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmExact); CEnfdRewindability *per = GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy); CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp); CReqdPropPlan *prppIncompatibleOrder = GPOS_NEW(mp) CReqdPropPlan(pcrsGetCopy, peo, ped, per, pcter); // Test that the plan is not valid. GPOS_ASSERT(!pexprPlan->FValidPlan(prppIncompatibleOrder, pdpctxtplan)); pdpctxtplan->Release(); prppIncompatibleOrder->Release(); pdrgpcrGet->Release(); prpp->Release(); pexprGet->Release(); pexprPlan->Release(); pexprGby->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_FValidPlan_InvalidDistribution // // @doc: // Test for CExpression::FValidPlan with incompatible distribution properties // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_FValidPlan_InvalidDistribution() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); CExpression *pexprGby = nullptr; CColRefSet *pcrs = nullptr; CExpression *pexprPlan = nullptr; CReqdPropPlan *prpp = nullptr; SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp); CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp); COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp); CDistributionSpec *pds = GPOS_NEW(mp) CDistributionSpecRandom(); CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec( CRewindabilitySpec::ErtNone, CRewindabilitySpec::EmhtNoMotion); CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy); CEnfdDistribution *ped = GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmExact); CEnfdRewindability *per = GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy); CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp); CColRefSet *pcrsCopy = GPOS_NEW(mp) CColRefSet(mp, *pcrs); CReqdPropPlan *prppIncompatibleDistribution = GPOS_NEW(mp) CReqdPropPlan(pcrsCopy, peo, ped, per, pcter); // Test that the plan is not valid. GPOS_ASSERT( !pexprPlan->FValidPlan(prppIncompatibleDistribution, pdpctxtplan)); pdpctxtplan->Release(); pexprPlan->Release(); prppIncompatibleDistribution->Release(); prpp->Release(); pexprGby->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_FValidPlan_InvalidRewindability // // @doc: // Test for CExpression::FValidPlan with incompatible rewindability properties // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_FValidPlan_InvalidRewindability() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); CExpression *pexprGby = nullptr; CColRefSet *pcrs = nullptr; CExpression *pexprPlan = nullptr; CReqdPropPlan *prpp = nullptr; SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp); CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp); COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp); CDistributionSpec *pds = GPOS_NEW(mp) CDistributionSpecSingleton(CDistributionSpecSingleton::EstMaster); CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec( CRewindabilitySpec::ErtRewindable, CRewindabilitySpec::EmhtNoMotion); CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy); CEnfdDistribution *ped = GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmExact); CEnfdRewindability *per = GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy); CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp); CColRefSet *pcrsCopy = GPOS_NEW(mp) CColRefSet(mp, *pcrs); CReqdPropPlan *prppIncompatibleRewindability = GPOS_NEW(mp) CReqdPropPlan(pcrsCopy, peo, ped, per, pcter); // Test that the plan is not valid. GPOS_ASSERT( !pexprPlan->FValidPlan(prppIncompatibleRewindability, pdpctxtplan)); pdpctxtplan->Release(); pexprPlan->Release(); prppIncompatibleRewindability->Release(); prpp->Release(); pexprGby->Release(); return GPOS_OK; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_FValidPlan_InvalidCTEs // // @doc: // Test for CExpression::FValidPlan with incompatible CTE properties // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_FValidPlan_InvalidCTEs() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); CExpression *pexprGby = nullptr; CColRefSet *pcrs = nullptr; CExpression *pexprPlan = nullptr; CReqdPropPlan *prpp = nullptr; SetupPlanForFValidPlanTest(mp, &pexprGby, &pcrs, &pexprPlan, &prpp); CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp); COrderSpec *pos = GPOS_NEW(mp) COrderSpec(mp); CDistributionSpec *pds = GPOS_NEW(mp) CDistributionSpecSingleton(CDistributionSpecSingleton::EstMaster); CRewindabilitySpec *prs = GPOS_NEW(mp) CRewindabilitySpec( CRewindabilitySpec::ErtNone, CRewindabilitySpec::EmhtNoMotion); CEnfdOrder *peo = GPOS_NEW(mp) CEnfdOrder(pos, CEnfdOrder::EomSatisfy); CEnfdDistribution *ped = GPOS_NEW(mp) CEnfdDistribution(pds, CEnfdDistribution::EdmExact); CEnfdRewindability *per = GPOS_NEW(mp) CEnfdRewindability(prs, CEnfdRewindability::ErmSatisfy); CCTEReq *pcter = GPOS_NEW(mp) CCTEReq(mp); ULONG ulCTEId = 0; CExpression *pexprProducer = CTestUtils::PexprLogicalCTEProducerOverSelect(mp, ulCTEId); CDrvdPropPlan *pdpplan = CDrvdPropPlan::Pdpplan(pexprPlan->PdpDerive()); pdpplan->AddRef(); pcter->Insert(ulCTEId, CCTEMap::EctProducer /*ect*/, true /*fRequired*/, pdpplan); CColRefSet *pcrsCopy = GPOS_NEW(mp) CColRefSet(mp, *pcrs); CReqdPropPlan *prppIncompatibleCTE = GPOS_NEW(mp) CReqdPropPlan(pcrsCopy, peo, ped, per, pcter); // Test that the plan is not valid. GPOS_ASSERT(!pexprPlan->FValidPlan(prppIncompatibleCTE, pdpctxtplan)); pdpctxtplan->Release(); pexprPlan->Release(); prppIncompatibleCTE->Release(); prpp->Release(); pexprGby->Release(); pexprProducer->Release(); return GPOS_OK; } #ifdef GPOS_DEBUG //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_FValidPlanError // // @doc: // Tests that CExpression::FValidPlan fails with an assert exception in debug mode // for bad input. // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_FValidPlanError() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // setup a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); // install opt context in TLS CAutoOptCtxt aoc(mp, &mda, nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); const IMDType *pmdtype = mda.PtMDType<IMDTypeInt4>(); GPOS_RESULT eres = GPOS_OK; // Test that in debug mode GPOS_ASSERT fails for non-physical expressions. { CColRefSet *pcrsInvalid = GPOS_NEW(mp) CColRefSet(mp); CColumnFactory *col_factory = COptCtxt::PoctxtFromTLS()->Pcf(); CColRef *pcrComputed = col_factory->PcrCreate(pmdtype, default_type_modifier); pcrsInvalid->Include(pcrComputed); CReqdPropPlan *prpp = PrppCreateRequiredProperties(mp, pcrsInvalid); IDatum *datum = GPOS_NEW(mp) gpnaucrates::CDatumInt8GPDB( CTestUtils::m_sysidDefault, 1 /*val*/, false /*is_null*/); CExpression *pexpr = GPOS_NEW(mp) CExpression(mp, GPOS_NEW(mp) CScalarConst(mp, datum)); CDrvdPropCtxtPlan *pdpctxtplan = GPOS_NEW(mp) CDrvdPropCtxtPlan(mp); GPOS_TRY { // FValidPlan should fail for expressions which are not physical. if (!pexpr->FValidPlan(prpp, pdpctxtplan)) { eres = GPOS_FAILED; } pdpctxtplan->Release(); } GPOS_CATCH_EX(ex) { pdpctxtplan->Release(); if (!GPOS_MATCH_EX(ex, CException::ExmaSystem, CException::ExmiAssert)) { GPOS_RETHROW(ex); } else { GPOS_RESET_EX; } } GPOS_CATCH_END; pexpr->Release(); prpp->Release(); } return eres; } #endif // GPOS_DEBUG //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresCheckCachedReqdCols // // @doc: // Helper for checking cached required columns // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresCheckCachedReqdCols(CMemoryPool *mp, CExpression *pexpr, CReqdPropPlan *prppInput) { if (pexpr->Pop()->FScalar()) { // scalar operators have no required columns return GPOS_OK; } GPOS_CHECK_STACK_SIZE; GPOS_ASSERT(nullptr != mp); GPOS_ASSERT(nullptr != prppInput); CExpressionHandle exprhdl(mp); exprhdl.Attach(pexpr); // init required properties of expression exprhdl.InitReqdProps(prppInput); // create array of child derived properties CDrvdPropArray *pdrgpdp = GPOS_NEW(mp) CDrvdPropArray(mp); GPOS_RESULT eres = GPOS_OK; const ULONG arity = pexpr->Arity(); for (ULONG ul = 0; GPOS_OK == eres && ul < arity; ul++) { CExpression *pexprChild = (*pexpr)[ul]; if (pexprChild->Pop()->FScalar()) { continue; } GPOS_ASSERT(nullptr != pexprChild->Prpp()); // extract cached required columns of the n-th child CColRefSet *pcrsChildReqd = pexprChild->Prpp()->PcrsRequired(); // compute required columns of the n-th child exprhdl.ComputeChildReqdCols(ul, pdrgpdp); // check if cached columns pointer is the same as computed columns pointer, // if this is not the case, then we have re-computed the same set of columns and test should fail if (pcrsChildReqd != exprhdl.Prpp(ul)->PcrsRequired()) { CAutoTrace at(mp); at.Os() << "\nExpression: \n" << *pexprChild; at.Os() << "\nCached cols: " << pcrsChildReqd << " : " << *pcrsChildReqd; at.Os() << "\nComputed cols: " << exprhdl.Prpp(ul)->PcrsRequired() << " : " << *exprhdl.Prpp(ul)->PcrsRequired(); eres = GPOS_FAILED; continue; } // call the function recursively for child expression GPOS_RESULT eres = EresCheckCachedReqdCols(mp, pexprChild, exprhdl.Prpp(ul)); if (GPOS_FAILED == eres) { eres = GPOS_FAILED; continue; } // add plan props of current child to derived props array CDrvdProp *pdp = pexprChild->PdpDerive(); pdp->AddRef(); pdrgpdp->Append(pdp); } pdrgpdp->Release(); return eres; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresComputeReqdCols // // @doc: // Helper for testing required column computation // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresComputeReqdCols(const CHAR *szFilePath) { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // reset metadata cache CMDCache::Reset(); // set up MD providers CMDProviderMemory *pmdp = GPOS_NEW(mp) CMDProviderMemory(mp, szFilePath); GPOS_CHECK_ABORT; GPOS_RESULT eres = GPOS_FAILED; { CAutoMDAccessor amda(mp, pmdp, CTestUtils::m_sysidDefault); CAutoOptCtxt aoc(mp, amda.Pmda(), nullptr, /* pceeval */ CTestUtils::GetCostModel(mp)); // read query expression CExpression *pexpr = CTestUtils::PexprReadQuery(mp, szFilePath); // optimize query CEngine eng(mp); CQueryContext *pqc = CTestUtils::PqcGenerate(mp, pexpr); eng.Init(pqc, nullptr /*search_stage_array*/); eng.Optimize(); // extract plan and decorate it with required columns CExpression *pexprPlan = eng.PexprExtractPlan(); // attempt computing required columns again -- // we make sure that we reuse cached required columns at each operator eres = EresCheckCachedReqdCols(mp, pexprPlan, pqc->Prpp()); pexpr->Release(); pexprPlan->Release(); GPOS_DELETE(pqc); } return eres; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_ReqdCols // // @doc: // Test for required columns computation // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_ReqdCols() { const CHAR *rgszTests[] = { "../data/dxl/tpch/q1.mdp", "../data/dxl/tpch/q3.mdp", "../data/dxl/expressiontests/WinFunc-OuterRef-Partition-Query.xml", "../data/dxl/expressiontests/WinFunc-OuterRef-Partition-Order-Query.xml", }; GPOS_RESULT eres = GPOS_OK; for (ULONG ul = 0; GPOS_OK == eres && ul < GPOS_ARRAY_SIZE(rgszTests); ul++) { const CHAR *szFilePath = rgszTests[ul]; eres = EresComputeReqdCols(szFilePath); } return eres; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::EresUnittest_InvalidSetOp // // @doc: // Test for invalid SetOp expression, // SetOp is expected to have no outer references in input columns, // when an outer reference needs to be fed to SetOp as input, we must // project it first and feed the projected column into SetOp // // For example, this is an invalid SetOp expression since it consumes // an outer reference from inner child // // +--CLogicalUnion [Output: "col0" (0)], [Input: ("col0" (0)), ("col6" (6))] // |--CLogicalGet ("T1"), Columns: ["col0" (0)] // +--CLogicalGet ("T2"), Columns: ["col3" (3)] // // // the valid expression should looks like this: // // +--CLogicalUnion [Output: "col0" (0)], [Input: ("col0" (0)), ("col7" (7))] // |--CLogicalGet ("T1"), Columns: ["col0" (0)] // +--CLogicalProject // |--CLogicalGet ("T2"), Columns: ["col3" (3)] // +--CScalarProjectList // +--CScalarProjectElement "col7" (7) // +--CScalarIdent "col6" (6) // // //--------------------------------------------------------------------------- GPOS_RESULT CExpressionTest::EresUnittest_InvalidSetOp() { CAutoMemoryPool amp; CMemoryPool *mp = amp.Pmp(); // Setup an MD cache with a file-based provider CMDProviderMemory *pmdp = CTestUtils::m_pmdpf; pmdp->AddRef(); CMDAccessor mda(mp, CMDCache::Pcache(), CTestUtils::m_sysidDefault, pmdp); { CAutoOptCtxt aoc(mp, &mda, nullptr /* pceeval */, CTestUtils::GetCostModel(mp)); // create two different Get expressions CWStringConst strName1(GPOS_WSZ_LIT("T1")); CMDIdGPDB *pmdid1 = GPOS_NEW(mp) CMDIdGPDB(GPOPT_TEST_REL_OID1, 1, 1); CTableDescriptor *ptabdesc1 = CTestUtils::PtabdescCreate(mp, 3, pmdid1, CName(&strName1)); CWStringConst strAlias1(GPOS_WSZ_LIT("T1Alias")); CExpression *pexprGet1 = CTestUtils::PexprLogicalGet(mp, ptabdesc1, &strAlias1); CColRefSet *pcrsOutput1 = pexprGet1->DeriveOutputColumns(); CWStringConst strName2(GPOS_WSZ_LIT("T2")); CMDIdGPDB *pmdid2 = GPOS_NEW(mp) CMDIdGPDB(GPOPT_TEST_REL_OID2, 1, 1); CTableDescriptor *ptabdesc2 = CTestUtils::PtabdescCreate(mp, 3, pmdid2, CName(&strName2)); CWStringConst strAlias2(GPOS_WSZ_LIT("T2Alias")); CExpression *pexprGet2 = CTestUtils::PexprLogicalGet(mp, ptabdesc2, &strAlias2); // create output columns of SetOp from output columns of first Get expression CColRefArray *pdrgpcrOutput = GPOS_NEW(mp) CColRefArray(mp); pdrgpcrOutput->Append(pcrsOutput1->PcrFirst()); // create input columns of SetOp while including an outer reference in inner child CColRef2dArray *pdrgpdrgpcrInput = GPOS_NEW(mp) CColRef2dArray(mp); CColRefArray *pdrgpcr1 = GPOS_NEW(mp) CColRefArray(mp); pdrgpcr1->Append(pcrsOutput1->PcrFirst()); pdrgpdrgpcrInput->Append(pdrgpcr1); CColRefArray *pdrgpcr2 = GPOS_NEW(mp) CColRefArray(mp); CColRef *pcrOuterRef = COptCtxt::PoctxtFromTLS()->Pcf()->PcrCreate( pcrsOutput1->PcrFirst()); pdrgpcr2->Append(pcrOuterRef); pdrgpdrgpcrInput->Append(pdrgpcr2); // create invalid SetOp expression CLogicalUnion *pop = GPOS_NEW(mp) CLogicalUnion(mp, pdrgpcrOutput, pdrgpdrgpcrInput); CExpression *pexprSetOp = GPOS_NEW(mp) CExpression(mp, pop, pexprGet1, pexprGet2); { CAutoTrace at(mp); at.Os() << "\nInvalid SetOp Expression: \n" << *pexprSetOp; } // deriving relational properties must fail (void) pexprSetOp->PdpDerive(); pexprSetOp->Release(); } return GPOS_FAILED; } //--------------------------------------------------------------------------- // @function: // CExpressionTest::PexprComplexJoinTree // // @doc: // Return an expression with several joins // //--------------------------------------------------------------------------- CExpression * CExpressionTest::PexprComplexJoinTree(CMemoryPool *mp) { // The plan will have this shape // // +--CLogicalInnerJoin // |--CLogicalUnion // | |--CLogicalLeftOuterJoin // | | |--CLogicalInnerJoin // | | | |--CLogicalGet // | | | +--CLogicalSelect // | | +--CLogicalInnerJoin // | | |--CLogicalGet // | | +--CLogicalDynamicGet // | +--CLogicalLeftOuterJoin // | |--CLogicalGet // | +--CLogicalGet // +--CLogicalInnerJoin // |--CLogicalGet // +--CLogicalSelect CExpression *pexprInnerJoin1 = CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>( mp, CTestUtils::PexprLogicalGet(mp), CTestUtils::PexprLogicalSelect(mp)); CExpression *pexprJoinIndex = CTestUtils::PexprLogicalJoinWithPartitionedAndIndexedInnerChild(mp); CExpression *pexprLeftJoin = CTestUtils::PexprLogicalJoin<CLogicalLeftOuterJoin>(mp, pexprInnerJoin1, pexprJoinIndex); CExpression *pexprOuterJoin = CTestUtils::PexprLogicalJoin<CLogicalLeftOuterJoin>(mp); CExpression *pexprInnerJoin4 = CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>(mp, pexprLeftJoin, pexprOuterJoin); CExpression *pexprInnerJoin5 = CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>( mp, CTestUtils::PexprLogicalGet(mp), CTestUtils::PexprLogicalSelect(mp)); CExpression *pexprTopJoin = CTestUtils::PexprLogicalJoin<CLogicalInnerJoin>( mp, pexprInnerJoin4, pexprInnerJoin5); return pexprTopJoin; } // EOF
32.387962
133
0.681011
[ "shape" ]
a74ddc2e5bb4f6387f122dc7d27e02479d93d977
2,828
cpp
C++
src/kademlia/dht_state.cpp
kamyu104/libtorrent-1
87ec445943324a243be2b9499b74dc0983a42af9
[ "BSL-1.0", "BSD-3-Clause" ]
9
2019-11-05T16:47:12.000Z
2022-03-05T15:21:25.000Z
src/kademlia/dht_state.cpp
kamyu104/libtorrent-1
87ec445943324a243be2b9499b74dc0983a42af9
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/kademlia/dht_state.cpp
kamyu104/libtorrent-1
87ec445943324a243be2b9499b74dc0983a42af9
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2016, 2021, Alden Torres Copyright (c) 2017, Steven Siloti Copyright (c) 2017-2021, Arvid Norberg All rights reserved. You may use, distribute and modify this code under the terms of the BSD license, see LICENSE file. */ #include "libtorrent/kademlia/dht_state.hpp" #include <libtorrent/bdecode.hpp> #include <libtorrent/aux_/socket_io.hpp> namespace libtorrent::dht { node_ids_t extract_node_ids(bdecode_node const& e, string_view key) { if (e.type() != bdecode_node::dict_t) return node_ids_t(); node_ids_t ret; // first look for an old-style nid auto const old_nid = e.dict_find_string_value(key); if (old_nid.size() == 20) { ret.emplace_back(address(), node_id(old_nid)); return ret; } auto const nids = e.dict_find_list(key); if (!nids) return ret; for (int i = 0; i < nids.list_size(); i++) { bdecode_node nid = nids.list_at(i); if (nid.type() != bdecode_node::string_t) continue; if (nid.string_length() < 20) continue; char const* in = nid.string_ptr(); node_id id(in); in += id.size(); address addr; if (nid.string_length() == 24) addr = aux::read_v4_address(in); else if (nid.string_length() == 36) addr = aux::read_v6_address(in); else continue; ret.emplace_back(addr, id); } return ret; } namespace { entry save_nodes(std::vector<udp::endpoint> const& nodes) { entry ret(entry::list_t); entry::list_type& list = ret.list(); for (auto const& ep : nodes) { std::string node; std::back_insert_iterator<std::string> out(node); aux::write_endpoint(ep, out); list.emplace_back(node); } return ret; } } // anonymous namespace void dht_state::clear() { nids.clear(); nids.shrink_to_fit(); nodes.clear(); nodes.shrink_to_fit(); nodes6.clear(); nodes6.shrink_to_fit(); } dht_state read_dht_state(bdecode_node const& e) { dht_state ret; if (e.type() != bdecode_node::dict_t) return ret; ret.nids = extract_node_ids(e, "node-id"); if (bdecode_node const nodes = e.dict_find_list("nodes")) ret.nodes = aux::read_endpoint_list<udp::endpoint>(nodes); if (bdecode_node const nodes = e.dict_find_list("nodes6")) ret.nodes6 = aux::read_endpoint_list<udp::endpoint>(nodes); return ret; } entry save_dht_state(dht_state const& state) { entry ret(entry::dictionary_t); auto& nids = ret["node-id"].list(); for (auto const& n : state.nids) { std::string nid; std::copy(n.second.begin(), n.second.end(), std::back_inserter(nid)); aux::write_address(n.first, std::back_inserter(nid)); nids.emplace_back(std::move(nid)); } entry const nodes = save_nodes(state.nodes); if (!nodes.list().empty()) ret["nodes"] = nodes; entry const nodes6 = save_nodes(state.nodes6); if (!nodes6.list().empty()) ret["nodes6"] = nodes6; return ret; } }
25.026549
80
0.674682
[ "vector" ]
a74e36c8c96650efef5ed52a2c33be4b520a7265
385
cpp
C++
samples/snippets/cpp/VS_Snippets_Remoting/Remoting_Sinks/CPP/client.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
421
2018-04-01T01:57:50.000Z
2022-03-28T15:24:42.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Remoting_Sinks/CPP/client.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
5,797
2018-04-02T21:12:23.000Z
2022-03-31T23:54:38.000Z
samples/snippets/cpp/VS_Snippets_Remoting/Remoting_Sinks/CPP/client.cpp
hamarb123/dotnet-api-docs
6aeb55784944a2f1f5e773b657791cbd73a92dd4
[ "CC-BY-4.0", "MIT" ]
1,482
2018-03-31T11:26:20.000Z
2022-03-30T22:36:45.000Z
// <snippet10> #using <remotable.dll> using namespace System; using namespace System::Runtime::Remoting; int main() { // Set up a remoting client. RemotingConfiguration::Configure( "Client.config" ); // Call a method on a remote object. Remotable ^ remoteObject = gcnew Remotable; Console::WriteLine( remoteObject->GetCount() ); } // </snippet10>
20.263158
56
0.664935
[ "object" ]
a74ecfac88a8361c6e3d75ea882dfef2a3a5e869
1,871
cpp
C++
aws-cpp-sdk-rekognition/source/model/ProjectDescription.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-rekognition/source/model/ProjectDescription.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-rekognition/source/model/ProjectDescription.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2020-11-04T03:18:11.000Z
2020-11-04T03:18:11.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/rekognition/model/ProjectDescription.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Rekognition { namespace Model { ProjectDescription::ProjectDescription() : m_projectArnHasBeenSet(false), m_creationTimestampHasBeenSet(false), m_status(ProjectStatus::NOT_SET), m_statusHasBeenSet(false) { } ProjectDescription::ProjectDescription(JsonView jsonValue) : m_projectArnHasBeenSet(false), m_creationTimestampHasBeenSet(false), m_status(ProjectStatus::NOT_SET), m_statusHasBeenSet(false) { *this = jsonValue; } ProjectDescription& ProjectDescription::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ProjectArn")) { m_projectArn = jsonValue.GetString("ProjectArn"); m_projectArnHasBeenSet = true; } if(jsonValue.ValueExists("CreationTimestamp")) { m_creationTimestamp = jsonValue.GetDouble("CreationTimestamp"); m_creationTimestampHasBeenSet = true; } if(jsonValue.ValueExists("Status")) { m_status = ProjectStatusMapper::GetProjectStatusForName(jsonValue.GetString("Status")); m_statusHasBeenSet = true; } return *this; } JsonValue ProjectDescription::Jsonize() const { JsonValue payload; if(m_projectArnHasBeenSet) { payload.WithString("ProjectArn", m_projectArn); } if(m_creationTimestampHasBeenSet) { payload.WithDouble("CreationTimestamp", m_creationTimestamp.SecondsWithMSPrecision()); } if(m_statusHasBeenSet) { payload.WithString("Status", ProjectStatusMapper::GetNameForProjectStatus(m_status)); } return payload; } } // namespace Model } // namespace Rekognition } // namespace Aws
20.788889
91
0.745056
[ "model" ]
a74fac71b2386b0883c16026944734b712550857
12,618
cpp
C++
tests/Usul/Math/Vector2.cpp
perryiv/usul
4c43ba6b00d6b8a36df76fcfaaa5243080e3adcb
[ "MIT" ]
null
null
null
tests/Usul/Math/Vector2.cpp
perryiv/usul
4c43ba6b00d6b8a36df76fcfaaa5243080e3adcb
[ "MIT" ]
null
null
null
tests/Usul/Math/Vector2.cpp
perryiv/usul
4c43ba6b00d6b8a36df76fcfaaa5243080e3adcb
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2019, Perry L Miller IV // All rights reserved. // MIT License: https://opensource.org/licenses/mit-license.html // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // Test the math functions. // //////////////////////////////////////////////////////////////////////////////// #include "Usul/Math/Functions.h" #include "Usul/Math/Vector2.h" #include "catch2/catch.hpp" #include <sstream> #include <iomanip> // Pythagorean triples. // http://mathworld.wolfram.com/PythagoreanTriple.html const unsigned int numPythagoreanTriples = 4; const unsigned char pythagoreanTriples[numPythagoreanTriples][4] = { { 3, 4, 5 }, { 5, 12, 13 }, { 8, 15, 17 }, { 7, 24, 25 } }; //////////////////////////////////////////////////////////////////////////////// // // Helper function to check the length. // //////////////////////////////////////////////////////////////////////////////// template < class ScalarType > inline void checkLength ( ScalarType v0, ScalarType v1, ScalarType len ) { typedef typename Usul::Math::Vector2 < ScalarType > VectorType; REQUIRE ( len == Usul::Math::length ( VectorType ( v0, v1 ) ) ); } //////////////////////////////////////////////////////////////////////////////// // // Helper function to check the angle between two vectors. // //////////////////////////////////////////////////////////////////////////////// template < class VectorType > inline void testAngle ( const VectorType &a, const VectorType &b, const typename VectorType::value_type &expected, unsigned int numDecimals ) { REQUIRE ( expected == Usul::Math::trunc ( Usul::Math::radToDeg ( Usul::Math::angle ( a, b ) ), numDecimals ) ); } //////////////////////////////////////////////////////////////////////////////// // // Test the math functions. // //////////////////////////////////////////////////////////////////////////////// #ifdef __GNUC__ TEMPLATE_TEST_CASE ( "Vector2 template math functions with all primitive types", "", int, long, ( unsigned int ), ( unsigned long ), float, double, ( long double ) ) #else TEMPLATE_TEST_CASE ( "Vector2 template math functions with all primitive types", "", char, short, ( unsigned char ), ( unsigned short ), int, long, ( unsigned int ), ( unsigned long ), float, double, ( long double ) ) #endif { typedef typename Usul::Math::Vector2 < TestType > VectorType; SECTION ( "Default constructor works" ) { const VectorType a; REQUIRE ( 0 == a[0] ); REQUIRE ( 0 == a[1] ); } SECTION ( "Constructor that takes 3 values works" ) { const VectorType a ( 1, 2 ); REQUIRE ( 1 == a[0] ); REQUIRE ( 2 == a[1] ); } SECTION ( "Constructor that takes an array works" ) { const VectorType a ( { 1, 2 } ); REQUIRE ( 1 == a[0] ); REQUIRE ( 2 == a[1] ); } SECTION ( "Default copy constructor works" ) { VectorType a ( 1, 2 ); const VectorType b ( a ); // Copy constructor. // Should be the same. REQUIRE ( a[0] == b[0] ); REQUIRE ( a[1] == b[1] ); // Is it different memory? a[0] = 4; // Changing one value. REQUIRE ( 4 == a[0] ); // It should be different. REQUIRE ( 1 == b[0] ); // It should be original value. } SECTION ( "Can call a function for all values" ) { unsigned int count = 0; Usul::Math::each ( VectorType ( 1, 2 ), [&] ( TestType value ) { ++count; // Need the static cast here to satisfy strict warnings. // Not making count a TestType because I want to make sure // a reliable interger type is being incremented. REQUIRE ( ( static_cast < TestType > ( count ) ) == value ); } ); REQUIRE ( VectorType::SIZE == count ); } SECTION ( "Equal vectors are equal" ) { REQUIRE ( true == Usul::Math::equal ( VectorType ( 1, 2 ), VectorType ( 1, 2 ) ) ); } SECTION ( "Different vectors are not equal" ) { VectorType a ( 1, 2 ); REQUIRE ( false == Usul::Math::equal ( a, VectorType ( 3, 2 ) ) ); REQUIRE ( false == Usul::Math::equal ( a, VectorType ( 1, 3 ) ) ); REQUIRE ( false == Usul::Math::equal ( a, VectorType ( 4, 5 ) ) ); } SECTION ( "Can scale a vector" ) { const VectorType a ( 1, 2 ); const TestType scale ( static_cast < TestType > ( 10 ) ); VectorType b; Usul::Math::scale ( a, scale, b ); REQUIRE ( 10 == b[0] ); REQUIRE ( 20 == b[1] ); const VectorType c = Usul::Math::scale ( a, scale ); REQUIRE ( 10 == c[0] ); REQUIRE ( 20 == c[1] ); } SECTION ( "Assigning is making a copy" ) { VectorType a ( 1, 2 ); VectorType b; b = a; // Assignment operator. // Should be the same. REQUIRE ( a[0] == b[0] ); REQUIRE ( a[1] == b[1] ); // Is it different memory? a[0] = 4; // Changing one value. REQUIRE ( 4 == a[0] ); // It should be different. REQUIRE ( 1 == b[0] ); // It should be original value. } SECTION ( "Setter functions work" ) { VectorType a; REQUIRE ( 0 == a[0] ); REQUIRE ( 0 == a[1] ); a.set ( VectorType ( 1, 2 ) ); REQUIRE ( 1 == a[0] ); REQUIRE ( 2 == a[1] ); a.set ( { 4, 5 } ); REQUIRE ( 4 == a[0] ); REQUIRE ( 5 == a[1] ); a.set ( 7, 8 ); REQUIRE ( 7 == a[0] ); REQUIRE ( 8 == a[1] ); } SECTION ( "Can add two vectors" ) { const VectorType a ( 1, 2 ); const VectorType b ( 4, 5 ); VectorType c; Usul::Math::add ( a, b, c ); REQUIRE ( 5 == c[0] ); REQUIRE ( 7 == c[1] ); const VectorType d = Usul::Math::add ( a, b ); REQUIRE ( 5 == d[0] ); REQUIRE ( 7 == d[1] ); const VectorType e = a + b; REQUIRE ( 5 == e[0] ); REQUIRE ( 7 == e[1] ); } SECTION ( "Can subtract two vectors" ) { const VectorType a ( 4, 5 ); const VectorType b ( 1, 2 ); VectorType c; Usul::Math::subtract ( a, b, c ); REQUIRE ( 3 == c[0] ); REQUIRE ( 3 == c[1] ); const VectorType d = Usul::Math::subtract ( a, b ); REQUIRE ( 3 == d[0] ); REQUIRE ( 3 == d[1] ); const VectorType e = a - b; REQUIRE ( 3 == e[0] ); REQUIRE ( 3 == e[1] ); } SECTION ( "Can scale a vector" ) { const VectorType a ( 1, 2 ); const TestType scale ( static_cast < TestType> ( 10 ) ); VectorType b; Usul::Math::scale ( a, scale, b ); REQUIRE ( 10 == b[0] ); REQUIRE ( 20 == b[1] ); const VectorType c = Usul::Math::scale ( a, scale ); REQUIRE ( 10 == c[0] ); REQUIRE ( 20 == c[1] ); const VectorType d = a * scale; REQUIRE ( 10 == d[0] ); REQUIRE ( 20 == d[1] ); } SECTION ( "Can get the dot product" ) { REQUIRE ( 11 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( 3, 4 ) ) ); REQUIRE ( 14 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( 4, 5 ) ) ); REQUIRE ( 17 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( 5, 6 ) ) ); } SECTION ( "Can get the distance squared between two points" ) { REQUIRE ( 8 == Usul::Math::distanceSquared ( VectorType ( 0, 0 ), VectorType ( 2, 2 ) ) ); REQUIRE ( 18 == Usul::Math::distanceSquared ( VectorType ( 0, 0 ), VectorType ( 3, 3 ) ) ); REQUIRE ( 18 == Usul::Math::distanceSquared ( VectorType ( 1, 2 ), VectorType ( 4, 5 ) ) ); REQUIRE ( 32 == Usul::Math::distanceSquared ( VectorType ( 0, 0 ), VectorType ( 4, 4 ) ) ); REQUIRE ( 50 == Usul::Math::distanceSquared ( VectorType ( 0, 0 ), VectorType ( 5, 5 ) ) ); } } //////////////////////////////////////////////////////////////////////////////// // // Test the math functions. // //////////////////////////////////////////////////////////////////////////////// #ifdef __GNUC__ TEMPLATE_TEST_CASE ( "Vector2 template math functions with signed primitive types", "", int, long, float, double, ( long double ) ) #else TEMPLATE_TEST_CASE ( "Vector2 template math functions with signed primitive types", "", short, int, long, float, double, ( long double ) ) #endif { typedef typename Usul::Math::Vector2 < TestType > VectorType; SECTION ( "Can get the absolute value of a vector" ) { const VectorType a ( 1, 2 ); const VectorType b ( -1, -2 ); REQUIRE ( false == Usul::Math::equal ( a, b ) ); REQUIRE ( true == Usul::Math::equal ( a, Usul::Math::absolute ( b ) ) ); } SECTION ( "Can get the dot product" ) { REQUIRE ( -11 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( -3, -4 ) ) ); REQUIRE ( -14 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( -4, -5 ) ) ); REQUIRE ( -17 == Usul::Math::dot ( VectorType ( 1, 2 ), VectorType ( -5, -6 ) ) ); } SECTION ( "Can get the distance squared between two points" ) { REQUIRE ( 18 == Usul::Math::distanceSquared(VectorType ( -1, -1 ), VectorType ( 2, 2 ) ) ); } } //////////////////////////////////////////////////////////////////////////////// // // Test the math functions. // //////////////////////////////////////////////////////////////////////////////// TEMPLATE_TEST_CASE ( "Vector2 template math functions with floating point types", "", float, double, ( long double ) ) { typedef typename Usul::Math::Vector2 < TestType > VectorType; SECTION ( "Can get the length" ) { checkLength < TestType > ( 3, 4, 5 ); checkLength < TestType > ( 5, 12, 13 ); checkLength < TestType > ( 8, 15, 17 ); checkLength < TestType > ( 7, 24, 25 ); } SECTION ( "Can get the length of pythagorean quadruples" ) { // Test all pythagorean quadruples. for ( unsigned int i = 0; i < numPythagoreanTriples; ++i ) { const auto q = pythagoreanTriples[i]; checkLength ( static_cast < TestType > ( q[0] ), static_cast < TestType > ( q[1] ), static_cast < TestType > ( q[2] ) ); } } SECTION ( "Can normalize" ) { // They are almost never exact so we have to convert to a string to compare. auto isUnitLength = [] ( const VectorType &v ) { const TestType len = Usul::Math::length ( v ); std::ostringstream s; s << len; REQUIRE ( "1" == s.str() ); }; // Test all pythagorean quadruples. for ( unsigned int i = 0; i < numPythagoreanTriples; ++i ) { const auto q = pythagoreanTriples[i]; const VectorType a ( static_cast < TestType > ( q[0] ), static_cast < TestType > ( q[1] ) ); const TestType len = static_cast < TestType > ( q[2] ); REQUIRE ( len == Usul::Math::length ( a ) ); // We want the original length. VectorType b; TestType originalLength = 0; Usul::Math::normalize ( a, b, &originalLength ); REQUIRE ( len == originalLength ); isUnitLength ( b ); // We do not want the original length. VectorType c; Usul::Math::normalize ( a, c ); isUnitLength ( c ); // We want a new vector. const VectorType d = Usul::Math::normalize ( a ); REQUIRE ( len == Usul::Math::length ( a ) ); isUnitLength ( d ); } } SECTION ( "Can get the distance between two points" ) { const VectorType a ( 1, 2 ); const VectorType b ( 3, 4 ); // Got the answer from here using "distance between two points": // https://www.wolframalpha.com const std::string expected ( "2.82843" ); // We need the answer with only so many decimals. std::ostringstream answer; answer << std::fixed << std::setprecision ( 5 ) << Usul::Math::distance ( a, b ); REQUIRE ( expected == answer.str() ); } } TEST_CASE ( "Angle between two vectors" ) { SECTION ( "Can get the angle between two vectors of floats" ) { typedef float TestType; typedef typename Usul::Math::Vector2 < TestType > VectorType; testAngle ( VectorType ( 5, 24 ), VectorType ( 1, 3 ), static_cast < TestType > ( 6.6666 ), 4 ); } SECTION ( "Can get the angle between two vectors of doubles" ) { typedef double TestType; typedef typename Usul::Math::Vector2 < TestType > VectorType; testAngle ( VectorType ( 5, 24 ), VectorType ( 1, 3 ), static_cast < TestType > ( 6.66665989 ), 8 ); } // SECTION ( "Can get the angle between two vectors of long doubles" ) // { // typedef long double TestType; // typedef typename Usul::Math::Vector2 < TestType > VectorType; // // // Why doesn't this one work? // testAngle ( VectorType ( 5, 24 ), VectorType ( 1, 3 ), // static_cast < TestType > ( 6.66665989 ), 8 ); // } }
28.04
113
0.520526
[ "vector" ]
a7512d3bf3cffcb100fe292e50fc7b7b23fa0aa0
1,972
cpp
C++
test/operators/test_im2sequence_op.cpp
purushothamgowthu/paddle-mobile
fb8a569e47084c3fb22b7bd002b1eea413d089ea
[ "Apache-2.0" ]
1
2018-09-06T06:45:00.000Z
2018-09-06T06:45:00.000Z
test/operators/test_im2sequence_op.cpp
purushothamgowthu/paddle-mobile
fb8a569e47084c3fb22b7bd002b1eea413d089ea
[ "Apache-2.0" ]
null
null
null
test/operators/test_im2sequence_op.cpp
purushothamgowthu/paddle-mobile
fb8a569e47084c3fb22b7bd002b1eea413d089ea
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2018 PaddlePaddle 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 "../executor_for_test.h" #include "../test_include.h" #include "operators/im2sequence_op.h" int main() { paddle_mobile::Loader<paddle_mobile::CPU> loader; auto program = loader.Load(g_ocr_recg); PADDLE_MOBILE_ENFORCE(program.originProgram != nullptr, "program file read fail"); Executor4Test<paddle_mobile::CPU, paddle_mobile::operators::ReluOp<paddle_mobile::CPU, float>> executor(program, "im2sequence"); // 1. input_tensors; vector<Tensor> input_tensors; Tensor input1; auto input1_data = CreateInput<float>(&input1, {2, 2, 3, 3}, -1, 1); input_tensors.push_back(input1); // 2. input_names vector<string> input_names({ "conv2d_19.tmp_1", }); // 3. output_names vector<string> output_names({"im2sequence_0.tmp_0"}); // 4. out_dims; vector<DDim> out_ddims; auto out_ddim = paddle_mobile::framework::make_ddim({8, 9}); out_ddims.push_back(out_ddim); auto output = executor.Predict<LoDTensor>(input_tensors, input_names, output_names, out_ddims); auto output0_data = output[0]->data<float>(); for (int j = 0; j < input_tensors[0].numel(); ++j) { DLOG << " value of input: " << input1_data[j]; } for (int j = 0; j < output[0]->numel(); ++j) { DLOG << " value of output: " << output0_data[j]; } return 0; }
31.301587
76
0.681542
[ "vector" ]
a751b20376c496f65b0ec14e2de5bcc5ac2518a5
20,527
cpp
C++
display-caf/sdm/libs/core/display_base.cpp
rahulsnair/android_device_motorola_athenecaf
52399442131dc51ea35cc6fcae1e49683b2bc60b
[ "FTL" ]
null
null
null
display-caf/sdm/libs/core/display_base.cpp
rahulsnair/android_device_motorola_athenecaf
52399442131dc51ea35cc6fcae1e49683b2bc60b
[ "FTL" ]
null
null
null
display-caf/sdm/libs/core/display_base.cpp
rahulsnair/android_device_motorola_athenecaf
52399442131dc51ea35cc6fcae1e49683b2bc60b
[ "FTL" ]
null
null
null
/* * Copyright (c) 2014 - 2015, The Linux Foundation. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of The Linux Foundation nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <utils/constants.h> #include <utils/debug.h> #include "display_base.h" #include "hw_info_interface.h" #define __CLASS__ "DisplayBase" namespace sdm { // TODO(user): Have a single structure handle carries all the interface pointers and variables. DisplayBase::DisplayBase(DisplayType display_type, DisplayEventHandler *event_handler, HWDeviceType hw_device_type, BufferSyncHandler *buffer_sync_handler, CompManager *comp_manager, RotatorInterface *rotator_intf, HWInfoInterface *hw_info_intf) : display_type_(display_type), event_handler_(event_handler), hw_device_type_(hw_device_type), buffer_sync_handler_(buffer_sync_handler), comp_manager_(comp_manager), rotator_intf_(rotator_intf), state_(kStateOff), hw_device_(0), display_comp_ctx_(0), display_attributes_(NULL), num_modes_(0), active_mode_index_(0), pending_commit_(false), vsync_enable_(false), underscan_supported_(false), max_mixer_stages_(0), hw_info_intf_(hw_info_intf), color_mgr_(NULL) { } DisplayError DisplayBase::Init() { DisplayError error = kErrorNone; hw_panel_info_ = HWPanelInfo(); hw_intf_->GetHWPanelInfo(&hw_panel_info_); error = hw_intf_->GetNumDisplayAttributes(&num_modes_); if (error != kErrorNone) { goto CleanupOnError; } display_attributes_ = new HWDisplayAttributes[num_modes_]; if (!display_attributes_) { error = kErrorMemory; goto CleanupOnError; } for (uint32_t i = 0; i < num_modes_; i++) { error = hw_intf_->GetDisplayAttributes(&display_attributes_[i], i); if (error != kErrorNone) { goto CleanupOnError; } } active_mode_index_ = GetBestConfig(); error = hw_intf_->SetDisplayAttributes(active_mode_index_); if (error != kErrorNone) { goto CleanupOnError; } error = comp_manager_->RegisterDisplay(display_type_, display_attributes_[active_mode_index_], hw_panel_info_, &display_comp_ctx_); if (error != kErrorNone) { goto CleanupOnError; } if (rotator_intf_) { error = rotator_intf_->RegisterDisplay(display_type_, &display_rotator_ctx_); if (error != kErrorNone) { goto CleanupOnError; } } if (hw_info_intf_) { HWResourceInfo hw_resource_info = HWResourceInfo(); hw_info_intf_->GetHWResourceInfo(&hw_resource_info); int max_mixer_stages = hw_resource_info.num_blending_stages; int property_value = Debug::GetMaxPipesPerMixer(display_type_); if (property_value >= 0) { max_mixer_stages = MIN(UINT32(property_value), hw_resource_info.num_blending_stages); } DisplayBase::SetMaxMixerStages(max_mixer_stages); } color_mgr_ = ColorManagerProxy::CreateColorManagerProxy(display_type_, hw_intf_, display_attributes_[active_mode_index_], hw_panel_info_); if (!color_mgr_) { DLOGW("Unable to create ColorManagerProxy for display = %d", display_type_); } return kErrorNone; CleanupOnError: if (display_comp_ctx_) { comp_manager_->UnregisterDisplay(display_comp_ctx_); } if (display_attributes_) { delete[] display_attributes_; display_attributes_ = NULL; } hw_intf_->Close(); return error; } DisplayError DisplayBase::Deinit() { if (rotator_intf_) { rotator_intf_->UnregisterDisplay(display_rotator_ctx_); } if (color_mgr_) { delete color_mgr_; color_mgr_ = NULL; } comp_manager_->UnregisterDisplay(display_comp_ctx_); if (display_attributes_) { delete[] display_attributes_; display_attributes_ = NULL; } hw_intf_->Close(); return kErrorNone; } DisplayError DisplayBase::Prepare(LayerStack *layer_stack) { DisplayError error = kErrorNone; if (!layer_stack) { return kErrorParameters; } pending_commit_ = false; if (state_ == kStateOn) { // Clean hw layers for reuse. hw_layers_.info = HWLayersInfo(); hw_layers_.info.stack = layer_stack; hw_layers_.output_compression = 1.0f; comp_manager_->PrePrepare(display_comp_ctx_, &hw_layers_); while (true) { error = comp_manager_->Prepare(display_comp_ctx_, &hw_layers_); if (error != kErrorNone) { break; } if (IsRotationRequired(&hw_layers_)) { if (!rotator_intf_) { continue; } error = rotator_intf_->Prepare(display_rotator_ctx_, &hw_layers_); } else { // Release all the previous rotator sessions. if (rotator_intf_) { error = rotator_intf_->Purge(display_rotator_ctx_, &hw_layers_); } } if (error == kErrorNone) { error = hw_intf_->Validate(&hw_layers_); if (error == kErrorNone) { // Strategy is successful now, wait for Commit(). pending_commit_ = true; break; } } } comp_manager_->PostPrepare(display_comp_ctx_, &hw_layers_); } else { return kErrorNotSupported; } return error; } DisplayError DisplayBase::Commit(LayerStack *layer_stack) { DisplayError error = kErrorNone; if (!layer_stack) { return kErrorParameters; } if (state_ != kStateOn) { return kErrorNotSupported; } if (!pending_commit_) { DLOGE("Commit: Corresponding Prepare() is not called for display = %d", display_type_); return kErrorUndefined; } pending_commit_ = false; // Layer stack attributes has changed, need to Reconfigure, currently in use for Hybrid Comp if (layer_stack->flags.attributes_changed) { error = comp_manager_->ReConfigure(display_comp_ctx_, &hw_layers_); if (error != kErrorNone) { return error; } error = hw_intf_->Validate(&hw_layers_); if (error != kErrorNone) { return error; } } if (rotator_intf_ && IsRotationRequired(&hw_layers_)) { error = rotator_intf_->Commit(display_rotator_ctx_, &hw_layers_); if (error != kErrorNone) { return error; } } // check if feature list cache is dirty and pending. // If dirty, need program to hardware blocks. if (color_mgr_) error = color_mgr_->Commit(); if (error != kErrorNone) { // won't affect this execution path. DLOGW("ColorManager::Commit(...) isn't working"); } error = hw_intf_->Commit(&hw_layers_); if (error != kErrorNone) { return error; } if (rotator_intf_ && IsRotationRequired(&hw_layers_)) { error = rotator_intf_->PostCommit(display_rotator_ctx_, &hw_layers_); if (error != kErrorNone) { return error; } } error = comp_manager_->PostCommit(display_comp_ctx_, &hw_layers_); if (error != kErrorNone) { return error; } return kErrorNone; } DisplayError DisplayBase::Flush() { DisplayError error = kErrorNone; if (state_ != kStateOn) { return kErrorNone; } hw_layers_.info.count = 0; error = hw_intf_->Flush(); if (error == kErrorNone) { comp_manager_->Purge(display_comp_ctx_); pending_commit_ = false; } else { DLOGV("Failed to flush device."); } return error; } DisplayError DisplayBase::GetDisplayState(DisplayState *state) { if (!state) { return kErrorParameters; } *state = state_; return kErrorNone; } DisplayError DisplayBase::GetNumVariableInfoConfigs(uint32_t *count) { if (!count) { return kErrorParameters; } *count = num_modes_; return kErrorNone; } DisplayError DisplayBase::GetConfig(DisplayConfigFixedInfo *fixed_info) { if (!fixed_info) { return kErrorParameters; } return kErrorNone; } DisplayError DisplayBase::GetConfig(uint32_t index, DisplayConfigVariableInfo *variable_info) { if (!variable_info || index >= num_modes_) { return kErrorParameters; } *variable_info = display_attributes_[index]; return kErrorNone; } DisplayError DisplayBase::GetActiveConfig(uint32_t *index) { if (!index) { return kErrorParameters; } *index = active_mode_index_; return kErrorNone; } DisplayError DisplayBase::GetVSyncState(bool *enabled) { if (!enabled) { return kErrorParameters; } return kErrorNone; } bool DisplayBase::IsUnderscanSupported() { return underscan_supported_; } DisplayError DisplayBase::SetDisplayState(DisplayState state) { DisplayError error = kErrorNone; DLOGI("Set state = %d, display %d", state, display_type_); if (state == state_) { DLOGI("Same state transition is requested."); return kErrorNone; } switch (state) { case kStateOff: hw_layers_.info.count = 0; error = hw_intf_->Flush(); if (error == kErrorNone) { comp_manager_->Purge(display_comp_ctx_); error = hw_intf_->PowerOff(); } break; case kStateOn: error = hw_intf_->PowerOn(); break; case kStateDoze: error = hw_intf_->Doze(); break; case kStateDozeSuspend: error = hw_intf_->DozeSuspend(); break; case kStateStandby: error = hw_intf_->Standby(); break; default: DLOGE("Spurious state = %d transition requested.", state); break; } if (error == kErrorNone) { state_ = state; } return error; } DisplayError DisplayBase::SetActiveConfig(uint32_t index) { DisplayError error = kErrorNone; if (index >= num_modes_) { return kErrorParameters; } error = hw_intf_->SetDisplayAttributes(index); if (error != kErrorNone) { return error; } active_mode_index_ = index; if (display_comp_ctx_) { comp_manager_->UnregisterDisplay(display_comp_ctx_); } error = comp_manager_->RegisterDisplay(display_type_, display_attributes_[index], hw_panel_info_, &display_comp_ctx_); return error; } DisplayError DisplayBase::SetMaxMixerStages(uint32_t max_mixer_stages) { DisplayError error = kErrorNone; if (comp_manager_) { error = comp_manager_->SetMaxMixerStages(display_comp_ctx_, max_mixer_stages); if (error == kErrorNone) { max_mixer_stages_ = max_mixer_stages; } } return error; } DisplayError DisplayBase::SetDisplayMode(uint32_t mode) { return kErrorNotSupported; } DisplayError DisplayBase::IsScalingValid(const LayerRect &crop, const LayerRect &dst, bool rotate90) { return comp_manager_->ValidateScaling(crop, dst, rotate90); } void DisplayBase::AppendDump(char *buffer, uint32_t length) { DumpImpl::AppendString(buffer, length, "\n-----------------------"); DumpImpl::AppendString(buffer, length, "\ndevice type: %u", display_type_); DumpImpl::AppendString(buffer, length, "\nstate: %u, vsync on: %u, max. mixer stages: %u", state_, INT(vsync_enable_), max_mixer_stages_); DumpImpl::AppendString(buffer, length, "\nnum configs: %u, active config index: %u", num_modes_, active_mode_index_); DisplayConfigVariableInfo &info = display_attributes_[active_mode_index_]; DumpImpl::AppendString(buffer, length, "\nres:%u x %u, dpi:%.2f x %.2f, fps:%.2f," "vsync period: %u", info.x_pixels, info.y_pixels, info.x_dpi, info.y_dpi, info.fps, info.vsync_period_ns); DumpImpl::AppendString(buffer, length, "\n"); uint32_t num_layers = 0; uint32_t num_hw_layers = 0; if (hw_layers_.info.stack) { num_layers = hw_layers_.info.stack->layer_count; num_hw_layers = hw_layers_.info.count; } if (num_hw_layers == 0) { DumpImpl::AppendString(buffer, length, "\nNo hardware layers programmed"); return; } HWLayersInfo &layer_info = hw_layers_.info; LayerRect &l_roi = layer_info.left_partial_update; LayerRect &r_roi = layer_info.right_partial_update; DumpImpl::AppendString(buffer, length, "\nROI(L T R B) : LEFT(%d %d %d %d), RIGHT(%d %d %d %d)", INT(l_roi.left), INT(l_roi.top), INT(l_roi.right), INT(l_roi.bottom), INT(r_roi.left), INT(r_roi.top), INT(r_roi.right), INT(r_roi.bottom)); const char *header = "\n| Idx | Comp Type | Split | WB | Pipe | W x H | Format | Src Rect (L T R B) | Dst Rect (L T R B) | Z | Flags | Deci(HxV) |"; //NOLINT const char *newline = "\n|-----|-------------|--------|----|-------|-------------|--------------------|---------------------|---------------------|----|------------|-----------|"; //NOLINT const char *format = "\n| %3s | %11s " "| %6s " "| %2s | 0x%03x | %4d x %4d | %18s " "| %4d %4d %4d %4d " "| %4d %4d %4d %4d " "| %2s | %10s " "| %9s |"; //NOLINT DumpImpl::AppendString(buffer, length, "\n"); DumpImpl::AppendString(buffer, length, newline); DumpImpl::AppendString(buffer, length, header); DumpImpl::AppendString(buffer, length, newline); for (uint32_t i = 0; i < num_hw_layers; i++) { uint32_t layer_index = hw_layers_.info.index[i]; Layer &layer = hw_layers_.info.stack->layers[layer_index]; LayerBuffer *input_buffer = layer.input_buffer; HWLayerConfig &layer_config = hw_layers_.config[i]; HWRotatorSession &hw_rotator_session = layer_config.hw_rotator_session; char idx[8] = { 0 }; const char *comp_type = GetName(layer.composition); const char *buffer_format = GetName(input_buffer->format); const char *rotate_split[2] = { "Rot-L", "Rot-R" }; const char *comp_split[2] = { "Comp-L", "Comp-R" }; snprintf(idx, sizeof(idx), "%d", layer_index); for (uint32_t count = 0; count < hw_rotator_session.hw_block_count; count++) { char writeback_id[8]; HWRotateInfo &rotate = hw_rotator_session.hw_rotate_info[count]; LayerRect &src_roi = rotate.src_roi; LayerRect &dst_roi = rotate.dst_roi; snprintf(writeback_id, sizeof(writeback_id), "%d", rotate.writeback_id); DumpImpl::AppendString(buffer, length, format, idx, comp_type, rotate_split[count], writeback_id, rotate.pipe_id, input_buffer->width, input_buffer->height, buffer_format, INT(src_roi.left), INT(src_roi.top), INT(src_roi.right), INT(src_roi.bottom), INT(dst_roi.left), INT(dst_roi.top), INT(dst_roi.right), INT(dst_roi.bottom), "-", "- ", "- "); // print the below only once per layer block, fill with spaces for rest. idx[0] = 0; comp_type = ""; } if (hw_rotator_session.hw_block_count > 0) { input_buffer = &hw_rotator_session.output_buffer; buffer_format = GetName(input_buffer->format); } for (uint32_t count = 0; count < 2; count++) { char decimation[16]; char flags[16]; char z_order[8]; HWPipeInfo &pipe = (count == 0) ? layer_config.left_pipe : layer_config.right_pipe; if (!pipe.valid) { continue; } LayerRect &src_roi = pipe.src_roi; LayerRect &dst_roi = pipe.dst_roi; snprintf(z_order, sizeof(z_order), "%d", pipe.z_order); snprintf(flags, sizeof(flags), "0x%08x", layer.flags.flags); snprintf(decimation, sizeof(decimation), "%3d x %3d", pipe.horizontal_decimation, pipe.vertical_decimation); DumpImpl::AppendString(buffer, length, format, idx, comp_type, comp_split[count], "-", pipe.pipe_id, input_buffer->width, input_buffer->height, buffer_format, INT(src_roi.left), INT(src_roi.top), INT(src_roi.right), INT(src_roi.bottom), INT(dst_roi.left), INT(dst_roi.top), INT(dst_roi.right), INT(dst_roi.bottom), z_order, flags, decimation); // print the below only once per layer block, fill with spaces for rest. idx[0] = 0; comp_type = ""; } DumpImpl::AppendString(buffer, length, newline); } } int DisplayBase::GetBestConfig() { return (num_modes_ == 1) ? 0 : -1; } bool DisplayBase::IsRotationRequired(HWLayers *hw_layers) { HWLayersInfo &layer_info = hw_layers->info; for (uint32_t i = 0; i < layer_info.count; i++) { Layer& layer = layer_info.stack->layers[layer_info.index[i]]; HWRotatorSession *hw_rotator_session = &hw_layers->config[i].hw_rotator_session; if (hw_rotator_session->hw_block_count) { return true; } } return false; } const char * DisplayBase::GetName(const LayerComposition &composition) { switch (composition) { case kCompositionGPU: return "GPU"; case kCompositionSDE: return "SDE"; case kCompositionHybrid: return "HYBRID"; case kCompositionBlit: return "BLIT"; case kCompositionGPUTarget: return "GPU_TARGET"; case kCompositionBlitTarget: return "BLIT_TARGET"; default: return "UNKNOWN"; } } const char * DisplayBase::GetName(const LayerBufferFormat &format) { switch (format) { case kFormatARGB8888: return "ARGB_8888"; case kFormatRGBA8888: return "RGBA_8888"; case kFormatBGRA8888: return "BGRA_8888"; case kFormatXRGB8888: return "XRGB_8888"; case kFormatRGBX8888: return "RGBX_8888"; case kFormatBGRX8888: return "BGRX_8888"; case kFormatRGBA5551: return "RGBA_5551"; case kFormatRGBA4444: return "RGBA_4444"; case kFormatRGB888: return "RGB_888"; case kFormatBGR888: return "BGR_888"; case kFormatRGB565: return "RGB_565"; case kFormatRGBA8888Ubwc: return "RGBA_8888_UBWC"; case kFormatRGBX8888Ubwc: return "RGBX_8888_UBWC"; case kFormatRGB565Ubwc: return "RGB_565_UBWC"; case kFormatYCbCr420Planar: return "Y_CB_CR_420"; case kFormatYCrCb420Planar: return "Y_CR_CB_420"; case kFormatYCbCr420SemiPlanar: return "Y_CBCR_420"; case kFormatYCrCb420SemiPlanar: return "Y_CRCB_420"; case kFormatYCbCr420SemiPlanarVenus: return "Y_CBCR_420_VENUS"; case kFormatYCbCr422H1V2SemiPlanar: return "Y_CBCR_422_H1V2"; case kFormatYCrCb422H1V2SemiPlanar: return "Y_CRCB_422_H1V2"; case kFormatYCbCr422H2V1SemiPlanar: return "Y_CBCR_422_H2V1"; case kFormatYCrCb422H2V1SemiPlanar: return "Y_CRCB_422_H2V2"; case kFormatYCbCr420SPVenusUbwc: return "Y_CBCR_420_VENUS_UBWC"; case kFormatYCbCr422H2V1Packed: return "YCBYCR_422_H2V1"; default: return "UNKNOWN"; } } DisplayError DisplayBase::ColorSVCRequestRoute(const PPDisplayAPIPayload &in_payload, PPDisplayAPIPayload *out_payload, PPPendingParams *pending_action) { if (color_mgr_) return color_mgr_->ColorSVCRequestRoute(in_payload, out_payload, pending_action); else return kErrorParameters; } DisplayError DisplayBase::ApplyDefaultDisplayMode() { if (color_mgr_) return color_mgr_->ApplyDefaultDisplayMode(); else return kErrorParameters; } } // namespace sdm
32.325984
191
0.663711
[ "3d" ]
a757c71e8ddfa4f7a1e116de4d0b62388b8a8864
17,961
cpp
C++
src/min_cg_old.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
3
2018-06-06T05:43:36.000Z
2020-07-18T14:31:37.000Z
src/min_cg_old.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
null
null
null
src/min_cg_old.cpp
sinamoeini/mapp4py
923ef57ee5bdb6231bec2885c09a58993b6c0f1f
[ "MIT" ]
7
2018-01-16T03:21:20.000Z
2020-07-20T19:36:13.000Z
#include "min_cg_old.h" #include <stdlib.h> using namespace MAPP_NS; /*-------------------------------------------- constructor --------------------------------------------*/ MinCGOld::MinCGOld(type0 __e_tol, bool(&__H_dof)[__dim__][__dim__],bool __affine,type0 __max_dx,LineSearch* __ls): Min(__e_tol,__H_dof,__affine,__max_dx,__ls), atoms(NULL), ff(NULL), xprt(NULL) { } /*-------------------------------------------- destructor --------------------------------------------*/ MinCGOld::~MinCGOld() { atoms=NULL; ff=NULL; } /*-------------------------------------------- --------------------------------------------*/ type0 MinCGOld::calc_ndofs() { return 0.0; } /*-------------------------------------------- --------------------------------------------*/ void MinCGOld::force_calc() { ff->derivative(); if(chng_box) Algebra::DoLT<__dim__>::func([this](int i,int j){f.A[i][j]=H_dof[i][j] ? f.A[i][j]:0.0;}); } /*-------------------------------------------- --------------------------------------------*/ void MinCGOld::prep() { x_d=h; if(!chng_box) return; const int natms_lcl=atoms->natms_lcl; type0* xvec=x0.vecs[0]->begin(); type0* hvec=h.vecs[0]->begin(); type0* x_dvec=x_d.vecs[0]->begin(); Algebra::MLT_mul_MLT(atoms->H,h.A,x_d.A); if(affine) { for(int iatm=0;iatm<natms_lcl;iatm++,xvec+=__dim__,x_dvec+=__dim__) Algebra::V_mul_MLT(xvec,h.A,x_dvec); } else { for(int iatm=0;iatm<natms_lcl;iatm++,xvec+=__dim__,x_dvec+=__dim__,hvec+=__dim__) Algebra::V_mul_MLT_add_in(xvec,h.A,x_dvec); } } /*-------------------------------------------- init before a run --------------------------------------------*/ void MinCGOld::init() { x.~VecTens(); new (&x) VecTens<type0,1>(atoms,chng_box,atoms->H,atoms->x); f.~VecTens(); new (&f) VecTens<type0,1>(atoms,chng_box,ff->F_H,ff->f); h.~VecTens(); new (&h) VecTens<type0,1>(atoms,chng_box,__dim__); x0.~VecTens(); new (&x0) VecTens<type0,1>(atoms,chng_box,__dim__); x_d.~VecTens(); new (&x_d) VecTens<type0,1>(atoms,chng_box,__dim__); f0.~VecTens(); new (&f0) VecTens<type0,1>(atoms,chng_box,__dim__); dynamic=new DynamicMD(atoms,ff,chng_box,{},{atoms->x_dof,h.vecs[0],x0.vecs[0],x_d.vecs[0],f0.vecs[0]},{atoms->x_d}); dynamic->init(); if(xprt) { try { xprt->atoms=atoms; xprt->init(); } catch(std::string& err_msg) { fin(); throw err_msg; } } } #ifdef POTFIT /*-------------------------------------------- init before a run --------------------------------------------*/ void MinCGOld::init(vec* ext_vec_0) { x.~VecTens(); new (&x) VecTens<type0,1>(atoms,chng_box,atoms->H,atoms->x); f.~VecTens(); new (&f) VecTens<type0,1>(atoms,chng_box,ff->F_H,ff->f); h.~VecTens(); new (&h) VecTens<type0,1>(atoms,chng_box,__dim__); x0.~VecTens(); new (&x0) VecTens<type0,1>(atoms,chng_box,__dim__); x_d.~VecTens(); new (&x_d) VecTens<type0,1>(atoms,chng_box,__dim__); f0.~VecTens(); new (&f0) VecTens<type0,1>(atoms,chng_box,__dim__); dynamic=new DynamicMD(atoms,ff,chng_box,{},{atoms->x_dof,h.vecs[0],x0.vecs[0],x_d.vecs[0],f0.vecs[0], ext_vec_0 },{atoms->x_d}); dynamic->init(); if(xprt) { try { xprt->atoms=atoms; xprt->init(); } catch(std::string& err_msg) { fin(); throw err_msg; } } } #endif /*-------------------------------------------- finishing minimization --------------------------------------------*/ void MinCGOld::fin() { if(xprt) { xprt->fin(); xprt->atoms=NULL; } dynamic->fin(); delete dynamic; dynamic=NULL; f0.~VecTens(); x_d.~VecTens(); x0.~VecTens(); h.~VecTens(); f.~VecTens(); x.~VecTens(); } /*-------------------------------------------- ff_test --------------------------------------------*/ #include "random.h" void MinCGOld::ff_test(int seed,type0 __max_dx,type0 __max_st,int __n_desc) { bool __chng_box=chng_box; chng_box=true; bool __H_dof[__dim__][__dim__]; Algebra::V_eq<__dim__*__dim__>(&H_dof[0][0],&__H_dof[0][0]); Algebra::DoLT<__dim__>::func([this](int i,int j) {H_dof[i][j]=H_dof[j][i]=true;}); x.~VecTens(); new (&x) VecTens<type0,1>(atoms,chng_box,atoms->H,atoms->x); f.~VecTens(); new (&f) VecTens<type0,1>(atoms,chng_box,ff->F_H,ff->f); h.~VecTens(); new (&h) VecTens<type0,1>(atoms,chng_box,__dim__); x0.~VecTens(); new (&x0) VecTens<type0,1>(atoms,chng_box,__dim__); x_d.~VecTens(); new (&x_d) VecTens<type0,1>(atoms,chng_box,__dim__); dynamic=new DynamicMD(atoms,ff,chng_box,{},{atoms->x_dof,h.vecs[0],x0.vecs[0],x_d.vecs[0]},{atoms->x_d}); dynamic->init(); /* creating random h*/ Random rand(seed+atoms->comm_rank); int natms_lcl=atoms->natms_lcl; type0* __h=h.vecs[0]->begin(); for(int i=0;i<__dim__*natms_lcl;i++) __h[i]=(2.0*rand.uniform()-1.0)*__max_dx; Algebra::DoLT<__dim__>::func([this,&rand,&__max_st](int i,int j) {h.A[i][j]=(2.0*rand.uniform()-1.0)*__max_st;}); x0=x; force_calc(); f_h=f*h; prep(); type0 alpha=0.0; type0 dalpha=1.0/static_cast<type0>(__n_desc); type0 u0=F(alpha); type0 du=0.0; type0 du_alpha=0.0; ThermoDynamics thermo(12,"alpha",alpha,"delta_U",du,"dU*alpha",du_alpha); thermo.init(); for(int i=0;i<__n_desc+1;i++) { du=F(alpha)-u0; du_alpha=-alpha*f_h; thermo.print(i); alpha+=dalpha; } thermo.fin(); dynamic->fin(); delete dynamic; dynamic=NULL; x_d.~VecTens(); x0.~VecTens(); h.~VecTens(); f.~VecTens(); x.~VecTens(); Algebra::V_eq<__dim__*__dim__>(&__H_dof[0][0],&H_dof[0][0]); chng_box=__chng_box; } /*-------------------------------------------- min --------------------------------------------*/ void MinCGOld::run(int nsteps) { if(dynamic_cast<LineSearchGoldenSection*>(ls)) return run(dynamic_cast<LineSearchGoldenSection*>(ls),nsteps); if(dynamic_cast<LineSearchBrent*>(ls)) return run(dynamic_cast<LineSearchBrent*>(ls),nsteps); if(dynamic_cast<LineSearchBackTrack*>(ls)) return run(dynamic_cast<LineSearchBackTrack*>(ls),nsteps); } /*-------------------------------------------- --------------------------------------------*/ type0 MinCGOld::F(type0 alpha) { x=x0+alpha*x_d; if(chng_box) atoms->update_H(); dynamic->update<true>(); return ff->value(); } /*-------------------------------------------- inner product of f and h --------------------------------------------*/ type0 MinCGOld::dF(type0 alpha,type0& drev) { x=x0+alpha*x_d; if(chng_box) atoms->update_H(); dynamic->update<true>(); force_calc(); drev=-(f*h); return atoms->pe; } /*-------------------------------------------- find maximum h lets find the next sensible number x=x_0+h*alpha (x-x0)/alpha=sqrt(eps)/alpha --------------------------------------------*/ void MinCGOld::ls_prep(type0& dfa,type0& h_norm,type0& max_a) { h_norm=h*h; dfa=-f_h; if(h_norm==0.0) { max_a=0.0; dfa=0.0; return; } if(dfa>=0.0) { max_a=0.0; dfa=1.0; return; } h_norm=sqrt(h_norm); type0 max_x_d_lcl=0.0; type0 max_x_d; type0* x_dvec=x_d.vecs[0]->begin(); const int n=atoms->natms_lcl*__dim__; for(int i=0;i<n;i++) max_x_d_lcl=MAX(max_x_d_lcl,fabs(x_dvec[i])); MPI_Allreduce(&max_x_d_lcl,&max_x_d,1,Vec<type0>::MPI_T,MPI_MAX,atoms->world); max_a=fabs(max_dx/max_x_d); } /*-------------------------------------------- reset to initial position --------------------------------------------*/ void MinCGOld::F_reset() { x=x0; if(chng_box) atoms->update_H(); dynamic->update<true>(); } /*------------------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------------------------------------------------------------------------------------------*/ PyObject* MinCGOld::__new__(PyTypeObject* type,PyObject* args,PyObject* kwds) { Object* __self=reinterpret_cast<Object*>(type->tp_alloc(type,0)); PyObject* self=reinterpret_cast<PyObject*>(__self); return self; } /*-------------------------------------------- --------------------------------------------*/ int MinCGOld::__init__(PyObject* self,PyObject* args,PyObject* kwds) { FuncAPI<type0,symm<bool[__dim__][__dim__]>,bool,type0,OP<LineSearch>> f("__init__",{"e_tol","H_dof","affine","max_dx","ls"}); f.noptionals=5; f.logics<0>()[0]=VLogics("ge",0.0); f.logics<3>()[0]=VLogics("gt",0.0); //set the defualts f.val<0>()=sqrt(std::numeric_limits<type0>::epsilon()); for(int i=0;i<__dim__;i++) for(int j=0;j<__dim__;j++)f.val<1>()[i][j]=false; f.val<2>()=false; f.val<3>()=1.0; PyObject* empty_tuple=PyTuple_New(0); PyObject* empty_dict=PyDict_New(); PyObject* __ls=LineSearchBackTrack::__new__(&LineSearchBackTrack::TypeObject,empty_tuple,empty_dict); LineSearchBackTrack::__init__(__ls,empty_tuple,empty_dict); Py_DECREF(empty_dict); Py_DECREF(empty_tuple); f.val<4>().ob=__ls; if(f(args,kwds)==-1) return -1; Object* __self=reinterpret_cast<Object*>(self); Py_INCREF(f.val<4>().ob); __self->ls=reinterpret_cast<LineSearch::Object*>(f.val<4>().ob); __self->min=new MinCGOld(f.val<0>(),f.val<1>(),f.val<2>(),f.val<3>(),&(__self->ls->ls)); __self->xprt=NULL; return 0; } /*-------------------------------------------- --------------------------------------------*/ PyObject* MinCGOld::__alloc__(PyTypeObject* type,Py_ssize_t) { Object* __self=new Object; Py_TYPE(__self)=type; Py_REFCNT(__self)=1; __self->min=NULL; __self->ls=NULL; __self->xprt=NULL; return reinterpret_cast<PyObject*>(__self); } /*-------------------------------------------- --------------------------------------------*/ void MinCGOld::__dealloc__(PyObject* self) { Object* __self=reinterpret_cast<Object*>(self); delete __self->min; __self->min=NULL; if(__self->ls) Py_DECREF(__self->ls); __self->ls=NULL; if(__self->xprt) Py_DECREF(__self->xprt); __self->xprt=NULL; delete __self; } /*--------------------------------------------*/ PyTypeObject MinCGOld::TypeObject={PyObject_HEAD_INIT(NULL)}; /*--------------------------------------------*/ int MinCGOld::setup_tp() { TypeObject.tp_name="mapp4py.md.min_cg"; TypeObject.tp_doc=R"---( __init__(e_tol=1.0e-8,H_dof=[[False],[False,False],[False,False,False]],affine=False,max_dx=1.0,ls=mapp4py.ls_bt()) CG minimization algorithm Parameters ---------- e_tol : double Energy tolerance criterion for stopping minimization H_dof : symm<bool[dim][dim]> Unitcell degrees of freedom during minimization, here dim is the dimension of simulation affine : bool If set to True atomic displacements would be affine max_dx : double Maximum displacement of any atom in one step of minimization ls : mapp4py.ls Line search method Notes ----- Cojugate Gradient (CG) algorithm for minimization, see :cite:`press_numerical_2007`. References ---------- .. bibliography:: ../refs.bib :filter: docname in docnames :style: unsrt )---"; TypeObject.tp_flags=Py_TPFLAGS_DEFAULT; TypeObject.tp_basicsize=sizeof(Object); TypeObject.tp_new=__new__; TypeObject.tp_init=__init__; TypeObject.tp_alloc=__alloc__; TypeObject.tp_dealloc=__dealloc__; setup_tp_methods(); TypeObject.tp_methods=methods; setup_tp_getset(); TypeObject.tp_getset=getset; int ichk=PyType_Ready(&TypeObject); if(ichk<0) return ichk; Py_INCREF(&TypeObject); /* this is a shitty hack since python does not have a slot for __init__, __new__, __call__, and etc. they use a wrapper_desriptor with a default doc here I change it */ GET_WRAPPER_DOC(TypeObject,__init__)=NULL; return ichk; } /*--------------------------------------------*/ PyGetSetDef MinCGOld::getset[]=EmptyPyGetSetDef(8); /*--------------------------------------------*/ void MinCGOld::setup_tp_getset() { getset_e_tol(getset[0]); getset_H_dof(getset[1]); getset_affine(getset[2]); getset_max_dx(getset[3]); getset_ls(getset[4]); getset_ntally(getset[5]); getset_export(getset[6]); } /*--------------------------------------------*/ PyMethodDef MinCGOld::methods[]=EmptyPyMethodDef(3); /*--------------------------------------------*/ void MinCGOld::setup_tp_methods() { ml_run(methods[0]); ml_ff_test(methods[1]); } /*-------------------------------------------- --------------------------------------------*/ void MinCGOld::getset_export(PyGetSetDef& getset) { getset.name=(char*)"export"; getset.doc=(char*)R"---( (mapp4py.md.export) export object Export object to record the snapshots of the system while minimizing )---"; getset.get=[](PyObject* self,void*)->PyObject* { ExportMD::Object* xprt=reinterpret_cast<Object*>(self)->xprt; if(!xprt) Py_RETURN_NONE; Py_INCREF(xprt); return reinterpret_cast<PyObject*>(xprt); }; getset.set=[](PyObject* self,PyObject* op,void*)->int { VarAPI<OP<ExportMD>> xprt("export"); int ichk=xprt.set(op); if(ichk==-1) return -1; if(reinterpret_cast<Object*>(self)->xprt) Py_DECREF(reinterpret_cast<Object*>(self)->xprt); Py_INCREF(xprt.val.ob); reinterpret_cast<Object*>(self)->xprt=reinterpret_cast<ExportMD::Object*>(xprt.val.ob); return 0; }; } /*-------------------------------------------- --------------------------------------------*/ void MinCGOld::ml_run(PyMethodDef& tp_methods) { tp_methods.ml_flags=METH_VARARGS | METH_KEYWORDS; tp_methods.ml_name="run"; tp_methods.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { Object* __self=reinterpret_cast<Object*>(self); FuncAPI<OP<AtomsMD>,int> f("run",{"atoms","max_nsteps"}); f.logics<1>()[0]=VLogics("ge",0); if(f(args,kwds)) return NULL; AtomsMD* __atoms=reinterpret_cast<AtomsMD::Object*>(f.val<0>().ob)->atoms; ForceFieldMD* __ff=reinterpret_cast<AtomsMD::Object*>(f.val<0>().ob)->ff; ExportMD* __xprt=__self->xprt==NULL ? NULL:__self->xprt->xprt; try { __self->min->pre_run_chk(__atoms,__ff); } catch(std::string& err_msg) { PyErr_SetString(PyExc_TypeError,err_msg.c_str()); return NULL; } __self->min->atoms=__atoms; __self->min->ff=__ff; __self->min->xprt=__xprt; try { __self->min->init(); } catch(std::string& err_msg) { __self->min->xprt=NULL; __self->min->ff=NULL; __self->min->atoms=NULL; PyErr_SetString(PyExc_TypeError,err_msg.c_str()); return NULL; } __self->min->run(f.val<1>()); __self->min->fin(); __self->min->xprt=NULL; __self->min->ff=NULL; __self->min->atoms=NULL; Py_RETURN_NONE; }); tp_methods.ml_doc=(char*)R"---( run(atoms,max_nsteps) Execute minimization This method starts the energy minimization for a given atoms object and maximum number of steps. Parameters ---------- atoms : mapp4py.md.atoms System of interest max_nsteps : int Maximum number of steps to achieve energy minimization Returns ------- None )---"; } /*-------------------------------------------- --------------------------------------------*/ void MinCGOld::ml_ff_test(PyMethodDef& tp_methods) { tp_methods.ml_flags=METH_VARARGS | METH_KEYWORDS; tp_methods.ml_name="ff_test"; tp_methods.ml_meth=(PyCFunction)(PyCFunctionWithKeywords)( [](PyObject* self,PyObject* args,PyObject* kwds)->PyObject* { Object* __self=reinterpret_cast<Object*>(self); FuncAPI<OP<AtomsMD>,int,type0,type0,int> f("ff_test",{"atoms","seed","max_dx","max_strain","N"}); f.logics<1>()[0]=VLogics("ge",0); f.logics<2>()[0]=VLogics("ge",0.0); f.logics<3>()[0]=VLogics("ge",0.0); f.logics<4>()[0]=VLogics("gt",0); if(f(args,kwds)) return NULL; AtomsMD* __atoms=reinterpret_cast<AtomsMD::Object*>(f.val<0>().ob)->atoms; ForceFieldMD* __ff=reinterpret_cast<AtomsMD::Object*>(f.val<0>().ob)->ff; __self->min->atoms=__atoms; __self->min->ff=__ff; __self->min->ff_test(f.val<1>(),f.val<2>(),f.val<3>(),f.val<4>()); __self->min->ff=NULL; __self->min->atoms=NULL; Py_RETURN_NONE; }); tp_methods.ml_doc=(char*)R"---( ff_test,(atoms,seed,max_dx,max_strain,N) for the purpose of testing Parameters ---------- atoms : mapp4py.md.atoms System of interest max_nsteps : int Maximum number of steps to achieve energy minimization Returns ------- None )---"; }
27.846512
135
0.517789
[ "object" ]
a758d28f54bc64053f001f75be8b15493d22181a
4,310
hpp
C++
tests/cpp/security/typedefs.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
tests/cpp/security/typedefs.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
tests/cpp/security/typedefs.hpp
vaijira/geode-native
5a46b659b86ecc4890df59c1b7abe727192e5d06
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #ifndef GEODE_SECURITY_TYPEDEFS_H_ #define GEODE_SECURITY_TYPEDEFS_H_ #include "config.h" #ifdef _LINUX _Pragma("GCC system_header") #endif #include <vector> #include <string> #include <algorithm> namespace apache { namespace geode { namespace client { namespace testframework { namespace security { typedef enum { ID_NONE = 1, ID_DUMMY = 2, ID_LDAP = 3, ID_PKI = 4, ID_NOOP = 5, ID_DUMMY2 = 6, ID_DUMMY3 = 7 } ID; typedef enum { READER_ROLE = 1, WRITER_ROLE = 2, QUERY_ROLE = 3, ADMIN_ROLE = 4, NO_ROLE = 5 } ROLES; typedef enum { OP_GET = 0, OP_CREATE = 1, OP_UPDATE = 2, OP_DESTROY = 3, OP_INVALIDATE = 4, OP_REGISTER_INTEREST = 5, OP_UNREGISTER_INTEREST = 6, OP_CONTAINS_KEY = 7, OP_KEY_SET = 8, OP_QUERY = 9, OP_REGISTER_CQ = 10, OP_REGION_CLEAR = 11, OP_REGION_CREATE = 12, OP_REGION_DESTROY = 13, OP_GETALL = 14, OP_PUTALL = 15, OP_EXECUTE_FUNCTION = 16, OP_END = 17 } OperationCode; typedef std::vector<std::string> stringList; typedef std::vector<std::string> opCodeStrs; typedef std::vector<OperationCode> opCodeList; typedef std::vector<std::string> PerClientList; typedef std::vector<std::string> readerList; typedef std::vector<std::string> writerList; typedef std::vector<std::string> adminList; typedef std::vector<std::string> queryList; const opCodeStrs::value_type opCodeStrArr[] = {"get", "create", "update", "destroy", "invalidate", "register_interest", "unregister_interest", "contains_key", "key_set", "query", "register_cq", "region_clear", "region_create", "region_destroy", "get_all", "put_all", "execute_function", "end"}; static OperationCode strToOpCode(std::string& opCodeStr) { static opCodeStrs allOpCodes( opCodeStrArr, opCodeStrArr + sizeof opCodeStrArr / sizeof *opCodeStrArr); opCodeStrs::iterator it = std::find(allOpCodes.begin(), allOpCodes.end(), opCodeStr); OperationCode retCode = OP_END; if (it != allOpCodes.end()) { retCode = static_cast<OperationCode>(it - allOpCodes.begin()); if (allOpCodes[retCode] != opCodeStr) { retCode = OP_END; } } return retCode; } /* for future use static std::string opCodeToStr(OperationCode op) { static opCodeStrs allOpCodes(opCodeStrArr, opCodeStrArr + sizeof opCodeStrArr / sizeof *opCodeStrArr); return std::string(allOpCodes[ op ]); } */ } // namespace security } // namespace testframework } // namespace client } // namespace geode } // namespace apache #endif // GEODE_SECURITY_TYPEDEFS_H_
31.231884
75
0.556613
[ "vector" ]
a75ddf4004dd18ec2d4beb610ce44dc1b6285dcc
1,518
cpp
C++
102/10229.cpp
TheLurkingCat/UVA
41327badf07ef15f7fd88e8b6adcb5835f880565
[ "MIT" ]
7
2019-02-14T12:16:26.000Z
2021-12-25T06:34:51.000Z
102/10229.cpp
TheLurkingCat/UVA
41327badf07ef15f7fd88e8b6adcb5835f880565
[ "MIT" ]
null
null
null
102/10229.cpp
TheLurkingCat/UVA
41327badf07ef15f7fd88e8b6adcb5835f880565
[ "MIT" ]
null
null
null
/* 矩陣快速冪 */ #include <iostream> #include <vector> using namespace std; int mod; class matrix { public: vector<vector<long long>> mat; matrix(vector<vector<long long>>& d) { mat = d; } matrix(int a, int b, int c, int d) { mat = vector<vector<long long>>(2, vector<long long>(2, 0)); mat[0][0] = a; mat[0][1] = b; mat[1][0] = c; mat[1][1] = d; } matrix operator*(const matrix& other) { vector<vector<long long>> temp(2, vector<long long>(2, 0)); temp[0][0] = (mat[0][0] * other.mat[0][0] % mod + mat[0][1] * other.mat[1][0] % mod) % mod; temp[0][1] = (mat[0][0] * other.mat[0][1] % mod + mat[0][1] * other.mat[1][1] % mod) % mod; temp[1][0] = (mat[1][0] * other.mat[0][0] % mod + mat[1][1] * other.mat[1][0] % mod) % mod; temp[1][1] = (mat[1][0] * other.mat[0][1] % mod + mat[1][1] * other.mat[1][1] % mod) % mod; return matrix(temp); } matrix operator^(int exp) { matrix ret(1, 0, 0, 1); while (exp) { if (exp & 1) ret = ret * *this; *this = *this * *this; exp >>= 1; } return ret; } }; int main() { cin.tie(0); ios_base::sync_with_stdio(0); int n, m; while (cin >> n >> m) { if (n == 0) cout << "0\n"; else { mod = 1 << m; cout << ((matrix(1, 1, 1, 0) ^ (n - 1)) * matrix(1, 1, 1, 1)).mat[1][1] << "\n"; } } }
26.172414
99
0.438735
[ "vector" ]
a763cd1eeb88d0ef10f90fa9b287afdd0d84236d
1,345
cpp
C++
Summer_Training_2014/H/H_perm.cpp
Zubieta/CPP
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
8
2017-03-02T07:56:45.000Z
2021-08-07T20:20:19.000Z
Summer_Training_2014/H/H_perm.cpp
zubie7a/Algorithms
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
null
null
null
Summer_Training_2014/H/H_perm.cpp
zubie7a/Algorithms
fb4a3cbf2e4edcc590df15663cd28fb9ecab679c
[ "MIT" ]
1
2021-08-07T20:20:20.000Z
2021-08-07T20:20:20.000Z
/*Santiago Zubieta*/ #include <iostream> #include <numeric> #include <fstream> #include <climits> #include <cstring> #include <cstdio> #include <cmath> #include <queue> #include <list> #include <map> #include <set> #include <stack> #include <deque> #include <vector> #include <string> #include <cstdlib> #include <cassert> #include <sstream> #include <iterator> #include <algorithm> using namespace std; int main(){ int T; // Number of test cases cin >> T; while(T--){ string s; // String to read int n; // n-th permutation to find cin >> s >> n; sort(s.begin(), s.end()); // Sort the string so all possible permutations can be found for(int k = 0; k < n; k++){ // Go up to the n-th permutation next_permutation(s.begin(), s.end()); } // THIS IS VERY EXPENSIVE IN COMPUTATIONS BECAUSE IT CALCULATES EVERY // LEXICOGRAPHICALLY INCREASING PERMUTATION OF THE ORIGINAL STRING UP // TO THE DESIRED TARGED PERMUTATION, WHICH COULD BE 20! PERMUTATIONS // LATER! For that check out H_newperm.cpp, which lays out how to more // or less in much more less computations calculate the target permut- // tation directly, without going over all its previous ones. cout << s << endl; } }
27.44898
78
0.623792
[ "vector" ]
a767d87992704419a422c6c372e0065296268388
4,652
hpp
C++
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/convex_shape__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/convex_shape__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
null
null
null
Versionen/2021_06_15/rmf_ws/install/rmf_traffic_msgs/include/rmf_traffic_msgs/msg/detail/convex_shape__struct.hpp
flitzmo-hso/flitzmo_agv_control_system
99e8006920c03afbd93e4c7d38b4efff514c7069
[ "MIT" ]
2
2021-06-21T07:32:09.000Z
2021-08-17T03:05:38.000Z
// generated from rosidl_generator_cpp/resource/idl__struct.hpp.em // with input from rmf_traffic_msgs:msg/ConvexShape.idl // generated code does not contain a copyright notice #ifndef RMF_TRAFFIC_MSGS__MSG__DETAIL__CONVEX_SHAPE__STRUCT_HPP_ #define RMF_TRAFFIC_MSGS__MSG__DETAIL__CONVEX_SHAPE__STRUCT_HPP_ #include <rosidl_runtime_cpp/bounded_vector.hpp> #include <rosidl_runtime_cpp/message_initialization.hpp> #include <algorithm> #include <array> #include <memory> #include <string> #include <vector> #ifndef _WIN32 # define DEPRECATED__rmf_traffic_msgs__msg__ConvexShape __attribute__((deprecated)) #else # define DEPRECATED__rmf_traffic_msgs__msg__ConvexShape __declspec(deprecated) #endif namespace rmf_traffic_msgs { namespace msg { // message struct template<class ContainerAllocator> struct ConvexShape_ { using Type = ConvexShape_<ContainerAllocator>; explicit ConvexShape_(rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) { if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->type = 0; this->index = 0; } } explicit ConvexShape_(const ContainerAllocator & _alloc, rosidl_runtime_cpp::MessageInitialization _init = rosidl_runtime_cpp::MessageInitialization::ALL) { (void)_alloc; if (rosidl_runtime_cpp::MessageInitialization::ALL == _init || rosidl_runtime_cpp::MessageInitialization::ZERO == _init) { this->type = 0; this->index = 0; } } // field types and members using _type_type = uint8_t; _type_type type; using _index_type = uint8_t; _index_type index; // setters for named parameter idiom Type & set__type( const uint8_t & _arg) { this->type = _arg; return *this; } Type & set__index( const uint8_t & _arg) { this->index = _arg; return *this; } // constant declarations static constexpr uint8_t NONE = 0u; static constexpr uint8_t BOX = 1u; static constexpr uint8_t CIRCLE = 2u; // pointer types using RawPtr = rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> *; using ConstRawPtr = const rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> *; using SharedPtr = std::shared_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>; using ConstSharedPtr = std::shared_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> const>; template<typename Deleter = std::default_delete< rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>> using UniquePtrWithDeleter = std::unique_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>, Deleter>; using UniquePtr = UniquePtrWithDeleter<>; template<typename Deleter = std::default_delete< rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>> using ConstUniquePtrWithDeleter = std::unique_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> const, Deleter>; using ConstUniquePtr = ConstUniquePtrWithDeleter<>; using WeakPtr = std::weak_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>>; using ConstWeakPtr = std::weak_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> const>; // pointer types similar to ROS 1, use SharedPtr / ConstSharedPtr instead // NOTE: Can't use 'using' here because GNU C++ can't parse attributes properly typedef DEPRECATED__rmf_traffic_msgs__msg__ConvexShape std::shared_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator>> Ptr; typedef DEPRECATED__rmf_traffic_msgs__msg__ConvexShape std::shared_ptr<rmf_traffic_msgs::msg::ConvexShape_<ContainerAllocator> const> ConstPtr; // comparison operators bool operator==(const ConvexShape_ & other) const { if (this->type != other.type) { return false; } if (this->index != other.index) { return false; } return true; } bool operator!=(const ConvexShape_ & other) const { return !this->operator==(other); } }; // struct ConvexShape_ // alias to use template instance with default allocator using ConvexShape = rmf_traffic_msgs::msg::ConvexShape_<std::allocator<void>>; // constant definitions template<typename ContainerAllocator> constexpr uint8_t ConvexShape_<ContainerAllocator>::NONE; template<typename ContainerAllocator> constexpr uint8_t ConvexShape_<ContainerAllocator>::BOX; template<typename ContainerAllocator> constexpr uint8_t ConvexShape_<ContainerAllocator>::CIRCLE; } // namespace msg } // namespace rmf_traffic_msgs #endif // RMF_TRAFFIC_MSGS__MSG__DETAIL__CONVEX_SHAPE__STRUCT_HPP_
29.630573
156
0.755374
[ "vector" ]
a76c253b6aabea3f2f62a4774fd18b3ee7b3eaf0
20,356
hxx
C++
include/lineage/heuristics/greedy-lineage.hxx
rempfler/efficient-mlt
653be91ae707ab9c766ed0c08c512b30c61c51ab
[ "MIT" ]
3
2018-02-19T18:42:24.000Z
2020-04-20T03:09:02.000Z
include/lineage/heuristics/greedy-lineage.hxx
rempfler/efficient-mlt
653be91ae707ab9c766ed0c08c512b30c61c51ab
[ "MIT" ]
null
null
null
include/lineage/heuristics/greedy-lineage.hxx
rempfler/efficient-mlt
653be91ae707ab9c766ed0c08c512b30c61c51ab
[ "MIT" ]
1
2020-05-23T17:26:09.000Z
2020-05-23T17:26:09.000Z
#pragma once #ifndef LINEAGE_HEURISTICS_GREEDY_LINEAGE_HXX #define LINEAGE_HEURISTICS_GREEDY_LINEAGE_HXX #include <algorithm> #include <cmath> #include <fstream> #include <iostream> #include <limits> #include <map> #include <numeric> #include <queue> #include <random> #include <sstream> #include <stack> #include <utility> #include <vector> #include <andres/partition.hxx> #include <levinkov/timer.hxx> #include "heuristic-base.hxx" #include "lineage/evaluate.hxx" #include "lineage/problem-graph.hxx" #include "lineage/solution.hxx" namespace lineage { namespace heuristics { template <class EVA = std::vector<double>> class DynamicLineage { /// Class adapted from /// andres::graph::multicut::greedyAdditiveEdgeContraction public: DynamicLineage(Data& data) : data_(data) , vertices_(data.problemGraph.graph().numberOfVertices()) , partition_(vertices_.size()) , parents_(vertices_.size()) , children_(vertices_.size(), 0) , sizes_(vertices_.size(), 1) { setup(); } struct EdgeOperation { EdgeOperation(size_t _v0, size_t _v1, typename EVA::value_type _delta, size_t _edition = 0) { v0 = _v0; v1 = _v1; delta = _delta; edition = _edition; } size_t v0, v1; size_t edition; typename EVA::value_type delta; inline bool operator<(const EdgeOperation& other) const { return delta > other.delta; // inversed operation due to default-max order // in queue. } }; inline void setup() { const auto& graph = data_.problemGraph.graph(); const auto& costs = data_.costs; std::iota(parents_.begin(), parents_.end(), 0); for (size_t edge = 0; edge < graph.numberOfEdges(); ++edge) { const auto& v0 = graph.vertexOfEdge(edge, 0); const auto& v1 = graph.vertexOfEdge(edge, 1); updateEdgeWeight(v0, v1, costs[edge]); } objective_ = evaluate(data_, getSolution()); } template <class T> inline void initializeFromSolution(T&& edge_labels) { for (size_t edge = 0; edge < data_.problemGraph.graph().numberOfEdges(); ++edge) { const auto v0 = data_.problemGraph.graph().vertexOfEdge(edge, 0); const auto v1 = data_.problemGraph.graph().vertexOfEdge(edge, 1); if (edge_labels[edge] == 0) { applyMove({ v0, v1, 0, 0 }); } } } // takes over partition and tree from other. template <class T> inline void resetTo(const T& other) { this->vertices_ = other.vertices_; this->partition_ = other.partition_; this->children_ = other.children_; this->parents_ = other.parents_; this->sizes_ = other.sizes_; this->objective_ = other.objective_; } inline bool edgeExists(size_t a, size_t b) const { return !vertices_[a].empty() && vertices_[a].find(b) != vertices_[a].end(); } inline std::map<size_t, typename EVA::value_type> const& getAdjacentVertices(size_t v) const { return vertices_[v]; } inline typename EVA::value_type getEdgeWeight(size_t a, size_t b) const { return vertices_[a].at(b); } inline void removeVertex(size_t v) { for (auto& p : vertices_[v]) vertices_[p.first].erase(v); vertices_[v].clear(); } inline void updateEdgeWeight(size_t a, size_t b, typename EVA::value_type w) { vertices_[a][b] += w; vertices_[b][a] += w; } inline void setParent(size_t child, size_t parent) { if (!edgeExists(child, parent)) { throw std::runtime_error("Cannot set parent to non-adjacent node!"); } if (hasParent(child).first && hasParent(child).second != parent) { removeChild(hasParent(child).second); } parents_[findRep(child)] = findRep(parent); addChild(parent); } inline size_t findParent(size_t v) { auto rep = findRep(v); auto parent = findRep(parents_[rep]); if (parents_[rep] != parent) { // update lookup. parents_[rep] = parent; } if (parent == rep) { return v; } else { return parent; } } inline std::pair<bool, size_t> hasParent(size_t v) { auto parent = findParent(v); bool found = (parent != v) ? true : false; return std::make_pair(found, parent); } inline size_t children(size_t v) { auto rep = findRep(v); return children_[rep]; } inline bool hasChild(size_t v) { return children(v) > 0; } inline void addChild(size_t v) { auto rep = findRep(v); ++children_[rep]; if (this->data_.enforceBifurcationConstraint && children_[rep] > 2) throw std::runtime_error("has more than two children!"); } inline void removeChild(size_t v) { auto rep = findRep(v); if (children_[rep] == 0) { throw std::runtime_error("Has no children to remove!"); } --children_[rep]; } inline size_t findRep(size_t v) { return partition_.find(v); } inline void merge(const size_t v0, const size_t v1) { size_t stable_vertex = v0; size_t merge_vertex = v1; // merges are only allowed in-plane! if (getFrameOfNode(stable_vertex) != getFrameOfNode(merge_vertex)) { throw std::runtime_error( "Not allowed to merge nodes across frames!"); } if (getAdjacentVertices(stable_vertex).size() < getAdjacentVertices(merge_vertex).size()) { std::swap(stable_vertex, merge_vertex); } // if stable_vertex doesnt have a parent but merge_vertex does, // then we need to set it as stable_vertex's parent. { auto stable_parent = hasParent(stable_vertex); auto merge_parent = hasParent(merge_vertex); if (!stable_parent.first && merge_parent.first) { parents_[findRep(stable_vertex)] = merge_parent.second; } if (stable_parent.first && merge_parent.first) { // check if parent loses a child through the merge. if (stable_parent.second == merge_parent.second) { removeChild(stable_parent.second); } else { throw std::runtime_error( "Nodes with different parents cannot be merged!"); } } } // keep previous config (since the representative of the partition may // change). auto numberOfChildren = children(stable_vertex) + children(merge_vertex); auto hadParentBefore = hasParent(stable_vertex); auto newSize = sizes_[stable_vertex] + sizes_[merge_vertex]; partition_.merge(stable_vertex, merge_vertex); // keep the edge indices consistent to representatives! if (findRep(stable_vertex) == merge_vertex) { std::swap(stable_vertex, merge_vertex); } #ifdef DEBUG if (stable_vertex != findRep(stable_vertex) and merge_vertex != findRep(stable_vertex)) { throw std::runtime_error("Assumption violated!"); } #endif // update all edges. for (const auto& p : getAdjacentVertices(merge_vertex)) { const auto& other_vertex = p.first; if (other_vertex == stable_vertex) { continue; } updateEdgeWeight(stable_vertex, other_vertex, p.second); } removeVertex(merge_vertex); // apply previous settings. { sizes_[stable_vertex] = newSize; children_[stable_vertex] = numberOfChildren; if (hadParentBefore.first && hadParentBefore.second != findParent(stable_vertex)) { // dont use setParent to avoid increasing the children_ counter. parents_[stable_vertex] = hadParentBefore.second; } } } size_t sizeOf(size_t v0) { return sizes_[findRep(v0)]; } inline EdgeOperation proposeMove(const size_t v0, const size_t v1) { // increaseEdition(v0, v1); // invalidate old moves along (v0, v1) if (!edgeExists(v0, v1)) { throw std::runtime_error( "Cannot propose move for an edge that does not exist!"); } // first part of cost change through merge / setParent. auto delta = -getEdgeWeight(v0, v1); // potential merge. if (getFrameOfNode(v0) == getFrameOfNode(v1)) { const auto& p0 = hasParent(v0); const auto& p1 = hasParent(v1); // Cases that can be merged: if (p0.first xor p1.first) { // one with parents. if (getFrameOfNode(v0) != 0) { const size_t partitionSize = p0.first ? sizeOf(v1) : sizeOf(v0); delta -= data_.costBirth * partitionSize; } } else if (!p0.first && !p1.first) { // no parents. ; } else if (p0.first && p1.first && p0.second == p1.second) { // same parents. ; } else { // the rest cant. return { v0, v1, std::numeric_limits<typename EVA::value_type>::infinity(), 0 }; } // cost adjustments for all nodes that have either first // or second as a parent and share connections to the other. for (const auto& other : getAdjacentVertices(v1)) { const auto& v2 = other.first; const auto& p2 = hasParent(v2); if (edgeExists(v0, v2)) { // is v2 a parent to v0 and not v1? // (or vice versa) if (p0.second == findRep(v2) and p1.second != findRep(v2)) { delta -= getEdgeWeight(v1, v2); } else if (p1.second == findRep(v2) and p0.second != findRep(v2)) { delta -= getEdgeWeight(v0, v2); } else { // is either v0 or v1 a parent of v2? if (p2.first) { if (p2.second == findRep(v0)) { // v0 is parent to v2 delta -= getEdgeWeight(v1, v2); } else if (p2.second == findRep(v1)) { // v1 is parent to v2 delta -= getEdgeWeight(v0, v2); } } } } } // if one has no child, we gain a termination cost. if (!hasChild(v0) xor !hasChild(v1)) { if (getFrameOfNode(v0) != data_.problemGraph.numberOfFrames() - 1) { const size_t partitionSize = hasChild(v0) ? sizeOf(v1) : sizeOf(v0); delta -= data_.costTermination * partitionSize; } } else if (this->data_.enforceBifurcationConstraint && children(v0) + children(v1) >= 3) { delta = std::numeric_limits<typename EVA::value_type>::infinity(); } return { v0, v1, delta, 0 }; // Potential new parent. } else { size_t child = v0; size_t parent = v1; if (getFrameOfNode(child) < getFrameOfNode(parent)) { std::swap(child, parent); } // If bifurcation constraint is active: // dont allow more than two children! if (this->data_.enforceBifurcationConstraint) { if (children(parent) >= 2) { return { v0, v1, std::numeric_limits< typename EVA::value_type>::infinity(), 0 }; } } // is it a re-set? { auto parentOfChild = hasParent(child); if (parentOfChild.first) { if (parentOfChild.second == parent) { return { child, parent, std::numeric_limits< typename EVA::value_type>::infinity(), 0 }; } else { if (!edgeExists(child, parentOfChild.second)) { throw std::runtime_error( "Cannot have a parent with no connection!"); } delta += getEdgeWeight(child, parentOfChild.second); // would the current parent form a terminal? if (children(parentOfChild.second) == 1) { delta += sizeOf(parentOfChild.second) * data_.costTermination; } } // could we save birth costs? } else if (getFrameOfNode(child) != 0) { delta -= data_.costBirth * sizeOf(child); } } if (!hasChild(parent) and getFrameOfNode(parent) != data_.problemGraph.numberOfFrames() - 1) { delta -= data_.costTermination * sizeOf(parent); } return { v0, v1, delta, 0 }; } } inline void applyMove(const EdgeOperation move) { const auto frame0 = this->getFrameOfNode(move.v0); const auto frame1 = this->getFrameOfNode(move.v1); if (frame0 == frame1) { this->merge(move.v0, move.v1); } else { if (frame0 == frame1 - 1) { this->setParent(move.v1, move.v0); } else if (frame0 == frame1 + 1) { this->setParent(move.v0, move.v1); } } this->objective_ += move.delta; } inline size_t getFrameOfNode(const size_t vertex) { return data_.problemGraph.frameOfNode(vertex); } inline void logObj() { data_.timer.stop(); std::stringstream stream; stream << data_.timer.get_elapsed_seconds() << " " << "inf" // bound << " " << objective_ << " " << "nan" // gap << " 0 0 0" // violated constraints; << " 0 0 0" // termination/birth/bifuraction constr. << " 0 0\n"; { std::ofstream file(data_.solutionName + "-optimization-log.txt", std::ofstream::out | std::ofstream::app); file << stream.str(); file.close(); } data_.timer.start(); } inline lineage::Solution getSolution() { const auto& graph = data_.problemGraph.graph(); Solution solution; solution.edge_labels.resize(graph.numberOfEdges(), 1); for (size_t edge = 0; edge < graph.numberOfEdges(); ++edge) { const auto& v0 = graph.vertexOfEdge(edge, 0); const auto& v1 = graph.vertexOfEdge(edge, 1); const auto& frame0 = data_.problemGraph.frameOfNode(v0); const auto& frame1 = data_.problemGraph.frameOfNode(v1); if (frame0 == frame1) { if (findRep(v0) == findRep(v1)) { solution.edge_labels[edge] = 0; } } else if (frame0 == frame1 - 1) { // v0 could be parent to v1 if (findRep(v0) == findParent(v1)) { solution.edge_labels[edge] = 0; } } else if (frame0 == frame1 + 1) { // v1 could be parent to v0 if (findParent(v0) == findRep(v1)) { solution.edge_labels[edge] = 0; } } else { throw std::runtime_error( "Edge spanning over more than two frames found!"); } } return solution; } inline typename EVA::value_type getObjective() const { return objective_; } protected: using Partition = andres::Partition<size_t>; Data& data_; std::vector<std::map<size_t, typename EVA::value_type>> vertices_; Partition partition_; std::vector<size_t> parents_; std::vector<size_t> children_; std::vector<size_t> sizes_; typename EVA::value_type objective_{ .0 }; }; template <class EVA = std::vector<double>> class GreedyLineageAgglomeration : public DynamicLineage<EVA> { public: GreedyLineageAgglomeration(Data& data) : DynamicLineage<EVA>(data) , editions_(data.problemGraph.graph().numberOfVertices()) { } // dummy function to be compatible with standard interface. void setMaxIter(const size_t maxIter) { ; } inline void increaseEdition(const size_t v0, const size_t v1) { if (!this->edgeExists(v0, v1)) { throw std::runtime_error( "Cannot increase edition of an edge that does not exist!"); } if (v0 > v1) { ++editions_[v1][v0]; } else { ++editions_[v0][v1]; } } inline size_t getEdition(const size_t v0, const size_t v1) { if (v0 > v1) { return editions_[v1][v0]; } else { return editions_[v0][v1]; } } inline void proposeMove(const size_t v0, const size_t v1) { increaseEdition(v0, v1); // invalidate old moves along (v0, v1) auto move = DynamicLineage<EVA>::proposeMove(v0, v1); if (move.delta <= .0) { move.edition = getEdition(move.v0, move.v1); queue_.push(move); } } inline bool virtual applyBestOperationAndUpdate() { while (!queue_.empty()) { const auto move = queue_.top(); queue_.pop(); if (move.delta >= 0) { return false; } else if (!this->edgeExists(move.v0, move.v1)) { continue; } else if (move.edition != getEdition(move.v0, move.v1)) { continue; } this->applyMove(move); std::vector<size_t> neighbours; for (auto v : { move.v0, move.v1 }) { for (auto w : this->vertices_[v]) { neighbours.push_back(w.first); } } for (auto v : neighbours) { for (auto w : this->vertices_[v]) { proposeMove(v, w.first); } } return true; } return false; } inline void virtual optimize() { // initial queue of operations. for (size_t v0 = 0; v0 < this->vertices_.size(); ++v0) { for (const auto& other : this->vertices_[v0]) { const auto v1 = other.first; proposeMove(v0, v1); } } size_t iter = 0; while (applyBestOperationAndUpdate()) { if (not silent_) this->logObj(); ++iter; } if (not silent_) { this->data_.timer.stop(); std::cout << "[GLA] Stopping after " << iter << " moves in " << this->data_.timer.get_elapsed_seconds() << "s. Obj=" << this->objective_ << std::endl; this->data_.timer.start(); } } inline void setSilent(const bool flag) { silent_ = flag; } protected: std::priority_queue<typename DynamicLineage<EVA>::EdgeOperation> queue_; std::vector<std::map<size_t, size_t>> editions_; bool silent_{ false }; }; } // namespace heuristics } // namespace lineage #endif
31.077863
80
0.514197
[ "vector" ]
a76c5ee55ead6a92fce1223123e5db2910bab080
1,151
cpp
C++
HackerRank Solutions/Algorithms/Arrays And Sorting/Running Time of Quicksort.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
13
2021-09-02T07:30:02.000Z
2022-03-22T19:32:03.000Z
HackerRank Solutions/Algorithms/Arrays And Sorting/Running Time of Quicksort.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
null
null
null
HackerRank Solutions/Algorithms/Arrays And Sorting/Running Time of Quicksort.cpp
UtkarshPathrabe/Competitive-Coding
ba322fbb1b88682d56a9b80bdd92a853f1caa84e
[ "MIT" ]
3
2021-08-24T16:06:22.000Z
2021-09-17T15:39:53.000Z
#include <bits/stdc++.h> using namespace std; int shiftI = 0, shiftQ = 0; void Swap (int * a, int * b) { int temp = *a; *a = *b; *b = temp; } int Partition (vector<int> &Arr, int start, int end) { int i, j, p = Arr[end]; for (i = start - 1, j = start; j < end; j++) { if (Arr[j] < p) { i += 1; Swap(&Arr[i], &Arr[j]); shiftQ += 1; } } Swap (&Arr[i + 1], &Arr[end]); shiftQ += 1; return (i + 1); } void QuickSort (vector<int> &Arr, int start, int end) { if (start < end) { int pivot = Partition (Arr, start, end); QuickSort (Arr, start, pivot - 1); QuickSort (Arr, pivot + 1, end); } } void InsertionSort (vector<int> &Arr) { int len = Arr.size(); for (int i = 1; i < len; i++) { int Val = Arr[i], j = i - 1; while ((j >= 0) && (Arr[j] > Val)) { Arr[j + 1] = Arr[j]; j -= 1; shiftI += 1; } Arr[j + 1] = Val; } } int main (void) { vector <int> Arr1, Arr2; int Size; cin >> Size; for (int i = 0; i < Size; i++) { int temp; cin >> temp; Arr1.push_back(temp); Arr2.push_back(temp); } InsertionSort (Arr1); QuickSort (Arr2, 0, Size - 1); cout << shiftI - shiftQ << endl; return 0; }
18.269841
55
0.526499
[ "vector" ]
a76de7e55f3d8b3d0b3aac49671853fd3af954d4
731
cpp
C++
basic/dp/iterator/aggregate.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
basic/dp/iterator/aggregate.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
basic/dp/iterator/aggregate.cpp
Marveliu/learn-cpp
e1f121fb1d5d7decc5712817a3f4751f43fea1b8
[ "Apache-2.0" ]
null
null
null
//aggregate.cpp #include <iostream> #include "aggregate.h" #include "iterator.h" using namespace std; Aggregate::Aggregate() //定义抽象聚合类型的构造函数 { } Aggregate::~Aggregate() //定义抽象聚合类型的析构函数 { } ConcreteAggregate::ConcreteAggregate() //定义具体聚合类型的构造函数 { //向聚合类型中填充具体数据,数量为SIZE(5)个,保存在int类型的数组中 for (int i = 0; i < SIZE; i++) m_objs[i] = i; } ConcreteAggregate::~ConcreteAggregate() //定义具体聚合类型的析构函数 { } //定义生成迭代器的函数 Iterator *ConcreteAggregate::create_iterator() { return new ConcreteIterator(this); } //定义从聚合类型中获取具体元素的函数 Object ConcreteAggregate::get_item(int idx) { if (idx < this->get_size()) return m_objs[idx]; return -1; } int ConcreteAggregate::get_size() //定义获取聚合中有效数据个数的函数 { return SIZE; }
19.236842
55
0.703146
[ "object" ]
a76e78758fe56e20d82c6013adf80a3f2df67d59
1,095
cpp
C++
Database/main.cpp
Bestfast/Generatore_schede
008a1a8baf4ee34fc3655b352a3f5f6cd3c13517
[ "MIT" ]
2
2017-10-27T00:50:56.000Z
2018-02-12T08:10:59.000Z
Database/main.cpp
Bestfast/Generatore_schede
008a1a8baf4ee34fc3655b352a3f5f6cd3c13517
[ "MIT" ]
5
2017-10-16T14:53:04.000Z
2018-03-13T10:02:02.000Z
Database/main.cpp
Bestfast/Generatore_schede
008a1a8baf4ee34fc3655b352a3f5f6cd3c13517
[ "MIT" ]
1
2017-11-18T17:33:36.000Z
2017-11-18T17:33:36.000Z
#include "Database.h" #include <iostream> Database::Database(char const *filename) { database = NULL; open(filename); } Database::~Database() { } bool Database::open(char const *filename) { if(sqlite3_open(filename, &database) == SQLITE_OK) return true; return false; } vector<vector<string> > Database::query(char const *query) { sqlite3_stmt *statement; vector<vector<string> > results; if(sqlite3_prepare_v2(database, query, -1, &statement, 0) == SQLITE_OK) { int cols = sqlite3_column_count(statement); int result = 0; while(true) { result = sqlite3_step(statement); if(result == SQLITE_ROW) { vector<string> values; for(int col = 0; col < cols; col++) { values.push_back((char const *)sqlite3_column_text(statement, col)); } results.push_back(values); } else { break; } } sqlite3_finalize(statement); } string error = sqlite3_errmsg(database); if(error != "not an error") cout << query << " " << error << endl; return results; } void Database::close() { sqlite3_close(database); }
17.66129
73
0.647489
[ "vector" ]
a7721523001eb951d23be6e5aee22eee8c3c81eb
1,602
cpp
C++
paradigms/binary_search/154_find-minimum-in-rotated-sorted-array-ii.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
paradigms/binary_search/154_find-minimum-in-rotated-sorted-array-ii.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
paradigms/binary_search/154_find-minimum-in-rotated-sorted-array-ii.cpp
b1tank/leetcode
0b71eb7a4f52291ff072b1280d6b76e68f7adfee
[ "MIT" ]
null
null
null
// Author: b1tank // Email: b1tank@outlook.com //================================= /* 154_find-minimum-in-rotated-sorted-array-ii LeetCode Solution: - l + (r - l) / 2 ---- to avoid int overflow !!! - be careful with different left and right boundary change patterns - move less aggressively with the right pointer to tackle duplicates */ #include <iostream> #include <vector> #include <string> using namespace std; class Solution { public: int findMin(vector<int>& nums) { // int s = nums.size(); // int l = 0; // int r = s - 1; // while (l < r) { // int mid = l + (r - l) / 2; // if (nums[mid] < nums[r] || nums[mid] < nums[l] || (nums[mid] == nums[r] && nums[mid] > nums[l])) { // r = mid; // } else if (nums[mid] > nums[r] || nums[mid] > nums[l]) { // l = mid + 1; // } else { // r--; // l++; // } // } // return nums[l]; int s = nums.size(); int l = 0; int r = s - 1; while (l < r) { int mid = l + (r - l) / 2; if (nums[mid] < nums[r]) { r = mid; } else if (nums[mid] > nums[r]) { l = mid + 1; } else { r--; // move less aggressively just the right pointer; move left pointer will fail with the case [1, 2, 2] by missing the lowest int on the left } } return nums[l]; } };
29.127273
161
0.418227
[ "vector" ]
a772267242599ed609f05b2d28ad49056e91ed99
615
cpp
C++
Algorithm/0204 (Easy)Count Primes/Best-Approach.cpp
ZexinLi0w0/LeetCode
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
[ "MIT" ]
1
2020-12-03T10:10:15.000Z
2020-12-03T10:10:15.000Z
Algorithm/0204 (Easy)Count Primes/Best-Approach.cpp
ZexinLi0w0/LeetCode
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
[ "MIT" ]
null
null
null
Algorithm/0204 (Easy)Count Primes/Best-Approach.cpp
ZexinLi0w0/LeetCode
cf3988620ccdcc3d54b9beafd04c517c96f01bb9
[ "MIT" ]
null
null
null
class Solution { public: int countPrimes(int n) { if(n<=2) return 0; bool res[n]; //array is faster than vector memset(res, true, sizeof(res)); int counts = 2; for(int i = 2; i * i < n; i++){ if(res[i]){ int step = (i > 2) ? 2 * i : 2; //trick:prime is odd,except 2. for(int j=i*i;j<n;j += step){ //odd+even=odd if(res[j]){ res[j]=false; counts++; } } } } return n-counts; } };
27.954545
79
0.362602
[ "vector" ]
a7746c43d2b2f8123c8f185758cca8dc67497950
3,568
cpp
C++
src/ProfileTracer.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/ProfileTracer.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/ProfileTracer.cpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #include "config.h" #include <string.h> #include <errno.h> #include <limits.h> #include <iostream> #include <iomanip> #include "ProfileTracerImp.hpp" #include "geopm/PlatformIO.hpp" #include "geopm/PlatformTopo.hpp" #include "geopm/Helper.hpp" #include "geopm_hint.h" #include "Environment.hpp" #include "geopm/Exception.hpp" #include "CSV.hpp" #include "geopm_debug.hpp" #include "ApplicationSampler.hpp" #include "record.hpp" namespace geopm { ProfileTracerImp::ProfileTracerImp(const std::string &start_time) : ProfileTracerImp(start_time, 1024 * 1024, environment().do_trace_profile(), environment().trace_profile(), hostname()) { } ProfileTracerImp::ProfileTracerImp(const std::string &start_time, size_t buffer_size, bool is_trace_enabled, const std::string &file_name, const std::string &host_name) : m_is_trace_enabled(is_trace_enabled) { if (m_is_trace_enabled) { m_csv = geopm::make_unique<CSVImp>(file_name, host_name, start_time, buffer_size); m_csv->add_column("TIME", "double"); m_csv->add_column("PROCESS", "integer"); m_csv->add_column("EVENT", event_format); m_csv->add_column("SIGNAL", event_format); m_csv->activate(); } } ProfileTracerImp::~ProfileTracerImp() = default; std::string ProfileTracerImp::event_format(double value) { static bool is_signal = false; static int event_type; std::string result; if (!is_signal) { // This is a call to format the event column // Store the event type for the next call event_type = value; result = event_name((int)value); // The next call will format the signal column is_signal = true; } else { // This is a call to format the signal column switch (event_type) { case EVENT_REGION_ENTRY: case EVENT_REGION_EXIT: result = string_format_hex(value); break; case EVENT_EPOCH_COUNT: result = string_format_integer(value); break; default: result = "INVALID"; GEOPM_DEBUG_ASSERT(false, "ProfileTracer::event_format(): event out of range"); break; } // The next call will be to format the event column is_signal = false; } return result; } void ProfileTracerImp::update(const std::vector<record_s> &records) { if (m_is_trace_enabled) { std::vector<double> sample(M_NUM_COLUMN); for (const auto &it : records) { sample[M_COLUMN_TIME] = it.time; sample[M_COLUMN_PROCESS] = it.process; sample[M_COLUMN_EVENT] = it.event; sample[M_COLUMN_SIGNAL] = it.signal; m_csv->update(sample); } } } std::unique_ptr<ProfileTracer> ProfileTracer::make_unique(const std::string &start_time) { return geopm::make_unique<ProfileTracerImp>(start_time); } }
32.144144
99
0.552691
[ "vector" ]
a7754a2b7e02cea8555a5d79ee9d2b79c5149569
1,743
cpp
C++
aws-cpp-sdk-dax/source/model/NodeTypeSpecificValue.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
2
2019-03-11T15:50:55.000Z
2020-02-27T11:40:27.000Z
aws-cpp-sdk-dax/source/model/NodeTypeSpecificValue.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-dax/source/model/NodeTypeSpecificValue.cpp
curiousjgeorge/aws-sdk-cpp
09b65deba03cfbef9a1e5d5986aa4de71bc03cd8
[ "Apache-2.0" ]
1
2019-01-18T13:03:55.000Z
2019-01-18T13:03:55.000Z
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/dax/model/NodeTypeSpecificValue.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace DAX { namespace Model { NodeTypeSpecificValue::NodeTypeSpecificValue() : m_nodeTypeHasBeenSet(false), m_valueHasBeenSet(false) { } NodeTypeSpecificValue::NodeTypeSpecificValue(JsonView jsonValue) : m_nodeTypeHasBeenSet(false), m_valueHasBeenSet(false) { *this = jsonValue; } NodeTypeSpecificValue& NodeTypeSpecificValue::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("NodeType")) { m_nodeType = jsonValue.GetString("NodeType"); m_nodeTypeHasBeenSet = true; } if(jsonValue.ValueExists("Value")) { m_value = jsonValue.GetString("Value"); m_valueHasBeenSet = true; } return *this; } JsonValue NodeTypeSpecificValue::Jsonize() const { JsonValue payload; if(m_nodeTypeHasBeenSet) { payload.WithString("NodeType", m_nodeType); } if(m_valueHasBeenSet) { payload.WithString("Value", m_value); } return payload; } } // namespace Model } // namespace DAX } // namespace Aws
20.505882
78
0.730924
[ "model" ]
a7795b9d71e9e1101f4b18e1beda66c9eddc66bd
2,460
cpp
C++
component/oai-amf/src/contexts/ue_context.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/contexts/ue_context.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
component/oai-amf/src/contexts/ue_context.cpp
kukkalli/oai-cn5g-fed
15634fac935ac8671b61654bdf75bf8af07d3c3a
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the OpenAirInterface (OAI) Software Alliance under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The OpenAirInterface Software Alliance licenses this file to You under * the OAI Public License, Version 1.1 (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.openairinterface.org/?page_id=698 * * 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. *------------------------------------------------------------------------------- * For more information about the OpenAirInterface (OAI) Software Alliance: * contact@openairinterface.org */ #include "ue_context.hpp" //------------------------------------------------------------------------------ ue_context::ue_context() { ran_ue_ngap_id = 0; amf_ue_ngap_id = 0; rrc_estb_cause = {}; isUeContextRequest = false; cgi = {}; tai = {}; pdu_sessions = {}; tmsi = 0; } //------------------------------------------------------------------------------ bool ue_context::find_pdu_session_context( const std::uint8_t& session_id, std::shared_ptr<pdu_session_context>& context) const { std::shared_lock lock(m_pdu_session); if (pdu_sessions.count(session_id) > 0) { context = pdu_sessions.at(session_id); return true; } else { return false; } } //------------------------------------------------------------------------------ void ue_context::add_pdu_session_context( const std::uint8_t& session_id, const std::shared_ptr<pdu_session_context>& context) { std::unique_lock lock(m_pdu_session); pdu_sessions[session_id] = context; } void ue_context::copy_pdu_sessions(std::shared_ptr<ue_context>& ue_ctx) { pdu_sessions = ue_ctx->pdu_sessions; } bool ue_context::get_pdu_sessions_context( std::vector<std::shared_ptr<pdu_session_context>>& sessions_ctx) { std::shared_lock lock(m_pdu_session); for (auto s : pdu_sessions) { sessions_ctx.push_back(s.second); } return true; }
35.652174
81
0.620732
[ "vector" ]
a7812d51c6401e78146dd4e5c076f8d89e5714a7
3,691
cpp
C++
preprocessing/maskfusion-master-2/Core/Segmentation/PreSegmentation.cpp
Wayne-Mai/DynSLAM
7b62e13d2a33ff58ca888a346433a4891a228a20
[ "BSD-3-Clause" ]
null
null
null
preprocessing/maskfusion-master-2/Core/Segmentation/PreSegmentation.cpp
Wayne-Mai/DynSLAM
7b62e13d2a33ff58ca888a346433a4891a228a20
[ "BSD-3-Clause" ]
null
null
null
preprocessing/maskfusion-master-2/Core/Segmentation/PreSegmentation.cpp
Wayne-Mai/DynSLAM
7b62e13d2a33ff58ca888a346433a4891a228a20
[ "BSD-3-Clause" ]
null
null
null
/* * This file is part of https://github.com/martinruenz/maskfusion * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <list> #include <tuple> #include "../Model/Model.h" #include "PreSegmentation.h" PreSegmentation::PreSegmentation(){} PreSegmentation::~PreSegmentation() {} SegmentationResult PreSegmentation::performSegmentation(std::list<std::shared_ptr<Model> > &models, FrameDataPointer frame, unsigned char nextModelID, bool allowNew){ assert(frame->mask.type() == CV_8UC1); assert(frame->mask.isContinuous()); static std::vector<unsigned char> mapping(256, 0); // FIXME SegmentationResult result; result.hasNewLabel = false; result.fullSegmentation = cv::Mat::zeros(frame->mask.rows, frame->mask.cols, CV_8UC1); unsigned char modelIdToIndex[256]; unsigned char mIndex = 0; for (auto m : models) modelIdToIndex[m->getID()] = mIndex++; modelIdToIndex[nextModelID] = mIndex; std::vector<unsigned> outIdsArray(256, 0); // Should be faster than using a set // Replace unseen with zeroes (except new label) for (unsigned i = 0; i < frame->mask.total(); i++) { unsigned char& vIn = frame->mask.data[i]; if (vIn) { unsigned char& vOut = result.fullSegmentation.data[i]; if (mapping[vIn] != 0) { vOut = mapping[vIn]; outIdsArray[vOut]++; ; } else if (allowNew && !result.hasNewLabel) { vOut = nextModelID; mapping[vIn] = nextModelID; result.hasNewLabel = true; outIdsArray[vOut]++; } } else { outIdsArray[0]++; } } for (ModelListIterator m = models.begin(); m != models.end(); m++) result.modelData.push_back({(*m)->getID(), m, cv::Mat(), cv::Mat(), outIdsArray[(*m)->getID()] / (16 * 16), 0.4}); if (result.hasNewLabel) result.modelData.push_back({nextModelID, ModelListIterator(), cv::Mat(), cv::Mat(), unsigned(std::max((float)(outIdsArray[nextModelID] / (16 * 16)), 1.0f)), 0.4}); std::vector<unsigned> cnts(result.modelData.size(), 0); for (unsigned i = 0; i < frame->mask.total(); i++) { const size_t index = modelIdToIndex[result.fullSegmentation.data[i]]; result.modelData[index].depthMean += ((const float*)frame->depth.data)[i]; cnts[index]++; } for (size_t index = 0; index < result.modelData.size(); ++index) result.modelData[index].depthMean /= cnts[index] ? cnts[index] : 1; for (unsigned i = 0; i < frame->mask.total(); i++) { const size_t index = modelIdToIndex[result.fullSegmentation.data[i]]; result.modelData[index].depthStd += std::abs(result.modelData[index].depthMean - ((const float*)frame->depth.data)[i]); } for (size_t iindex = 0; iindex < result.modelData.size(); ++iindex) result.modelData[iindex].depthStd /= cnts[iindex] ? cnts[iindex] : 1; return result; }
41.011111
136
0.62097
[ "vector", "model" ]
a781eb588f98f7b84f1f632a2cb326538e3022e7
1,023
cpp
C++
UVa 12126 - Containers/sample/12126 - Containers.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 12126 - Containers/sample/12126 - Containers.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 12126 - Containers/sample/12126 - Containers.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <stdio.h> #include <stdlib.h> #include <vector> #include <string.h> #include <algorithm> #include <queue> #include <stack> using namespace std; struct SOL { long long L, W; SOL(long long a = 0, long long b = 0): L(a), W(b) {} bool operator<(const SOL &x) const { if (L * W != x.L * x.W) return L * W < x.L * x.W; return llabs(L - W) < llabs(x.L - x.W); } }; int main() { int testcase; long long N; scanf("%d", &testcase); while (testcase--) { scanf("%lld", &N); N = N/5 + (N%5 != 0); SOL best; for (long long i = 1; i * i <= N; i++) { SOL t(i * 44 + 4, (N/i + (N%i != 0)) * 10 + 2); if (i == 1) best = t; else best = min(best, t); } if (best.L < best.W) { swap(best.L, best.W); } printf("%lld X %lld = %lld\n", best.L, best.W, best.L * best.W); } return 0; } /* 6 1 15 22 29 36 43 */
19.673077
72
0.431085
[ "vector" ]
a78734ebc2c194741191a20fcf20003366ca9c47
1,248
hpp
C++
messages/camera.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-04-14T13:55:16.000Z
2020-04-14T13:55:16.000Z
messages/camera.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
4
2020-09-25T22:34:29.000Z
2022-02-09T23:45:12.000Z
messages/camera.hpp
stereoboy/isaac_sdk_20191213
73c863254e626c8d498870189fbfb20be4e10fb3
[ "FSFAP" ]
1
2020-07-02T11:51:17.000Z
2020-07-02T11:51:17.000Z
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #pragma once #include "engine/gems/geometry/pinhole.hpp" #include "messages/camera.capnp.h" #include "messages/image.hpp" #include "messages/math.hpp" namespace isaac { // Reads a pinhole model from PinholeProto inline geometry::PinholeD FromProto(::PinholeProto::Reader reader) { geometry::PinholeD pinhole; pinhole.dimensions = {reader.getRows(), reader.getCols()}; pinhole.focal = FromProto(reader.getFocal()); pinhole.center = FromProto(reader.getCenter()); return pinhole; } // Writes a pinhole model to PinholeProto inline void ToProto(const geometry::PinholeD& pinhole, ::PinholeProto::Builder builder) { builder.setRows(pinhole.dimensions[0]); builder.setCols(pinhole.dimensions[1]); ToProto(pinhole.focal, builder.initFocal()); ToProto(pinhole.center, builder.initCenter()); } } // namespace isaac
33.72973
89
0.778045
[ "geometry", "model" ]
a78824d3dbfec21ebabc4224f2f1432a1ce15512
4,971
cpp
C++
dev/PushNotifications/PushNotificationReceivedEventArgs.cpp
G-arj/WindowsAppSDK
4b9003aef5c22f4edbbb702bac6a5aa1a7d59ebc
[ "CC-BY-4.0", "MIT" ]
null
null
null
dev/PushNotifications/PushNotificationReceivedEventArgs.cpp
G-arj/WindowsAppSDK
4b9003aef5c22f4edbbb702bac6a5aa1a7d59ebc
[ "CC-BY-4.0", "MIT" ]
null
null
null
dev/PushNotifications/PushNotificationReceivedEventArgs.cpp
G-arj/WindowsAppSDK
4b9003aef5c22f4edbbb702bac6a5aa1a7d59ebc
[ "CC-BY-4.0", "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "pch.h" #include <winrt/Windows.ApplicationModel.background.h> #include <winrt/Windows.Storage.Streams.h> #include <winrt/Windows.Networking.PushNotifications.h> #include <TerminalVelocityFeatures-PushNotifications.h> #include "PushNotificationReceivedEventArgs.h" #include "Microsoft.Windows.PushNotifications.PushNotificationReceivedEventArgs.g.cpp" #include <iostream> #include <string> #include <externs.h> #include <PushNotificationDummyDeferral.h> #include "ValueMarshaling.h" #include "PushNotificationUtility.h" namespace winrt { using namespace Windows::ApplicationModel::Background; using namespace Windows::Storage::Streams; using namespace Windows::Storage; using namespace Windows::Networking::PushNotifications; } namespace winrt::Microsoft::Windows::PushNotifications::implementation { PushNotificationReceivedEventArgs::PushNotificationReceivedEventArgs(winrt::IBackgroundTaskInstance const& backgroundTask): m_backgroundTaskInstance(backgroundTask), m_rawNotificationPayload(BuildPayload(backgroundTask.TriggerDetails().as<RawNotification>().ContentBytes())), m_unpackagedAppScenario(false) { THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::PushNotifications::Feature_PushNotifications::IsEnabled()); } PushNotificationReceivedEventArgs::PushNotificationReceivedEventArgs(winrt::PushNotificationReceivedEventArgs const& args): m_rawNotificationPayload(BuildPayload(args.RawNotification().ContentBytes())), m_unpackagedAppScenario(false) { THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::PushNotifications::Feature_PushNotifications::IsEnabled()); } PushNotificationReceivedEventArgs::PushNotificationReceivedEventArgs(byte* const& payload, ULONG const& length) : m_rawNotificationPayload(BuildPayload(payload, length)), m_unpackagedAppScenario(true) { THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::PushNotifications::Feature_PushNotifications::IsEnabled()); } PushNotificationReceivedEventArgs::PushNotificationReceivedEventArgs(std::wstring const& payload) : m_rawNotificationPayload(BuildPayload(payload)), m_unpackagedAppScenario(true) { THROW_HR_IF(E_NOTIMPL, !::Microsoft::Windows::PushNotifications::Feature_PushNotifications::IsEnabled()); } std::vector<uint8_t> PushNotificationReceivedEventArgs::BuildPayload(winrt::Windows::Storage::Streams::IBuffer const& buffer) { return { buffer.data(), buffer.data() + (buffer.Length() * sizeof(uint8_t)) }; } std::vector<uint8_t> PushNotificationReceivedEventArgs::BuildPayload(byte* const& payload, ULONG const& length) { return { payload, payload + (length * sizeof(uint8_t)) }; } std::vector<uint8_t> PushNotificationReceivedEventArgs::BuildPayload(std::wstring const& payload) { std::string payloadToSimpleString{ ::winrt::Microsoft::Windows::PushNotifications::Helpers::WideStringToUtf8String(payload) }; return { payloadToSimpleString.c_str(), payloadToSimpleString.c_str() + (payloadToSimpleString.length() * sizeof(uint8_t)) }; } winrt::com_array<uint8_t> PushNotificationReceivedEventArgs::Payload() { return { m_rawNotificationPayload.data(), m_rawNotificationPayload.data() + (m_rawNotificationPayload.size() * sizeof(uint8_t)) }; } winrt::BackgroundTaskDeferral PushNotificationReceivedEventArgs::GetDeferral() { if (!m_unpackagedAppScenario) { THROW_HR_IF_NULL_MSG(E_ILLEGAL_METHOD_CALL, m_backgroundTaskInstance, "Foreground activation cannot call this."); return m_backgroundTaskInstance.GetDeferral(); } else { auto dummyDeferral = winrt::make<PushNotificationDummyDeferral>(); return dummyDeferral.as<winrt::BackgroundTaskDeferral>(); } } winrt::event_token PushNotificationReceivedEventArgs::Canceled(winrt::BackgroundTaskCanceledEventHandler const& handler) { if (!m_unpackagedAppScenario) { THROW_HR_IF_NULL_MSG(E_ILLEGAL_METHOD_CALL, m_backgroundTaskInstance, "Foreground activation cannot call this."); return m_backgroundTaskInstance.Canceled(handler); } else { return { 0 }; } } void PushNotificationReceivedEventArgs::Canceled(winrt::event_token const& token) noexcept { if (!m_unpackagedAppScenario) { THROW_HR_IF_NULL_MSG(E_ILLEGAL_METHOD_CALL, m_backgroundTaskInstance, "Foreground activation cannot call this."); m_backgroundTaskInstance.Canceled(token); } } }
41.773109
139
0.716154
[ "vector" ]
a78fe46fb0c6000b6b216c221eff2afa1da7796c
2,055
cpp
C++
heaps.cpp
kshitijanand36/Important-programs
6b5867896d64ab16453248e0f8c1ca0ba54036e3
[ "MIT" ]
null
null
null
heaps.cpp
kshitijanand36/Important-programs
6b5867896d64ab16453248e0f8c1ca0ba54036e3
[ "MIT" ]
null
null
null
heaps.cpp
kshitijanand36/Important-programs
6b5867896d64ab16453248e0f8c1ca0ba54036e3
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include<vector> #define pb push_back using namespace std; class Priority_Queue{ vector<int> pq; int last; public: void helper_insert(int curr){ int parent = (curr-1)/2; if(curr<=0){ return ; } if(pq[parent]<pq[curr]){ return; } if(pq[(curr-1)/2]>pq[curr]){ swap(pq[curr],pq[parent]); } helper_insert(parent); } int Min(int i,int j){ if(pq[i]<pq[j]) return i; return j; } bool empty(){ if(pq.size()==0) return true; return false; } void insert(int element){ pq.pb(element); helper_insert(pq.size()-1); for(int i=0;i<pq.size();i++){ cout<<pq[i]<<" "; } cout<<endl; } int get_min(){ return pq[0]; } int pop(){ int ans = pq[0]; swap(pq[0],pq[pq.size()-1]); pq.pop_back(); int curr = 0; while(2*curr +1 <pq.size()){ int left_child = 2*curr +1; int right_child = 2*curr +2; int min_child_index; if(right_child<pq.size()) min_child_index = Min(right_child,left_child); else{ min_child_index = left_child; } if(pq[min_child_index] > pq[curr]){ break; } if(pq[min_child_index] < pq[curr]){ swap(pq[min_child_index],pq[curr]); } curr = min_child_index; } return ans; } }; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); Priority_Queue p; p.insert(3534); p.insert(4); p.insert(24); p.insert(76); p.insert(3); p.insert(-23); while(!p.empty()){ cout<<p.pop()<<" "; } }
18.853211
64
0.424818
[ "vector" ]
042871c2e97d07ec4adb79b04488baddf5e2eefb
724
cc
C++
sdk/lib/fidl/cpp/object_coding_unittest.cc
yanyushr/fuchsia
98e70672a81a206d235503e398f37b7b65581f79
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
sdk/lib/fidl/cpp/object_coding_unittest.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
sdk/lib/fidl/cpp/object_coding_unittest.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Fuchsia 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 <lib/fidl/cpp/object_coding.h> #include <fidl/test/misc/cpp/fidl.h> #include <utility> #include "gtest/gtest.h" namespace fidl { namespace { TEST(EncodeObject, Struct) { fidl::test::misc::Int64Struct s; s.x = 123; std::vector<uint8_t> data; const char* err_msg; EXPECT_EQ(ZX_OK, EncodeObject(&s, &data, &err_msg)) << err_msg; fidl::test::misc::Int64Struct t; EXPECT_EQ(ZX_OK, DecodeObject(data.data(), data.size(), &t, &err_msg)) << err_msg; EXPECT_EQ(s.x, 123); EXPECT_EQ(t.x, 123); } } // namespace } // namespace fidl
25.857143
73
0.689227
[ "vector" ]
042c5cdbda8e0a0503f672c9503c66372b25410e
4,931
cpp
C++
Base/PLInput/src/Backend/Provider.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
1
2019-11-09T16:54:04.000Z
2019-11-09T16:54:04.000Z
Base/PLInput/src/Backend/Provider.cpp
naetherm/pixelligh
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Base/PLInput/src/Backend/Provider.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
null
null
null
/*********************************************************\ * File: Provider.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include "PLInput/Input/InputManager.h" #include "PLInput/Input/Devices/Device.h" #include "PLInput/Backend/Provider.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; namespace PLInput { //[-------------------------------------------------------] //[ RTTI interface ] //[-------------------------------------------------------] pl_class_metadata(Provider, "PLInput", PLCore::Object, "Input provider") pl_class_metadata_end(Provider) //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Default constructor */ Provider::Provider() { } /** * @brief * Destructor */ Provider::~Provider() { // Clean up Clear(); } /** * @brief * Get list of devices */ const List<Device*> &Provider::GetDevices() const { // Return device list return m_lstDevices; } /** * @brief * Detect devices */ void Provider::DetectDevices(bool bReset) { // Delete all devices? if (bReset) Clear(); // Flag all current devices as 'not confirmed' for (uint32 i=0; i<m_lstDevices.GetNumOfElements(); i++) m_lstDevices[i]->m_bConfirmed = false; // Detect new devices (the ones that are already there will be ignored by AddDevice) QueryDevices(); // Delete all devices that are no longer there (confirmed == false) for (uint32 i=0; i<m_lstDevices.GetNumOfElements(); i++) { Device *pDevice = m_lstDevices[i]; if (!pDevice->m_bConfirmed) { // Remove device InputManager::GetInstance()->RemoveDevice(pDevice); m_lstDevices.Remove(pDevice); delete pDevice; i--; } } } //[-------------------------------------------------------] //[ Protected functions ] //[-------------------------------------------------------] /** * @brief * Destroy all devices */ void Provider::Clear() { // Delete all input devices for (uint32 i=0; i<m_lstDevices.GetNumOfElements(); i++) { Device *pDevice = m_lstDevices[i]; InputManager::GetInstance()->RemoveDevice(pDevice); delete pDevice; } m_lstDevices.Clear(); } /** * @brief * Check if a device is already known */ bool Provider::CheckDevice(const String &sName) { // Check if the device is already present Device *pDevice = InputManager::GetInstance()->GetDevice(sName); if (pDevice) { // Update device pDevice->m_bConfirmed = true; return true; } // Not found return false; } /** * @brief * Add a new input device */ bool Provider::AddDevice(const String &sName, Device *pDevice) { // Check if the device is already present Device *pDeviceFound = InputManager::GetInstance()->GetDevice(sName); if (!pDeviceFound) { // Add device to manager if (InputManager::GetInstance()->AddDevice(pDevice)) { // Add device to own list - if we're in here, we now that the pDevice pointer is valid m_lstDevices.Add(pDevice); pDevice->m_bConfirmed = true; return true; } } // Error! return false; } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLInput
28.668605
97
0.544109
[ "object" ]
042d088be2cdd645d2265a8c3a357b382b1841ee
4,807
cpp
C++
csrc/mmdeploy/codebase/mmocr/panet.cpp
PeterH0323/mmdeploy-1
ac0b52f12ac897867b9bf3dae74b4192493b3d5f
[ "Apache-2.0" ]
null
null
null
csrc/mmdeploy/codebase/mmocr/panet.cpp
PeterH0323/mmdeploy-1
ac0b52f12ac897867b9bf3dae74b4192493b3d5f
[ "Apache-2.0" ]
null
null
null
csrc/mmdeploy/codebase/mmocr/panet.cpp
PeterH0323/mmdeploy-1
ac0b52f12ac897867b9bf3dae74b4192493b3d5f
[ "Apache-2.0" ]
null
null
null
// Copyright (c) OpenMMLab. All rights reserved. #include "mmdeploy/codebase/mmocr/panet.h" #include <algorithm> #include <opencv2/opencv.hpp> #include "mmdeploy/codebase/mmocr/mmocr.h" #include "mmdeploy/core/device.h" #include "mmdeploy/core/registry.h" #include "mmdeploy/core/serialization.h" #include "mmdeploy/core/utils/device_utils.h" namespace mmdeploy { namespace mmocr { std::vector<std::vector<float>> pixel_group_cpu(const cv::Mat_<float>& score, const cv::Mat_<uint8_t>& mask, const cv::Mat_<float>& embedding, const cv::Mat_<int32_t>& kernel_label, const cv::Mat_<uint8_t>& kernel_contour, int kernel_region_num, float dis_threshold); class PANHead : public MMOCR { public: explicit PANHead(const Value& config) : MMOCR(config) { if (config.contains("params")) { auto& params = config["params"]; min_text_avg_confidence_ = params.value("min_text_avg_confidence", min_text_avg_confidence_); min_kernel_confidence_ = params.value("min_kernel_confidence", min_kernel_confidence_); min_text_avg_confidence_ = params.value("min_text_avg_confidence", min_text_avg_confidence_); min_text_area_ = params.value("min_text_area", min_text_area_); rescale_ = params.value("rescale", rescale_); downsample_ratio_ = params.value("downsample_ratio", downsample_ratio_); } auto platform = Platform(device_.platform_id()).GetPlatformName(); auto creator = Registry<PaHeadImpl>::Get().GetCreator(platform); if (!creator) { MMDEPLOY_ERROR("PANHead: implementation for platform \"{}\" not found", platform); throw_exception(eEntryNotFound); } impl_ = creator->Create(nullptr); impl_->Init(stream_); } Result<Value> operator()(const Value& _data, const Value& _pred) noexcept { OUTCOME_TRY(auto pred, MakeAvailableOnDevice(_pred["output"].get<Tensor>(), device_, stream_)); OUTCOME_TRY(stream_.Wait()); if (pred.shape().size() != 4 || pred.shape(0) != 1 || pred.data_type() != DataType::kFLOAT) { MMDEPLOY_ERROR("unsupported `output` tensor, shape: {}, dtype: {}", pred.shape(), (int)pred.data_type()); return Status(eNotSupported); } // drop batch dimension pred.Squeeze(0); auto text_pred = pred.Slice(0); auto kernel_pred = pred.Slice(1); auto embed_pred = pred.Slice(2, pred.shape(0)); cv::Mat_<float> text_score; cv::Mat_<uint8_t> text; cv::Mat_<uint8_t> kernel; cv::Mat_<int> labels; cv::Mat_<float> embed; int region_num = 0; OUTCOME_TRY(impl_->Process(text_pred, kernel_pred, embed_pred, min_text_confidence_, min_kernel_confidence_, text_score, text, kernel, labels, embed, region_num)); auto text_points = pixel_group_cpu(text_score, text, embed, labels, kernel, region_num, min_text_avg_confidence_); auto scale_w = _data["img_metas"]["scale_factor"][0].get<float>(); auto scale_h = _data["img_metas"]["scale_factor"][1].get<float>(); TextDetectorOutput output; for (auto& text_point : text_points) { auto text_confidence = text_point[0]; auto area = text_point.size() - 2; if (filter_instance(static_cast<float>(area), text_confidence, min_text_area_, min_text_avg_confidence_)) { continue; } cv::Mat_<float> points(text_point.size() / 2 - 1, 2, text_point.data() + 2); cv::RotatedRect rect = cv::minAreaRect(points); std::vector<cv::Point2f> vertices(4); rect.points(vertices.data()); if (rescale_) { for (auto& p : vertices) { p.x /= scale_w * downsample_ratio_; p.y /= scale_h * downsample_ratio_; } } auto& bbox = output.boxes.emplace_back(); for (int i = 0; i < 4; ++i) { bbox[i * 2] = vertices[i].x; bbox[i * 2 + 1] = vertices[i].y; } output.scores.push_back(text_confidence); } return to_value(output); } static bool filter_instance(float area, float confidence, float min_area, float min_confidence) { return area < min_area || confidence < min_confidence; } float min_text_confidence_{.5f}; float min_kernel_confidence_{.5f}; float min_text_avg_confidence_{0.85}; float min_text_area_{16}; bool rescale_{true}; float downsample_ratio_{.25f}; std::unique_ptr<PaHeadImpl> impl_; }; REGISTER_CODEBASE_COMPONENT(MMOCR, PANHead); } // namespace mmocr MMDEPLOY_DEFINE_REGISTRY(mmocr::PaHeadImpl); } // namespace mmdeploy
37.263566
99
0.633867
[ "shape", "vector" ]
042d915ee204ccd3f4f05aae541a26e0dba130b8
5,603
hh
C++
svelte/tag.hh
Himujjal/go-tree-sitter
0e977561152c8cb0c8624309719ff2a9cfc869f6
[ "MIT" ]
null
null
null
svelte/tag.hh
Himujjal/go-tree-sitter
0e977561152c8cb0c8624309719ff2a9cfc869f6
[ "MIT" ]
null
null
null
svelte/tag.hh
Himujjal/go-tree-sitter
0e977561152c8cb0c8624309719ff2a9cfc869f6
[ "MIT" ]
null
null
null
#ifndef TAG_HH #define TAG_HH #include <algorithm> #include <map> #include <string> using std::map; using std::string; enum TagType { AREA, BASE, BASEFONT, BGSOUND, BR, COL, COMMAND, EMBED, FRAME, HR, IMAGE, IMG, INPUT, ISINDEX, KEYGEN, LINK, MENUITEM, META, NEXTID, PARAM, SOURCE, TRACK, WBR, END_OF_VOID_TAGS, A, ABBR, ADDRESS, ARTICLE, ASIDE, AUDIO, B, BDI, BDO, BLOCKQUOTE, BODY, BUTTON, CANVAS, CAPTION, CITE, CODE, COLGROUP, DATA, DATALIST, DD, DEL, DETAILS, DFN, DIALOG, DIV, DL, DT, EM, FIELDSET, FIGCAPTION, FIGURE, FOOTER, FORM, H1, H2, H3, H4, H5, H6, HEAD, HEADER, HGROUP, HTML, I, IFRAME, INS, KBD, LABEL, LEGEND, LI, MAIN, MAP, MARK, MATH, MENU, METER, NAV, NOSCRIPT, OBJECT, OL, OPTGROUP, OPTION, OUTPUT, P, PICTURE, PRE, PROGRESS, Q, RB, RP, RT, RTC, RUBY, S, SAMP, SCRIPT, SECTION, SELECT, SLOT, SMALL, SPAN, STRONG, STYLE, SUB, SUMMARY, SUP, SVG, TABLE, TBODY, TD, TEMPLATE, TEXTAREA, TFOOT, TH, THEAD, TIME, TITLE, TR, U, UL, VAR, VIDEO, CUSTOM, }; // Get the string->TagType match for the above enums static const map<string, TagType> get_tag_map() { map<string, TagType> result; #define TAG(name) result[#name] = name TAG(AREA); TAG(BASE); TAG(BASEFONT); TAG(BGSOUND); TAG(BR); TAG(COL); TAG(COMMAND); TAG(EMBED); TAG(FRAME); TAG(HR); TAG(IMAGE); TAG(IMG); TAG(INPUT); TAG(ISINDEX); TAG(KEYGEN); TAG(LINK); TAG(MENUITEM); TAG(META); TAG(NEXTID); TAG(PARAM); TAG(SOURCE); TAG(TRACK); TAG(WBR); TAG(A); TAG(ABBR); TAG(ADDRESS); TAG(ARTICLE); TAG(ASIDE); TAG(AUDIO); TAG(B); TAG(BDI); TAG(BDO); TAG(BLOCKQUOTE); TAG(BODY); TAG(BUTTON); TAG(CANVAS); TAG(CAPTION); TAG(CITE); TAG(CODE); TAG(COLGROUP); TAG(DATA); TAG(DATALIST); TAG(DD); TAG(DEL); TAG(DETAILS); TAG(DFN); TAG(DIALOG); TAG(DIV); TAG(DL); TAG(DT); TAG(EM); TAG(FIELDSET); TAG(FIGCAPTION); TAG(FIGURE); TAG(FOOTER); TAG(FORM); TAG(H1); TAG(H2); TAG(H3); TAG(H4); TAG(H5); TAG(H6); TAG(HEAD); TAG(HEADER); TAG(HGROUP); TAG(HTML); TAG(I); TAG(IFRAME); TAG(INS); TAG(KBD); TAG(LABEL); TAG(LEGEND); TAG(LI); TAG(MAIN); TAG(MAP); TAG(MARK); TAG(MATH); TAG(MENU); TAG(METER); TAG(NAV); TAG(NOSCRIPT); TAG(OBJECT); TAG(OL); TAG(OPTGROUP); TAG(OPTION); TAG(OUTPUT); TAG(P); TAG(PICTURE); TAG(PRE); TAG(PROGRESS); TAG(Q); TAG(RB); TAG(RP); TAG(RT); TAG(RTC); TAG(RUBY); TAG(S); TAG(SAMP); TAG(SCRIPT); TAG(SECTION); TAG(SELECT); TAG(SLOT); TAG(SMALL); TAG(SPAN); TAG(STRONG); TAG(STYLE); TAG(SUB); TAG(SUMMARY); TAG(SUP); TAG(SVG); TAG(TABLE); TAG(TBODY); TAG(TD); TAG(TEMPLATE); TAG(TEXTAREA); TAG(TFOOT); TAG(TH); TAG(THEAD); TAG(TIME); TAG(TITLE); TAG(TR); TAG(U); TAG(UL); TAG(VAR); TAG(VIDEO); #undef TAG return result; } static const map<string, TagType> TAG_TYPES_BY_TAG_NAME = get_tag_map(); static const TagType TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS[] = { ADDRESS, ARTICLE, ASIDE, BLOCKQUOTE, DETAILS, DIV, DL, FIELDSET, FIGCAPTION, FIGURE, FOOTER, FORM, H1, H2, H3, H4, H5, H6, HEADER, HR, MAIN, NAV, OL, P, PRE, SECTION, }; static const TagType *TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS_END = (TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS + sizeof(TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS) / sizeof(TagType)); struct Tag { TagType type; string custom_tag_name; // This default constructor is used in the case where there is not enough // space in the serialization buffer to store all of the tags. In that case, // tags that cannot be serialized will be treated as having an unknown type. // These tags will be closed via implicit end tags regardless of the next // closing tag is encountered. Tag() : type(END_OF_VOID_TAGS) {} Tag(TagType type, const string &name) : type(type), custom_tag_name(name) {} bool operator==(const Tag &other) const { if (type != other.type) return false; if (type == CUSTOM && custom_tag_name != other.custom_tag_name) return false; return true; } inline bool is_void() const { return type < END_OF_VOID_TAGS; } // if Tag can contain other tags inline bool can_contain(const Tag &tag) { TagType child = tag.type; switch (type) { case LI: return child != LI; case DT: case DD: return child != DT && child != DD; case P: return std::find(TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS, TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS_END, tag.type) == TAG_TYPES_NOT_ALLOWED_IN_PARAGRAPHS_END; case COLGROUP: return child == COL; case RB: case RT: case RP: return child != RB && child != RT && child != RP; case OPTGROUP: return child != OPTGROUP; case TR: return child != TR; case TD: case TH: return child != TD && child != TH && child != TR; default: return true; } } // TODO: no idea what it does static inline Tag for_name(const string &name) { map<string, TagType>::const_iterator type = TAG_TYPES_BY_TAG_NAME.find(name); if (type != TAG_TYPES_BY_TAG_NAME.end()) { return Tag(type->second, string()); } else { return Tag(CUSTOM, name); } } }; #endif
15.435262
78
0.594324
[ "object" ]
042f1918670613854faff16c1b434f91f2d472af
7,050
cc
C++
tensorflow/core/kernels/ctc_loss_op.cc
shishaochen/TensorFlow-0.8-Win
63221dfc4f1a1d064308e632ba12e6a54afe1fd8
[ "Apache-2.0" ]
1
2017-09-14T23:59:05.000Z
2017-09-14T23:59:05.000Z
tensorflow/core/kernels/ctc_loss_op.cc
shishaochen/TensorFlow-0.8-Win
63221dfc4f1a1d064308e632ba12e6a54afe1fd8
[ "Apache-2.0" ]
1
2016-10-19T02:43:04.000Z
2016-10-31T14:53:06.000Z
tensorflow/core/kernels/ctc_loss_op.cc
shishaochen/TensorFlow-0.8-Win
63221dfc4f1a1d064308e632ba12e6a54afe1fd8
[ "Apache-2.0" ]
8
2016-10-23T00:50:02.000Z
2019-04-21T11:11:57.000Z
/* 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. ==============================================================================*/ // See docs in ../ops/ctc_ops.cc. #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/bounds_check.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/util/ctc/ctc_loss_calculator.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" #ifdef _MSC_VER #undef max #endif namespace tensorflow { typedef Eigen::ThreadPoolDevice CPUDevice; class CTCLossOp : public OpKernel { typedef Eigen::Map<const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > InputMap; typedef Eigen::Map< Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> > OutputMap; public: explicit CTCLossOp(OpKernelConstruction* ctx) : OpKernel(ctx) { OP_REQUIRES_OK(ctx, ctx->GetAttr("preprocess_collapse_repeated", &preprocess_collapse_repeated_)); OP_REQUIRES_OK(ctx, ctx->GetAttr("ctc_merge_repeated", &ctc_merge_repeated_)); } void Compute(OpKernelContext* ctx) override { const Tensor* inputs; const Tensor* labels_indices; const Tensor* labels_values; const Tensor* seq_len; OP_REQUIRES_OK(ctx, ctx->input("inputs", &inputs)); OP_REQUIRES_OK(ctx, ctx->input("labels_indices", &labels_indices)); OP_REQUIRES_OK(ctx, ctx->input("labels_values", &labels_values)); OP_REQUIRES_OK(ctx, ctx->input("sequence_length", &seq_len)); OP_REQUIRES(ctx, inputs->shape().dims() == 3, errors::InvalidArgument("inputs is not a 3-Tensor")); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(seq_len->shape()), errors::InvalidArgument("sequence_length is not a vector")); OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(labels_indices->shape()), errors::InvalidArgument("labels_indices is not a matrix")); OP_REQUIRES(ctx, TensorShapeUtils::IsVector(labels_values->shape()), errors::InvalidArgument("labels_values is not a vector")); const TensorShape& inputs_shape = inputs->shape(); const int64 max_time = inputs_shape.dim_size(0); const int64 batch_size = inputs_shape.dim_size(1); const int64 num_classes_raw = inputs_shape.dim_size(2); OP_REQUIRES( ctx, FastBoundsCheck(num_classes_raw, std::numeric_limits<int>::max()), errors::InvalidArgument("num_classes cannot exceed max int")); const int num_classes = static_cast<const int>(num_classes_raw); OP_REQUIRES( ctx, batch_size == seq_len->dim_size(0), errors::InvalidArgument("len(sequence_length) != batch_size. ", "len(sequence_length): ", seq_len->dim_size(0), " batch_size: ", batch_size)); auto seq_len_t = seq_len->vec<int32>(); OP_REQUIRES(ctx, labels_indices->dim_size(0) == labels_values->dim_size(0), errors::InvalidArgument( "labels_indices and labels_values must contain the " "same number of rows, but saw shapes: ", labels_indices->shape().DebugString(), " vs. ", labels_values->shape().DebugString())); TensorShape labels_shape({batch_size, max_time}); std::vector<int64> order{0, 1}; sparse::SparseTensor labels_sp(*labels_indices, *labels_values, labels_shape, order); Status labels_sp_valid = labels_sp.IndicesValid(); OP_REQUIRES(ctx, labels_sp_valid.ok(), errors::InvalidArgument("label SparseTensor is not valid: ", labels_sp_valid.error_message())); ctc::CTCLossCalculator::LabelSequences labels_t(batch_size); for (const auto& g : labels_sp.group({0})) { // iterate by batch const int64 batch_indices = g.group()[0]; OP_REQUIRES(ctx, FastBoundsCheck(batch_indices, batch_size), errors::InvalidArgument("labels batch index must be between ", 0, " and ", batch_size, " but saw: ", batch_indices)); auto values = g.values<int32>(); std::vector<int>* b_values = &labels_t[batch_indices]; b_values->resize(values.size()); for (int i = 0; i < values.size(); ++i) (*b_values)[i] = values(i); } OP_REQUIRES(ctx, static_cast<size_t>(batch_size) == labels_t.size(), errors::InvalidArgument("len(labels) != batch_size. ", "len(labels): ", labels_t.size(), " batch_size: ", batch_size)); for (int64 b = 0; b < batch_size; ++b) { OP_REQUIRES( ctx, seq_len_t(b) <= max_time, errors::InvalidArgument("sequence_length(", b, ") <= ", max_time)); } Tensor* loss = nullptr; OP_REQUIRES_OK(ctx, ctx->allocate_output("loss", seq_len->shape(), &loss)); auto loss_t = loss->vec<float>(); Tensor* gradient; OP_REQUIRES_OK(ctx, ctx->allocate_output("gradient", inputs_shape, &gradient)); auto gradient_t = gradient->tensor<float, 3>(); auto inputs_t = inputs->tensor<float, 3>(); std::vector<OutputMap> gradient_list_t; std::vector<InputMap> input_list_t; for (std::size_t t = 0; t < max_time; ++t) { input_list_t.emplace_back(inputs_t.data() + t * batch_size * num_classes, batch_size, num_classes); gradient_list_t.emplace_back( gradient_t.data() + t * batch_size * num_classes, batch_size, num_classes); } gradient_t.setZero(); // Assumption: the blank index is num_classes - 1 ctc::CTCLossCalculator ctc_loss_calculator(num_classes - 1, 0); OP_REQUIRES_OK(ctx, ctc_loss_calculator.CalculateLoss( seq_len_t, labels_t, input_list_t, preprocess_collapse_repeated_, ctc_merge_repeated_, &loss_t, &gradient_list_t)); } private: bool preprocess_collapse_repeated_; bool ctc_merge_repeated_; TF_DISALLOW_COPY_AND_ASSIGN(CTCLossOp); }; REGISTER_KERNEL_BUILDER(Name("CTCLoss").Device(DEVICE_CPU), CTCLossOp); } // end namespace tensorflow
42.215569
80
0.635603
[ "shape", "vector" ]
0433ad84f2bd0cbbd775df376a6ddd49ffef9119
10,157
cpp
C++
decision_tree.cpp
ChristyanS/DecisionTree
04c81002ea5283551b8bd4114442246e49dc2931
[ "MIT" ]
null
null
null
decision_tree.cpp
ChristyanS/DecisionTree
04c81002ea5283551b8bd4114442246e49dc2931
[ "MIT" ]
null
null
null
decision_tree.cpp
ChristyanS/DecisionTree
04c81002ea5283551b8bd4114442246e49dc2931
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <fstream> #include <cmath> #include <map> using namespace std; int threads = 4; /** Projeto 01 - Implementação Paralela de uma Técnica de Inteligência Artificial i) Tempo gasto para processamento no parcode, sem paralelização, usando o dataset data_final: entre 10 e 11s (real time) ii) Código aberto utilizado para a versão sequencial. Pode ser encontrado aqui: https://github.com/lucasheriques/DecisionTree iii) Mudanças realizadas usando o OpenMP estão comentadas iv) Tempos de execução: Sequencial: entre 10 e 11s Paralela 1 thread: Paralela 2 thread: Paralela 4 thread: Paralela 8 thread: */ class Table { public: vector<string> attrName; vector<vector<string> > data; vector<vector<string> > attrValueList; void extractAttrValue() { attrValueList.resize(attrName.size()); for(int j=0; j<attrName.size(); j++) { map<string, int> value; #pragma omp parallel for num_threads(threads) for(int i=0; i<data.size(); i++) { value[data[i][j]]=1; } for(auto iter=value.begin(); iter != value.end(); iter++) { attrValueList[j].push_back(iter->first); } } } }; class Node { public: int criteriaAttrIndex; string attrValue; int treeIndex; bool isLeaf; string label; vector<int > children; Node() { isLeaf = false; } }; class DecisionTree { public: Table initialTable; vector<Node> tree; DecisionTree(Table table) { initialTable = table; initialTable.extractAttrValue(); Node root; root.treeIndex=0; tree.push_back(root); run(initialTable, 0); printTree(0, ""); cout<< "<-- finish generating decision tree -->" << endl << endl; } string guess(vector<string> row) { string label = ""; int leafNode = dfs(row, 0); if(leafNode == -1) { return "dfs failed"; } label = tree[leafNode].label; return label; } int dfs(vector<string>& row, int here) { if(tree[here].isLeaf) { return here; } int criteriaAttrIndex = tree[here].criteriaAttrIndex; for(int i=0;i<tree[here].children.size(); i++) { int next = tree[here].children[i]; if (row[criteriaAttrIndex] == tree[next].attrValue) { return dfs(row, next); } } return -1; } void run(Table table, int nodeIndex) { if(isLeafNode(table) == true) { tree[nodeIndex].isLeaf = true; tree[nodeIndex].label = table.data.back().back(); return; } int selectedAttrIndex = getSelectedAttribute(table); map<string, vector<int> > attrValueMap; for(int i=0;i<table.data.size();i++) { attrValueMap[table.data[i][selectedAttrIndex]].push_back(i); } tree[nodeIndex].criteriaAttrIndex = selectedAttrIndex; pair<string, int> majority = getMajorityLabel(table); if((double)majority.second/table.data.size() > 0.8) { tree[nodeIndex].isLeaf = true; tree[nodeIndex].label = majority.first; return; } for(int i=0;i< initialTable.attrValueList[selectedAttrIndex].size(); i++) { string attrValue = initialTable.attrValueList[selectedAttrIndex][i]; Table nextTable; vector<int> candi = attrValueMap[attrValue]; for(int i=0;i<candi.size(); i++) { nextTable.data.push_back(table.data[candi[i]]); } Node nextNode; nextNode.attrValue = attrValue; nextNode.treeIndex = (int)tree.size(); tree[nodeIndex].children.push_back(nextNode.treeIndex); tree.push_back(nextNode); // for empty table if(nextTable.data.size()==0) { nextNode.isLeaf = true; nextNode.label = getMajorityLabel(table).first; tree[nextNode.treeIndex] = nextNode; } else { run(nextTable, nextNode.treeIndex); } } } double getEstimatedError(double f, int N) { double z = 0.69; if(N==0) { cout << ":: getEstimatedError :: N is zero" << endl; exit(0); } return (f+z*z/(2*N)+z*sqrt(f/N-f*f/N+z*z/(4*N*N)))/(1+z*z/N); } pair<string, int> getMajorityLabel(Table table) { string majorLabel = ""; int majorCount = 0; map<string, int> labelCount; for(int i=0;i< table.data.size(); i++) { labelCount[table.data[i].back()]++; if(labelCount[table.data[i].back()] > majorCount) { majorCount = labelCount[table.data[i].back()]; majorLabel = table.data[i].back(); } } return {majorLabel, majorCount}; } bool isLeafNode(Table table) { for(int i=1;i < table.data.size();i++) { if(table.data[0].back() != table.data[i].back()) { return false; } } return true; } int getSelectedAttribute(Table table) { int maxAttrIndex = -1; double maxAttrValue = 0.0; // except label #pragma omp parallel for num_threads(threads) for(int i=0; i< initialTable.attrName.size()-1; i++) { if(maxAttrValue < getGainRatio(table, i)) { maxAttrValue = getGainRatio(table, i); maxAttrIndex = i; } } return maxAttrIndex; } double getGainRatio(Table table, int attrIndex) { return getGain(table, attrIndex)/getSplitInfoAttrD(table, attrIndex); } double getInfoD(Table table) { double ret = 0.0; int itemCount = (int)table.data.size(); map<string, int> labelCount; for(int i=0;i<table.data.size();i++) { labelCount[table.data[i].back()]++; } for(auto iter=labelCount.begin(); iter != labelCount.end(); iter++) { double p = (double)iter->second/itemCount; ret += -1.0 * p * log(p)/log(2); } return ret; } double getInfoAttrD(Table table, int attrIndex) { double ret = 0.0; int itemCount = (int)table.data.size(); map<string, vector<int> > attrValueMap; #pragma omp parallel for num_threads(threads) for(int i=0;i<table.data.size();i++) { attrValueMap[table.data[i][attrIndex]].push_back(i); } for(auto iter=attrValueMap.begin(); iter != attrValueMap.end(); iter++) { Table nextTable; for(int i=0;i<iter->second.size(); i++) { nextTable.data.push_back(table.data[iter->second[i]]); } int nextItemCount = (int)nextTable.data.size(); ret += (double)nextItemCount/itemCount * getInfoD(nextTable); } return ret; } double getGain(Table table, int attrIndex) { return getInfoD(table)-getInfoAttrD(table, attrIndex); } double getSplitInfoAttrD(Table table, int attrIndex) { double ret = 0.0; int itemCount = (int)table.data.size(); map<string, vector<int> > attrValueMap; #pragma omp parallel for num_threads(threads) for(int i=0;i<table.data.size();i++) { attrValueMap[table.data[i][attrIndex]].push_back(i); } for(auto iter=attrValueMap.begin(); iter != attrValueMap.end(); iter++) { Table nextTable; for(int i=0;i<iter->second.size(); i++) { nextTable.data.push_back(table.data[iter->second[i]]); } int nextItemCount = (int)nextTable.data.size(); double d = (double)nextItemCount/itemCount; ret += -1.0 * d * log(d) / log(2); } return ret; } /* * Enumerates through all the nodes of the tree and prints all the branches */ void printTree(int nodeIndex, string branch) { if (tree[nodeIndex].isLeaf == true) cout << branch << "Label: " << tree[nodeIndex].label << "\n"; #pragma omp parallel for num_threads(threads) for(int i = 0; i < tree[nodeIndex].children.size(); i++) { int childIndex = tree[nodeIndex].children[i]; string attributeName = initialTable.attrName[tree[nodeIndex].criteriaAttrIndex]; string attributeValue = tree[childIndex].attrValue; printTree(childIndex, branch + attributeName + " = " + attributeValue + ", "); } } }; class InputReader { private: ifstream fin; Table table; public: InputReader(string filename) { fin.open(filename); if(!fin) { cout << filename << " file could not be opened\n"; exit(0); } parse(); } void parse() { string str; bool isAttrName = true; while(!getline(fin, str).eof()){ vector<string> row; int pre = 0; for(int i=0;i<str.size();i++){ if(str[i] == '\t') { string col = str.substr(pre, i-pre); row.push_back(col); pre = i+1; } } string col = str.substr(pre, str.size()-pre-1); row.push_back(col); if(isAttrName) { table.attrName = row; isAttrName = false; } else { table.data.push_back(row); } } } Table getTable() { return table; } }; class OutputPrinter { private: ofstream fout; public: OutputPrinter(string filename) { fout.open(filename); if(!fout) { cout << filename << " file could not be opened\n"; exit(0); } } string joinByTab(vector<string> row) { string ret = ""; #pragma omp parallel for num_threads(threads) for(int i=0; i< row.size(); i++) { ret += row[i]; if(i != row.size() -1) { ret += '\t'; } } return ret; } void addLine(string str) { fout << str << endl; } }; int main(int argc, const char * argv[]) { if(argc!=4) { cout << "Please follow this format. dt.exe [train.txt] [test.txt] [result.txt]"; return 0; } string trainFileName = argv[1]; InputReader trainInputReader(trainFileName); DecisionTree decisionTree(trainInputReader.getTable()); string testFileName = argv[2]; InputReader testInputReader(testFileName); Table test = testInputReader.getTable(); string resultFileName = argv[3]; OutputPrinter outputPrinter(resultFileName); outputPrinter.addLine(outputPrinter.joinByTab(test.attrName)); #pragma omp parallel for num_threads(threads) for(int i=0;i < test.data.size(); i++) { vector<string> result = test.data[i]; result.push_back(decisionTree.guess(test.data[i])); outputPrinter.addLine(outputPrinter.joinByTab(result)); } /* for answer check */ /* InputReader answerInputReader("dt_answer1.txt"); Table answer = answerInputReader.getTable(); int totalCount = (int)answer.data.size(); int hitCount = 0; for(int i=0;i < test.data.size(); i++) { if(answer.data[i].back() == decisionTree.guess(test.data[i])) { hitCount++; } } cout << "Accuracy: " << (double)hitCount/totalCount*100 << "%"; cout << "(" << hitCount << "/" << totalCount << ")" << endl; */ return 0; }
24.125891
125
0.637491
[ "vector" ]
04340219a93da2b21fe007223b571b183ee82168
1,304
hpp
C++
allocore/allocore/protocol/opencl/al_OpenCLImage3D.hpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
allocore/allocore/protocol/opencl/al_OpenCLImage3D.hpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
allocore/allocore/protocol/opencl/al_OpenCLImage3D.hpp
donghaoren/AlloSystem
7674cc8597e470a355a5dab1dac9191c2c2e8086
[ "BSD-3-Clause" ]
null
null
null
#ifndef AL_OPENCL_IMAGE3D_H #define AL_OPENCL_IMAGE3D_H 1 #include "al_OpenCLInternal.hpp" #include "al_OpenCLContext.hpp" #include "al_OpenCLMemoryBuffer.hpp" #include <vector> #include <string> using std::vector; using std::list; using std::string; namespace al { namespace cl { class OpenCLImage3D : public OpenCLMemoryBuffer { public: OpenCLImage3D(cl_mem mem=0) : OpenCLMemoryBuffer(mem) {} virtual ~OpenCLImage3D() {} void create( OpenCLContext &ctx, cl_mem_flags usage, const cl_image_format *format, size_t width, size_t height, size_t depth, size_t rowstride, size_t planestride, void *ptr ); virtual void create( OpenCLContext &ctx, cl_mem_flags usage, AlloArray *array ); OpenCLEvent enqueue_read( OpenCLCommandQueue &queue, bool block, size_t offset, size_t size, void *ptr ) { printf("NOT IMPLEMENTED for IMAGE2D\n"); return OpenCLEvent(0); } virtual OpenCLEvent enqueue_read( OpenCLCommandQueue &queue, bool block, size_t offset, AlloArray *array ); OpenCLEvent enqueue_read( OpenCLCommandQueue &queue, bool block, const size_t origin[3], const size_t region[3], size_t rowstride, size_t planestride, void *ptr ); protected: }; } // cl:: } // al:: #endif // AL_OPENCL_IMAGE3D_H
16.935065
70
0.712423
[ "vector" ]
04380e575335c5148fe537fad1d3e4a4600d42a5
9,697
hh
C++
xdl/third_party/seastar/util/log.hh
hitflame/x-deeplearning
c8029396c6ae6dbf397a34a1801ceadc824e4f8d
[ "Apache-2.0" ]
4,071
2018-12-13T04:17:38.000Z
2022-03-30T03:29:35.000Z
xdl/third_party/seastar/util/log.hh
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
359
2018-12-21T01:14:57.000Z
2022-02-15T07:18:02.000Z
xdl/third_party/seastar/util/log.hh
laozhuang727/x-deeplearning
781545783a4e2bbbda48fc64318fb2c6d8bbb3cc
[ "Apache-2.0" ]
1,054
2018-12-20T09:57:42.000Z
2022-03-29T07:16:53.000Z
/* * This file is open source software, licensed to you under the terms * of the Apache License, Version 2.0 (the "License"). See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. 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. */ /* * Copyright (C) 2015 Cloudius Systems, Ltd. */ #ifndef LOG_HH_ #define LOG_HH_ #include "core/sstring.hh" #include <unordered_map> #include <exception> #include <iosfwd> #include <atomic> #include <mutex> #include <boost/lexical_cast.hpp> /// \addtogroup logging /// @{ namespace seastar { /// \brief log level used with \see {logger} /// used with the logger.do_log method. /// Levels are in increasing order. That is if you want to see debug(3) logs you /// will also see error(0), warn(1), info(2). /// enum class log_level { error, warn, info, debug, trace, }; std::ostream& operator<<(std::ostream& out, log_level level); std::istream& operator>>(std::istream& in, log_level& level); } // Boost doesn't auto-deduce the existence of the streaming operators for some reason namespace boost { template<> seastar::log_level lexical_cast(const std::string& source); } namespace seastar { class logger; class logger_registry; /// \brief Logger class for stdout or syslog. /// /// Java style api for logging. /// \code {.cpp} /// static seastar::logger logger("lsa-api"); /// logger.info("Triggering compaction"); /// \endcode /// The output format is: (depending on level) /// DEBUG %Y-%m-%d %T,%03d [shard 0] - "your msg" \n /// class logger { sstring _name; std::atomic<log_level> _level = { log_level::info }; static std::atomic<bool> _stdout; static std::atomic<bool> _syslog; private: struct stringer { // no need for virtual dtor, since not dynamically destroyed virtual void append(std::ostream& os) = 0; }; template <typename Arg> struct stringer_for final : stringer { explicit stringer_for(const Arg& arg) : arg(arg) {} const Arg& arg; virtual void append(std::ostream& os) override { os << arg; } }; template <typename... Args> void do_log(log_level level, const char* fmt, Args&&... args); void really_do_log(log_level level, const char* fmt, stringer** stringers, size_t n); void failed_to_log(std::exception_ptr ex); public: explicit logger(sstring name); logger(logger&& x); ~logger(); bool is_shard_zero(); /// Test if desired log level is enabled /// /// \param level - enum level value (info|error...) /// \return true if the log level has been enabled. bool is_enabled(log_level level) const { return level <= _level.load(std::memory_order_relaxed); } /// logs to desired level if enabled, otherwise we ignore the log line /// /// \param fmt - printf style format /// \param args - args to print string /// template <typename... Args> void log(log_level level, const char* fmt, Args&&... args) { if (is_enabled(level)) { try { do_log(level, fmt, std::forward<Args>(args)...); } catch (...) { failed_to_log(std::current_exception()); } } } /// Log with error tag: /// ERROR %Y-%m-%d %T,%03d [shard 0] - "your msg" \n /// /// \param fmt - printf style format /// \param args - args to print string /// template <typename... Args> void error(const char* fmt, Args&&... args) { log(log_level::error, fmt, std::forward<Args>(args)...); } /// Log with warning tag: /// WARN %Y-%m-%d %T,%03d [shard 0] - "your msg" \n /// /// \param fmt - printf style format /// \param args - args to print string /// template <typename... Args> void warn(const char* fmt, Args&&... args) { log(log_level::warn, fmt, std::forward<Args>(args)...); } /// Log with info tag: /// INFO %Y-%m-%d %T,%03d [shard 0] - "your msg" \n /// /// \param fmt - printf style format /// \param args - args to print string /// template <typename... Args> void info(const char* fmt, Args&&... args) { log(log_level::info, fmt, std::forward<Args>(args)...); } /// Log with info tag on shard zero only: /// INFO %Y-%m-%d %T,%03d [shard 0] - "your msg" \n /// /// \param fmt - printf style format /// \param args - args to print string /// template <typename... Args> void info0(const char* fmt, Args&&... args) { if (is_shard_zero()) { log(log_level::info, fmt, std::forward<Args>(args)...); } } /// Log with info tag: /// DEBUG %Y-%m-%d %T,%03d [shard 0] - "your msg" \n /// /// \param fmt - printf style format /// \param args - args to print string /// template <typename... Args> void debug(const char* fmt, Args&&... args) { log(log_level::debug, fmt, std::forward<Args>(args)...); } /// Log with trace tag: /// TRACE %Y-%m-%d %T,%03d [shard 0] - "your msg" \n /// /// \param fmt - printf style format /// \param args - args to print string /// template <typename... Args> void trace(const char* fmt, Args&&... args) { log(log_level::trace, fmt, std::forward<Args>(args)...); } /// \return name of the logger. Usually one logger per module /// const sstring& name() const { return _name; } /// \return current log level for this logger /// log_level level() const { return _level.load(std::memory_order_relaxed); } /// \param level - set the log level /// void set_level(log_level level) { _level.store(level, std::memory_order_relaxed); } /// Also output to stdout. default is true static void set_stdout_enabled(bool enabled); /// Also output to syslog. default is false /// /// NOTE: syslog() can block, which will stall the reactor thread. /// this should be rare (will have to fill the pipe buffer /// before syslogd can clear it) but can happen. static void set_syslog_enabled(bool enabled); }; /// \brief used to keep a static registry of loggers /// since the typical use case is to do: /// \code {.cpp} /// static seastar::logger("my_module"); /// \endcode /// this class is used to wrap around the static map /// that holds pointers to all logs /// class logger_registry { mutable std::mutex _mutex; std::unordered_map<sstring, logger*> _loggers; public: /// loops through all registered loggers and sets the log level /// Note: this method locks /// /// \param level - desired level: error,info,... void set_all_loggers_level(log_level level); /// Given a name for a logger returns the log_level enum /// Note: this method locks /// /// \return log_level for the given logger name log_level get_logger_level(sstring name) const; /// Sets the log level for a given logger /// Note: this method locks /// /// \param name - name of logger /// \param level - desired level of logging void set_logger_level(sstring name, log_level level); /// Returns a list of registered loggers /// Note: this method locks /// /// \return all registered loggers std::vector<sstring> get_all_logger_names(); /// Registers a logger with the static map /// Note: this method locks /// void register_logger(logger* l); /// Unregisters a logger with the static map /// Note: this method locks /// void unregister_logger(logger* l); /// Swaps the logger given the from->name() in the static map /// Note: this method locks /// void moved(logger* from, logger* to); }; logger_registry& global_logger_registry(); enum class logger_timestamp_style { none, boot, real, }; struct logging_settings final { std::unordered_map<sstring, log_level> logger_levels; log_level default_level; bool stdout_enabled; bool syslog_enabled; logger_timestamp_style stdout_timestamp_style = logger_timestamp_style::real; }; /// Shortcut for configuring the logging system all at once. /// void apply_logging_settings(const logging_settings&); /// \cond internal extern thread_local uint64_t logging_failures; sstring pretty_type_name(const std::type_info&); sstring level_name(log_level level); template <typename T> class logger_for : public logger { public: logger_for() : logger(pretty_type_name(typeid(T))) {} }; template <typename... Args> void logger::do_log(log_level level, const char* fmt, Args&&... args) { [&](auto&&... stringers) { stringer* s[sizeof...(stringers)] = {&stringers...}; this->really_do_log(level, fmt, s, sizeof...(stringers)); } (stringer_for<Args>(std::forward<Args>(args))...); } /// \endcond } // end seastar namespace // Pretty-printer for exceptions to be logged, e.g., std::current_exception(). namespace std { std::ostream& operator<<(std::ostream&, const std::exception_ptr&); std::ostream& operator<<(std::ostream&, const std::exception&); std::ostream& operator<<(std::ostream&, const std::system_error&); } #endif /* LOG_HH_ */ /// @}
29.474164
89
0.631226
[ "vector" ]
043883e0b35157db8973bc89fa1acbcc93351d36
1,651
hpp
C++
src/type-system/factories/generators/random/RandomNextIntFactory.hpp
inexorgame/entity-system
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
19
2018-10-11T09:19:48.000Z
2020-04-19T16:36:58.000Z
src/type-system/factories/generators/random/RandomNextIntFactory.hpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
132
2018-07-28T12:30:54.000Z
2020-04-25T23:05:33.000Z
src/type-system/factories/generators/random/RandomNextIntFactory.hpp
inexorgame-obsolete/entity-system-inactive
230a6f116fb02caeace79bc9b32f17fe08687c36
[ "MIT" ]
3
2019-03-02T16:19:23.000Z
2020-02-18T05:15:29.000Z
#pragma once #include "base/LifeCycleComponent.hpp" #include "entity-system/factories/entities/entity-instance-builder-factory/EntityInstanceBuilderFactory.hpp" #include "entity-system/model/entities/entity-instances/EntityInstance.hpp" namespace inexor::entity_system::type_system { using EntityInstancePtr = std::shared_ptr<EntityInstance>; using EntityInstancePtrOpt = std::optional<EntityInstancePtr>; using EntityInstanceBuilderFactoryPtr = std::shared_ptr<EntityInstanceBuilderFactory>; /// @class RandomNextIntFactory /// @brief Factory for creating entity instances of type RANDOM_NEXT_INT. class RandomNextIntFactory : public LifeCycleComponent { public: /// @brief Constructs a factory for creating entity instances of type RANDOM_NEXT_INT. /// @note The dependencies of this class will be injected automatically. /// @param entity_instance_builder_factory Factory for creating entity instance builders. RandomNextIntFactory(EntityInstanceBuilderFactoryPtr entity_instance_builder_factory); /// Destructor. ~RandomNextIntFactory(); /// Returns the name of the component std::string get_component_name() override; /// Creates a counter with the default values: millis = 1000, step = 1, start_value = 0. EntityInstancePtrOpt create_instance(); /// @brief Creates an counter with the specified /// @param min ? /// @param min ? EntityInstancePtrOpt create_instance(int min, int max); private: /// Factory for creating entity instance builders. EntityInstanceBuilderFactoryPtr entity_instance_builder_factory; }; } // namespace inexor::entity_system::type_system
38.395349
108
0.775893
[ "model" ]
043b4492a25bb40890b0262c2b7ccc006d29fcc5
2,743
cpp
C++
collection/cp/bcw_codebook-master/Contest/WF2011/pI.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
1
2019-03-24T13:12:01.000Z
2019-03-24T13:12:01.000Z
collection/cp/bcw_codebook-master/Contest/WF2011/pI.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
collection/cp/bcw_codebook-master/Contest/WF2011/pI.cpp
daemonslayer/Notebook
a9880be9bd86955afd6b8f7352822bc18673eda3
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> #include<unistd.h> using namespace std; #define FZ(n) memset((n),0,sizeof(n)) #define FMO(n) memset((n),-1,sizeof(n)) #define F first #define S second #define PB push_back #define ALL(x) begin(x),end(x) #define SZ(x) ((int)(x).size()) #define IOS ios_base::sync_with_stdio(0); cin.tie(0) template<typename A, typename B> ostream& operator <<(ostream &s, const pair<A,B> &p) { return s<<"("<<p.first<<","<<p.second<<")"; } template<typename T> ostream& operator <<(ostream &s, const vector<T> &c) { s<<"[ "; for (auto it : c) s << it << " "; s<<"]"; return s; } // Let's Fight! typedef pair<int, int> pii; const int MAXN = 1000005; int N, K; int px[MAXN], py[MAXN]; vector<pii> event[MAXN*4]; vector<int> es[MAXN*4]; int seg[MAXN*10], tag[MAXN*10]; void initSeg() { for(int i=0; i<8*K+4; i++) seg[i] = tag[i] = 0; } void clearTag(int s, int lb, int rb) { if(rb - lb > 1) { seg[2*s] += tag[s]; seg[2*s+1] += tag[s]; tag[2*s] += tag[s]; tag[2*s+1] += tag[s]; } tag[s] = 0; } void addSeg(int s, int lb, int rb, int l, int r, int val) { if(rb <= l || r <= lb) return; if(l <= lb && rb <= r) { seg[s] += val; tag[s] += val; } else { int mb = (lb + rb) / 2; clearTag(s, lb, rb); addSeg(2*s, lb, mb, l, r, val); addSeg(2*s+1, mb, rb, l, r, val); seg[s] = min(seg[2*s], seg[2*s+1]); } } int qrySeg() { return seg[1]; } bool test() { //cout<<"TEST "<<K<<endl; initSeg(); for(int i=0; i<=2*K; i++) { event[i].clear(); es[i].clear(); } for(int i=0; i<N; i++) { int x1 = px[i], x2 = px[i] + 2*K, y1 = py[i], y2 = py[i] + 2*K; if(x2<0 || y2<0 || x1>2*K || y1>2*K) continue; x1 = max(x1, 0); y1 = max(y1, 0); x2 = min(x2, 2*K); y2 = min(y2, 2*K); //cout<<x1<<"~"<<x2<<" , "<<y1<<"~"<<y2<<endl; event[x1].PB({y1, y2+1}); es[x1].PB(1); if(x2+1 <= 2*K) { event[x2+1].PB({y1, y2+1}); es[x2+1].PB(-1); } } for(int i=0; i<=2*K; i++) { for(int j=0; j<(int)event[i].size(); j++) { int lb = event[i][j].F, rb = event[i][j].S, val = es[i][j]; addSeg(1, 0, 2*K+1, lb, rb, val); } int res = qrySeg(); if(res == 0) return true; } return false; } int calc() { int lb = 0, rb = MAXN - 1; while(lb < rb) { int mb = (lb + rb) / 2; K = mb; if(test()) lb = mb + 1; else rb = mb; } return lb; } int main() { IOS; int t = 0; while(~scanf("%d", &N) && N != -1) { t++; for(int i=0; i<N; i++) scanf("%d%d", &px[i], &py[i]); int ans = calc(); cout<<"Case "<<t<<": "; if(ans == MAXN - 1) cout<<"never"<<endl; else cout<<ans<<endl; } return 0; }
18.046053
67
0.47685
[ "vector" ]
043cba5e58de2998cc6f36c0cd54d523ecb5e83e
1,349
cpp
C++
drape_frontend/overlay_batcher.cpp
ToshUxanoff/omim
a8acb5821c72bd78847d1c49968b14d15b1e06ee
[ "Apache-2.0" ]
1
2021-07-02T08:45:02.000Z
2021-07-02T08:45:02.000Z
drape_frontend/overlay_batcher.cpp
ToshUxanoff/omim
a8acb5821c72bd78847d1c49968b14d15b1e06ee
[ "Apache-2.0" ]
1
2020-06-15T15:16:23.000Z
2020-06-15T15:59:19.000Z
drape_frontend/overlay_batcher.cpp
maksimandrianov/omim
cbc5a80d09d585afbda01e471887f63b9d3ab0c2
[ "Apache-2.0" ]
1
2018-10-01T10:27:21.000Z
2018-10-01T10:27:21.000Z
#include "drape_frontend/overlay_batcher.hpp" #include "drape_frontend/map_shape.hpp" #include "drape/batcher.hpp" #include "drape/render_bucket.hpp" #include "drape/texture_manager.hpp" namespace df { uint32_t const kOverlayIndexBufferSize = 30000; uint32_t const kOverlayVertexBufferSize = 20000; OverlayBatcher::OverlayBatcher(TileKey const & key) : m_batcher(kOverlayIndexBufferSize, kOverlayVertexBufferSize) { int const kAverageRenderDataCount = 5; m_data.reserve(kAverageRenderDataCount); m_batcher.StartSession([this, key](dp::RenderState const & state, drape_ptr<dp::RenderBucket> && bucket) { FlushGeometry(key, state, std::move(bucket)); }); } void OverlayBatcher::Batch(ref_ptr<dp::GraphicsContext> context, drape_ptr<MapShape> const & shape, ref_ptr<dp::TextureManager> texMng) { m_batcher.SetFeatureMinZoom(shape->GetFeatureMinZoom()); shape->Draw(context, make_ref(&m_batcher), texMng); } void OverlayBatcher::Finish(ref_ptr<dp::GraphicsContext> context, TOverlaysRenderData & data) { m_batcher.EndSession(context); data.swap(m_data); } void OverlayBatcher::FlushGeometry(TileKey const & key, dp::RenderState const & state, drape_ptr<dp::RenderBucket> && bucket) { m_data.emplace_back(key, state, std::move(bucket)); } } // namespace df
29.977778
106
0.733877
[ "shape" ]
043e0766f5b8e5f87432144ff618afe4dd7219a6
1,146
cpp
C++
aws-cpp-sdk-sqs/source/model/TagQueueRequest.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-sqs/source/model/TagQueueRequest.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-sqs/source/model/TagQueueRequest.cpp
Nexuscompute/aws-sdk-cpp
e7ef485e46e6962c9e084b8c9b104c1bfcceaf26
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/sqs/model/TagQueueRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::SQS::Model; using namespace Aws::Utils; TagQueueRequest::TagQueueRequest() : m_queueUrlHasBeenSet(false), m_tagsHasBeenSet(false) { } Aws::String TagQueueRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=TagQueue&"; if(m_queueUrlHasBeenSet) { ss << "QueueUrl=" << StringUtils::URLEncode(m_queueUrl.c_str()) << "&"; } if(m_tagsHasBeenSet) { unsigned tagsCount = 1; for(auto& item : m_tags) { ss << "Tag." << tagsCount << ".Key=" << StringUtils::URLEncode(item.first.c_str()) << "&"; ss << "Tag." << tagsCount << ".Value=" << StringUtils::URLEncode(item.second.c_str()) << "&"; tagsCount++; } } ss << "Version=2012-11-05"; return ss.str(); } void TagQueueRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const { uri.SetQueryString(SerializePayload()); }
22.92
75
0.643106
[ "model" ]
0442c0c9283e75088f03d61a916255cfa8e49d05
3,396
cc
C++
media/cast/test/fake_video_encode_accelerator.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/cast/test/fake_video_encode_accelerator.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/cast/test/fake_video_encode_accelerator.cc
tmpsantos/chromium
802d4aeeb33af25c01ee5994037bbf14086d4ac0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:23:37.000Z
2020-11-04T07:23:37.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/cast/test/fake_video_encode_accelerator.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/single_thread_task_runner.h" namespace media { namespace cast { namespace test { static const unsigned int kMinimumInputCount = 1; static const size_t kMinimumOutputBufferSize = 123456; FakeVideoEncodeAccelerator::FakeVideoEncodeAccelerator( const scoped_refptr<base::SingleThreadTaskRunner>& task_runner, std::vector<uint32>* stored_bitrates) : task_runner_(task_runner), stored_bitrates_(stored_bitrates), client_(NULL), first_(true), weak_this_factory_(this) { DCHECK(stored_bitrates_); } FakeVideoEncodeAccelerator::~FakeVideoEncodeAccelerator() { weak_this_factory_.InvalidateWeakPtrs(); } bool FakeVideoEncodeAccelerator::Initialize( media::VideoFrame::Format input_format, const gfx::Size& input_visible_size, VideoCodecProfile output_profile, uint32 initial_bitrate, Client* client) { client_ = client; if (output_profile != media::VP8PROFILE_ANY && output_profile != media::H264PROFILE_MAIN) { return false; } task_runner_->PostTask( FROM_HERE, base::Bind(&FakeVideoEncodeAccelerator::DoRequireBitstreamBuffers, weak_this_factory_.GetWeakPtr(), kMinimumInputCount, input_visible_size, kMinimumOutputBufferSize)); return true; } void FakeVideoEncodeAccelerator::Encode(const scoped_refptr<VideoFrame>& frame, bool force_keyframe) { DCHECK(client_); DCHECK(!available_buffer_ids_.empty()); // Fake that we have encoded the frame; resulting in using the full output // buffer. int32 id = available_buffer_ids_.front(); available_buffer_ids_.pop_front(); bool is_key_fame = force_keyframe; if (first_) { is_key_fame = true; first_ = false; } task_runner_->PostTask( FROM_HERE, base::Bind(&FakeVideoEncodeAccelerator::DoBitstreamBufferReady, weak_this_factory_.GetWeakPtr(), id, kMinimumOutputBufferSize, is_key_fame)); } void FakeVideoEncodeAccelerator::UseOutputBitstreamBuffer( const BitstreamBuffer& buffer) { available_buffer_ids_.push_back(buffer.id()); } void FakeVideoEncodeAccelerator::RequestEncodingParametersChange( uint32 bitrate, uint32 framerate) { stored_bitrates_->push_back(bitrate); } void FakeVideoEncodeAccelerator::Destroy() { delete this; } void FakeVideoEncodeAccelerator::SendDummyFrameForTesting(bool key_frame) { DoBitstreamBufferReady(0, 23, key_frame); } void FakeVideoEncodeAccelerator::DoRequireBitstreamBuffers( unsigned int input_count, const gfx::Size& input_coded_size, size_t output_buffer_size) const { client_->RequireBitstreamBuffers( input_count, input_coded_size, output_buffer_size); } void FakeVideoEncodeAccelerator::DoBitstreamBufferReady( int32 bitstream_buffer_id, size_t payload_size, bool key_frame) const { client_->BitstreamBufferReady(bitstream_buffer_id, payload_size, key_frame); } } // namespace test } // namespace cast } // namespace media
29.789474
79
0.72821
[ "vector" ]
044418bcc2c669dbf5647d6257d31ae2698645dd
13,299
hpp
C++
liblava/frame/input.hpp
TheLavaBlock/LavaBlock
fc2eadb75dfa58622a1941911f20fe31f8780f30
[ "MIT" ]
11
2018-10-26T02:15:53.000Z
2019-05-25T16:08:17.000Z
liblava/frame/input.hpp
TheLavaBlock/LavaBlock
fc2eadb75dfa58622a1941911f20fe31f8780f30
[ "MIT" ]
null
null
null
liblava/frame/input.hpp
TheLavaBlock/LavaBlock
fc2eadb75dfa58622a1941911f20fe31f8780f30
[ "MIT" ]
null
null
null
/** * @file liblava/frame/input.hpp * @brief Input handling * @authors Lava Block OÜ and contributors * @copyright Copyright (c) 2018-present, MIT License */ #pragma once #include <liblava/core/id.hpp> #include <liblava/util/utility.hpp> namespace lava { /** * @brief Input keys */ enum class key : i32 { unknown = -1, /* printable keys */ space = 32, apostrophe = 29, /* ' */ comma = 44, /* , */ minus = 45, /* - */ period = 46, /* . */ slash = 47, /* / */ _0 = 48, _1, _2, _3, _4, _5, _6, _7, _8, _9, semicolon = 59, /* ; */ equal = 61, /* = */ a = 65, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, left_bracket = 91, /* [ */ backslash = 92, /* \ */ right_bracket = 93, /* ] */ grave_accent = 96, /* ` */ world_1 = 161, /* non-US #1 */ world_2 = 162, /* non-US #2 */ /* function keys */ escape = 256, enter, tab, backspace, insert, del, /* delete */ right, left, down, up, page_up, page_down, home, end, caps_lock = 280, scroll_lock, num_lock, print_screen, pause, f1 = 290, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12, f13, f14, f15, f16, f17, f18, f19, f20, f21, f22, f23, f24, f25, kp_0 = 320, kp_1, kp_2, kp_3, kp_4, kp_5, kp_6, kp_7, kp_8, kp_9, kp_decimal, kp_divide, kp_multiply, kp_subtract, kp_add, kp_enter, kp_equal, left_shift = 340, left_control, left_alt, left_super, right_shift, right_control, right_alt, right_super, menu, last = menu, }; /// Key type using key_t = key; /// Reference to key using key_ref = key const&; /// List of keys using keys = std::vector<key>; /// Reference to list of keys using keys_ref = keys const&; /** * @brief Convert input key to string * * @param k Input key * * @return string String representation */ string to_string(key k); /** * @brief Get scancode based on key * * @param key Input key * * @return i32 Input scan code */ i32 get_scancode(key key); /** * @brief Input actions */ enum class action : type { release = 0, press, repeat }; /// Action type using action_t = action; /// Refernece to action using action_ref = action const&; /** * @brief Input mods */ enum class mod : type { none = 0 << 0, shift = 1 << 0, control = 1 << 1, alt = 1 << 2, super = 1 << 3, caps_lock = 1 << 4, num_lock = 1 << 5, }; ENUM_FLAG_OPERATORS(mod) /// Mod type using mod_t = mod; /** * @brief Check if mod is active * * @param m Target mod * @param c Mod to check * * @return true Mod is active * @return false Mod is not active */ inline bool check_mod(mod m, mod c) { return (m & c) != mod::none; } /// Reference to mod using mod_ref = mod const&; /** * @brief Convert input mod to string * * @param m Input mod * * @return string String representation */ string to_string(mod m); /** * @brief Key event */ struct key_event { /// Reference to key event using ref = key_event const&; /// Key event function using func = std::function<bool(ref)>; /// List of key event listeners using listeners = std::map<id, func>; /// List of key events using list = std::vector<key_event>; /// Sender id id sender; /// Input key key_t key; /// Input action action_t action; /// Input mod mod_t mod; /// Input scan code i32 scancode = 0; /** * @brief Check if key is pressed * * @param k Key to check * * @return true Key is pressed * @return false Key is not pressed */ bool pressed(key_ref k) const { return (action == action::press) && (key == k); } /** * @brief Check if key is released * * @param k Key to check * * @return true Key is released * @return false Key is not released */ bool released(key_ref k) const { return (action == action::release) && (key == k); } /** * @brief Check if key is repeated * * @param k Key to check * * @return true Key is repeated * @return false Key is not repeated */ bool repeated(key_ref k) const { return (action == action::repeat) && (key == k); } /** * @brief Check if key is active * * @return true Key is pressed or repeated * @return false Key is not active */ bool active() const { return (action == action::press) || (action == action::repeat); } /** * @brief Check if key is pressed with mod * * @param k Key to check * @param m Mods to check * * @return true Key is pressed with mod * @return false Key is not pressed with mod */ bool pressed(key_ref k, mod_ref m) const { return pressed(k) && (mod == m); } }; /** * @brief Input scroll offset */ struct scroll_offset { /// X offset r64 x = 0.0; /// Y offset r64 y = 0.0; }; /** * @brief Scroll event */ struct scroll_event { /// Reference to scroll event using ref = scroll_event const&; /// Scroll event function using func = std::function<bool(ref)>; /// List of scroll event listeners using listeners = std::map<id, func>; /// List of scroll events using list = std::vector<scroll_event>; /// Sender id id sender; /// Input scroll offset scroll_offset offset; }; /** * @brief Input mouse position */ struct mouse_position { /// X position r64 x = 0.0; /// Y position r64 y = 0.0; }; /// Reference to mouse position using mouse_position_ref = mouse_position const&; /** * @brief Mouse move event */ struct mouse_move_event { /// Reference to mouse move event using ref = mouse_move_event const&; /// Mouse move event function using func = std::function<bool(ref)>; /// List of mouse move event listeners using listeners = std::map<id, func>; /// List of mouse move events using list = std::vector<mouse_move_event>; /// Sender id id sender; /// Input mouse position mouse_position position; }; /** * @brief Input mouse buttons */ enum class mouse_button : type { _1 = 0, _2, _3, _4, _5, _6, _7, _8, last = _8, left = _1, right = _2, middle = _3, }; /// Reference to mouse button using mouse_button_ref = mouse_button const&; /** * @brief Mouse button event */ struct mouse_button_event { /// Reference to mouse button event using ref = mouse_button_event const&; /// Mouse button event function using func = std::function<bool(ref)>; /// List of mouse button event listeners using listeners = std::map<id, func>; /// List of mouse button events using list = std::vector<mouse_button_event>; /// Sender id id sender; /// Input mouse button mouse_button button; /// Input action action_t action; /// Input mod mod_t mod; /** * @brief Check if mouse button is pressed * * @param b Mouse button to check * * @return true Mouse button is pressed * @return false Mouse button is not pressed */ bool pressed(mouse_button_ref b) const { return action == action::press && button == b; } /** * @brief Check if mouse button is released * * @param b Mouse button to check * * @return true Mouse button is released * @return false Mouse button is not released */ bool released(mouse_button_ref b) const { return action == action::release && button == b; } }; /** * @brief Path drop event */ struct path_drop_event { /// Reference to path drop event using ref = path_drop_event const&; /// Path drop event function using func = std::function<bool(ref)>; /// List of path drop event listeners using listeners = std::map<id, func>; /// List of path drop events using list = std::vector<path_drop_event>; /// Sender id id sender; /// List of files string_list files; }; /** * @brief Mouse active event */ struct mouse_active_event { /// Reference to mouse active event using ref = mouse_active_event const&; /// Mouse active event function using func = std::function<bool(ref)>; /// List of mouse active event listeners using listeners = std::map<id, func>; /// List of mouse active events using list = std::vector<mouse_active_event>; /// Sender id id sender; /// Active state bool active = false; }; /** * @brief Input callback */ struct input_callback { /// Const pointer to input callback using cptr = input_callback const*; /// List of input callbacks using list = std::vector<input_callback*>; /// List of const input callbacks using clist = std::vector<cptr>; /** * @brief Input callback functions * * @tparam T Type of callback */ template<typename T> using func = std::function<bool(typename T::ref)>; /// Called on key event key_event::func on_key_event; /// Called on scroll event scroll_event::func on_scroll_event; /// Called on mouse move event mouse_move_event::func on_mouse_move_event; /// Called on mouse button event mouse_button_event::func on_mouse_button_event; /// Called on mouse active event mouse_active_event::func on_mouse_active_event; /// Called on path drop event path_drop_event::func on_path_drop_event; }; /** * @brief List of input events * * @tparam T Type of event */ template<typename T> struct input_events : T::list { /** * @brief Add event to list * * @param event Event to add */ void add(typename T::ref event) { this->push_back(event); } /// List of event listeners id_listeners<T> listeners; }; /// List of key events using input_key_events = input_events<key_event>; /// List of scroll events using input_scroll_events = input_events<scroll_event>; /// List of mouse move events using input_mouse_move_events = input_events<mouse_move_event>; /// List of mouse button events using input_mouse_button_events = input_events<mouse_button_event>; /// List of mouse active events using input_mouse_active_events = input_events<mouse_active_event>; /// List of path drop events using input_path_drop_events = input_events<path_drop_event>; /// Input ignore result constexpr bool const input_ignore = false; /// Input done result constexpr bool const input_done = true; /** * @brief Input handling */ struct input { /// List of key events input_key_events key; /// List of scroll events input_scroll_events scroll; /// List of mouse move events input_mouse_move_events mouse_move; /// List of mouse button events input_mouse_button_events mouse_button; /// List of mouse active events input_mouse_active_events mouse_active; /// List of path drop events input_path_drop_events path_drop; /** * @brief Handle events */ void handle_events(); /** * @brief Add callback to the input handling * * @param callback Callback to add */ void add(input_callback::cptr callback) { callbacks.push_back(callback); } /** * @brief Remove callback from the input handling * * @param callback Callback to remove */ void remove(input_callback::cptr callback) { lava::remove(callbacks, callback); } /** * @brief Get the mouse position * * @return mouse_position_ref Current mouse position */ mouse_position_ref get_mouse_position() const { return current_position; } /** * @brief Set the mouse position * * @param position Current mouse position */ void set_mouse_position(mouse_position_ref position) { current_position = position; } private: /** * @brief Handle mouse events */ void handle_mouse_events(); /// Current mouse position mouse_position current_position; /// List of input callbacks input_callback::clist callbacks; }; /// Input type using input_t = input; /** * @brief Tooltip */ struct tooltip { /** * @brief Construct a new tooltip * * @param name Name of tooltip * @param key Input key * @param mod Input mod */ tooltip(string_ref name, key_t key, mod_t mod) : name(name), key(key), mod(mod) { } /// List of tooltips using list = std::vector<tooltip>; /// Name of tooltip string name; /// Input key key_t key; /// Input mod mod_t mod; }; } // namespace lava
18.217808
71
0.579216
[ "vector" ]
0446b6032de6d53aa32af747bfcff4228947475b
6,713
cpp
C++
src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.cpp
liangoaix/OpenMS
cccbc5d872320f197091596db275f35b4d0458cd
[ "Zlib", "Apache-2.0" ]
null
null
null
src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.cpp
liangoaix/OpenMS
cccbc5d872320f197091596db275f35b4d0458cd
[ "Zlib", "Apache-2.0" ]
null
null
null
src/openms/source/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.cpp
liangoaix/OpenMS
cccbc5d872320f197091596db275f35b4d0458cd
[ "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2013. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Clemens Groepl $ // $Authors: Marc Sturm, Clemens Groepl, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.h> // Derived classes are included here #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmIdentification.h> #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmLabeled.h> #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmUnlabeled.h> #include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmQT.h> #include <OpenMS/KERNEL/ConversionHelper.h> using namespace std; namespace OpenMS { //register products here void FeatureGroupingAlgorithm::registerChildren() { // deprecated: // Factory<FeatureGroupingAlgorithm>::registerProduct ( FeatureGroupingAlgorithmIdentification::getProductName(), &FeatureGroupingAlgorithmIdentification::create ); Factory<FeatureGroupingAlgorithm>::registerProduct(FeatureGroupingAlgorithmLabeled::getProductName(), &FeatureGroupingAlgorithmLabeled::create); Factory<FeatureGroupingAlgorithm>::registerProduct(FeatureGroupingAlgorithmUnlabeled::getProductName(), &FeatureGroupingAlgorithmUnlabeled::create); Factory<FeatureGroupingAlgorithm>::registerProduct(FeatureGroupingAlgorithmQT::getProductName(), &FeatureGroupingAlgorithmQT::create); } FeatureGroupingAlgorithm::FeatureGroupingAlgorithm() : DefaultParamHandler("FeatureGroupingAlgorithm") { } void FeatureGroupingAlgorithm::group(const vector<ConsensusMap> & maps, ConsensusMap & out) { LOG_WARN << "FeatureGroupingAlgorithm::group() does not support ConsensusMaps directly. Converting to FeatureMaps." << endl; vector<FeatureMap<> > maps_f; for (Size i = 0; i < maps.size(); ++i) { FeatureMap<> fm; MapConversion::convert(maps[i], true, fm); maps_f.push_back(fm); } // call FeatureMap version of group() group(maps_f, out); } void FeatureGroupingAlgorithm::transferSubelements( const vector<ConsensusMap> & maps, ConsensusMap & out) const { // accumulate file descriptions from the input maps: // cout << "Updating file descriptions..." << endl; out.getFileDescriptions().clear(); // mapping: (map index, original id) -> new id map<pair<Size, UInt64>, Size> mapid_table; for (Size i = 0; i < maps.size(); ++i) { const ConsensusMap & consensus = maps[i]; for (ConsensusMap::FileDescriptions::const_iterator desc_it = consensus.getFileDescriptions().begin(); desc_it != consensus.getFileDescriptions().end(); ++desc_it) { Size counter = mapid_table.size(); mapid_table[make_pair(i, desc_it->first)] = counter; out.getFileDescriptions()[counter] = desc_it->second; } } // look-up table: input map -> unique ID -> consensus feature // cout << "Creating look-up table..." << endl; vector<map<UInt64, ConsensusMap::ConstIterator> > feat_lookup(maps.size()); for (Size i = 0; i < maps.size(); ++i) { const ConsensusMap & consensus = maps[i]; for (ConsensusMap::ConstIterator feat_it = consensus.begin(); feat_it != consensus.end(); ++feat_it) { // do NOT use "id_lookup[i][feat_it->getUniqueId()] = feat_it;" here as // you will get "attempt to copy-construct an iterator from a singular // iterator" in STL debug mode: feat_lookup[i].insert(make_pair(feat_it->getUniqueId(), feat_it)); } } // adjust the consensus features: // cout << "Adjusting consensus features..." << endl; for (ConsensusMap::iterator cons_it = out.begin(); cons_it != out.end(); ++cons_it) { ConsensusFeature adjusted = ConsensusFeature( static_cast<BaseFeature>(*cons_it)); // remove sub-features for (ConsensusFeature::HandleSetType::const_iterator sub_it = cons_it->getFeatures().begin(); sub_it != cons_it->getFeatures().end(); ++sub_it) { UInt64 id = sub_it->getUniqueId(); Size map_index = sub_it->getMapIndex(); ConsensusMap::ConstIterator origin = feat_lookup[map_index][id]; for (ConsensusFeature::HandleSetType::const_iterator handle_it = origin->getFeatures().begin(); handle_it != origin->getFeatures().end(); ++handle_it) { FeatureHandle handle = *handle_it; Size new_id = mapid_table[make_pair(map_index, handle.getMapIndex())]; handle.setMapIndex(new_id); adjusted.insert(handle); } } *cons_it = adjusted; } } FeatureGroupingAlgorithm::~FeatureGroupingAlgorithm() { } }
45.666667
168
0.66334
[ "vector" ]
044b4d54dd91d29f408643a3e5da6d0afbda620a
685
hpp
C++
poptorch/include/poptorch/AutomaticCasting.hpp
gglin001/poptorch
61f38ed2d8c6b672e023862eb698865fa7f4724e
[ "MIT" ]
128
2020-12-08T22:22:46.000Z
2022-03-23T10:54:26.000Z
poptorch/include/poptorch/AutomaticCasting.hpp
gglin001/poptorch
61f38ed2d8c6b672e023862eb698865fa7f4724e
[ "MIT" ]
4
2021-06-22T14:26:28.000Z
2022-02-15T11:25:05.000Z
poptorch/include/poptorch/AutomaticCasting.hpp
gglin001/poptorch
61f38ed2d8c6b672e023862eb698865fa7f4724e
[ "MIT" ]
7
2020-12-09T20:32:56.000Z
2022-01-18T16:12:24.000Z
// Copyright (c) 2020 Graphcore Ltd. All rights reserved. #ifndef INCLUDE_POPTORCH_AUTOMATIC_CASTING_HPP #define INCLUDE_POPTORCH_AUTOMATIC_CASTING_HPP #include <string> #include <vector> namespace torch { namespace jit { struct Graph; } // namespace jit } // namespace torch namespace poptorch { void setAutocastEnabled(bool enabled); void setAutocastHalf(std::vector<std::string> &&ops); void setAutocastFloat(std::vector<std::string> &&ops); void setAutocastPromote(std::vector<std::string> &&ops); void setAutocastDemote(std::vector<std::string> &&ops); void automaticCasting(torch::jit::Graph *graph); } // namespace poptorch #endif // INCLUDE_POPTORCH_IMPLICIT_CASTING_HPP
26.346154
57
0.778102
[ "vector" ]
044c48554040e47ee5173fcfbf7c9c964e786938
4,367
cpp
C++
epublib/src/main/jni/NativeFormats/fbreader/src/library/Tag.cpp
zhupeipei/NovelReader
8eed755ed6da162d7f52fdf23d1bad8c63b01b10
[ "MIT" ]
2
2021-07-30T02:36:46.000Z
2021-09-04T23:04:43.000Z
epublib/src/main/jni/NativeFormats/fbreader/src/library/Tag.cpp
zhupeipei/NovelReader
8eed755ed6da162d7f52fdf23d1bad8c63b01b10
[ "MIT" ]
null
null
null
epublib/src/main/jni/NativeFormats/fbreader/src/library/Tag.cpp
zhupeipei/NovelReader
8eed755ed6da162d7f52fdf23d1bad8c63b01b10
[ "MIT" ]
2
2021-06-03T08:59:58.000Z
2021-07-30T04:42:53.000Z
/* * Copyright (C) 2009-2015 FBReader.ORG Limited <contact@fbreader.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ #include <set> #include <algorithm> #include <AndroidUtil.h> #include <JniEnvelope.h> #include <ZLUnicodeUtil.h> #include "Tag.h" TagList Tag::ourRootTags; std::map <int,shared_ptr<Tag> > Tag::ourTagsById; const std::string Tag::DELIMITER = "/"; shared_ptr<Tag> Tag::getTag(const std::string &name, shared_ptr<Tag> parent, int tagId) { if (name.empty()) { return 0; } TagList &tags = parent.isNull() ? ourRootTags : parent->myChildren; for (TagList::const_iterator it = tags.begin(); it != tags.end(); ++it) { if ((*it)->name() == name) { return *it; } } shared_ptr<Tag> t = new Tag(name, parent, tagId); tags.push_back(t); if (tagId > 0) { ourTagsById[tagId] = t; } return t; } shared_ptr<Tag> Tag::getTagByFullName(const std::string &fullName) { std::string tag = fullName; ZLUnicodeUtil::utf8Trim(tag); std::size_t index = tag.rfind(DELIMITER); if (index == std::string::npos) { return getTag(tag); } else { std::string lastName = tag.substr(index + 1); ZLUnicodeUtil::utf8Trim(lastName); return getTag(lastName, getTagByFullName(tag.substr(0, index))); } } shared_ptr<Tag> Tag::getTagById(int tagId) { std::map<int,shared_ptr<Tag> >::const_iterator it = ourTagsById.find(tagId); return it != ourTagsById.end() ? it->second : 0; } shared_ptr<Tag> Tag::cloneSubTag(shared_ptr<Tag> tag, shared_ptr<Tag> oldparent, shared_ptr<Tag> newparent) { std::vector<std::string> levels; while (tag != oldparent) { levels.push_back(tag->name()); tag = tag->parent(); if (tag.isNull()) { return 0; } } if (levels.empty()) { return 0; } shared_ptr<Tag> res = newparent; while (!levels.empty()) { res = getTag(levels.back(), res); levels.pop_back(); } return res; } void Tag::collectAncestors(shared_ptr<Tag> tag, TagList &parents) { for (; !tag.isNull(); tag = tag->parent()) { parents.push_back(tag); } std::reverse(parents.begin(), parents.end()); } void Tag::collectTagNames(std::vector<std::string> &tags) { std::set<std::string> tagsSet; TagList stack(ourRootTags); while (!stack.empty()) { shared_ptr<Tag> tag = stack.back(); stack.pop_back(); tagsSet.insert(tag->fullName()); stack.insert(stack.end(), tag->myChildren.begin(), tag->myChildren.end()); } tags.insert(tags.end(), tagsSet.begin(), tagsSet.end()); } Tag::Tag(const std::string &name, shared_ptr<Tag> parent, int tagId) : myName(name), myParent(parent), myLevel(parent.isNull() ? 0 : parent->level() + 1), myTagId(tagId), myJavaTag(0) { } Tag::~Tag() { JNIEnv *env = AndroidUtil::getEnv(); env->DeleteGlobalRef(myJavaTag); } const std::string &Tag::fullName() const { if (myParent.isNull()) { return myName; } if (myFullName.empty()) { myFullName = myParent->fullName() + DELIMITER + myName; } return myFullName; } jobject Tag::javaTag(JNIEnv *env) const { if (myJavaTag != 0) { return myJavaTag; } jobject parentTag = 0; if (!myParent.isNull()) { parentTag = myParent->javaTag(env); } jobject javaName = env->NewStringUTF(myName.c_str()); jobject tag = AndroidUtil::StaticMethod_Tag_getTag->call(parentTag, javaName); myJavaTag = env->NewGlobalRef(tag); env->DeleteLocalRef(tag); env->DeleteLocalRef(javaName); return myJavaTag; } bool Tag::isAncestorOf(shared_ptr<Tag> tag) const { if (tag->level() <= level()) { return false; } while (tag->level() > level()) { tag = tag->parent(); } return &*tag == this; } void Tag::setTagId(shared_ptr<Tag> tag, int tagId) { if (tag.isNull() || tag->myTagId != 0) { return; } tag->myTagId = tagId; ourTagsById[tagId] = tag; }
26.307229
185
0.681017
[ "vector" ]
0450732818169ceb127fbb15b731d85f38e6834b
12,632
cpp
C++
src/add-ons/kernel/interrupt_controllers/openpic/openpic.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/add-ons/kernel/interrupt_controllers/openpic/openpic.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/add-ons/kernel/interrupt_controllers/openpic/openpic.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2006, Ingo Weinhold <bonefish@cs.tu-berlin.de>. * All rights reserved. Distributed under the terms of the MIT License. */ /*- * Copyright (C) 2002 Benno Rice. * 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 Benno Rice ``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 TOOLS GMBH 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. * * $FreeBSD$ */ #include <stdio.h> #include <string.h> #include <ByteOrder.h> #include <KernelExport.h> #include <AutoDeleter.h> #include <bus/PCI.h> #include <interrupt_controller.h> #include <util/kernel_cpp.h> #include "openpic.h" #define OPENPIC_MODULE_NAME "interrupt_controllers/openpic/device_v1" enum { OPENPIC_MIN_REGISTER_SPACE_SIZE = 0x21000, OPENPIC_MAX_REGISTER_SPACE_SIZE = 0x40000, }; struct openpic_supported_device { const char *name; uint16 vendor_id; uint16 device_id; uint32 register_offset; }; static openpic_supported_device sSupportedDevices[] = { { "Intrepid I/O Controller", 0x106b, 0x003e, 0x40000 }, {} }; static device_manager_info *sDeviceManager; static pci_module_info *sPCIBusManager; struct openpic_info : interrupt_controller_info { openpic_info() { memset(this, 0, sizeof(openpic_info)); register_area = -1; } ~openpic_info() { // unmap registers) if (register_area >= 0) delete_area(register_area); // uninit parent node driver if (pci) //XXX do I mean it ? sDeviceManager->put_node(sDeviceManager->get_parent_node(node)); } openpic_supported_device *supported_device; device_node *node; pci_device_module_info *pci; pci_device *device; addr_t physical_registers; // physical registers base addr_t virtual_registers; // virtual (mapped) // registers base area_id register_area; // register area size_t register_space_size; }; static openpic_supported_device * openpic_check_supported_device(uint16 vendorID, uint16 deviceID) { for (openpic_supported_device *supportedDevice = sSupportedDevices; supportedDevice->name; supportedDevice++) { if (supportedDevice->vendor_id == vendorID && supportedDevice->device_id == deviceID) { return supportedDevice; } } return NULL; } static uint32 openpic_read(openpic_info *info, int reg) { return B_SWAP_INT32(info->pci->read_io_32(info->device, info->virtual_registers + reg)); } static void openpic_write(openpic_info *info, int reg, uint32 val) { info->pci->write_io_32(info->device, info->virtual_registers + reg, B_SWAP_INT32(val)); } static int openpic_read_irq(openpic_info *info, int cpu) { return openpic_read(info, OPENPIC_IACK(cpu)) & OPENPIC_VECTOR_MASK; } static void openpic_eoi(openpic_info *info, int cpu) { openpic_write(info, OPENPIC_EOI(cpu), 0); // the Linux driver does this: //openpic_read(info, OPENPIC_EOI(cpu)); } static void openpic_enable_irq(openpic_info *info, int irq, int type) { // TODO: Align this code with the sequence recommended in the Open PIC // Specification (v 1.2 section 5.2.2). uint32 x; x = openpic_read(info, OPENPIC_SRC_VECTOR(irq)); x &= ~(OPENPIC_IMASK | OPENPIC_SENSE_LEVEL | OPENPIC_SENSE_EDGE); if (type == IRQ_TYPE_LEVEL) x |= OPENPIC_SENSE_LEVEL; else x |= OPENPIC_SENSE_EDGE; openpic_write(info, OPENPIC_SRC_VECTOR(irq), x); } static void openpic_disable_irq(openpic_info *info, int irq) { uint32 x; x = openpic_read(info, OPENPIC_SRC_VECTOR(irq)); x |= OPENPIC_IMASK; openpic_write(info, OPENPIC_SRC_VECTOR(irq), x); } static void openpic_set_priority(openpic_info *info, int cpu, int pri) { uint32 x; x = openpic_read(info, OPENPIC_CPU_PRIORITY(cpu)); x &= ~OPENPIC_CPU_PRIORITY_MASK; x |= pri; openpic_write(info, OPENPIC_CPU_PRIORITY(cpu), x); } static status_t openpic_init(openpic_info *info) { uint32 x = openpic_read(info, OPENPIC_FEATURE); const char *featureVersion; char versionBuffer[64]; switch (x & OPENPIC_FEATURE_VERSION_MASK) { case 1: featureVersion = "1.0"; break; case 2: featureVersion = "1.2"; break; case 3: featureVersion = "1.3"; break; default: snprintf(versionBuffer, sizeof(versionBuffer), "unknown (feature reg: 0x%lx)", x); featureVersion = versionBuffer; break; } info->cpu_count = ((x & OPENPIC_FEATURE_LAST_CPU_MASK) >> OPENPIC_FEATURE_LAST_CPU_SHIFT) + 1; info->irq_count = ((x & OPENPIC_FEATURE_LAST_IRQ_MASK) >> OPENPIC_FEATURE_LAST_IRQ_SHIFT) + 1; /* * PSIM seems to report 1 too many IRQs */ // if (sc->sc_psim) // sc->sc_nirq--; dprintf("openpic: Version %s, supports %d CPUs and %d irqs\n", featureVersion, info->cpu_count, info->irq_count); /* disable all interrupts */ for (int irq = 0; irq < info->irq_count; irq++) openpic_write(info, OPENPIC_SRC_VECTOR(irq), OPENPIC_IMASK); openpic_set_priority(info, 0, 15); /* we don't need 8259 passthrough mode */ x = openpic_read(info, OPENPIC_CONFIG); x |= OPENPIC_CONFIG_8259_PASSTHRU_DISABLE; openpic_write(info, OPENPIC_CONFIG, x); /* send all interrupts to cpu 0 */ for (int irq = 0; irq < info->irq_count; irq++) openpic_write(info, OPENPIC_IDEST(irq), 1 << 0); for (int irq = 0; irq < info->irq_count; irq++) { x = irq; x |= OPENPIC_IMASK; x |= OPENPIC_POLARITY_POSITIVE; x |= OPENPIC_SENSE_LEVEL; x |= 8 << OPENPIC_PRIORITY_SHIFT; openpic_write(info, OPENPIC_SRC_VECTOR(irq), x); } /* XXX IPI */ /* XXX set spurious intr vector */ openpic_set_priority(info, 0, 0); /* clear all pending interrupts */ for (int irq = 0; irq < info->irq_count; irq++) { openpic_read_irq(info, 0); openpic_eoi(info, 0); } return B_OK; } // #pragma mark - driver interface static status_t openpic_std_ops(int32 op, ...) { switch (op) { case B_MODULE_INIT: case B_MODULE_UNINIT: return B_OK; default: return B_ERROR; } } static float openpic_supports_device(device_node *parent) { const char *bus; uint16 vendorID; uint16 deviceID; // get the bus (should be PCI) if (sDeviceManager->get_attr_string(parent, B_DEVICE_BUS, &bus, false) != B_OK) { return B_ERROR; } // get vendor and device ID if (sDeviceManager->get_attr_uint16(parent, B_DEVICE_VENDOR_ID, &vendorID, false) != B_OK || sDeviceManager->get_attr_uint16(parent, B_DEVICE_ID, &deviceID, false) != B_OK) { return B_ERROR; } // check, whether bus, vendor and device ID match if (strcmp(bus, "pci") != 0 || !openpic_check_supported_device(vendorID, deviceID)) { return 0.0; } return 0.6; } static status_t openpic_register_device(device_node *parent) { device_node *newNode; device_attr attrs[] = { // info about ourself { B_DEVICE_TYPE, B_UINT16_TYPE, { ui16: PCI_base_peripheral }}, { B_DEVICE_SUB_TYPE, B_UINT16_TYPE, { ui16: PCI_pic }}, // TODO How do we identify ourselves as OpenPIC? { B_DEVICE_INTERFACE, B_UINT16_TYPE, { ui16: PCI_pic_8259 }}, {} }; io_resource resources[] = { // TODO Fill in whatever necessary {} }; return sDeviceManager->register_node(parent, OPENPIC_MODULE_NAME, attrs, resources, &newNode); } static status_t openpic_init_driver(device_node *node, void **cookie) { openpic_info *info = new(nothrow) openpic_info; if (!info) return B_NO_MEMORY; ObjectDeleter<openpic_info> infoDeleter(info); info->node = node; // get interface to PCI device void *aCookie; status_t status = sDeviceManager->get_driver(sDeviceManager->get_parent_node(node), (driver_module_info**)&info->pci, &aCookie); if (status != B_OK) return status; info->pci->info.init_driver(node, (void**)&info->device); // get the pci info for the device pci_info pciInfo; info->pci->get_pci_info(info->device, &pciInfo); // find supported device info info->supported_device = openpic_check_supported_device(pciInfo.vendor_id, pciInfo.device_id); if (!info->supported_device) { dprintf("openpic: device (0x%04hx:0x%04hx) not supported\n", pciInfo.vendor_id, pciInfo.device_id); return B_ERROR; } dprintf("openpic: found supported device: %s (0x%04hx:0x%04hx)\n", info->supported_device->name, pciInfo.vendor_id, pciInfo.device_id); // get register space addr_t physicalRegisterBase = pciInfo.u.h0.base_registers[0]; uint32 registerSpaceSize = pciInfo.u.h0.base_register_sizes[0]; if (registerSpaceSize < info->supported_device->register_offset || registerSpaceSize - info->supported_device->register_offset < OPENPIC_MIN_REGISTER_SPACE_SIZE) { dprintf("openpic: register space too small\n"); } physicalRegisterBase += info->supported_device->register_offset; registerSpaceSize -= info->supported_device->register_offset; if (registerSpaceSize > OPENPIC_MAX_REGISTER_SPACE_SIZE) registerSpaceSize = OPENPIC_MAX_REGISTER_SPACE_SIZE; // map register space void *virtualRegisterBase = NULL; area_id registerArea = map_physical_memory("openpic registers", physicalRegisterBase, registerSpaceSize, B_ANY_KERNEL_ADDRESS, B_KERNEL_READ_AREA | B_KERNEL_WRITE_AREA, &virtualRegisterBase); if (registerArea < 0) return info->register_area; info->physical_registers = physicalRegisterBase; info->register_space_size = registerSpaceSize; info->register_area = registerArea; info->virtual_registers = (addr_t)virtualRegisterBase; // init the controller status = openpic_init(info); if (status != B_OK) return status; // keep the info infoDeleter.Detach(); *cookie = info; dprintf("openpic_init_driver(): Successfully initialized!\n"); return B_OK; } static void openpic_uninit_driver(void *cookie) { openpic_info *info = (openpic_info*)cookie; delete info; } static status_t openpic_register_child_devices(void *cookie) { return B_OK; } static status_t openpic_rescan_child_devices(void *cookie) { return B_OK; } static void openpic_device_removed(void *driverCookie) { // TODO: ... } // #pragma mark - interrupt_controller interface static status_t openpic_get_controller_info(void *cookie, interrupt_controller_info *_info) { if (!_info) return B_BAD_VALUE; openpic_info *info = (openpic_info*)cookie; *_info = *info; return B_OK; } static status_t openpic_enable_io_interrupt(void *cookie, int irq, int type) { openpic_info *info = (openpic_info*)cookie; openpic_enable_irq(info, irq, type); return B_OK; } static status_t openpic_disable_io_interrupt(void *cookie, int irq) { openpic_info *info = (openpic_info*)cookie; openpic_disable_irq(info, irq); return B_OK; } static int openpic_acknowledge_io_interrupt(void *cookie) { openpic_info *info = (openpic_info*)cookie; int cpu = 0; // Note: We direct all I/O interrupts to CPU 0. We could nevertheless // check against the value of the "Who Am I Register". int irq = openpic_read_irq(info, cpu); if (irq == 255) return -1; // spurious interrupt // signal end of interrupt openpic_eoi(info, cpu); return irq; } static interrupt_controller_module_info sControllerModuleInfo = { { { OPENPIC_MODULE_NAME, 0, openpic_std_ops }, openpic_supports_device, openpic_register_device, openpic_init_driver, openpic_uninit_driver, openpic_register_child_devices, openpic_rescan_child_devices, openpic_device_removed, NULL, // suspend NULL // resume }, openpic_get_controller_info, openpic_enable_io_interrupt, openpic_disable_io_interrupt, openpic_acknowledge_io_interrupt, }; module_dependency module_dependencies[] = { { B_DEVICE_MANAGER_MODULE_NAME, (module_info **)&sDeviceManager }, { B_PCI_MODULE_NAME, (module_info**)&sPCIBusManager}, {} }; module_info *modules[] = { (module_info *)&sControllerModuleInfo, NULL };
23.699812
84
0.735275
[ "vector" ]
0451befa2ef14b1c93b15f28eb7591d2ff57a357
40,668
cpp
C++
third_party/nuke/lib/Fuser/SceneXform.cpp
jonntd/dwa_usd_plugins
e1aacff9d3670f364e18ae352ece53a734c93dff
[ "Apache-2.0" ]
2
2019-08-08T15:55:32.000Z
2020-05-16T05:56:36.000Z
third_party/nuke/lib/Fuser/SceneXform.cpp
lucienfostier/dwa_usd_plugins
e1aacff9d3670f364e18ae352ece53a734c93dff
[ "Apache-2.0" ]
null
null
null
third_party/nuke/lib/Fuser/SceneXform.cpp
lucienfostier/dwa_usd_plugins
e1aacff9d3670f364e18ae352ece53a734c93dff
[ "Apache-2.0" ]
1
2020-03-25T06:31:03.000Z
2020-03-25T06:31:03.000Z
// // Copyright 2019 DreamWorks Animation // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // /// @file Fuser/FuserSceneXform.cpp /// /// @author Jonathan Egstad #include "SceneXform.h" #include "NukeKnobInterface.h" // for getVec3Knob #include "AxisOp.h" #include "CameraOp.h" #include "LightOp.h" #include <DDImage/ViewerContext.h> // for display3d_names_source string list #include <DDImage/ArrayKnobI.h> // for ArrayKnobI::ValueProvider // Do we want to expose parenting scale? //#define ENABLE_PARENT_SCALE 1 //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ namespace Fsr { /*! 'class WorldMatrixProvider' is declared in DDImage::AxisOp.h as an opaque pointer and is likely implemented inside the AxisOp class, but since we can't see its implementation from outside we need to reimplement it here... This may fail miserably but we'll attempt to override the one in the AxisOp base class since the pointer is exposed as protected. From checking the value of that pointer it appears to be set during the AxisOp::knobs() method, so we'll do the same in SceneXform::_addAxisOpKnobs(). At least it's a double-precision interface so we can provide values from a Fsr::Mat4d! :) */ class WorldMatrixProvider : public DD::Image::ArrayKnobI::ValueProvider { protected: Fsr::SceneXform* m_xform; Fsr::AxisKnobWrapper* m_xform_knob; public: //! WorldMatrixProvider(Fsr::SceneXform* xform, Fsr::AxisKnobWrapper* xform_knob) : m_xform(xform), m_xform_knob(xform_knob) { // } /*! This function should return true if the knob is presently an output knob. This allows this functionality to be toggled on/off without (with a bool knob for example) without having to call ->setValueProvider() after the initial setup. */ /*virtual*/ bool provideValuesEnabled(const DD::Image::ArrayKnobI*, const DD::Image::OutputContext&) const { return true; } /*! This function should return the values to be displayed in the output knob. The vector must match the array_size() of the Array_Knob. */ /*virtual*/ std::vector<double> provideValues(const DD::Image::ArrayKnobI*, const DD::Image::OutputContext& context) const { // Get the concatenated world matrix at the OutputContext: assert(m_xform); const Fsr::Mat4d m = m_xform->getWorldTransformAt(context); // Swap row/column order: std::vector<double> array(16); for (int i=0; i < 16; ++i) array[i] = m[i%4][i/4]; return array; } }; //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ // TODO: putting these implementations here for now: // These match the order of enums in Fsr::Mat4 and Fsr::Vec3. // The strings defined also match the corresponding string arrays in DD::Image // so that Enumeration_Knobs using these save the thing as stock Nuke: /*extern*/ const char* xform_orders[] = { "SRT", "STR", "RST", "RTS", "TSR", "TRS", 0 }; /*extern*/ const char* axis_directions[] = { "-X", "+X", "-Y", "+Y", "-Z", "+Z", 0 }; /*extern*/ const char* rotation_orders[] = { "XYZ", "XZY", "YXZ", "YZX", "ZXY", "ZYX", 0 }; //----------------------------------------- // These match the strings in DD::Image::LookAt so Enumeration_Knobs using these // save the same thing as stock Nuke: /*static*/ const char* const Lookat::method_list[] = { "vectors", "quaternions", 0 }; /*! */ Lookat::Lookat() : k_lookat_enable(true), k_lookat_axis((int)Fsr::AXIS_Z_PLUS), k_lookat_do_rx(true), k_lookat_do_ry(true), k_lookat_do_rz(true), k_lookat_method(USE_VECTORS), k_lookat_mix(1.0) { // } /*! */ void Lookat::addLookatKnobs(DD::Image::Knob_Callback f, const char* label) { //DD::Image::Text_knob(f, label); DD::Image::Bool_knob(f, &k_lookat_enable, "lookat_enable", "enable"); DD::Image::Bool_knob(f, &k_lookat_do_rx, "lookat_rx", "x rot"); DD::Image::Bool_knob(f, &k_lookat_do_ry, "lookat_ry", "y rot"); DD::Image::Bool_knob(f, &k_lookat_do_rz, "lookat_rz", "z rot"); // DD::Image::Enumeration_knob(f, &k_lookat_method, method_list, "lookat_method", "method"); DD::Image::SetFlags(f, DD::Image::Knob::STARTLINE); DD::Image::Enumeration_knob(f, &k_lookat_axis, axis_directions, "lookat_align_axis", "align axis"); DD::Image::ClearFlags(f, DD::Image::Knob::STARTLINE); DD::Image::Tooltip(f, "Selects which axis points towards the lookat point."); // DD::Image::Double_knob(f, &k_lookat_mix, "lookat_mix", "mix"); DD::Image::SetFlags(f, DD::Image::Knob::STARTLINE | DD::Image::Knob::NO_MULTIVIEW); DD::Image::SetFlags(f, DD::Image::Knob::NO_MULTIVIEW); DD::Image::Tooltip(f, "How much the lookat rotations affect the output rotations."); } /*! */ void Lookat::appendLookatHash(DD::Image::Hash& hash) const { if (!k_lookat_enable) return; hash.append(k_lookat_axis); hash.append(k_lookat_do_rx); hash.append(k_lookat_do_ry); hash.append(k_lookat_do_rz); hash.append(k_lookat_method); hash.append(k_lookat_mix); } //------------------------------------------------------------------------------------ //------------------------------------------------------------------------------------ #ifdef FUSER_USE_KNOB_RTTI const char* SceneXformRTTIKnob = "FsrSceneXform"; #endif /*! */ SceneXform::SceneXform() : SceneOpExtender(), m_input_xform(NULL), kParentTranslate(NULL), kParentRotate(NULL), kParentScale(NULL), kAxisKnob(NULL), kFsrAxisKnob(NULL) { // //std::cout << "SceneXform::ctor(" << this << ")" << std::endl; } /*! Returns true if Op is a Fuser SceneXform. For a statically-linked Fuser lib this is a hack - we test for a dummy knob so we can test the class without using RTTI which fails when dso plugins are statically linked to this class. */ /*static*/ bool SceneXform::isSceneXform(DD::Image::Op* op) { #ifdef FUSER_USE_KNOB_RTTI // HACK!!!!: Test for dummy knob so we can test for class without using RTTI...: return (op && op->knob(SceneXformRTTIKnob) != NULL); #else // TODO: this probably does not work due to multiple-inheritance...: return (dynamic_cast<SceneXform*>(op) != NULL); #endif } /*! Returns op cast to Fuser SceneXform if possible, otherwise NULL. For a statically-linked Fuser lib this is a hack - we test for a dummy knob so we can test the class without using RTTI which fails when dso plugins are statically linked to this class. */ /*static*/ SceneXform* SceneXform::asSceneXform(DD::Image::Op* op) { if (!op || !isSceneXform(op)) return NULL; //----------------------------------------------------------------------------- // This crap is required to get around the wonky way we're multiple-inheriting // from DD::Image::AxisOp/CameraOp/LightOp and the SceneXform classes. // We can't static_cast directly to a SceneXform as we need the fundamental // class first, ie FuserAxisOp/FuserCameraOp/FuserLightOp: //----------------------------------------------------------------------------- FuserAxisOp* axis = FuserAxisOp::asFuserAxisOp(op); if (axis) return static_cast<Fsr::SceneXform*>(axis); FuserCameraOp* camera = FuserCameraOp::asFuserCameraOp(op); if (camera) return static_cast<Fsr::SceneXform*>(camera); FuserLightOp* light = FuserLightOp::asFuserLightOp(op); if (light) return static_cast<Fsr::SceneXform*>(light); return NULL; } //! /*virtual*/ int SceneXform::xformInputs() const { const int parent_input = parentingInput(); const int lookat_input = lookatInput(); // Add parent and lookat inputs if valid: int inputs = (parent_input >= 0)?1:0; if (lookat_input >= 0 && lookat_input != parent_input) ++inputs; return inputs; } //! /*virtual*/ bool SceneXform::testInput(int input, DD::Image::Op* op) const { const int parent_input = parentingInput(); const int lookat_input = lookatInput(); if (input == parent_input) { // Allow *only* AxisOp connections on parent input: DD::Image::AxisOp* axis = dynamic_cast<DD::Image::AxisOp*>(op); if (axis) return true; } else if (input == lookat_input) { // Lookat input only supports AxisOps for now: DD::Image::AxisOp* axis = dynamic_cast<DD::Image::AxisOp*>(op); if (axis) return true; // TODO: allow lookat to support objects in GeometryList! //DD::Image::GeoOp* geo = dynamic_cast<DD::Image::GeoOp*>(op); //if (geo) // return true; } return false; } /*! Return the Op to connect to this input if the arrow is disconnected in Nuke, or if the Op Nuke tries fails the test_input() test. */ /*virtual*/ DD::Image::Op* SceneXform::defaultInput(int input) const { const int parent_input = parentingInput(); const int lookat_input = lookatInput(); if (input == parent_input) return NULL; // allow null Op on parent input else if (input == lookat_input) return NULL; // allow null Op on lookat input return NULL; } //! /*virtual*/ const char* SceneXform::inputLabel(int input, char* buffer) const { const int parent_input = parentingInput(); const int lookat_input = lookatInput(); if (input == parent_input) return "parent"; else if (input == lookat_input) return "look"; return buffer; } //------------------------------------------------------------------------------------ /*! Call this from owner (FuserAxisOp, FuserCameraOp, FuserLightOp)::knobs() to replace the AxisKnob knobs. Adds the local transform knobs matching the typical AxisKnob ones. This is valid as of Nuke 12. */ void SceneXform::_addOpTransformKnobs(DD::Image::Knob_Callback f, DD::Image::Matrix4* localtransform) { assert(localtransform); // Add the stock single-precision Axis_knob. We still need to create it since there's // internal Nuke logic that crashes if this doesn't exist on the Op. The Axis_knob // creates the child knobs 'translate', 'rotate', 'scaling', etc: kAxisKnob = DD::Image::Axis_knob(f, localtransform, "transform", NULL/*label*/); // Add our double-precision Fsr::AxisKnob which calculates a parallel double-precision // matrix from the same child knobs as the stock Axis_knob. This relies on the // DD::Image::Axis_knob macro being called out separately: kFsrAxisKnob = static_cast<Fsr::AxisKnobWrapper*>(Fsr::AxisKnobWrapper_knob(f, &m_local_matrix, SceneXformRTTIKnob)); } /*! Call this from owner (FuserAxisOp, FuserCameraOp, FuserLightOp)::knobs() to replace the AxisOp baseclass' knobs() implementation. Adds the local transform knobs matching the AxisOp base class. If the AxisOp class gets additional knob vars added in newer Nuke versions this will need to be updated! This is valid as of Nuke 11.3. In AxisOp.h: Matrix4 localtransform_; //!< Local matrix that Axis_Knob fills in Matrix4 local_; //!< Local matrix after look at performed Matrix4 matrix_; //!< Object matrix - local&parent Matrix4 imatrix_; //!< Inverse object matrix bool inversion_updated; //!< Whether imatrix_ is valid Axis_KnobI* axis_knob; //!< reference to the transformation knob WorldMatrixProvider* _worldMatrixProvider; */ void SceneXform::_addAxisOpTransformKnobs(DD::Image::Knob_Callback f, DD::Image::Matrix4* localtransform, DD::Image::Axis_KnobI** axis_knob, DD::Image::WorldMatrixProvider** worldMatrixProvider) { assert(localtransform); assert(axis_knob); assert(worldMatrixProvider); _addOpTransformKnobs(f, localtransform); // Assign the Axis_KnobI interface pointer on the AxisOp base class: if (f.makeKnobs()) *axis_knob = kAxisKnob->axisKnob(); DD::Image::BeginGroup(f, "", "World matrix"); { DD::Image::SetFlags(f, DD::Image::Knob::CLOSED); // Create the world matrix output array - these are doubles internally! DD::Image::Knob* kWorldMatrixKnob = DD::Image::Array_knob(f, NULL/*array*/, 4/*w*/, 4/*h*/, "world_matrix", ""); DD::Image::SetFlags(f, DD::Image::Knob::STARTLINE | DD::Image::Knob::DO_NOT_WRITE); DD::Image::Tooltip(f, "The world matrix is read-only and allows you to see and expression link " "to the completely concatenated (world) matrix of this op."); DD::Image::SetFlags(f, DD::Image::Knob::ENDLINE); // Create the output value provider for the matrix knob. // Only override base class with our Fsr::Mat4d provider class if // it's not already assigned to avoid any possible conflict/crash: if (kWorldMatrixKnob && f.makeKnobs() && *worldMatrixProvider == NULL) { Fsr::WorldMatrixProvider* wmp = new WorldMatrixProvider(this, kFsrAxisKnob); assert(wmp); // Assign the value provider pointer on the AxisOp base class: DD::Image::ArrayKnobI* array = dynamic_cast<DD::Image::ArrayKnobI*>(kWorldMatrixKnob); assert(array); array->setValueProvider(wmp); // Store into AxisOp cast to DD::Image::WorldMatrixProvider - hopefully this works! *worldMatrixProvider = reinterpret_cast<DD::Image::WorldMatrixProvider*>(wmp); } } DD::Image::EndGroup(f); } //------------------------------------------------------------------------------------ /*! */ /*virtual*/ void SceneXform::addParentingKnobs(DD::Image::Knob_Callback f, bool group_open) { //std::cout << " SceneXform::addParentingKnobs(" << this << ") makeKnobs=" << f.makeKnobs() << std::endl; //DD::Image::Divider(f, "Parent constraint"); //---------------------------------------- //DD::Image::BeginGroup(f, "", "@b;Parent constraint"); { //if (group_open) // DD::Image::ClearFlags(f, DD::Image::Knob::CLOSED); //else // DD::Image::SetFlags(f, DD::Image::Knob::CLOSED); // XYZ_knob is always floats but we don't want to store floats, so // point the knobs at a dummy value and later use Knob::store() to get // the underlying doubles: DD::Image::Vector3 dflt(0.0f, 0.0f, 0.0f); kParentTranslate = DD::Image::XYZ_knob(f, &dflt.x, "parent_translate", "parent translate"); DD::Image::SetFlags(f, DD::Image::Knob::NO_HANDLES); DD::Image::Tooltip(f, "This translate is applied prior to the local transform allowing a " "parenting hierarchy to be kept separate from the local transform.\n" "\n" "When loading xform node data from a scene file the node's parent " "transform can be placed here.\n"); kParentRotate = DD::Image::XYZ_knob(f, &dflt.x, "parent_rotate", "parent rotate"); DD::Image::SetFlags(f, DD::Image::Knob::NO_HANDLES); DD::Image::Tooltip(f, "This rotate is applied prior to the local transform allowing a " "parenting hierarchy to be kept separate from the local transform.\n" "\n" "When loading xform node data from a scene file the node's parent " "transform can be placed here.\n"); #ifdef ENABLE_PARENT_SCALE kParentScale = DD::Image::XYZ_knob(f, &dflt.x, "parent_scale", "parent scale"); DD::Image::SetFlags(f, DD::Image::Knob::NO_HANDLES); DD::Image::Tooltip(f, "This scale is applied prior to the local transform allowing a " "parenting hierarchy to be kept separate from the local transform.\n" "\n" "When loading xform node data from a scene file the node's parent " "transform can be placed here.\n"); #else // Create a dummy knob so that scripts load without failure and the scene loaders don't fail. // But since we're not setting kParentScale the transform code will not fail either. DD::Image::XYZ_knob(f, &dflt.x, "parent_scale", DD::Image::INVISIBLE); DD::Image::SetFlags(f, DD::Image::Knob::DO_NOT_WRITE | DD::Image::Knob::NO_ANIMATION | DD::Image::Knob::NO_RERENDER); #endif } //DD::Image::EndGroup(f); //---------------------------------------- #if 0 //DD::Image::Bool_knob(f, &k_parent_xform_enable, "parent_transform_enable", "parent enable"); // DD::Image::SetFlags(f, DD::Image::Knob::EARLY_STORE); // DD::Image::Tooltip(f, "If enabled this transform is applied prior to the local transform, " // "allowing the parenting hierarchy to be kept separate from the local " // "transform.\n" // "\n" // "When loading xform node data from a scene file the node's parent transform " // "is placed here when this is enabled. If not enabled the parent transform " // "is combined with the node's local transform.\n"); //DD::Image::Bool_knob(f, &k_parent_xform_live, "parent_transform_live", "update from input"); // DD::Image::SetFlags(f, DD::Image::Knob::EARLY_STORE); // DD::Image::Tooltip(f, "If enabled the parent transform knobs are updated live from the current parenting " // "connection of this node.\n"); #endif } /*! */ /*virtual*/ void SceneXform::addLookatKnobs(DD::Image::Knob_Callback f) { //std::cout << " SceneXform::addLookatKnobs() makeKnobs=" << f.makeKnobs() << std::endl; //DD::Image::Divider(f, "@b;Lookat Constraint"); //---------------------------------------- DD::Image::BeginGroup(f, "lookat", "@b;Lookat Constraint"); { //if (m_group_open) // DD::Image::ClearFlags(f, DD::Image::Knob::CLOSED); //else // DD::Image::SetFlags(f, DD::Image::Knob::CLOSED); DD::Image::ClearFlags(f, DD::Image::Knob::CLOSED); //DD::Image::SetFlags(f, DD::Image::Knob::CLOSED); m_lookat.addLookatKnobs(f, "lookat"/*label*/); } DD::Image::EndGroup(f); //---------------------------------------- } //------------------------------------------------------------------------------------ /*! */ /*virtual*/ int SceneXform::knobChanged(DD::Image::Knob* k, int call_again) { //std::cout << "SceneXform::knobChanged('" << k->name() << "')" << std::endl; #if 0 DD::Image::Op* op = sceneOp(); #ifdef DEBUG assert(op); #endif if (k == &DD::Image::Knob::showPanel) { const int parent_input = parentingInput(); if (parent_input < 0) enableParentTransformKnobs(true); else enableParentTransformKnobs(dynamic_cast<DD::Image::AxisOp*>(op->input(parent_input))); //enableLocalTransformKnobs(k_scene.read_enabled); call_again = 1; // we want to be called again } else if (k == &DD::Image::Knob::inputChange) { // Note - this only gets called if the panel is open, don't use // it to check for a general input change: //std::cout << "inputChanged input0=" << op->input(0) << std::endl; enableParentTransformKnobs(k_parent_xform_enable); call_again = 1; // we want to be called again } #endif return call_again; } /*! */ /*virtual*/ void SceneXform::enableParentTransformKnobs(bool parent_xform_enabled) { //DD::Image::Op* op = sceneOp(); #ifdef DEBUG //assert(op); #endif //DD::Image::Knob* k; k = op->knob("parent_transform_live"); if (k) k->enable(parent_xform_enabled); if (kParentTranslate) kParentTranslate->enable(parent_xform_enabled); if (kParentRotate ) kParentRotate->enable(parent_xform_enabled); if (kParentScale ) kParentScale->enable(parent_xform_enabled); } /*! */ /*virtual*/ void SceneXform::enableLocalTransformKnobs(bool read_enabled) { DD::Image::Op* op = sceneOp(); #ifdef DEBUG assert(op); #endif DD::Image::Knob* k; // turn on local controls if not reading from file: const bool local_enabled = (!read_enabled); k = op->knob("transform" ); if (k) k->enable(local_enabled); k = op->knob("uniform_scale"); if (k) k->visible(local_enabled); k = op->knob("skew" ); if (k) k->visible(local_enabled); k = op->knob("pivot" ); if (k) k->visible(local_enabled); } /*! */ /*virtual*/ void SceneXform::enableSceneXformExtraKnobs(bool read_enabled) { // base class does nothing } //------------------------------------------------------------------------------------ /*! Call this from owner (AxisOp-subclass)::_validate() to replace the AxisOp baseclass' _validate() implementation. Builds the double-precision matrices replacing the stock single-precision ones, then saves that result in the single-precision ones so that built in code still works. Since the concatenation of the world matrix is done in double-precision there's a better chance that the final single-precision ones aren't as badly degraded. Any code that knows about the Fsr::SceneXform class can get direct access to the double-precision ones. If the AxisOp class gets additional transform vars added in newer Nuke versions this will need to be updated! This is valid as of Nuke 11.3. In AxisOp.h: Matrix4 localtransform_; //!< Local matrix that Axis_Knob fills in Matrix4 local_; //!< Local matrix after look at performed Matrix4 matrix_; //!< Object matrix - local&parent Matrix4 imatrix_; //!< Inverse object matrix bool inversion_updated; //!< Whether imatrix_ is valid */ void SceneXform::_validateAxisOpMatrices(bool for_real, DD::Image::Matrix4* localtransform, DD::Image::Matrix4* local, DD::Image::Matrix4* matrix, bool* inversion_updated) { #if 1//def DEBUG assert(localtransform); assert(local); assert(matrix); assert(inversion_updated); #endif DD::Image::Op* op = const_cast<SceneXform*>(this)->sceneOp(); #ifdef DEBUG assert(op); #endif //std::cout << "SceneXform('" << op->node_name() << "' " << this << ")::_validateAxisOpMatrices()"; //std::cout << " frame=" << op->outputContext().frame() << ", view=" << op->outputContext().view() << std::endl; // This logic is also implemented in getInputParentTransformAt(), but this // one assumes the input Op has the same OutputContext, and also gets // m_input_xform pointer: const int parent_input = parentingInput(); if (parent_input < 0) { // Locally defined parent source m_input_xform = NULL; m_input_matrix.setToIdentity(); // TODO: what to do here? Likely need to call a virtual function on subclass. } else { DD::Image::AxisOp* parent_axis = dynamic_cast<DD::Image::AxisOp*>(op->input(parent_input)); if (parent_axis) { parent_axis->validate(for_real); m_input_xform = asSceneXform(parent_axis); //std::cout << " parent='" << op->input(parent_input)->node_name() << "' m_input_xform=" << m_input_xform << std::endl; if (m_input_xform) m_input_matrix = m_input_xform->getWorldTransform(); else m_input_matrix = Fsr::Mat4d(parent_axis->matrix()); // single-precision parent } else m_input_matrix.setToIdentity(); } // Extract the local transform from the Axis_Knob knobs, build the parent // transform and lookat rotations, then produce double-precision matrices // from the lot to use: m_parent_matrix = getParentConstraintTransformAt(op->outputContext()); m_local_matrix = getLocalTransformAt(op->outputContext()); #if 0 applyLookatTransformAt(concat_matrix, op->outputContext()); #endif m_world_matrix = m_input_matrix; m_world_matrix *= m_parent_matrix; m_world_matrix *= m_local_matrix; // Update the single-precision matrices in the AxisOp base class: m_local_matrix.toDDImage(*localtransform); // overwrite AxisKnob...? m_local_matrix.toDDImage(*local); // (with lookat) m_world_matrix.toDDImage(*matrix); *inversion_updated = false; // invalidate the inverted matrix. //std::cout << " input_matrix" << m_input_matrix << std::endl; //std::cout << " parent_matrix" << m_parent_matrix << std::endl; //std::cout << " local_matrix" << m_local_matrix << std::endl; //std::cout << " world_matrix" << m_world_matrix << std::endl; //std::cout << " localtransform_" << *localtransform << std::endl; //std::cout << " local_" << *local << std::endl; //std::cout << " matrix_" << *matrix << std::endl; //std::cout << " inversion_updated=" << *inversion_updated << std::endl; } /*! Builds the input transform matrix. Will be identity if no input. */ /*virtual*/ Fsr::Mat4d SceneXform::getInputParentTransformAt(const DD::Image::OutputContext& context) const { //std::cout << " SceneXform('" << const_cast<SceneXform*>(this)->sceneOp()->node_name() << "' " << this << ")::getInputParentTransformAt()" << std::endl; const int parent_input = parentingInput(); if (parent_input < 0) { // Locally defined parent source: // TODO: what to do here? I assume we should call a virtual method to // get matrix from subclass. return Fsr::Mat4d::getIdentity(); } DD::Image::Op* op = const_cast<SceneXform*>(this)->sceneOp(); #ifdef DEBUG assert(op); #endif op->validate(false); // make sure m_input_xform is up to date DD::Image::AxisOp* parent_axis = dynamic_cast<DD::Image::AxisOp*>(op->input(parent_input)); if (parent_axis) { //std::cout << " parent='" << parent_axis->node_name() << "' m_input_xform=" << m_input_xform << std::endl; // Check if input is a SceneXform and access the double-precision methods: if (m_input_xform) return m_input_xform->getWorldTransformAt(context); // Single-precision parent: DD::Image::Matrix4 m; parent_axis->matrixAt(context, m); return Fsr::Mat4d(m); } return Fsr::Mat4d::getIdentity(); } /*! Builds the local parent transform matrix from the parent knobs. */ /*virtual*/ Fsr::Mat4d SceneXform::getParentConstraintTransformAt(const DD::Image::OutputContext& context) const { //std::cout << " SceneXform('" << const_cast<SceneXform*>(this)->sceneOp()->node_name() << "' " << this << ")::getParentConstraintTransformAt()" << std::endl; Fsr::Mat4d m; m.setToIdentity(); // Transform order is always SRT for parent contraint: if (kParentTranslate) { Fsr::Vec3d translate; getVec3Knob(kParentTranslate, context, translate); m.translate(translate); } if (kParentRotate) { // Rotation order is always XYZ for parent contraint: Fsr::Vec3d rotate; getVec3Knob(kParentRotate, context, rotate); m.rotate(Fsr::XYZ_ORDER, rotate.asRadians()); } if (kParentScale) { Fsr::Vec3d scale; getVec3Knob(kParentScale, context, scale); m.scale(scale); } return m; } /*! Builds the local transform matrix. Does not include lookat rotations. */ /*virtual*/ Fsr::Mat4d SceneXform::getLocalTransformAt(const DD::Image::OutputContext& context) const { //std::cout << " SceneXform('" << const_cast<SceneXform*>(this)->sceneOp()->node_name() << "' " << this << ")::getLocalTransformAt()" << std::endl; // Just in case, shouldn't happen but don't crash... if (!kFsrAxisKnob) { DD::Image::Op* op = const_cast<SceneXform*>(this)->sceneOp(); std::cerr << "SceneXform('" << op->node_name() << "' " << this << ")::getLocalTransformAt()"; std::cerr << " warning, kFsrAxisKnob is NULL, likely due to a coding error." << std::endl; return Fsr::Mat4d::getIdentity(); } return kFsrAxisKnob->getMatrixAt(context); } /*! Modifes matrix with lookat function applied. Requires concatendated world transform up to local matrix to find vector origin. Make sure the OutputContexts match. Returns true if lookat was applied. */ /*virtual*/ bool SceneXform::applyLookatTransformAt(Fsr::Mat4d& concat_matrix, const DD::Image::OutputContext& context) const { #if 1 return false; #else const int lookat_input = this->lookatInput(); Fsr::Vec3d xformP; Fsr::Vec3d lookP; bool have_lookat_position = false; if (lookat_input < 0) { // Locally defined lookat source: //have_lookat_position = getLookatPoint(lookP); } else { // Get the position of the input AxisOp: // TODO: support lookat connections to GeometryList objects DD::Image::AxisOp* lookat_axis = dynamic_cast<DD::Image::AxisOp*>(axis->input(lookat_input)); if (lookat_axis) { lookP = lookat_axis->matrix().translation(); have_lookat_position = true; } } if (have_lookat_position) { // Need our worldspace position to include parent: Fsr::Mat4d world_matrix; getParentingTransform(context, world_matrix); // If the xform order is not translate-last then we need // to build the full transform to get the translation // point... if (!axis_vals.use_matrix && (axis_vals.xform_order == Fsr::SRT_ORDER || axis_vals.xform_order == Fsr::RST_ORDER)) { world_matrix.translate(axis_vals.translate); } else { // Build the local matrix just to get absolute translation... :( world_matrix.applyTransform(axis_vals.xform_order, axis_vals.rot_order, axis_vals.translate, axis_vals.rotate, axis_vals.totalScaling(), axis_vals.skew, axis_vals.pivot); } xformP = world_matrix.getTranslation(); std::cout.precision(7); std::cout << " xformP" << xformP << std::endl; std::cout << " lookP" << lookP << std::endl; #if 0 // Also check if lookat is enabled and we can't trivially derive the translation // of the xform to use as a lookat source point the also output matrix: if (lookat_axis != NULL && !axis_vals.use_matrix) { //std::cout << " lookat enabled" << std::endl; // In the special (and common) case of SRT and RST xform order the translation // point is always the translation value, so we can simply overwrite the rotations // with the derived ones. if (xform_order == Fsr::SRT_ORDER || xform_order == Fsr::RST_ORDER) use_matrix = false; else use_matrix = true; // enable matrix mode for all other transform orders } // Write a matrix if 'useMatrix' (specify matrix) is enabled on the AxisOp, // or lookat has forced it: if (axis_vals.use_matrix) { // Use the Axis_KnobI interface to get the user-defined matrix without // the lookat matrix mixed in: DD::Image::Matrix4 m = axis_knob->axisKnob()->matrix(context); if (lookat_axis != NULL) const_cast<DD::Image::AxisOp*>(axis)->lookMatrixAt(context, m); // apply lookat transform matrix = m; } else { // In the special-case lookat mode where the final translation point is always // the translation knob value we can simply overwrite the rotations with the // derived lookat ones: if (lookat_axis != NULL) { Fsr::AxisDirection look_axis = Fsr::AXIS_Z_PLUS; bool look_rotate_x = true; bool look_rotate_y = true; double look_rotate_z = true; bool look_strength = 1.0; bool look_use_quaternions = false; // DD::Image::Knob* k; DD::Image::Hash dummy_hash; k = axis->knob("look_axis" ); if (k) k->store(DD::Image::IntPtr, &look_axis, dummy_hash, context); k = axis->knob("look_rotate_x" ); if (k) k->store(DD::Image::BoolPtr, &look_rotate_x, dummy_hash, context); k = axis->knob("look_rotate_y" ); if (k) k->store(DD::Image::BoolPtr, &look_rotate_y, dummy_hash, context); k = axis->knob("look_rotate_z" ); if (k) k->store(DD::Image::BoolPtr, &look_rotate_z, dummy_hash, context); k = axis->knob("look_strength" ); if (k) k->store(DD::Image::DoublePtr, &look_strength, dummy_hash, context); k = axis->knob("look_use_quaternions"); if (k) k->store(DD::Image::BoolPtr, &look_use_quaternions, dummy_hash, context); //std::cout << " look_axis=" << look_axis; //std::cout << ", look_rotate_x=" << look_rotate_x << ", look_rotate_y=" << look_rotate_y << ", look_rotate_z=" << look_rotate_z; //std::cout << ", look_strength=" << look_strength << ", look_use_quaternions=" << look_use_quaternions; //std::cout << std::endl; // Remap look axis enum from Nuke's to Fuser's (should do nothing...!): switch (look_axis) { // Stoopid DDImage LookAt class has protected enums... case 0/*DD::Image::LookAt::kAxisZPlus*/: look_axis = Fsr::AXIS_Z_PLUS; break; case 1/*DD::Image::LookAt::kAxisZMinus*/: look_axis = Fsr::AXIS_Z_MINUS; break; case 2/*DD::Image::LookAt::kAxisYPlus*/: look_axis = Fsr::AXIS_Y_PLUS; break; case 3/*DD::Image::LookAt::kAxisYMinus*/: look_axis = Fsr::AXIS_Y_MINUS; break; case 4/*DD::Image::LookAt::kAxisXPlus*/: look_axis = Fsr::AXIS_X_PLUS; break; case 5/*DD::Image::LookAt::kAxisXMinus*/: look_axis = Fsr::AXIS_X_MINUS; break; } // Decompose lookat vector into rotations, replacing the ones from AxisOp. // Build vector from point to lookat point and convert to rotations: const Fsr::Vec3d axisP(axis->matrix().translation()); const Fsr::Vec3d lookP(lookat_axis->matrix().translation()); //std::cout << " axisP=" << axisP << std::endl; //std::cout << " lookP=" << lookP << std::endl; Fsr::Vec3d look_rotations; Fsr::Lookat::vectorToRotations((look_use_quaternions) ? Fsr::Lookat::USE_QUATS : Fsr::Lookat::USE_VECTORS, (lookP - axisP), look_axis, look_rotate_x, look_rotate_y, look_rotate_z, look_strength, look_rotations); // In lookat mode we always use ZXY order: rot_order = Fsr::ZXY_ORDER; //std::cout << " new rotate" << rotate << std::endl; } } #endif } #endif } /*! Builds the entire transform matrix. Includes parent, local and lookat. */ /*virtual*/ Fsr::Mat4d SceneXform::getWorldTransformAt(const DD::Image::OutputContext& context) const { //std::cout << "SceneXform('" << const_cast<SceneXform*>(this)->sceneOp()->node_name() << "' " << this << ")::getWorldTransformAt()" << std::endl; // Extract the local transform from the Axis_Knob knobs, build the parent // transform and lookat rotations, then produce double-precision matrices // from the lot to use: Fsr::Mat4d m; m = getInputParentTransformAt(context); m *= getParentConstraintTransformAt(context); m *= getLocalTransformAt(context); //std::cout << " world_matrix" << m << std::endl; return m; } //------------------------------------------------------------------------------------ /*! */ /*virtual*/ void SceneXform::buildHandles(DD::Image::ViewerContext* ctx) { #if 0 DD::Image::AxisOp* axis = asAxisOp(); #ifdef DEBUG assert(axis); #endif DD::Image::Matrix4 saved_matrix = ctx->modelmatrix; // Go up the inputs asking them to build their handles. // Do this first so that other ops always have a chance to draw! axis->DD::Image::Op::build_input_handles(ctx); // inputs are drawn in current world space if (axis->node_disabled()) return; // Only draw the camera's icon in 3D view: // TODO: what about stereo window controls in 2D? if (ctx->transform_mode() == DD::Image::VIEWER_2D) return; ctx->modelmatrix = saved_matrix; axis->validate(false); // get transforms up to date // Local knobs are drawn/manipulated in parent's space context, // so mult in just parent xform. ctx->modelmatrix will be saved // in each build-knob entry: ctx->modelmatrix *= m_input_matrix.asDDImage(); ctx->modelmatrix *= m_parent_matrix.asDDImage(); // Let op build any of its local-space handles (3D transform, 2D controls, etc): DD::Image::Op::build_knob_handles(ctx); // Only draw the camera icon if viewer is in 3D mode: if (ctx->viewer_mode() > VIEWER_2D && AxisOp::display3d_) { axis->DD::Image::Op::add_draw_handle(ctx); ctx->expand_bbox(node_selected(), local_.a03, local_.a13, local_.a23); } ctx->modelmatrix = saved_matrix; // don't leave matrix messed up #endif } } // namespace Fsr // end of FuserSceneXform.cpp // // Copyright 2019 DreamWorks Animation //
37.173675
163
0.587956
[ "object", "vector", "transform", "3d" ]
045a70a74499cf11a527467c074195faed60fe96
1,716
cc
C++
quickstart/ReverseGroups.cc
shortthirdman/code-eval-challenges
27d8f2474a95d4836397b3c5970dcabd5e2bff5e
[ "MIT" ]
2
2018-06-24T17:09:16.000Z
2020-08-03T11:44:54.000Z
quickstart/ReverseGroups.cc
shortthirdman/code-eval-challenges
27d8f2474a95d4836397b3c5970dcabd5e2bff5e
[ "MIT" ]
null
null
null
quickstart/ReverseGroups.cc
shortthirdman/code-eval-challenges
27d8f2474a95d4836397b3c5970dcabd5e2bff5e
[ "MIT" ]
null
null
null
/* Reverse Groups Share on LinkedIn Description: Given a list of numbers and a positive integer k, reverse the elements of the list, k items at a time. If the number of elements is not a multiple of k, then the remaining items in the end should be left as is. Input sample: Your program should accept as its first argument a path to a filename. Each line in this file contains a list of numbers and the number k, separated by a semicolon. The list of numbers are comma delimited. e.g. 1,2,3,4,5;2 1,2,3,4,5;3 Output sample: Print out the new comma separated list of numbers obtained after reversing. e.g. 2,1,4,3,5 3,2,1,4,5 */ #include <iostream> #include <fstream> #include <sstream> #include <vector> #include <algorithm> using namespace std; int main(int argc, char *argv[]) { ifstream ifs(argv[1]); int k; string line; vector<int> table; while (getline(ifs, line)) { int pos = line.find(';'); istringstream(line.substr(pos+1)) >> k; string data = line.substr(0, pos); replace(data.begin(), data.end(), ',', ' '); istringstream iss(data); int cur; table.clear(); bool start = false; while (iss >> cur) { table.push_back(cur); if (table.size() == k) { for (int i = table.size()-1; i >= 0; --i) { if (start) cout << ","; cout << table[i]; start = true; } table.clear(); } } for (int i = 0; i < table.size(); ++i) { if (start) cout << ','; cout << table[i]; start = true; } cout << endl; } return 0; }
26.4
211
0.555944
[ "vector" ]
045c6a8c5e71d987c9f68f717e2214bd60d172cd
58,518
cc
C++
src/nameserver/name_server_create_remote_test.cc
daifengxin/OpenMLDB
e145a2cb58c9dc885e03d68b3b3b22d3cedfc195
[ "Apache-2.0" ]
1
2021-08-23T12:02:30.000Z
2021-08-23T12:02:30.000Z
src/nameserver/name_server_create_remote_test.cc
daifengxin/OpenMLDB
e145a2cb58c9dc885e03d68b3b3b22d3cedfc195
[ "Apache-2.0" ]
null
null
null
src/nameserver/name_server_create_remote_test.cc
daifengxin/OpenMLDB
e145a2cb58c9dc885e03d68b3b3b22d3cedfc195
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 4Paradigm * * 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 <brpc/server.h> #include <gflags/gflags.h> #include <sched.h> #include <unistd.h> #include "base/file_util.h" #include "base/glog_wapper.h" #include "client/ns_client.h" #include "gtest/gtest.h" #include "nameserver/name_server_impl.h" #include "proto/name_server.pb.h" #include "proto/tablet.pb.h" #include "rpc/rpc_client.h" #include "tablet/tablet_impl.h" #include "common/timer.h" DECLARE_string(endpoint); DECLARE_string(db_root_path); DECLARE_string(zk_cluster); DECLARE_string(zk_root_path); DECLARE_int32(zk_session_timeout); DECLARE_int32(request_timeout_ms); DECLARE_int32(zk_keep_alive_check_interval); DECLARE_int32(make_snapshot_threshold_offset); DECLARE_uint32(name_server_task_max_concurrency); DECLARE_bool(auto_failover); using ::fedb::zk::ZkClient; namespace fedb { namespace nameserver { void AddDefaultSchema(uint64_t abs_ttl, uint64_t lat_ttl, ::fedb::type::TTLType ttl_type, ::fedb::nameserver::TableInfo* table_meta) { auto column_desc = table_meta->add_column_desc(); column_desc->set_name("idx0"); column_desc->set_data_type(::fedb::type::kString); auto column_desc1 = table_meta->add_column_desc(); column_desc1->set_name("value"); column_desc1->set_data_type(::fedb::type::kString); auto column_key = table_meta->add_column_key(); column_key->set_index_name("idx0"); column_key->add_col_name("idx0"); ::fedb::common::TTLSt* ttl_st = column_key->mutable_ttl(); ttl_st->set_abs_ttl(abs_ttl); ttl_st->set_lat_ttl(lat_ttl); ttl_st->set_ttl_type(ttl_type); } inline std::string GenRand() { return std::to_string(rand() % 10000000 + 1); // NOLINT } class MockClosure : public ::google::protobuf::Closure { public: MockClosure() {} ~MockClosure() {} void Run() {} }; class NameServerImplRemoteTest : public ::testing::Test { public: NameServerImplRemoteTest() {} ~NameServerImplRemoteTest() {} void Start(NameServerImpl* nameserver) { nameserver->running_ = true; } std::vector<std::list<std::shared_ptr<OPData>>>& GetTaskVec( NameServerImpl* nameserver) { return nameserver->task_vec_; } std::map<std::string, std::shared_ptr<::fedb::nameserver::TableInfo>>& GetTableInfo(NameServerImpl* nameserver) { return nameserver->table_info_; } ZoneInfo* GetZoneInfo(NameServerImpl* nameserver) { return &(nameserver->zone_info_); } void CreateTableRemoteBeforeAddRepClusterFunc( NameServerImpl* nameserver_1, NameServerImpl* nameserver_2, ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub>& name_server_client_1, //NOLINT ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub>& name_server_client_2, //NOLINT std::string db); void CreateAndDropTableRemoteFunc( NameServerImpl* nameserver_1, NameServerImpl* nameserver_2, ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub>& name_server_client_1, //NOLINT ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub>& name_server_client_2, //NOLINT std::string db); }; void StartNameServer(brpc::Server& server, // NOLINT NameServerImpl* nameserver) { // NOLINT bool ok = nameserver->Init(""); ASSERT_TRUE(ok); sleep(4); brpc::ServerOptions options; if (server.AddService(nameserver, brpc::SERVER_OWNS_SERVICE) != 0) { PDLOG(WARNING, "Fail to add service"); exit(1); } if (server.Start(FLAGS_endpoint.c_str(), &options) != 0) { PDLOG(WARNING, "Fail to start server"); exit(1); } } void StartNameServer(brpc::Server& server) { // NOLINT NameServerImpl* nameserver = new NameServerImpl(); bool ok = nameserver->Init(""); ASSERT_TRUE(ok); sleep(4); brpc::ServerOptions options; if (server.AddService(nameserver, brpc::SERVER_OWNS_SERVICE) != 0) { PDLOG(WARNING, "Fail to add service"); exit(1); } if (server.Start(FLAGS_endpoint.c_str(), &options) != 0) { PDLOG(WARNING, "Fail to start server"); exit(1); } } void StartTablet(brpc::Server* server) { ::fedb::tablet::TabletImpl* tablet = new ::fedb::tablet::TabletImpl(); bool ok = tablet->Init(""); ASSERT_TRUE(ok); sleep(2); brpc::ServerOptions options1; if (server->AddService(tablet, brpc::SERVER_OWNS_SERVICE) != 0) { PDLOG(WARNING, "Fail to add service"); exit(1); } if (server->Start(FLAGS_endpoint.c_str(), &options1) != 0) { PDLOG(WARNING, "Fail to start server"); exit(1); } ok = tablet->RegisterZK(); ASSERT_TRUE(ok); sleep(2); } void NameServerImplRemoteTest::CreateTableRemoteBeforeAddRepClusterFunc( NameServerImpl* nameserver_1, NameServerImpl* nameserver_2, ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub>& name_server_client_1, ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub>& name_server_client_2, std::string db) { // NOLINT bool ok = false; std::string name = "test" + GenRand(); { CreateTableRequest request; GeneralResponse response; TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); table_info->set_db(db); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); AddDefaultSchema(0, 0, ::fedb::type::kAbsoluteTime, table_info); PartitionMeta* meta = partion->add_partition_meta(); meta->set_endpoint("127.0.0.1:9931"); meta->set_is_leader(true); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta1 = partion1->add_partition_meta(); meta1->set_endpoint("127.0.0.1:9931"); meta1->set_is_leader(true); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(307, response.code()); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta2 = partion2->add_partition_meta(); meta2->set_endpoint("127.0.0.1:9931"); meta2->set_is_leader(true); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); sleep(3); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_db(db); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(0, response.table_info_size()); } { ::fedb::nameserver::SwitchModeRequest request; ::fedb::nameserver::GeneralResponse response; request.set_sm(kLEADER); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::SwitchMode, &request, &response, FLAGS_request_timeout_ms, 1); } { std::string alias = "remote"; std::string msg; ::fedb::nameserver::ClusterAddress add_request; ::fedb::nameserver::GeneralResponse add_response; add_request.set_alias(alias); add_request.set_zk_path(FLAGS_zk_root_path); add_request.set_zk_endpoints(FLAGS_zk_cluster); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::AddReplicaCluster, &add_request, &add_response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, add_response.code()); sleep(20); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_db(db); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(1, response.table_info_size()); ASSERT_EQ(name, response.table_info(0).name()); ASSERT_EQ(3, response.table_info(0).table_partition_size()); } std::map<std::string, std::shared_ptr<::fedb::nameserver::TableInfo>>& table_info_map_r = GetTableInfo(nameserver_2); uint32_t rtid = 0; for (const auto& table_info : table_info_map_r) { if (table_info.second->name() == name) { rtid = table_info.second->tid(); for (const auto& table_partition : table_info.second->table_partition()) { if (table_partition.pid() == 1) { ASSERT_EQ(0, table_partition.remote_partition_meta_size()); } } break; } } std::map<std::string, std::shared_ptr<::fedb::nameserver::TableInfo>>& table_info_map = GetTableInfo(nameserver_1); for (const auto& table_info : table_info_map) { if (table_info.second->name() == name) { for (const auto& table_partition : table_info.second->table_partition()) { if (table_partition.pid() == 1) { for (const auto& meta : table_partition.remote_partition_meta()) { ASSERT_EQ(rtid, meta.remote_tid()); ASSERT_EQ("remote", meta.alias()); } break; } } break; } } { ::fedb::nameserver::DropTableRequest request; request.set_name(name); request.set_db(db); ::fedb::nameserver::GeneralResponse response; bool ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::DropTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); sleep(5); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_db(db); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(0, response.table_info_size()); } } TEST_F(NameServerImplRemoteTest, CreateTableRemoteBeforeAddRepCluster) { // local ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9631"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); NameServerImpl* nameserver_1 = new NameServerImpl(); brpc::Server server; StartNameServer(server, nameserver_1); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_1(FLAGS_endpoint, ""); name_server_client_1.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9931"; brpc::Server server1; StartTablet(&server1); // remote ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9632"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); NameServerImpl* nameserver_2 = new NameServerImpl(); brpc::Server server2; StartNameServer(server2, nameserver_2); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_2(FLAGS_endpoint, ""); name_server_client_2.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9932"; brpc::Server server3; StartTablet(&server3); // test remote without db CreateTableRemoteBeforeAddRepClusterFunc(nameserver_1, nameserver_2, name_server_client_1, name_server_client_2, ""); } TEST_F(NameServerImplRemoteTest, CreateTableRemoteBeforeAddRepClusterWithDb) { // local ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9631"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); NameServerImpl* nameserver_1 = new NameServerImpl(); brpc::Server server; StartNameServer(server, nameserver_1); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_1(FLAGS_endpoint, ""); name_server_client_1.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9931"; brpc::Server server1; StartTablet(&server1); // remote ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9632"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); NameServerImpl* nameserver_2 = new NameServerImpl(); brpc::Server server2; StartNameServer(server2, nameserver_2); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_2(FLAGS_endpoint, ""); name_server_client_2.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9932"; brpc::Server server3; StartTablet(&server3); // create db std::string db = "db" + GenRand(); { ::fedb::nameserver::CreateDatabaseRequest request; ::fedb::nameserver::GeneralResponse response; request.set_db(db); bool ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateDatabase, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); } // use db create table CreateTableRemoteBeforeAddRepClusterFunc(nameserver_1, nameserver_2, name_server_client_1, name_server_client_2, db); } void NameServerImplRemoteTest::CreateAndDropTableRemoteFunc( NameServerImpl* nameserver_1, NameServerImpl* nameserver_2, ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub>& name_server_client_1, ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub>& name_server_client_2, std::string db) { bool ok = false; { ::fedb::nameserver::SwitchModeRequest request; ::fedb::nameserver::GeneralResponse response; request.set_sm(kLEADER); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::SwitchMode, &request, &response, FLAGS_request_timeout_ms, 1); } { std::string alias = "remote"; std::string msg; ::fedb::nameserver::ClusterAddress add_request; ::fedb::nameserver::GeneralResponse add_response; add_request.set_alias(alias); add_request.set_zk_path(FLAGS_zk_root_path); add_request.set_zk_endpoints(FLAGS_zk_cluster); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::AddReplicaCluster, &add_request, &add_response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, add_response.code()); sleep(2); } std::string name = "test" + GenRand(); { CreateTableRequest request; GeneralResponse response; TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); AddDefaultSchema(0, 0, ::fedb::type::kAbsoluteTime, table_info); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta = partion->add_partition_meta(); meta->set_endpoint("127.0.0.1:9931"); meta->set_is_leader(true); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta1 = partion1->add_partition_meta(); meta1->set_endpoint("127.0.0.1:9931"); meta1->set_is_leader(true); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(307, response.code()); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta2 = partion2->add_partition_meta(); meta2->set_endpoint("127.0.0.1:9931"); meta2->set_is_leader(true); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); sleep(5); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(1, response.table_info_size()); ASSERT_EQ(name, response.table_info(0).name()); ASSERT_EQ(3, response.table_info(0).table_partition_size()); } std::map<std::string, std::shared_ptr<::fedb::nameserver::TableInfo>>& table_info_map_r = GetTableInfo(nameserver_2); uint32_t rtid = 0; for (const auto& table_info : table_info_map_r) { if (table_info.second->name() == name) { rtid = table_info.second->tid(); for (const auto& table_partition : table_info.second->table_partition()) { if (table_partition.pid() == 1) { ASSERT_EQ(0, table_partition.remote_partition_meta_size()); } } break; } } std::map<std::string, std::shared_ptr<::fedb::nameserver::TableInfo>>& table_info_map = GetTableInfo(nameserver_1); for (const auto& table_info : table_info_map) { if (table_info.second->name() == name) { for (const auto& table_partition : table_info.second->table_partition()) { if (table_partition.pid() == 1) { for (const auto& meta : table_partition.remote_partition_meta()) { ASSERT_EQ(rtid, meta.remote_tid()); ASSERT_EQ("remote", meta.alias()); } break; } } break; } } { ::fedb::nameserver::DropTableRequest request; request.set_name(name); ::fedb::nameserver::GeneralResponse response; bool ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::DropTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); sleep(5); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(0, response.table_info_size()); } } TEST_F(NameServerImplRemoteTest, CreateAndDropTableRemoteWithDb) { // local ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9631"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); NameServerImpl* nameserver_1 = new NameServerImpl(); brpc::Server server; StartNameServer(server, nameserver_1); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_1(FLAGS_endpoint, ""); name_server_client_1.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9931"; brpc::Server server1; StartTablet(&server1); // remote ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9632"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); NameServerImpl* nameserver_2 = new NameServerImpl(); brpc::Server server2; StartNameServer(server2, nameserver_2); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_2(FLAGS_endpoint, ""); name_server_client_2.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9932"; brpc::Server server3; StartTablet(&server3); // create db std::string db = "db" + GenRand(); { ::fedb::nameserver::CreateDatabaseRequest request; ::fedb::nameserver::GeneralResponse response; request.set_db(db); bool ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateDatabase, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); } CreateAndDropTableRemoteFunc(nameserver_1, nameserver_2, name_server_client_1, name_server_client_2, db); } TEST_F(NameServerImplRemoteTest, CreateAndDropTableRemote) { // local ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9631"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); NameServerImpl* nameserver_1 = new NameServerImpl(); brpc::Server server; StartNameServer(server, nameserver_1); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_1(FLAGS_endpoint, ""); name_server_client_1.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9931"; brpc::Server server1; StartTablet(&server1); // remote ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9632"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); NameServerImpl* nameserver_2 = new NameServerImpl(); brpc::Server server2; StartNameServer(server2, nameserver_2); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_2(FLAGS_endpoint, ""); name_server_client_2.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9932"; brpc::Server server3; StartTablet(&server3); CreateAndDropTableRemoteFunc(nameserver_1, nameserver_2, name_server_client_1, name_server_client_2, ""); } TEST_F(NameServerImplRemoteTest, CreateTableInfo) { // local ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9631"; brpc::Server server; NameServerImpl* nameserver_1 = new NameServerImpl(); StartNameServer(server, nameserver_1); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_1(FLAGS_endpoint, ""); name_server_client_1.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9931"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server1; StartTablet(&server1); FLAGS_endpoint = "127.0.0.1:9941"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server2; StartTablet(&server2); FLAGS_endpoint = "127.0.0.1:9951"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server3; StartTablet(&server3); // remote ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9632"; brpc::Server server4; StartNameServer(server4); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_2(FLAGS_endpoint, ""); name_server_client_2.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9932"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server5; StartTablet(&server5); FLAGS_endpoint = "127.0.0.1:9942"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server6; StartTablet(&server6); bool ok = false; { ::fedb::nameserver::SwitchModeRequest request; ::fedb::nameserver::GeneralResponse response; request.set_sm(kLEADER); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::SwitchMode, &request, &response, FLAGS_request_timeout_ms, 1); } { std::string alias = "remote"; std::string msg; ::fedb::nameserver::ClusterAddress add_request; ::fedb::nameserver::GeneralResponse add_response; add_request.set_alias(alias); add_request.set_zk_path(FLAGS_zk_root_path); add_request.set_zk_endpoints(FLAGS_zk_cluster); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::AddReplicaCluster, &add_request, &add_response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, add_response.code()); sleep(2); } ZoneInfo* zone_info = GetZoneInfo(nameserver_1); std::string name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); PartitionMeta* meta_13 = partion->add_partition_meta(); meta_13->set_endpoint("127.0.0.1:9951"); meta_13->set_is_leader(false); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9931"); meta_21->set_is_leader(true); PartitionMeta* meta_22 = partion1->add_partition_meta(); meta_22->set_endpoint("127.0.0.1:9941"); meta_22->set_is_leader(false); PartitionMeta* meta_23 = partion1->add_partition_meta(); meta_23->set_endpoint("127.0.0.1:9951"); meta_23->set_is_leader(false); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9931"); meta_31->set_is_leader(true); PartitionMeta* meta_32 = partion2->add_partition_meta(); meta_32->set_endpoint("127.0.0.1:9941"); meta_32->set_is_leader(false); PartitionMeta* meta_33 = partion2->add_partition_meta(); meta_33->set_endpoint("127.0.0.1:9951"); meta_33->set_is_leader(false); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfo, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(2, (int32_t)(response.table_info().replica_num())); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_name(name); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(1, response.table_info_size()); ASSERT_EQ(name, response.table_info(0).name()); ASSERT_EQ(3, response.table_info(0).table_partition_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(0).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(1).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(2).partition_meta_size()); } name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9941"); meta_21->set_is_leader(true); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9951"); meta_31->set_is_leader(true); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfo, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(1, (int64_t)(response.table_info().replica_num())); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_name(name); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(1, response.table_info_size()); ASSERT_EQ(name, response.table_info(0).name()); ASSERT_EQ(3, response.table_info(0).table_partition_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(0).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(1).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(2).partition_meta_size()); } name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9941"); meta_21->set_is_leader(true); PartitionMeta* meta_22 = partion1->add_partition_meta(); meta_22->set_endpoint("127.0.0.1:9951"); meta_22->set_is_leader(false); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9951"); meta_31->set_is_leader(true); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfo, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(2, (signed)response.table_info().replica_num()); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_name(name); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(1, response.table_info_size()); ASSERT_EQ(name, response.table_info(0).name()); ASSERT_EQ(3, response.table_info(0).table_partition_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(0).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(1).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(2).partition_meta_size()); } FLAGS_endpoint = "127.0.0.1:9952"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server7; StartTablet(&server7); name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); PartitionMeta* meta_13 = partion->add_partition_meta(); meta_13->set_endpoint("127.0.0.1:9951"); meta_13->set_is_leader(false); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9931"); meta_21->set_is_leader(true); PartitionMeta* meta_22 = partion1->add_partition_meta(); meta_22->set_endpoint("127.0.0.1:9941"); meta_22->set_is_leader(false); PartitionMeta* meta_23 = partion1->add_partition_meta(); meta_23->set_endpoint("127.0.0.1:9951"); meta_23->set_is_leader(false); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9931"); meta_31->set_is_leader(true); PartitionMeta* meta_32 = partion2->add_partition_meta(); meta_32->set_endpoint("127.0.0.1:9941"); meta_32->set_is_leader(false); PartitionMeta* meta_33 = partion2->add_partition_meta(); meta_33->set_endpoint("127.0.0.1:9951"); meta_33->set_is_leader(false); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfo, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(3, (signed)response.table_info().replica_num()); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_name(name); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(1, response.table_info_size()); ASSERT_EQ(name, response.table_info(0).name()); ASSERT_EQ(3, response.table_info(0).table_partition_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(0).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(1).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(2).partition_meta_size()); } name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9931"); meta_21->set_is_leader(true); PartitionMeta* meta_23 = partion1->add_partition_meta(); meta_23->set_endpoint("127.0.0.1:9951"); meta_23->set_is_leader(false); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9931"); meta_31->set_is_leader(true); PartitionMeta* meta_33 = partion2->add_partition_meta(); meta_33->set_endpoint("127.0.0.1:9951"); meta_33->set_is_leader(false); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfo, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(2, (signed)response.table_info().replica_num()); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_name(name); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(1, response.table_info_size()); ASSERT_EQ(name, response.table_info(0).name()); ASSERT_EQ(3, response.table_info(0).table_partition_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(0).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(1).partition_meta_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(2).partition_meta_size()); } name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); PartitionMeta* meta_13 = partion->add_partition_meta(); meta_13->set_endpoint("127.0.0.1:9951"); meta_13->set_is_leader(false); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfo, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(1, response.table_info().table_partition_size()); ASSERT_EQ(3, (signed)response.table_info().replica_num()); } { ::fedb::nameserver::ShowTableRequest request; ::fedb::nameserver::ShowTableResponse response; request.set_name(name); ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::ShowTable, &request, &response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(1, response.table_info_size()); ASSERT_EQ(name, response.table_info(0).name()); ASSERT_EQ(1, response.table_info(0).table_partition_size()); ASSERT_EQ( 1, response.table_info(0).table_partition(0).partition_meta_size()); } } TEST_F(NameServerImplRemoteTest, CreateTableInfoSimply) { // local ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9631"; NameServerImpl* nameserver_1 = new NameServerImpl(); brpc::Server server; StartNameServer(server, nameserver_1); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_1(FLAGS_endpoint, ""); name_server_client_1.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9931"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server1; StartTablet(&server1); FLAGS_endpoint = "127.0.0.1:9941"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server2; StartTablet(&server2); FLAGS_endpoint = "127.0.0.1:9951"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server3; StartTablet(&server3); // remote ns and tablet // ns FLAGS_zk_cluster = "127.0.0.1:6181"; FLAGS_zk_root_path = "/rtidb3" + GenRand(); FLAGS_endpoint = "127.0.0.1:9632"; brpc::Server server4; StartNameServer(server4); ::fedb::RpcClient<::fedb::nameserver::NameServer_Stub> name_server_client_2(FLAGS_endpoint, ""); name_server_client_2.Init(); // tablet FLAGS_endpoint = "127.0.0.1:9932"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server5; StartTablet(&server5); FLAGS_endpoint = "127.0.0.1:9942"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server6; StartTablet(&server6); bool ok = false; { ::fedb::nameserver::SwitchModeRequest request; ::fedb::nameserver::GeneralResponse response; request.set_sm(kLEADER); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::SwitchMode, &request, &response, FLAGS_request_timeout_ms, 1); } { std::string alias = "remote"; std::string msg; ::fedb::nameserver::ClusterAddress add_request; ::fedb::nameserver::GeneralResponse add_response; add_request.set_alias(alias); add_request.set_zk_path(FLAGS_zk_root_path); add_request.set_zk_endpoints(FLAGS_zk_cluster); ok = name_server_client_1.SendRequest( &::fedb::nameserver::NameServer_Stub::AddReplicaCluster, &add_request, &add_response, FLAGS_request_timeout_ms, 1); ASSERT_TRUE(ok); ASSERT_EQ(0, add_response.code()); sleep(2); } ZoneInfo* zone_info = GetZoneInfo(nameserver_1); std::string name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); PartitionMeta* meta_13 = partion->add_partition_meta(); meta_13->set_endpoint("127.0.0.1:9951"); meta_13->set_is_leader(false); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9931"); meta_21->set_is_leader(true); PartitionMeta* meta_22 = partion1->add_partition_meta(); meta_22->set_endpoint("127.0.0.1:9941"); meta_22->set_is_leader(false); PartitionMeta* meta_23 = partion1->add_partition_meta(); meta_23->set_endpoint("127.0.0.1:9951"); meta_23->set_is_leader(false); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9931"); meta_31->set_is_leader(true); PartitionMeta* meta_32 = partion2->add_partition_meta(); meta_32->set_endpoint("127.0.0.1:9941"); meta_32->set_is_leader(false); PartitionMeta* meta_33 = partion2->add_partition_meta(); meta_33->set_endpoint("127.0.0.1:9951"); meta_33->set_is_leader(false); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfoSimply, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(2, (signed)response.table_info().replica_num()); } name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9941"); meta_21->set_is_leader(true); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9951"); meta_31->set_is_leader(true); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfoSimply, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(1, (signed)response.table_info().replica_num()); } name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9941"); meta_21->set_is_leader(true); PartitionMeta* meta_22 = partion1->add_partition_meta(); meta_22->set_endpoint("127.0.0.1:9951"); meta_22->set_is_leader(false); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9951"); meta_31->set_is_leader(true); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfoSimply, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(2, (signed)response.table_info().replica_num()); } FLAGS_endpoint = "127.0.0.1:9952"; FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); brpc::Server server7; StartTablet(&server7); name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); PartitionMeta* meta_13 = partion->add_partition_meta(); meta_13->set_endpoint("127.0.0.1:9951"); meta_13->set_is_leader(false); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9931"); meta_21->set_is_leader(true); PartitionMeta* meta_22 = partion1->add_partition_meta(); meta_22->set_endpoint("127.0.0.1:9941"); meta_22->set_is_leader(false); PartitionMeta* meta_23 = partion1->add_partition_meta(); meta_23->set_endpoint("127.0.0.1:9951"); meta_23->set_is_leader(false); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9931"); meta_31->set_is_leader(true); PartitionMeta* meta_32 = partion2->add_partition_meta(); meta_32->set_endpoint("127.0.0.1:9941"); meta_32->set_is_leader(false); PartitionMeta* meta_33 = partion2->add_partition_meta(); meta_33->set_endpoint("127.0.0.1:9951"); meta_33->set_is_leader(false); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfoSimply, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(3, (signed)response.table_info().replica_num()); } name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); TablePartition* partion1 = table_info->add_table_partition(); partion1->set_pid(2); PartitionMeta* meta_21 = partion1->add_partition_meta(); meta_21->set_endpoint("127.0.0.1:9931"); meta_21->set_is_leader(true); PartitionMeta* meta_23 = partion1->add_partition_meta(); meta_23->set_endpoint("127.0.0.1:9951"); meta_23->set_is_leader(false); TablePartition* partion2 = table_info->add_table_partition(); partion2->set_pid(0); PartitionMeta* meta_31 = partion2->add_partition_meta(); meta_31->set_endpoint("127.0.0.1:9931"); meta_31->set_is_leader(true); PartitionMeta* meta_33 = partion2->add_partition_meta(); meta_33->set_endpoint("127.0.0.1:9951"); meta_33->set_is_leader(false); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfoSimply, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(3, response.table_info().table_partition_size()); ASSERT_EQ(2, (signed)response.table_info().replica_num()); } name = "test" + GenRand(); { ::fedb::nameserver::CreateTableInfoRequest request; ::fedb::nameserver::CreateTableInfoResponse response; ::fedb::nameserver::ZoneInfo* zone_info_p = request.mutable_zone_info(); zone_info_p->CopyFrom(*zone_info); TableInfo* table_info = request.mutable_table_info(); table_info->set_name(name); TablePartition* partion = table_info->add_table_partition(); partion->set_pid(1); PartitionMeta* meta_11 = partion->add_partition_meta(); meta_11->set_endpoint("127.0.0.1:9931"); meta_11->set_is_leader(true); PartitionMeta* meta_12 = partion->add_partition_meta(); meta_12->set_endpoint("127.0.0.1:9941"); meta_12->set_is_leader(false); PartitionMeta* meta_13 = partion->add_partition_meta(); meta_13->set_endpoint("127.0.0.1:9951"); meta_13->set_is_leader(false); bool ok = name_server_client_2.SendRequest( &::fedb::nameserver::NameServer_Stub::CreateTableInfoSimply, &request, &response, FLAGS_request_timeout_ms, 3); ASSERT_TRUE(ok); ASSERT_EQ(0, response.code()); ASSERT_EQ(name, response.table_info().name()); ASSERT_EQ(1, response.table_info().table_partition_size()); } } } // namespace nameserver } // namespace fedb int main(int argc, char** argv) { FLAGS_zk_session_timeout = 100000; ::testing::InitGoogleTest(&argc, argv); srand(time(NULL)); ::fedb::base::SetLogLevel(INFO); ::google::ParseCommandLineFlags(&argc, &argv, true); // FLAGS_db_root_path = "/tmp/" + ::fedb::nameserver::GenRand(); return RUN_ALL_TESTS(); }
39.971311
100
0.644041
[ "vector" ]
045e3431fd256b0742f3946ffab152c4b0cc61b1
2,673
cpp
C++
v2_hashTable/Entry.cpp
salmanfs815/English-Klingon-Translator
6b6a4030759642f9a7e2c5a004636e915ff67fb7
[ "MIT" ]
null
null
null
v2_hashTable/Entry.cpp
salmanfs815/English-Klingon-Translator
6b6a4030759642f9a7e2c5a004636e915ff67fb7
[ "MIT" ]
null
null
null
v2_hashTable/Entry.cpp
salmanfs815/English-Klingon-Translator
6b6a4030759642f9a7e2c5a004636e915ff67fb7
[ "MIT" ]
null
null
null
/* * Entry.cpp * * Entry Class to be used in nodes of BST for assn3-cmpt225 * * Authors: Salman Siddiqui and Raj Mahey * Date: 2016-07-05 */ #include "Entry.h" #include <string> #include <iostream> #include <algorithm> using namespace std; /* private attributes: string english; string klingon; */ //This is the default constructor, english and klingon remain unset Entry::Entry() { english = ""; klingon = "<not found>"; } //This constructor sets only the english word to engWord Entry::Entry(string engWord) { english = engWord; klingon = "<not found>"; } //This constructor accepts both an english word and its klingon conversion and sets both variables Entry::Entry(string engWord, string klingWord) { english = engWord; klingon = klingWord; } //default destructor, doesnt do anything interesting Entry::~Entry() { } //Gets the english version of this Entry objects "word" string Entry::getEnglish() const { return english; } //Sets the english version of this Entry objects "word" void Entry::setEnglish(string engWord) { english = engWord; } //Gets the klingon version of this Entry objects "word" string Entry::getKlingon() const { return klingon; } //Sets the klingon version of this Entry objects "word" void Entry::setKlingon(string klingWord) { klingon = klingWord; } //returns true if rhs Entry objects english word is same as this bool Entry::operator==(const Entry& rhs) const { string word1 = english; string word2 = rhs.getEnglish(); transform(word1.begin(), word1.end(), word1.begin(),::tolower); transform(word2.begin(), word2.end(), word2.begin(),::tolower); return word1.compare(word2) == 0; } //returns true if rhs Entry objects english word is <= as this bool Entry::operator>(const Entry& rhs) const { string word1 = english; string word2 = rhs.getEnglish(); transform(word1.begin(), word1.end(), word1.begin(),::tolower); transform(word2.begin(), word2.end(), word2.begin(),::tolower); return word1.compare(word2) > 0; } //returns true if rhs Entry objects english word is > same as this bool Entry::operator<(const Entry& rhs) const { string word1 = english; string word2 = rhs.getEnglish(); transform(word1.begin(), word1.end(), word1.begin(),::tolower); transform(word2.begin(), word2.end(), word2.begin(),::tolower); return word1.compare(word2) < 0; } //Outputs the entry objects english word, followed by a colon, followed by the klingon translation ostream& operator<<(ostream& os, const Entry& rhs) { os << rhs.getEnglish() << ":" << rhs.getKlingon(); return os; }
23.243478
99
0.680135
[ "transform" ]
046150ee8625fc89427ad6741fae19fb4ada6bf7
2,845
hpp
C++
services/network_service/network_service.hpp
cyberduckninja/RocketJoe
f0cfb51850423c218c3630f7a664afb48b2b8319
[ "BSD-3-Clause" ]
9
2020-07-20T15:32:07.000Z
2021-06-04T13:02:58.000Z
services/network_service/network_service.hpp
cyberduckninja/RocketJoe
f0cfb51850423c218c3630f7a664afb48b2b8319
[ "BSD-3-Clause" ]
22
2020-06-06T07:27:00.000Z
2021-01-14T23:11:22.000Z
services/network_service/network_service.hpp
cyberduckninja/RocketJoe
f0cfb51850423c218c3630f7a664afb48b2b8319
[ "BSD-3-Clause" ]
3
2020-08-29T07:07:49.000Z
2021-06-04T13:02:59.000Z
#pragma once #include "beast-compact.hpp" #include <boost/smart_ptr/intrusive_ptr.hpp> #include "context.hpp" #include "dto.hpp" #include "http_client.hpp" #include "routes.hpp" #include "log/log.hpp" #include <goblin-engineer/core.hpp> #include "excutor.hpp" namespace ge = goblin_engineer; class network_service_t final : public goblin_engineer::abstract_manager_service { public: using address_book = std::function<actor_zeta::actor_address(actor_zeta::detail::string_view)>; class client_t final { public: enum type_t { UNKNOWN = -1, PLAIN_WS, SSL_WS, }; client_t() = default; client_t( const host_t& host, const port_t& port, const std::string& init_message, type_t type) : host_(host) , port_(port) , init_message_(init_message) , type_(type) {} /*client_t(const client_t&) = default; client_t(client_t&&) = default;*/ ~client_t() = default; host_t host_; port_t port_; std::string init_message_; type_t type_; }; using clients_t = std::vector<client_t>; network_service_t(std::string name, net::io_context&, tcp::endpoint, const clients_t&, size_t num_workers, size_t max_throughput, log_t& log); network_service_t(std::string name, net::io_context&, tcp::endpoint, const clients_t&, size_t num_workers, size_t max_throughput, log_t& log, address_book addresses); ~network_service_t() override; void http_write(session_id&, response_t&); void ws_write(session_id&, ws_message_ptr); void ws_broadcast(std::string&); void close_session(session_id&); void run(); void http_client_write(tcp::resolver::results_type&&, request_t&&); void enqueue_base(goblin_engineer::message_ptr, actor_zeta::execution_device*) override; auto executor() noexcept -> actor_zeta::abstract_executor* override; void on_accept(beast::error_code ec, tcp::socket socket); auto get_executor() noexcept -> goblin_engineer::abstract_executor* override; private: std::atomic_int actor_index_ = 0; goblin_engineer::executor_ptr coordinator_; net::io_context& io_context_; net::strand<net::io_context::executor_type> ioc_read_; net::strand<net::io_context::executor_type> ioc_write_; tcp::acceptor acceptor_; http_client_handler_t http_client_; session_handler_ptr server_session_handler_; session_handler_ptr client_session_handler_; log_t log_; ssl::context ssl_ctx_{ssl::context::tlsv12}; //session_handlers_t session_handlers_; std::deque<ge::message_ptr> messages_; void do_accept_(); }; using network_service_ptr = boost::intrusive_ptr<network_service_t>;
31.263736
101
0.676626
[ "vector" ]
0462599e5ec215d71ec4cc18ca81b230b5d790f7
2,218
cpp
C++
chapter20/ex02_jack_jill.cpp
ClassAteam/stroustrup-ppp
ea9e85d4ea9890038eb5611c3bc82734c8706ce7
[ "MIT" ]
124
2018-06-23T10:16:56.000Z
2022-03-19T15:16:12.000Z
chapter20/ex02_jack_jill.cpp
therootfolder/stroustrup-ppp
b1e936c9a67b9205fdc9712c42496b45200514e2
[ "MIT" ]
23
2018-02-08T20:57:46.000Z
2021-10-08T13:58:29.000Z
chapter20/ex02_jack_jill.cpp
ClassAteam/stroustrup-ppp
ea9e85d4ea9890038eb5611c3bc82734c8706ce7
[ "MIT" ]
65
2019-05-27T03:05:56.000Z
2022-03-26T03:43:05.000Z
// // Stroustrup - Programming Principles & Practice // // Chapter 20 Jack and Jill example // #include <iostream> #include <stdexcept> #include <vector> #include <fstream> #include <memory> // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // mocks double* get_from_jack(int* count) // mock jack data // must return double* { constexpr int chunk = 8; std::ifstream ifs {"jack.txt"}; if (!ifs) throw std::runtime_error("Could not open file jack.txt"); int size = chunk; std::unique_ptr<double[]> da {new double[size]}; for (int i = 0; ifs >> da[i]; ++i) { *count += 1; if (i + 1 == size) { std::unique_ptr<double[]> p {new double[size + chunk]}; std::copy(da.get(), da.get() + size, p.get()); size += chunk; da = std::move(p); } } return da.release(); } std::vector<double>* get_from_jill() { std::ifstream ifs {"jill.txt"}; if (!ifs) throw std::runtime_error("Could not open file jill.txt"); std::unique_ptr<std::vector<double>> v {new std::vector<double>}; for (double d; ifs >> d; ) v->push_back(d); return v.release(); } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * double* high(double* first, double* last) // return a pointer to the element in [first,last) that is highest { double h = -1; double* high; for (double* p = first; p != last; ++p) if (h < *p) { high = p; h = *p; } return high; } void fct() { int jack_count = 0; double* jack_data = get_from_jack(&jack_count); std::vector<double>* jill_data = get_from_jill(); // process.. double* jack_high = high(jack_data, jack_data + jack_count); std::vector<double>& v = *jill_data; double* jill_high = high(&v[0], &v[0] + v.size()); std::cout << "Jill's max: " << *jill_high << "; Jack's max: " << *jack_high << '\n'; delete [] jack_data; delete jill_data; } int main() try { fct(); } catch(std::exception& e) { std::cerr << "Exception: " << e.what() << '\n'; return 1; } catch(...) { std::cerr << "Unknown exception\n"; return 2; }
22.865979
79
0.519838
[ "vector" ]
04633d5c157fa28db220fe5ae1be0e4349c4557a
1,085
cpp
C++
Templates/Project/Volund_Engine/src/Scene/Skybox.cpp
Kaj9296/Volund-Engine
2416edc6297da4818f0a9f5613daf2223ff868d9
[ "MIT" ]
null
null
null
Templates/Project/Volund_Engine/src/Scene/Skybox.cpp
Kaj9296/Volund-Engine
2416edc6297da4818f0a9f5613daf2223ff868d9
[ "MIT" ]
null
null
null
Templates/Project/Volund_Engine/src/Scene/Skybox.cpp
Kaj9296/Volund-Engine
2416edc6297da4818f0a9f5613daf2223ff868d9
[ "MIT" ]
null
null
null
#pragma once #include "PCH/PCH.h" #include "Skybox.h" #include "Components/Camera.h" namespace Volund { bool SkyboxClass::HasCubeMap() { return this->cubeMap != nullptr; } CubeMap* SkyboxClass::GetCubeMap() { return this->cubeMap; } void SkyboxClass::SetCubeMap(CubeMap const& cubeMap) { if (&cubeMap != (GPUBuffer*)&NULL_CUBEMAP) { this->cubeMap = (CubeMap*)&cubeMap; } else { this->cubeMap = nullptr; } } void SkyboxClass::Render(GPUBuffer& Buffer, Camera const& Cam) { if (this->HasCubeMap()) { Buffer.BindFramebuffer(); this->shader.SetSampler(*this->cubeMap, "Skybox"); this->shader.SetMat4(Cam.OriginViewMatrix, "View"); this->shader.SetMat4(Cam.ProjectionMatrix, "Projection"); glBlendFunc(GL_ONE, GL_ONE); glDisable(GL_CULL_FACE); this->shader.DrawMesh(this->mesh); glEnable(GL_CULL_FACE); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } } SkyboxClass::SkyboxClass() { this->shader.Init(SHADER_PATH + "SkyBox.shader"); this->mesh.Init(PRIMITIVES_PATH + "SkyBox.obj"); } } //namespace Volund
20.092593
63
0.688479
[ "mesh", "render" ]
0465b7bdca211c6fc0d2eb86503ea7ccdf5c56b5
3,727
cc
C++
chrome_frame/chrome_launcher_utils.cc
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
chrome_frame/chrome_launcher_utils.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
chrome_frame/chrome_launcher_utils.cc
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.000Z
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome_frame/chrome_launcher_utils.h" #include "base/base_switches.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/path_service.h" #include "base/string_util.h" #include "base/win/windows_version.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_switches.h" #include "chrome_frame/chrome_frame_automation.h" #include "chrome_frame/policy_settings.h" namespace { const char kUpdateCommandFlag[] = "--update-cmd"; // Searches for the path to chrome_launcher.exe. Will return false if this // executable cannot be found, otherwise the command line will be placed in // |command_line|. bool CreateChromeLauncherCommandLine(scoped_ptr<CommandLine>* command_line) { DCHECK(command_line); bool success = false; // The launcher EXE will be in the same directory as the Chrome Frame DLL, // so create a full path to it based on this assumption. FilePath module_path; if (PathService::Get(base::FILE_MODULE, &module_path)) { FilePath current_dir = module_path.DirName(); FilePath chrome_launcher = current_dir.Append( chrome_launcher::kLauncherExeBaseName); if (file_util::PathExists(chrome_launcher)) { command_line->reset(new CommandLine(chrome_launcher)); success = true; } } if (!success) { NOTREACHED() << "Could not find " << chrome_launcher::kLauncherExeBaseName << " in output dir."; } return success; } } // namespace namespace chrome_launcher { const wchar_t kLauncherExeBaseName[] = L"chrome_launcher.exe"; bool CreateUpdateCommandLine(const std::wstring& update_command, scoped_ptr<CommandLine>* command_line) { DCHECK(command_line); bool success = false; if (CreateChromeLauncherCommandLine(command_line)) { (*command_line)->AppendArg(kUpdateCommandFlag); (*command_line)->AppendArg(WideToASCII(update_command)); success = true; } return success; } bool CreateLaunchCommandLine(scoped_ptr<CommandLine>* command_line) { DCHECK(command_line); // Shortcut for OS versions that don't need the integrity broker. if (base::win::GetVersion() < base::win::VERSION_VISTA) { command_line->reset(new CommandLine(GetChromeExecutablePath())); // When we do not use the Chrome Launcher, we need to add the optional extra // parameters from the group policy here (this is normally done by the // chrome launcher). We don't do this when we use the launcher as the // optional arguments could trip off sanitization checks and prevent Chrome // from being launched. const CommandLine& additional_params = PolicySettings::GetInstance()->AdditionalLaunchParameters(); command_line->get()->AppendArguments(additional_params, false); return true; } return CreateChromeLauncherCommandLine(command_line); } FilePath GetChromeExecutablePath() { FilePath cur_path; PathService::Get(base::DIR_MODULE, &cur_path); cur_path = cur_path.Append(chrome::kBrowserProcessExecutableName); // The installation model for Chrome places the DLLs in a versioned // sub-folder one down from the Chrome executable. If we fail to find // chrome.exe in the current path, try looking one up and launching that // instead. if (!file_util::PathExists(cur_path)) { PathService::Get(base::DIR_MODULE, &cur_path); cur_path = cur_path.DirName().Append(chrome::kBrowserProcessExecutableName); } return cur_path; } } // namespace chrome_launcher
33.881818
80
0.735712
[ "model" ]
046741d09ccc362384d21e4e1e53af281bc97b76
8,757
hpp
C++
app/src/main/cpp/isEngine/ext_lib/TMXLoader/tmx/MapObject.hpp
Is-Daouda/is-Engine-TMXLoader
db6d75a82326f44d66170acf70224d6a8cf20bad
[ "Zlib" ]
null
null
null
app/src/main/cpp/isEngine/ext_lib/TMXLoader/tmx/MapObject.hpp
Is-Daouda/is-Engine-TMXLoader
db6d75a82326f44d66170acf70224d6a8cf20bad
[ "Zlib" ]
null
null
null
app/src/main/cpp/isEngine/ext_lib/TMXLoader/tmx/MapObject.hpp
Is-Daouda/is-Engine-TMXLoader
db6d75a82326f44d66170acf70224d6a8cf20bad
[ "Zlib" ]
null
null
null
/********************************************************************* Matt Marchant 2013 - 2016 SFML Tiled Map Loader - https://github.com/bjorn/tiled/wiki/TMX-Map-Format http://trederia.blogspot.com/2013/05/tiled-map-loader-for-sfml.html Zlib License: This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. *********************************************************************/ #ifndef MAP_OBJECT_HPP_ #define MAP_OBJECT_HPP_ #include "Helpers.hpp" #include "DebugShape.hpp" //TODO what's with all these includes??? #include <SFML/Graphics/Color.hpp> #include <SFML/Graphics/Drawable.hpp> #include <SFML/Graphics/Font.hpp> #include <SFML/Graphics/Image.hpp> #include <SFML/Graphics/VertexArray.hpp> #include <SFML/Graphics/RectangleShape.hpp> #include <SFML/Graphics/RenderStates.hpp> #include <SFML/Graphics/RenderTarget.hpp> #include <SFML/Graphics/Sprite.hpp> #include <SFML/Graphics/Text.hpp> #include <SFML/Graphics/Transformable.hpp> #include <SFML/System/NonCopyable.hpp> #include <string> #include <vector> #include <map> #include <iostream> #include <memory> namespace tmx { class TileQuad; enum MapObjectShape { Rectangle, Ellipse, Circle, Polygon, Polyline, Tile }; /*! \brief Map Object class. */ class TMX_EXPORT_API MapObject final : public sf::Transformable { private: struct Segment { Segment(const sf::Vector2f& start, const sf::Vector2f& end) : Start (start) , End(end){} bool intersects(const Segment& segment); sf::Vector2f Start; sf::Vector2f End; }; public: MapObject(); /*! \brief Returns requested property or an empty string if property not found */ std::string getPropertyString(const std::string& name); /*! \brief Returns precomputed centre of mass, or zero for polylines */ sf::Vector2f getCentre() const { return m_centrePoint; } /*! \brief Returns the type of shape of the object */ MapObjectShape getShapeType() const { return m_shape; } /*! \brief Returns the object's name */ std::string getName() const { return m_name; } /*! \brief Returns the object's type */ std::string getType() const { return m_type; } /*! \brief Returns the name of the object's parent layer */ std::string getParent() const { return m_parent; } /*! \brief Returns the object's AABB in world coordinates */ sf::FloatRect getAABB() const { return getTransform().transformRect(m_AABB); } /*! \brief Returns visibility */ bool visible() const { return m_visible; } /*! \brief Sets a property value, or adds it if property doesn't exist */ void setProperty(const std::string& name, const std::string& value); /*! \brief Sets the width and height of the object */ void setSize(const sf::Vector2f& size){ m_size = size; } /*! \brief Sets the object's name */ void setName(const std::string& name){ m_name = name; } /*! \brief Ssets the object's type */ void setType(const std::string& type){ m_type = type; } /*! \brief Sets the name of the object's parent layer */ void setParent(const std::string& parent){ m_parent = parent; } /*! \brief Sets the shape type */ void setShapeType(MapObjectShape shape){ m_shape = shape; } /*! \brief Sets visibility */ void setVisible(bool visible); /*! \brief Adds a point to the list of polygonal points. If calling this manually call createDebugShape() afterwards to rebuild debug output and AABB */ void addPoint(const sf::Vector2f& point){ m_polypoints.push_back(point); } /*! \brief Checks if an object contains given point in world coords. Always returns false for polylines. */ bool contains(sf::Vector2f point) const; /*! \brief Checks if two objects intersect, including polylines */ bool intersects(const MapObject& object) const; /*! \brief Creates a shape used for debug drawing - points are in world space */ void createDebugShape(const sf::Color& colour); /*! \brief Draws debug shape to given target */ void drawDebugShape(sf::RenderTarget& rt) const; /*! \brief Returns the first point of poly point member (if any) in world coordinates */ sf::Vector2f firstPoint() const; /*! \brief Returns the last point of poly point member (if any) in world coordinates */ sf::Vector2f lastPoint() const; /*! \brief Returns a unit vector normal to the polyline segment if intersected. \param start The start point of the segment to test in world coords \param end The end point of the segment to test in world coords */ sf::Vector2f collisionNormal(const sf::Vector2f& start, const sf::Vector2f& end) const; /*! \brief Creates a vector of segments making up the poly shape */ void createSegments(); /*! \brief Returns whether an object's poly shape is convex or not */ bool convex() const; /*! \brief Returns a const reference to the array of points making up the object */ const std::vector<sf::Vector2f>& polyPoints() const; /*! \brief Reverses the winding of object points */ void reverseWinding(); /*! \brief Sets the quad used to draw the tile for tile objects */ void setQuad(TileQuad* quad); /*! \brief Set the position of the object in world coordinates */ void setPosition(float, float); /*! \brief Set the position of the object in world coordinates */ void setPosition(const sf::Vector2f&); /*! \brief Move the objects position, in world coordinates */ void move(float, float); /*! \brief Set the position of the object in world coordinates */ void move(const sf::Vector2f&); private: //object properties, reflects those which are part of the tmx format std::string m_name, m_type, m_parent; //parent is name of layer to which object belongs sf::Vector2f m_size; std::map <std::string, std::string> m_properties;//map of custom name/value properties bool m_visible; std::vector<sf::Vector2f> m_polypoints; //list of points defining any polygonal shape MapObjectShape m_shape; DebugShape m_debugShape; sf::Vector2f m_centrePoint; std::vector<Segment> m_polySegs; //segments which make up shape, if any TileQuad* m_tileQuad; float m_furthestPoint; //furthest distance from centre of object to vertex - used for intersection testing //AABB created from polygonal shapes, used for adding MapObjects to a QuadTreeNode. //Note that the position of this box many not necessarily match the MapObject's position, as polygonal //points may have negative values relative to the object's world position. sf::FloatRect m_AABB; //returns centre of poly shape if available, else centre of //bounding rectangle in world space sf::Vector2f calcCentre() const; //precomputes centre point and furthest point to be used in intersection testing void calcTestValues(); //creates an AABB around the object based on its polygonal points, in world space void createAABB(); }; using MapObjects = std::vector<MapObject>; /*! \brief Represents a single tile on a layer */ struct TMX_EXPORT_API MapTile final { /*! \brief Returns the base centre point of sprite / tile */ sf::Vector2f getBase() const { return sf::Vector2f(sprite.getPosition().x + (sprite.getLocalBounds().width / 2.f), sprite.getPosition().y + sprite.getLocalBounds().height); } sf::Sprite sprite; sf::Vector2i gridCoord; sf::RenderStates renderStates; //used to perform any rendering with custom shaders or blend mode }; using MapTiles = std::vector<MapTile>; }; #endif //MAP_OBJECT_HPP_
31.728261
108
0.66621
[ "object", "shape", "vector" ]
04692108df098404e01267dbe0a40c12a4a3da3f
4,940
hpp
C++
src/webots/nodes/WbTrack.hpp
yjf18340/webots
60d441c362031ab8fde120cc0cd97bdb1a31a3d5
[ "Apache-2.0" ]
1
2019-11-13T08:12:02.000Z
2019-11-13T08:12:02.000Z
src/webots/nodes/WbTrack.hpp
chinakwy/webots
7c35a359848bafe81fe0229ac2ed587528f4c73e
[ "Apache-2.0" ]
null
null
null
src/webots/nodes/WbTrack.hpp
chinakwy/webots
7c35a359848bafe81fe0229ac2ed587528f4c73e
[ "Apache-2.0" ]
1
2020-09-25T02:01:45.000Z
2020-09-25T02:01:45.000Z
// Copyright 1996-2019 Cyberbotics Ltd. // // 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. // // WbTrack.hpp // // Implemented node class representing a generic robot tank track #ifndef WB_TRACK_HPP #define WB_TRACK_HPP #include "WbSolid.hpp" class WbBaseNode; class WbBrake; class WbLinearMotor; class WbLogicalDevice; class WbPositionSensor; class WbSFInt; class WbSFVector2; class WbShape; class WbTextureTransform; class WbTrackWheel; struct WrNode; class WbTrack : public WbSolid { Q_OBJECT public: explicit WbTrack(WbTokenizer *tokenizer = NULL); WbTrack(const WbTrack &other); explicit WbTrack(const WbNode &other); virtual ~WbTrack(); // reimplemented public functions int nodeType() const override { return WB_NODE_TRACK; } void preFinalize() override; void createWrenObjects() override; void postFinalize() override; void prePhysicsStep(double ms) override; void exportNodeSubNodes(WbVrmlWriter &writer) const override; void setMatrixNeedUpdate() override; void reset() override; void save() override; double contactSurfaceVelocity() const { return mSurfaceVelocity; } double position() const { return mMotorPosition; } QVector<WbLogicalDevice *> devices() const; WbLinearMotor *motor() const; WbPositionSensor *positionSensor() const; WbBrake *brake() const; void animateMesh(); protected slots: void updateChildren() override; private: WbTrack &operator=(const WbTrack &); // non copyable WbNode *clone() const override { return new WbTrack(*this); } void init(); WbMFNode *mDeviceField; WbSFVector2 *mTextureAnimationField; WbSFNode *mGeometryField; WbSFInt *mGeometriesCountField; // internal fields WbLinearMotor *mLinearMotor; WbBrake *mBrake; double mMotorPosition; double mSurfaceVelocity; dBodyID mBodyID; // wheels QVector<WbTrackWheel *> mWheelsList; void clearWheelsList(); // texture animation WbShape *mShape; WbTextureTransform *mTextureTransform; WbVector2 mInitialTextureTransformTranslation; // geometries animation struct PathSegment { PathSegment(const WbVector2 &pointA, const WbVector2 &pointB, double angle, double r, const WbVector2 &c, const WbVector2 &direction) : startPoint(pointA), endPoint(pointB), initialRotation(angle), radius(r), center(c), increment(direction) {} PathSegment(const WbVector2 &pointA, const WbVector2 &pointB, double angle, const WbVector2 &normalizedDirection) : startPoint(pointA), endPoint(pointB), initialRotation(angle), radius(-1), center(WbVector2()), increment(normalizedDirection) {} PathSegment() : initialRotation(M_PI), radius(0.0) {} WbVector2 startPoint; WbVector2 endPoint; double initialRotation; double radius; // round path only WbVector2 center; // round path only WbVector2 increment; // straight path only }; struct BeltPosition { BeltPosition(const WbVector2 &pos, double angle, int index) : position(pos), rotation(angle), segmentIndex(index) {} BeltPosition() : rotation(0.0), segmentIndex(0) {} WbVector2 position; double rotation; int segmentIndex; }; double mPathLength; double mPathStepSize; QVector<PathSegment> mPathList; BeltPosition mFirstGeometryPosition; void computeBeltPath(); BeltPosition computeNextGeometryPosition(BeltPosition current, double stepSize, bool segmentChanged = false) const; // animated mesh struct AnimatedObject { WbGeometry *geometry; WrMaterial *material; bool castShadows; }; double mAnimationStepSize; QList<AnimatedObject *> mAnimatedObjectList; QList<WrTransform *> mBeltElements; QList<BeltPosition> mBeltPositions; QList<WrNode *> mWrenNodes; WbWrenMeshBuffers *createMeshBuffers(const WbGeometry *geom) const; void initAnimatedGeometriesBeltPosition(); void clearAnimatedGeometries(); bool findAndConnectAnimatedGeometries(bool connectSignals, QList<WbShape *> *shapeList); void exportAnimatedGeometriesMesh(WbVrmlWriter &writer) const; private slots: void addDevice(int index); void updateDevices(); void updateShapeNode(); void updateTextureTransform(); void updateWheelsList(); void updateAnimatedGeometriesAfterFinalization(WbBaseNode *node); void updateAnimatedGeometries(); void updateAnimatedGeometriesPath(); void updateTextureAnimation(); }; #endif
28.72093
120
0.742105
[ "mesh", "geometry" ]
046b7b4afedf99065c010efd5e227319cb36fa58
26,297
cpp
C++
mystrategy/src/MyStrategy.cpp
kswaldemar/raicup2016
e365112403ca65826c70f50b4ecdd16737a0581b
[ "MIT" ]
null
null
null
mystrategy/src/MyStrategy.cpp
kswaldemar/raicup2016
e365112403ca65826c70f50b4ecdd16737a0581b
[ "MIT" ]
null
null
null
mystrategy/src/MyStrategy.cpp
kswaldemar/raicup2016
e365112403ca65826c70f50b4ecdd16737a0581b
[ "MIT" ]
null
null
null
#include "MyStrategy.h" #include "FieldsDescription.h" #include "PathFinder.h" #include "Logger.h" #include "VisualDebug.h" #include "BehaviourConfig.h" #include <cassert> #include <list> #include <algorithm> using namespace model; using namespace std; using namespace geom; BehaviourConfig::Damage BehaviourConfig::damage = BehaviourConfig::Damage(); BehaviourConfig::NavK BehaviourConfig::navigation_k = BehaviourConfig::NavK(); BehaviourConfig::BulletF BehaviourConfig::bullet = BehaviourConfig::BulletF(); BehaviourConfig::Targeting BehaviourConfig::targeting = BehaviourConfig::Targeting(); MyStrategy::MyStrategy() { } void MyStrategy::move(const Wizard &self, const World &world, const Game &game, Move &move) { //Initialize info pack first initialize_info_pack(self, world, game); //Initialize once static bool initialized = initialize_strategy(self, world, game); assert(initialized); //Update information each_tick_update(self, world, game); fields::FieldMap strategic_map = create_danger_map(); //Try learn something if (game.isSkillsEnabled()) { m_sb->try_level_up(move); } //Check for stucking in place static int hold_time = 0; if (std::abs(self.getSpeedX()) + std::abs(self.getSpeedY()) < 0.1) { ++hold_time; } else { hold_time = 0; } const bool not_moved = hold_time >= 7; const Point2D me{self.getX(), self.getY()}; //Pre actions VISUAL(beginPre()); Behaviour current_action = BH_COUNT; static Behaviour prev_action = BH_COUNT; Vec2D dir; double danger_level = strategic_map.get_value(me); fields::FieldMap navigation(fields::FieldMap::MIN); int nav_radius = 2000; double best_enemy = m_ev->choose_enemy(); const bool have_target = best_enemy > 0; const bool can_shoot = m_ev->can_shoot_to_target(); bool hold_face = have_target; if (danger_level <= BehaviourConfig::danger_attack_t && current_action == BH_COUNT && have_target) { //Danger is ok to attack //Enemy choosen prev_action = current_action; current_action = BH_ATTACK; auto description = m_ev->destroy(move); if (self.getDistanceTo(description.pt.x, description.pt.y) >= description.att_range) { m_bhs[BH_ATTACK].update_target(description.pt); if (m_bhs[BH_ATTACK].is_path_spoiled()) { auto way = m_pf->find_way(description.pt, description.att_range - PathFinder::GRID_SIZE); m_bhs[BH_ATTACK].load_path(std::move(way), description.pt); } dir = m_bhs[BH_ATTACK].get_next_direction(self); navigation.add_field(std::make_unique<fields::LinearField>( me + dir, 0, nav_radius, BehaviourConfig::navigation_k.attack, -BehaviourConfig::navigation_k.attack * nav_radius )); } else if (self.getDistanceTo(description.pt.x, description.pt.y) <= description.att_range) { current_action = BH_MINIMIZE_DANGER; } } static bool go_for_bonus = false; go_for_bonus = danger_level <= BehaviourConfig::danger_bonus_earn_t && m_ev->can_leave_battlefield() && (m_pf->bonuses_is_under_control() || go_for_bonus); if (go_for_bonus) { //Here check for bonuses time and go to one of them if (m_bhs[BH_EARN_BONUS].is_path_spoiled()) { const double my_speed = game.getWizardForwardSpeed() * m_i.ew->get_wizard_movement_factor(self); const double max_dist = 1600; const int bonus_overtime = 100; const MyBonus *best = nullptr; double min_dist = 1e5; for (const auto &b : m_i.ew->get_bonuses()) { const double dist = self.getDistanceTo(b.getX(), b.getY()) - game.getBonusRadius(); if (dist >= max_dist || dist >= min_dist) { continue; } int reach_time = static_cast<int>(ceil(dist / my_speed)); int diff = b.getRemainingTime() - reach_time; if (diff <= bonus_overtime) { best = &b; min_dist = dist; } } if (best != nullptr) { m_bhs[BH_EARN_BONUS].update_target(best->getPoint()); auto way = m_pf->find_way(best->getPoint(), game.getBonusRadius() + 5); m_bhs[BH_EARN_BONUS].load_path( std::move(way), best->getPoint() ); go_for_bonus = true; } else { go_for_bonus = false; } } if (!m_bhs[BH_EARN_BONUS].is_path_spoiled()) { go_for_bonus = true; dir = m_bhs[BH_EARN_BONUS].get_next_direction(self); navigation.clear(); navigation.add_field(std::make_unique<fields::LinearField>( me + dir, 0, nav_radius, BehaviourConfig::navigation_k.bonus, -BehaviourConfig::navigation_k.bonus * nav_radius )); } else { go_for_bonus = false; } if (go_for_bonus) { prev_action = current_action; current_action = BH_EARN_BONUS; hold_face = can_shoot; } } //Prevent bonus denying for (const auto &b : m_i.ew->get_bonuses()) { int rem_time = b.getRemainingTime(); if (rem_time > 0 && rem_time < 26) { const double d1 = game.getBonusRadius() + self.getRadius(); m_damage_map.add_field(std::make_unique<fields::LinearField>( b.getPoint(), 0, d1, -0.1 / d1, 1 )); } } geom::Point2D waypoint{0, 0}; // if (danger_level <= BehaviourConfig::danger_scout_t && current_action == BH_COUNT) { //Move by waypoints prev_action = current_action; current_action = BH_SCOUT; Vec2D wp_next = m_pf->get_next_waypoint(); VISUAL(circle(wp_next.x, wp_next.y, PathFinder::WAYPOINT_RADIUS, 0x001111)); m_bhs[BH_SCOUT].update_target(wp_next); if (m_bhs[BH_SCOUT].is_path_spoiled()) { auto way = m_pf->find_way(wp_next, PathFinder::WAYPOINT_RADIUS - PathFinder::GRID_SIZE); m_bhs[BH_SCOUT].load_path( std::move(way), wp_next ); } dir = m_bhs[BH_SCOUT].get_next_direction(self); navigation.clear(); navigation.add_field(std::make_unique<fields::LinearField>( me + dir, 0, nav_radius, BehaviourConfig::navigation_k.next_wp, -BehaviourConfig::navigation_k.next_wp * nav_radius )); waypoint = me + dir; VISUAL(line(self.getX(), self.getY(), self.getX() + dir.x, self.getY() + dir.y, 0xFF0000)); } if (current_action == BH_COUNT || current_action == BH_MINIMIZE_DANGER) { prev_action = current_action; current_action = BH_MINIMIZE_DANGER; auto wp_prev = m_pf->get_previous_waypoint(); if (wp_prev.x > 0 && wp_prev.y > 0) { VISUAL(circle(wp_prev.x, wp_prev.y, PathFinder::WAYPOINT_RADIUS, 0x002211)); navigation.add_field( std::make_unique<fields::LinearField>( wp_prev, 0, nav_radius, BehaviourConfig::navigation_k.prev_wp, -BehaviourConfig::navigation_k.prev_wp * 500 ) ); if (m_bhs[BH_MINIMIZE_DANGER].is_path_spoiled() && not_moved) { //Possibly stuck in place auto way = m_pf->find_way(wp_prev, PathFinder::WAYPOINT_RADIUS - PathFinder::GRID_SIZE); m_bhs[BH_MINIMIZE_DANGER].update_target(wp_prev); m_bhs[BH_MINIMIZE_DANGER].load_path( std::move(way), wp_prev ); } if (!m_bhs[BH_MINIMIZE_DANGER].is_path_spoiled()) { dir = m_bhs[BH_MINIMIZE_DANGER].get_next_direction(self); navigation.clear(); navigation.add_field(std::make_unique<fields::LinearField>( me + dir, 0, nav_radius, BehaviourConfig::navigation_k.prev_wp, -BehaviourConfig::navigation_k.prev_wp * nav_radius )); } } } //static int last_hp = self.getLife(); //if (self.getLife() < last_hp) { // LOG("Hurt was on tick %d\n", world.getTickIndex() - 1); //} //last_hp = self.getLife(); // // //static geom::Point2D initial = me; //navigation.add_field(std::make_unique<fields::LinearField>( // initial, 0, 300, 0.0001, -0.03 //)); const auto &bullets_map = m_ev->get_bullet_damage_map(); dir = potential_vector(me, {&m_damage_map, &navigation, &bullets_map}); if (dir.len() > EPS) { m_pf->move_along(dir, move, hold_face); } //Check tree blocking way const MyLivingUnit *block_obstacle = nullptr; bool destroy_obstacle = false; if ((waypoint.x > 0 && waypoint.y > 0 && !m_i.ew->check_no_collision(waypoint, self.getRadius(), &block_obstacle)) // Obstacle blocking way || (!m_i.ew->check_no_collision(me, self.getRadius() + 4.5, &block_obstacle) && dir.len() <= EPS) // Local minimum because of obstacle ) { //We will meet collision soon VISUAL(fillCircle(waypoint.x, waypoint.y, 10, 0x990000)); if (block_obstacle && block_obstacle->getType() == MyLivingUnit::TREE) { m_ev->destroy(move, {block_obstacle->getX(), block_obstacle->getY()}, block_obstacle->getRadius()); destroy_obstacle = true; } } if ((current_action == BH_MINIMIZE_DANGER || current_action == BH_EARN_BONUS) && can_shoot && !destroy_obstacle) { //Shoot to enemy, when retreating m_ev->destroy(move); } //TODO: Rewrite it const auto &skills = self.getSkills(); const auto &statuses = self.getStatuses(); const bool has_shield = std::find(skills.cbegin(), skills.cend(), model::SKILL_SHIELD) != skills.cend(); const bool has_haste = std::find(skills.cbegin(), skills.cend(), model::SKILL_HASTE) != skills.cend(); bool shielded = false; bool hastened = false; for (const auto &st : statuses) { shielded = shielded || st.getType() == STATUS_SHIELDED; hastened = hastened || st.getType() == STATUS_HASTENED; } if (has_shield && !shielded && self.getMana() >= game.getShieldManacost()) { move.setAction(ACTION_SHIELD); } else if (has_haste && !hastened && self.getMana() >= game.getHasteManacost()) { move.setAction(ACTION_HASTE); } visualise_field_maps( { &m_damage_map, //&navigation, //&bullets_map, }, me ); VISUAL(endPre()); VISUAL(beginPost()); //m_ev->m_bhandler.visualise_projectiles(); //// //m_ev->m_bhandler.check_projectiles_hit(me, self.getRadius()); //for (const auto &i : m_i.ew->get_obstacles()) { // VISUAL(fillCircle(i.getX(), i.getY(), 5, 0x550011)); //} #ifdef RUNNING_LOCAL { char buf[20]; auto bonuses = m_i.ew->get_bonuses(); sprintf(buf, "%d", bonuses[0].getRemainingTime()); VISUAL(text(bonuses[0].getX(), bonuses[0].getY() + 50, buf, 0x111199)); sprintf(buf, "%d", bonuses[1].getRemainingTime()); VISUAL(text(bonuses[1].getX(), bonuses[1].getY() + 50, buf, 0x111199)); } #endif #ifdef RUNNING_LOCAL for (const auto &i : m_i.ew->get_hostile_towers()) { char buf[20]; sprintf(buf, "%d", i.getRemainingActionCooldownTicks()); VISUAL(text(i.getX(), i.getY() + 50, buf, 0x00CC00)); } #endif // //#ifdef RUNNING_LOCAL // dir *= 3; // VISUAL(line(self.getX(), self.getY(), self.getX() + dir.x, self.getY() + dir.y, 0xB325DA)); // char buf[10]; // char c = 'N'; // assert(current_action != BH_COUNT); // switch (current_action) { // case BH_MINIMIZE_DANGER:c = 'M'; // break; // case BH_ATTACK:c = 'A'; // break; // case BH_SCOUT:c = 'R'; // break; // case BH_EARN_BONUS: c = 'B'; // break; // } // sprintf(buf, "%c %3.1lf%%", c, m_damage_map.get_value(self.getX(), self.getY())); // VISUAL(text(self.getX() - 70, self.getY() - 60, buf, 0xFF0000)); // sprintf(buf, "[%5.5lf]", strategic_map.get_value(me)); // VISUAL(text(me.x - 70, me.y - 80, buf, 0xFF9900)); // //Vec2D spd{self.getSpeedX(), self.getSpeedY()}; // //sprintf(buf, "spd %3.1lf", spd.len()); // //VISUAL(text(self.getX(), self.getY() - 70, buf, 0x009911)); //#endif VISUAL(endPost()); //if (world.getTickIndex() % 100 == 0) { // LOG("Try to learn %d\n", move.getSkillToLearn()); //} } void MyStrategy::initialize_info_pack(const model::Wizard &self, const model::World &world, const model::Game &game) { m_i.s = &self; m_i.w = &world; m_i.g = &game; } bool MyStrategy::initialize_strategy(const model::Wizard &self, const model::World &world, const model::Game &game) { m_pf = make_unique<PathFinder>(m_i); m_ev = make_unique<Eviscerator>(m_i); m_sb = make_unique<SkillBuilder>(); m_i.ew = make_unique<ExWorld>(world, game); m_bhs[BH_MINIMIZE_DANGER].PATH_SPOIL_TIME = 100; return true; } void MyStrategy::each_tick_update(const model::Wizard &self, const model::World &world, const model::Game &game) { //Check about our death static int last_tick = 0; int cur_tick = world.getTickIndex(); if (cur_tick - last_tick >= game.getWizardMinResurrectionDelayTicks()) { //Seems resurrection m_pf = make_unique<PathFinder>(m_i); } last_tick = cur_tick; m_i.ew->update_world(self, world, game); //Calculate danger map update_damage_map(); m_pf->update_info(m_i, m_damage_map); m_ev->update_info(m_i); m_sb->update_info(m_i); for (int i = 0; i < BH_COUNT; ++i) { m_bhs[i].update_clock(world.getTickIndex()); } } geom::Vec2D MyStrategy::potential_vector(const Point2D &pt, const std::vector<const fields::FieldMap *> &fmaps) const { constexpr double ANGLE_STEP = 1; constexpr int all_steps = static_cast<int>((360 + ANGLE_STEP) / ANGLE_STEP); std::array<double, all_steps + 1> forces; forces.fill(0); static std::array<double, all_steps> sin_table; static std::array<double, all_steps> cos_table; static std::array<double, all_steps> rad; static bool first_time = true; if (first_time) { first_time = false; for (int i = 0; i < all_steps; ++i) { rad[i] = deg_to_rad(i * ANGLE_STEP); sin_table[i] = sin(rad[i]); cos_table[i] = cos(rad[i]); } } const double factor = m_i.ew->get_wizard_movement_factor(*m_i.s); const double strafe = m_i.g->getWizardStrafeSpeed() * factor; const double fwd = m_i.g->getWizardForwardSpeed() * factor; const double back = m_i.g->getWizardBackwardSpeed() * factor; const int steps = static_cast<int>(360.0 / ANGLE_STEP); double b = fwd; double a = strafe; const double my_angle = m_i.s->getAngle() + pi / 2; const double turn_cos = cos(my_angle); const double turn_sin = sin(my_angle); for (int i = 0; i <= steps; ++i) { double angle = rad[i]; if (angle > pi) { b = back; } Vec2D cur{a * cos_table[i], -b * sin_table[i]}; //Rotate double x1 = cur.x * turn_cos - cur.y * turn_sin; double y1 = cur.y * turn_cos + cur.x * turn_sin; cur.x = x1 + pt.x; cur.y = y1 + pt.y; if (m_i.ew->check_no_collision(cur, m_i.s->getRadius())) { for (const auto &fmap : fmaps) { forces[i] += fmap->get_value(cur); } } else { forces[i] = 1e5; } } for (const auto &fmap : fmaps) { forces[all_steps] += fmap->get_value(pt); } int min_idx = all_steps; for (int i = 0; i < forces.size(); ++i) { if (forces[i] < forces[min_idx]) { min_idx = i; } } if (min_idx == all_steps) { //Local minimum found, so best to stay here return {0, 0}; } double angle = rad[min_idx]; if (angle > pi) { b = back; } else { b = fwd; } double x = a * cos_table[min_idx]; double y = -b * sin_table[min_idx]; double x1 = x * turn_cos - y * turn_sin; double y1 = y * turn_cos + x * turn_sin; return {x1, y1}; } void MyStrategy::update_damage_map() { m_damage_map.clear(); auto &damage_fields = m_damage_map; const double my_speed = m_i.g->getWizardBackwardSpeed() * m_i.ew->get_wizard_movement_factor(*m_i.s); const double my_radius = m_i.s->getRadius(); const double life_factor = 1.0 - m_i.s->getLife() / m_i.s->getMaxLife(); const double klife = 1.0 + life_factor; for (const auto &i : m_i.ew->get_hostile_creeps()) { const Point2D unit_center{i->getX(), i->getY()}; double at_range; double force; if (i->getType() == MINION_FETISH_BLOWDART) { at_range = m_i.g->getFetishBlowdartAttackRange(); force = BehaviourConfig::damage.fetish * klife; } else { at_range = m_i.g->getOrcWoodcutterAttackRange(); force = BehaviourConfig::damage.orc * klife; } at_range += my_radius; const double narrow_attack_range = m_ev->get_minion_aggression_radius(*i); if (narrow_attack_range < at_range) { at_range = narrow_attack_range; } double d1 = at_range - i->getRemainingActionCooldownTicks() * my_speed; if (d1 >= 1) { damage_fields.add_field(std::make_unique<fields::LinearField>( unit_center, 0, d1, -force / d1, BehaviourConfig::damage.center_mult * force )); } else { d1 = 0; } at_range += BehaviourConfig::damage.minion_extra_r * life_factor; if (!eps_equal(d1, at_range)) { damage_fields.add_field(std::make_unique<fields::LinearField>( unit_center, d1, at_range, -force / (at_range - d1), force + (force / (at_range - d1)) * d1 )); } } for (const auto &i : m_i.ew->get_hostile_wizards()) { const Point2D unit_center{i->getX(), i->getY()}; const double at_range = i->getCastRange() + my_radius; //TODO: Respect mana //TODO: Respect skills (fireball, frostbolt, ultimate magic missile) //TODO: Respect haste increased turn speed int rem_cooldown = i->getRemainingActionCooldownTicks(); const double angle_to_me = std::abs(i->getAngleTo(*m_i.s)); rem_cooldown += static_cast<int>(ceil(angle_to_me / m_i.g->getWizardMaxTurnAngle())); double d1 = at_range - rem_cooldown * my_speed; const double force = BehaviourConfig::damage.wizard * klife; if (d1 >= 1) { damage_fields.add_field(std::make_unique<fields::LinearField>( unit_center, 0, d1, -force / d1, BehaviourConfig::damage.center_mult * force )); } else { d1 = 0; } if (!eps_equal(d1, at_range)) { damage_fields.add_field(std::make_unique<fields::LinearField>( unit_center, d1, at_range, -force / (at_range - d1), force + (force / (at_range - d1)) * d1 )); } } for (const auto &i : m_i.ew->get_hostile_towers()) { const Point2D unit_center{i.getX(), i.getY()}; const double at_range = i.getAttackRange() + 1; double force; if (m_ev->tower_maybe_attack_me(i)) { force = BehaviourConfig::damage.tower_active; } else { force = BehaviourConfig::damage.tower; } if (m_i.g->isRawMessagesEnabled()) { force = BehaviourConfig::damage.tower * 0.6; } force *= klife; const double retr_diff = i.getRemainingActionCooldownTicks() * my_speed; double d1 = at_range - retr_diff; if (d1 >= 1) { damage_fields.add_field(std::make_unique<fields::LinearField>( unit_center, 0, d1, -force / d1, BehaviourConfig::damage.center_mult * force )); } else { d1 = 0; } damage_fields.add_field(std::make_unique<fields::LinearField>( unit_center, d1, at_range, -force / retr_diff, force + (force / retr_diff) * d1 )); #ifdef RUNNING_LOCAL { char buf[10]; sprintf(buf, "%3d", i.getRemainingActionCooldownTicks()); VISUAL(text(i.getX(), i.getY() + 30, buf, 0x004400)); } #endif } } void MyStrategy::visualise_field_maps(const std::vector<const fields::FieldMap *> &fmaps, const geom::Point2D &center) { #ifdef RUNNING_LOCAL const int GRID_SIZE = 30; const int half = GRID_SIZE / 2; Vec2D tmp; for (int x = -600; x <= 600; x += GRID_SIZE) { for (int y = -600; y <= 600; y += GRID_SIZE) { double x_a = center.x + x; double y_a = center.y + y; double force = 0; for (const auto &fmap : fmaps) { force += fmap->get_value(x_a, y_a); } force *= 255; force = std::min(force, 255.0); force = std::max(force, -255.0); if (eps_equal(force, 0)) { continue; } int color = static_cast<uint8_t>(std::abs(force)); color = 255 - color; if (force < 0) { color = (color << 16) | 0xff00 | color; } else { //color = (color << 16) | (color << 8) | color; color = (color << 16) | (color << 8) | 0xff; } VISUAL(fillRect(x_a - half - 1, y_a - half - 1, x_a + half, y_a + half, color)); } } #endif } fields::FieldMap MyStrategy::create_danger_map() { using namespace fields; FieldMap ret(FieldMap::ADD); const double my_speed = m_i.g->getWizardBackwardSpeed() * m_i.ew->get_wizard_movement_factor(*m_i.s); const int my_life = m_i.s->getLife(); const double my_max_life = m_i.s->getMaxLife(); //TODO: Respect self shield for (const auto &i : m_i.ew->get_hostile_towers()) { DangerField::Config conf = { i.getDamage(), i.getAttackRange(), i.getRemainingActionCooldownTicks(), i.getCooldown(), 0 // Tower cannot move }; ret.add_field(std::make_unique<DangerField>( i.getPoint(), 0, i.getAttackRange() + 1, my_speed, my_life, my_max_life, conf )); } for (const auto &i : m_i.ew->get_hostile_creeps()) { const double attack_range = i->getType() == MINION_ORC_WOODCUTTER ? m_i.g->getOrcWoodcutterAttackRange() : m_i.g->getFetishBlowdartAttackRange(); //TODO: Respect minion angle as increased remaining cooldown DangerField::Config conf = { i->getDamage(), attack_range + m_i.s->getRadius(), i->getRemainingActionCooldownTicks(), i->getCooldownTicks(), m_i.g->getMinionSpeed() }; //TODO: Check that minion will attack us and narrow field if not //TODO: Adjust to emulate going away ret.add_field(std::make_unique<DangerField>( geom::Point2D(i->getX(), i->getY()), 0, i->getVisionRange(), my_speed, my_life, my_max_life, conf )); } for (const auto &i : m_i.ew->get_hostile_wizards()) { const auto cooldowns = i->getRemainingCooldownTicksByAction(); const double speed = m_i.g->getWizardForwardSpeed() * m_i.ew->get_wizard_movement_factor(*i); int overtime = 0; const double angle = std::abs(i->getAngleTo(*m_i.s)); //TODO: Respect haste increased turn speed overtime += static_cast<int>(ceil(angle / m_i.g->getWizardMaxTurnAngle())); //TODO: Respect damage increase auras //TODO: Honor fireball and frostbolt ultimates DangerField::Config conf = { m_i.g->getMagicMissileDirectDamage(), i->getCastRange() + m_i.s->getRadius(), cooldowns[ACTION_MAGIC_MISSILE], m_i.g->getMagicMissileCooldownTicks() + overtime, speed, }; ret.add_field(std::make_unique<DangerField>( geom::Point2D(i->getX(), i->getY()), 0, i->getVisionRange(), my_speed, my_life, my_max_life, conf )); } return ret; }
34.738441
121
0.551508
[ "vector", "model", "3d" ]
046e3abd484d8fdbb9038f815a1fc77e17c53fd0
4,789
cpp
C++
Plugins/PointSprite/ParaViewPlugin/Qvis/AttributeSubject.cpp
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
Plugins/PointSprite/ParaViewPlugin/Qvis/AttributeSubject.cpp
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
Plugins/PointSprite/ParaViewPlugin/Qvis/AttributeSubject.cpp
cjh1/ParaView
b0eba067c87078d5fe56ec3cb21447f149e1f31a
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************** * * Copyright (c) 2000 - 2007, The Regents of the University of California * Produced at the Lawrence Livermore National Laboratory * All rights reserved. * * This file is part of VisIt. For details, see http://www.llnl.gov/visit/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * 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 disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or materials provided with the distribution. * - Neither the name of the UC/LLNL 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 REGENTS OF THE UNIVERSITY OF * CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * *****************************************************************************/ #include <AttributeSubject.h> // ******************************************************************* // Method: AttributeSubject::AttributeSubject // // Purpose: // Constructor for the AttributeSubject class. // // Arguments: // formatString : This string describes the kinds of attributes that // are contained in the object. // // Programmer: Brad Whitlock // Creation: Mon Aug 7 12:53:39 PDT 2000 // // Modifications: // // ******************************************************************* AttributeSubject::AttributeSubject(const char *formatString) : AttributeGroup(formatString), Subject() { // nothing special here. } // ******************************************************************* // Method: AttributeSubject::~AttributeSubject // // Purpose: // Destructor for the AttributeSubject class. // // Programmer: Brad Whitlock // Creation: Mon Aug 7 12:54:49 PDT 2000 // // Modifications: // // ******************************************************************* AttributeSubject::~AttributeSubject() { // nothing special here either. } // ******************************************************************* // Method: AttributeSubject::Notify() // // Purpose: // Tells all Observers to update, then unselects all the attributes. // // Programmer: Brad Whitlock // Creation: Wed Aug 9 15:55:06 PST 2000 // // Modifications: // // ******************************************************************* void AttributeSubject::Notify() { // Call the base class's Notify method. Subject::Notify(); // Now that all the Obsevrers have been called, unselect all the // attributes. UnSelectAll(); } // **************************************************************************** // Method: AttributeSubject::CreateCompatible // // Purpose: // Creates a compatible object of the specified type. // // Programmer: Brad Whitlock // Creation: Wed Oct 30 14:11:37 PST 2002 // // Modifications: // // **************************************************************************** AttributeSubject * AttributeSubject::CreateCompatible(const std::string &) const { return 0; } // **************************************************************************** // Method: AttributeSubject::TypeName // // Purpose: // Returns the name of the type. // // Returns: The name of the type. // // Programmer: Kathleen Bonnell // Creation: June 20, 2006 // // Modifications: // // **************************************************************************** const std::string AttributeSubject::TypeName() const { return "AttributeSubject"; }
33.027586
79
0.579244
[ "object" ]
0473caa467a05dc0721769dc37e9a9114367480c
3,738
cpp
C++
examples/demo_input.cpp
NBiermann/cpp-terminal
efe33d80725e6bd4b4abf3fd3769a02efe90c392
[ "Unlicense" ]
null
null
null
examples/demo_input.cpp
NBiermann/cpp-terminal
efe33d80725e6bd4b4abf3fd3769a02efe90c392
[ "Unlicense" ]
null
null
null
examples/demo_input.cpp
NBiermann/cpp-terminal
efe33d80725e6bd4b4abf3fd3769a02efe90c392
[ "Unlicense" ]
null
null
null
/* */ #include "../cpp-terminal/base.hpp" #include "../cpp-terminal/input.hpp" #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wzero-as-null-pointer-constant" #pragma GCC diagnostic ignored "-Wc++98-c++11-compat-binary-literal" #pragma GCC diagnostic ignored "-Wc++98-c++11-compat-pedantic" #pragma GCC diagnostic ignored "-Wsign-conversion" #endif // defined #include "unicodelib_encodings.h" #if defined(__GNUC__) || defined(__clang__) #pragma GCC diagnostic pop #endif // defined #include <iostream> #include <iomanip> #include <vector> #include <string> #include <fstream> #include <set> using namespace std; using namespace Term; std::map<int, std::string> keyname{ {Key::BACKSPACE, "BACKSPACE"}, {Key::ENTER, "ENTER"}, {Key::TAB, "TAB"}, {Key::ESC, "ESC"}, {Key::SHIFT, "SHIFT"}, {Key::CTRL, "CTRL"}, {Key::ALT, "ALT"}, {Key::ARROW_UP, "ARROW_UP"}, {Key::ARROW_DOWN, "ARROW_DOWN"}, {Key::ARROW_RIGHT, "ARROW_RIGHT"}, {Key::ARROW_LEFT, "ARROW_LEFT"}, {Key::PAGE_UP, "PAGE_UP"}, {Key::PAGE_DOWN, "PAGE_DOWN"}, {Key::HOME, "HOME"}, {Key::END, "END"}, {Key::DEL, "DEL"}, {Key::INSERT, "INSERT"}, {Key::NUMERIC_5, "NUMERIC_5"}, {Key::F1, "F1"}, {Key::F2, "F2"}, {Key::F3, "F3"}, {Key::F4, "F4"}, {Key::F5, "F5"}, {Key::F6, "F6"}, {Key::F7, "F7"}, {Key::F8, "F8"}, {Key::F9, "F9"}, {Key::F10, "F10"}, {Key::F11, "F11"}, {Key::F12, "F12"}, {Key::UNKNOWN, "UNKNOWN"} }; int main() { int ctrl_c_count = 2; try { Terminal term(RAW_INPUT | DISABLE_CTRL_C); while (true) { u32string s = Term::Private::read_sequence(); if (s.size() == 1) { cout << "codepoint " << hex << (int)s[0] << dec << " (hex)" << endl; } else { cout << "sequence = " << hex; for (auto c : s) cout << (int)c << " "; cout << "(hex)" << dec << endl << "sequence = <ESC> "; for (auto it = s.begin() + 1; it != s.end(); ++it) cout << unicode::utf8::encode_codepoint(*it) << " "; cout << dec << endl; } cout << "recognized input = "; char32_t c = Term::Private::decode_sequence(s); if (c == U'\x3') --ctrl_c_count; else ctrl_c_count = 2; if (c & Key::SHIFT) { cout << "Shift-"; c = c & ~Key::SHIFT; } if (c & Key::ALT) { cout << "Alt-"; c = c & ~Key::ALT; } if (c & Key::CTRL) { cout << "Ctrl-"; c = c & ~Key::CTRL; } if (keyname.count(c)) { cout << keyname[c] << endl; } else if (c < 27) { cout << "Ctrl-" << char('A' + c - 1) << endl; } else if (c < 32) { cout << "Ctrl-" << char('0' + c - 24) << endl; } else { cout << unicode::utf8::encode_codepoint(c) << endl; } if (c == U'\x3') { if (ctrl_c_count) { cout << "press CTRL-C again to exit" << endl; } else { cout << "aborting ..." << endl; break; } } cout << endl; } } catch (const std::runtime_error& re) { std::cerr << "Runtime error: " << re.what() << std::endl; return 2; } catch (...) { std::cerr << "Unknown error." << std::endl; return 1; } return 0; }
28.534351
73
0.453451
[ "vector" ]
0474c74a60ef43c00d213538de3596cd95ee52c2
3,016
cpp
C++
unittests/Mutators/ScalarValueMutatorTest.cpp
myfreeweb/mull
ac74f0e7b08652037f5e893d06d2aaa38e91ac02
[ "Apache-2.0" ]
null
null
null
unittests/Mutators/ScalarValueMutatorTest.cpp
myfreeweb/mull
ac74f0e7b08652037f5e893d06d2aaa38e91ac02
[ "Apache-2.0" ]
null
null
null
unittests/Mutators/ScalarValueMutatorTest.cpp
myfreeweb/mull
ac74f0e7b08652037f5e893d06d2aaa38e91ac02
[ "Apache-2.0" ]
null
null
null
#include "Config.h" #include "Context.h" #include "Mutators/ScalarValueMutator.h" #include "MutationPoint.h" #include "TestModuleFactory.h" #include "Toolchain/Compiler.h" #include "Toolchain/Toolchain.h" #include "Filter.h" #include "Testee.h" #include "MutationsFinder.h" #include <llvm/IR/Instructions.h> #include <llvm/IR/LLVMContext.h> #include <llvm/IR/Module.h> #include "gtest/gtest.h" using namespace mull; using namespace llvm; static TestModuleFactory TestModuleFactory; TEST(ScalarValueMutator, getMutationPoint) { auto mullModule = TestModuleFactory.create_SimpleTest_ScalarValue_Module(); Context mullContext; mullContext.addModule(std::move(mullModule)); auto scalarValueFunction = mullContext.lookupDefinedFunction("scalar_value"); std::vector<std::unique_ptr<Testee>> testees; testees.emplace_back(make_unique<Testee>(scalarValueFunction, nullptr, 1)); auto mergedTestees = mergeTestees(testees); Config config; config.normalizeParallelizationConfig(); std::vector<std::unique_ptr<Mutator>> mutators; mutators.emplace_back(make_unique<ScalarValueMutator>()); MutationsFinder finder(std::move(mutators), config); Filter filter; std::vector<MutationPoint *> mutationPoints = finder.getMutationPoints(mullContext, mergedTestees, filter); ASSERT_EQ(mutationPoints.size(), 4U); ASSERT_TRUE(isa<StoreInst>(mutationPoints[0]->getOriginalValue())); ASSERT_TRUE(isa<StoreInst>(mutationPoints[1]->getOriginalValue())); ASSERT_TRUE(isa<BinaryOperator>(mutationPoints[2]->getOriginalValue())); ASSERT_TRUE(isa<BinaryOperator>(mutationPoints[3]->getOriginalValue())); ASSERT_EQ(mutationPoints[0]->getAddress().getFnIndex(), 0); ASSERT_EQ(mutationPoints[0]->getAddress().getBBIndex(), 0); ASSERT_EQ(mutationPoints[0]->getAddress().getIIndex(), 4); ASSERT_EQ(mutationPoints[1]->getAddress().getFnIndex(), 0); ASSERT_EQ(mutationPoints[1]->getAddress().getBBIndex(), 0); ASSERT_EQ(mutationPoints[1]->getAddress().getIIndex(), 5); ASSERT_EQ(mutationPoints[2]->getAddress().getFnIndex(), 0); ASSERT_EQ(mutationPoints[2]->getAddress().getBBIndex(), 0); ASSERT_EQ(mutationPoints[2]->getAddress().getIIndex(), 9); ASSERT_EQ(mutationPoints[3]->getAddress().getFnIndex(), 0); ASSERT_EQ(mutationPoints[3]->getAddress().getBBIndex(), 0); ASSERT_EQ(mutationPoints[3]->getAddress().getIIndex(), 12); } TEST(DISABLED_ScalarValueMutator, failingMutationPoint) { auto mullModule = TestModuleFactory.create_CustomTest_OpenSSL_bio_enc_test_Module(); MutationPointAddress address(15, 10, 7); ScalarValueMutator mutator; MutationPoint point(&mutator, address, nullptr, mullModule.get(), "diagnostics", SourceLocation::nullSourceLocation()); Config config; Toolchain toolchain(config); // auto mutant = point.cloneModuleAndApplyMutation(); // toolchain.compiler().compileModule(mutant.get()); }
37.234568
121
0.730106
[ "vector" ]
04773cf9d18ea63362bc9aa7b95b92b0ec825c45
52,675
cpp
C++
src/core/impl/graph/static_infer_impl.cpp
csf0429/MegEngine
4cb7fa8e28cbe7fd23c000e4657300f1db0726ae
[ "Apache-2.0" ]
5,168
2020-03-19T06:10:04.000Z
2022-03-31T11:11:54.000Z
src/core/impl/graph/static_infer_impl.cpp
csf0429/MegEngine
4cb7fa8e28cbe7fd23c000e4657300f1db0726ae
[ "Apache-2.0" ]
286
2020-03-25T01:36:23.000Z
2022-03-31T10:26:33.000Z
src/core/impl/graph/static_infer_impl.cpp
csf0429/MegEngine
4cb7fa8e28cbe7fd23c000e4657300f1db0726ae
[ "Apache-2.0" ]
515
2020-03-19T06:10:05.000Z
2022-03-30T09:15:59.000Z
/** * \file src/core/impl/graph/static_infer_impl.cpp * MegEngine is Licensed under the Apache License, Version 2.0 (the "License") * * Copyright (c) 2014-2021 Megvii Inc. All rights reserved. * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ #define LOG_INFER_RESULT 0 #include "./static_infer_impl.h" #include "./cg_impl.h" #include "./impl_common.h" #include "megbrain/graph/exc_extra_info.h" #include "megbrain/graph/helper.h" #include "megbrain/graph/operator_node.h" #include "megbrain/graph/var_node.h" #include "megbrain/utils/shared_set.h" #if LOG_INFER_RESULT #include "megbrain/tensor_iter.h" #endif #include <cstring> #include <deque> using namespace mgb; using namespace cg; using namespace static_infer; namespace { constexpr size_t INFER_VALUE_SIZE_THRESH_FOR_WARNING = 1024, INFER_VALUE_CHECK_UNCHANGE_MAX_SIZE = TensorLayout::MAX_NDIM; constexpr bool is_static_infer_type(InferType::Flag t) { return t & (InferType::RT_STATIC | InferType::CONST); } #if MGB_ENABLE_EXCEPTION [[noreturn]] void update_rethrow_exc(VarNode* var, MegBrainError& exc) { if (var && !exc.extra_info()) { OperatorNodeExcExtraInfo::record(var->owner_opr(), exc); } throw; } #endif } // namespace /* ===================== nested class decls ===================== */ MGB_DEFINE_CLS_WITH_SUPER(StaticInferManagerImpl::TagTraitBase, TagHandler) // { const bool m_is_const; protected: InferType::Flag m_infer_type = InferType::NO_DESC; //! added each time do_infer() is called and returns //! InferResult::CHANGED size_t m_inp_element_version = 0; TagTraitBase(Tag tag, bool is_const) : Super(tag), m_is_const{is_const} {} public: using TagTraitArray = SmallVector<TagTraitBase*>; /*! * \brief whether this tag is TagConstShapeTrait * * This is not the same as InferType::CONST, which also includes const * value but is lazily inferred. */ bool is_const() const { return m_is_const; } InferType::Flag infer_type() const { return m_infer_type; } //! version of most recent infer result size_t infer_result_version() const { return m_inp_element_version; } size_t update_infer_result_version() override { infer(false, false); return m_inp_element_version; } /*! * \brief get inferred value for pure nodes * * Note: inferencing would be skipped if m_inp_element_synced is true * * \param recomp_mutable_srcnode whether to re-compute mutable src * nodes; if this is true, then this tag must be a mutable src * (i.e. calling infer() on an intermediate trait with * recomp_mutable_srcnode being true is not allowed). * \param allow_fail whether to allow returning nullptr result * \return inferred value, or nullptr if failed */ const InpElement* infer(bool recomp_mutable_srcnode, bool allow_fail); /*! * \brief core implementation for infer(), without handling exceptions * * If infer result changes, all traits that depend on this one would be * marked as out-of-sync. * * \param[out] cur_active_var current variable, used for backtracing */ virtual const InpElement* infer_withoutexc( VarNode** cur_active_var, bool recomp_mutable_srcnode) = 0; virtual const TagTraitArray& deps() const = 0; //! convert to TagTraitMutableBase; return nullptr on failure inline TagTraitMutableBase* as_mutable(); //! assert this is mutable and convert to TagTraitMutableBase inline TagTraitMutableBase* as_mutable_safe(); }; /*! * \brief TagConstShapeTrait is used when the shape of Tag is const * * This is used to reduce memory usage and shorten the inference chain. */ MGB_DEFINE_CLS_WITH_SUPER( StaticInferManagerImpl::TagConstShapeTrait final, TagTraitBase) // { struct InferResultCache { Spinlock mtx; #if __DEPLOY_ON_XP_SP2__ ThinHashMap<size_t, InpElement> storage; #else ThinHashMap<std::thread::id, InpElement> storage; #endif }; static TagTraitArray sm_empty_deps; static InferResultCache sm_result_cache; public: TagConstShapeTrait(Tag tag) : Super(tag, true) { m_infer_type = InferType::CONST; m_inp_element_version = 1; } TagHandlerType handler_type() const override { return TagHandlerType::SHAPE; } void sync_from_var() override { mgb_throw(InternalError, "sync_from_var() called on const shape"); } const InpElement* infer_withoutexc( VarNode** cur_active_var, bool recomp_mutable_srcnode) override { InpElement* ret; { // thread_local not supported on ios; so we us a manual impl MGB_LOCK_GUARD(sm_result_cache.mtx); #if __DEPLOY_ON_XP_SP2__ ret = &sm_result_cache.storage[0]; #else ret = &sm_result_cache.storage[std::this_thread::get_id()]; #endif } ret->m_shape = &tag()->shape(); return ret; } TagTraitArray& deps() const override { return sm_empty_deps; } }; StaticInferManagerImpl::TagConstShapeTrait::TagTraitArray StaticInferManagerImpl::TagConstShapeTrait::sm_empty_deps; StaticInferManagerImpl::TagConstShapeTrait::InferResultCache StaticInferManagerImpl::TagConstShapeTrait::sm_result_cache; //! non-const tag trait that requires inference MGB_DEFINE_CLS_WITH_SUPER( StaticInferManagerImpl::TagTraitMutableBase, TagTraitBase) // { public: TagTraitMutableBase(Tag tag) : Super(tag, false) {} /*! * \brief tags on which this tag depends (i.e. required to infer this * tag) */ const TagTraitArray& deps() const final { return m_deps; } /*! * \brief sync shape/value from corresponding var, used for * dependents without shape_desc */ void sync_from_var() override; const SharedSet<TagHandler*, TagHandlerSet>& missing_inp() { if (!m_initialized && !m_missing_input) { mgb_assert(m_infer_type == InferType::NO_DESC); m_missing_input.insert(this); } return m_missing_input; } /*! * \brief add an extra receiver to this trait; so when this trait * changes, *ptr* would be marked out of sync */ void add_extra_receiver(TagTraitMutableBase* ptr) { auto rst = m_receivers.insert(ptr); mgb_assert(rst.second); } /*! * \brief add an extra dependency * * Extra deps can only exist due to implicitly computed value through * sub graph, and only should be added by SubgraphStaticInferHelperImpl */ void add_extra_dep(TagTraitBase* t) { mgb_assert(tag()->owner_graph() == t->tag()->owner_graph()); m_deps.push_back(t); } void remove_extra_receiver(TagTraitMutableBase* ptr) { auto cnt = m_receivers.erase(ptr); mgb_assert(cnt == 1); } //! whether previous inference succeeds bool prev_infer_succeed() const { return m_infer_withoutexc_ret; } //! original deps given in the InferDesc by the caller virtual const DepVal& raw_deps() = 0; protected: //! current infer result, to be used by dependents InpElement m_inp_element; enum class InferResult { UNCHANGED, CHANGED, FAILED }; /*! * \brief infer the shape or value and update m_inp_element * \return whether its shape or value is actually updated */ virtual InferResult do_infer(const InpVal& inp) = 0; /*! * \brief set the shape or value from corresponding VarNode * \return whether its shape or value is actually updated */ virtual InferResult do_sync_from_var() = 0; /*! * \brief initialize deps and infer_type */ void init(SourceType src_type, StaticInferManagerImpl* mgr); bool is_mutable_src() const { return m_deps.empty() && m_infer_type == InferType::RT_STATIC; } /*! * \brief whether init() has been called (i.e. whether infer desc is * set) */ bool initialized() const { return m_initialized; } private: bool m_initialized = false; //! whether current m_inp_element reflects newest input value bool m_inp_element_synced = false; InpElement* m_infer_withoutexc_ret = nullptr; //! record previous run_id to skip calling infer() if input is the same size_t m_prev_inp_run_id = 0; TagTraitArray m_deps; ThinHashSet<TagTraitMutableBase*> m_receivers; //! all missing inputs SharedSet<TagHandler*, TagHandlerSet> m_missing_input; //! recursively set m_inp_element_synced of this and all receivers to //! false void reset_inp_element_synced(); const InpElement* infer_withoutexc( VarNode** cur_active_var, bool recomp_mutable_srcnode) override final; }; //! mutable shape inference MGB_DEFINE_CLS_WITH_SUPER( StaticInferManagerImpl::TagShapeTrait final, TagTraitMutableBase) // { TensorShape m_shape; ShapeInferDesc m_desc; const DepVal& raw_deps() override { return m_desc.deps; } TagHandlerType handler_type() const override { return TagHandlerType::SHAPE; } InferResult set_shape(const TensorShape& shp); InferResult do_infer(const InpVal& inp) override; InferResult do_sync_from_var() override { return set_shape(tag()->shape()); } public: using Super::Super; void init(const ShapeInferDesc& desc, StaticInferManagerImpl* mgr) { m_desc = desc; Super::init(desc.src_type, mgr); } }; //! mutable value inference MGB_DEFINE_CLS_WITH_SUPER( StaticInferManagerImpl::TagValueTrait final, TagTraitMutableBase) // { bool m_log_printed = false; //!< used for detection src value change TensorLayout m_prev_layout; DeviceTensorStorage m_prev_value; DeviceTensorND m_cur_value; ValueInferDesc m_desc; const DepVal& raw_deps() override { return m_desc.deps; } TagHandlerType handler_type() const override { return TagHandlerType::VALUE; } /*! * \brief called after finishing writing to get_writable_value() */ InferResult update_value(); InferResult do_infer(const InpVal& inp) override; InferResult do_sync_from_var() override { // strictly speaking the sync should be implemented by CompNode::Event, // however m_cur_value is on cpu::default, so we can just sync in this // caller thread m_cur_value.copy_from(tag()->dev_tensor().sync()); return update_value(); } public: TagValueTrait(Tag tag) : Super{tag}, m_cur_value{CompNode::default_cpu(), tag->dtype()} {} void init(const ValueInferDesc& desc, StaticInferManagerImpl* mgr) { m_desc = desc; Super::init(desc.src_type, mgr); } }; struct StaticInferManagerImpl::TagTraitContainer { TagTraitBase* shape; TagValueTrait* value; TagTraitBase* select(DepType type) { if (type == DepType::VALUE) return value; mgb_assert(type == DepType::SHAPE); return shape; } InferType get_infer_type() { return {shape ? shape->infer_type() : InferType::NO_DESC, value ? value->infer_type() : InferType::NO_DESC}; } }; /* ===================== misc ===================== */ const DeviceTensorND& InpElement::value() const { mgb_assert(m_value, "value not available"); return *m_value; } /* ===================== TagTraitBase ===================== */ StaticInferManagerImpl::TagTraitMutableBase* StaticInferManagerImpl::TagTraitBase:: as_mutable() { return is_const() ? nullptr : static_cast<TagTraitMutableBase*>(this); } StaticInferManagerImpl::TagTraitMutableBase* StaticInferManagerImpl::TagTraitBase:: as_mutable_safe() { mgb_assert(!is_const()); return static_cast<TagTraitMutableBase*>(this); } const InpElement* StaticInferManagerImpl::TagTraitBase::infer( bool recomp_mutable_srcnode, bool allow_fail) { VarNode* cur_var = nullptr; MGB_TRY { auto ret = infer_withoutexc(&cur_var, recomp_mutable_srcnode); if (!ret && !allow_fail) { // find the first var that causes infer failure cur_var = nullptr; for (auto trait = this->as_mutable_safe();;) { if (trait->deps().empty()) { cur_var = trait->tag(); break; } mgb_assert(!trait->prev_infer_succeed()); bool found = false; for (auto i : trait->deps()) { auto imut = i->as_mutable(); if (imut && !imut->prev_infer_succeed()) { found = true; trait = imut; break; } } mgb_assert(found); } mgb_throw( GraphError, "failed to perform static inference for var%s\n" "NOTE: this is caused by var%s", cg::dump_var_info({tag()}).c_str(), cg::dump_var_info({cur_var}).c_str()); } return ret; } MGB_CATCH(MegBrainError & exc, { if (!cur_var) { cur_var = tag(); } update_rethrow_exc(cur_var, exc); }) } /* ===================== TagTraitDepIter ===================== */ /*! * \brief iterate over the dependencies of traits in topological order * * Note: * If \p cb_pre is empty, a default impl checking the VisitedSet would be used. * If \p cb_post is empty, no action would be taken when visiting of a trait * finishs. */ class StaticInferManagerImpl::TagTraitDepIter { public: using VisitedSet = ThinHashSet<TagTraitBase*>; /*! * callback for before visiting a trait; it must return a bool indicating * whether this tag should be visited */ using CallbackPre = thin_function<bool(VisitedSet& visited, TagTraitBase*)>; //! callback for after visiting a trait using CallbackPost = thin_function<void(TagTraitBase*)>; explicit TagTraitDepIter(CallbackPre cb_pre, CallbackPost cb_post) : m_cb_pre{std::move(cb_pre)}, m_cb_post{std::move(cb_post)} { if (!m_cb_pre) { m_cb_pre = [](VisitedSet& visited, TagTraitBase* trait) { return visited.insert(trait).second; }; } if (!m_cb_post) { m_cb_post = [](TagTraitBase*) {}; } } void add(TagTraitBase* trait); private: struct Frame { TagTraitBase* trait; TagTraitBase* const* deps; TagTraitBase* const* deps_end; }; SmallVector<Frame, 1024> m_stack; CallbackPre m_cb_pre; CallbackPost m_cb_post; ThinHashSet<TagTraitBase*> m_visited; void push_stack(TagTraitBase* trait); }; void StaticInferManagerImpl::TagTraitDepIter::add(TagTraitBase* trait) { push_stack(trait); while (!m_stack.empty()) { auto&& frame = m_stack.back(); if (frame.deps == frame.deps_end) { m_cb_post(frame.trait); m_stack.pop_back(); } else { auto next = *(frame.deps++); push_stack(next); } } } void StaticInferManagerImpl::TagTraitDepIter::push_stack(TagTraitBase* trait) { if (m_cb_pre(m_visited, trait)) { auto&& deps = trait->deps(); m_stack.push_back({trait, deps.data(), deps.data() + deps.size()}); } } /* ===================== TagTraitMutableBase ===================== */ void StaticInferManagerImpl::TagTraitMutableBase::init( SourceType src_type, StaticInferManagerImpl* mgr) { mgb_assert(!m_initialized, "can not overwrite infer desc"); m_initialized = true; if (src_type == SourceType::CONSTANT) { mgb_assert(raw_deps().empty()); m_infer_type = InferType::CONST; return; } if (src_type == SourceType::MUTABLE) { mgb_assert(raw_deps().empty()); m_infer_type = InferType::RT_STATIC; return; } mgb_assert(src_type == SourceType::DEP && !raw_deps().empty()); for (auto&& i : raw_deps()) { auto dst0 = mgr->get_tag_trait_for_dep(i); m_deps.push_back(dst0); if (dst0->is_const()) { m_infer_type = std::max(m_infer_type, InferType::CONST); continue; } auto dst = static_cast<TagTraitMutableBase*>(dst0); dst->m_receivers.insert(this); // compute infer type and missing_inp if (!dst->m_initialized) { // dst has no infer desc mgb_assert(dst->m_infer_type == InferType::NO_DESC); m_infer_type = InferType::MISSING_INP; m_missing_input.merge_from(dst->missing_inp()); } else { mgb_assert(dst->m_infer_type != InferType::NO_DESC); m_infer_type = std::max(m_infer_type, dst->infer_type()); if (dst->infer_type() == InferType::MISSING_INP) m_missing_input.merge_from(dst->missing_inp()); } } mgb_assert(m_infer_type != InferType::NO_DESC); if (m_infer_type != InferType::MISSING_INP) mgb_assert(!m_missing_input); } const InpElement* StaticInferManagerImpl::TagTraitMutableBase::infer_withoutexc( VarNode** cur_active_var, bool recomp_mutable_srcnode) { InpVal inp_val; auto infer_single_core = [&inp_val, cur_active_var](TagTraitMutableBase* trait) -> InpElement* { inp_val.run_id = 0; inp_val.val.clear(); // all dependencies should have been processed due to topological iter // order, so we only check if any of them fails for (auto&& dep : trait->m_deps) { const InpElement* cur_inp; if (dep->is_const()) { cur_inp = dep->infer_withoutexc(cur_active_var, false); } else { auto dt = static_cast<TagTraitMutableBase*>(dep); cur_inp = dt->m_infer_withoutexc_ret; if (!cur_inp) { return nullptr; } } inp_val.val.push_back(*cur_inp); inp_val.run_id += dep->infer_result_version(); } if (!trait->deps().empty() && inp_val.run_id == trait->m_prev_inp_run_id) { // inputs unchanged, and middle nodes are required to be pure return &trait->m_inp_element; } *cur_active_var = trait->tag(); auto rst = trait->do_infer(inp_val); if (rst == InferResult::FAILED) { // intermediate traits should never fail (already checked in // do_infer()) mgb_assert(trait->deps().empty()); return nullptr; } trait->m_prev_inp_run_id = inp_val.run_id; if (rst == InferResult::CHANGED) { ++trait->m_inp_element_version; trait->reset_inp_element_synced(); } return &trait->m_inp_element; }; auto infer_single = [infer_single_core](TagTraitBase* trait_) { auto trait = static_cast<TagTraitMutableBase*>(trait_); trait->m_infer_withoutexc_ret = infer_single_core(trait); trait->m_inp_element_synced = true; }; if (recomp_mutable_srcnode) { mgb_assert(is_mutable_src()); infer_single(this); return m_infer_withoutexc_ret; } if (m_inp_element_synced) { return m_infer_withoutexc_ret; } auto cb_pre = [](TagTraitDepIter::VisitedSet&, TagTraitBase* trait_) { auto trait = trait_->as_mutable(); // m_inp_element_synced would be set to true after processing the trait, // so it can be used as the visit mark return trait && !trait->m_inp_element_synced; }; TagTraitDepIter dep_iter{cb_pre, infer_single}; dep_iter.add(this); return m_infer_withoutexc_ret; } void StaticInferManagerImpl::TagTraitMutableBase::sync_from_var() { mgb_assert(!m_initialized && m_infer_type == InferType::NO_DESC); auto rst = do_sync_from_var(); mgb_assert(rst != InferResult::FAILED); if (rst == InferResult::CHANGED) { ++m_inp_element_version; reset_inp_element_synced(); } } void StaticInferManagerImpl::TagTraitMutableBase::reset_inp_element_synced() { if (!m_inp_element_synced) { return; } m_inp_element_synced = false; SmallVector<TagTraitMutableBase*, 1024> stack{this}; while (!stack.empty()) { auto top = stack.back(); stack.pop_back(); for (auto i : top->m_receivers) { if (i->m_inp_element_synced) { i->m_inp_element_synced = false; stack.push_back(i); } } } } /* ===================== TagShapeTrait ===================== */ StaticInferManagerImpl::TagShapeTrait::InferResult StaticInferManagerImpl:: TagShapeTrait::set_shape(const TensorShape& shp) { mgb_assert(shp.ndim || tag()->contain_flag(VarNode::Flag::ALLOW_EMPTY_SHAPE)); m_inp_element.m_shape = &m_shape; if (shp.eq_shape(m_shape)) return InferResult::UNCHANGED; #if LOG_INFER_RESULT mgb_log_debug( "shape changed: %s: %s", cg::dump_var_info({tag()}).c_str(), shp.to_string().c_str()); #endif m_shape = shp; return InferResult::CHANGED; } StaticInferManagerImpl::TagShapeTrait::InferResult StaticInferManagerImpl:: TagShapeTrait::do_infer(const InpVal& inp) { if (!initialized()) { if (!m_shape.ndim) { mgb_log_debug( "uninitialized shape during static infer: var=%s", cg::dump_var_info({tag()}).c_str()); return InferResult::FAILED; } return InferResult::UNCHANGED; } TensorShape dest; bool succ = m_desc.infer_func(dest, inp); if (!succ) { mgb_assert(is_mutable_src(), "infer failed for non-mutable src tag"); return InferResult::FAILED; } return set_shape(dest); } /* ===================== TagValueTrait ===================== */ StaticInferManagerImpl::TagValueTrait::InferResult StaticInferManagerImpl:: TagValueTrait::update_value() { m_inp_element.m_value = &m_cur_value; mgb_assert( m_cur_value.comp_node() == CompNode::default_cpu() && m_cur_value.layout().ndim && m_cur_value.dtype() == tag()->dtype()); auto span = m_cur_value.layout().span(); if (span.dist_elem() >= INFER_VALUE_SIZE_THRESH_FOR_WARNING && !m_log_printed) { mgb_log_debug( "compute static_infer_value() for %s: " "span dist too large (%zu)", cg::dump_var_info({tag()}).c_str(), span.dist_byte()); m_log_printed = true; } // check value change for src nodes and small mid nodes if (deps().empty() || m_cur_value.shape().total_nr_elems() <= INFER_VALUE_CHECK_UNCHANGE_MAX_SIZE) { if (!m_cur_value.layout().is_contiguous_allow_brdcst()) { DeviceTensorND tmp; tmp.copy_from(m_cur_value); std::swap(m_cur_value, tmp); } auto&& cur_storage = m_cur_value.storage(); auto sz = m_cur_value.layout().span().dist_byte(); if (m_prev_layout.ndim && m_prev_layout.eq_layout(m_cur_value.layout())) { mgb_assert(sz <= m_prev_value.size()); if (!memcmp(cur_storage.ptr(), m_prev_value.ptr(), sz)) return InferResult::UNCHANGED; } m_prev_layout = m_cur_value.layout(); m_prev_value.comp_node(cur_storage.comp_node()).ensure_size(sz); memcpy(m_prev_value.ptr(), cur_storage.ptr(), sz); } else { m_prev_layout.ndim = 0; } #if LOG_INFER_RESULT auto&& val = m_cur_value; auto vstr = ssprintf("shape=%s value={", val.shape().to_string().c_str()); for (float v : tensor_iter_valonly(val)) vstr.append(ssprintf("%.3g, ", v)); vstr.pop_back(); vstr.back() = '}'; mgb_log_debug( "value changed: %s: %s", cg::dump_var_info({tag()}).c_str(), vstr.c_str()); #endif return InferResult::CHANGED; } StaticInferManagerImpl::TagValueTrait::InferResult StaticInferManagerImpl:: TagValueTrait::do_infer(const InpVal& inp) { if (!initialized()) { if (m_cur_value.empty()) { mgb_log_debug( "uninitialized value during static infer: var=%s", cg::dump_var_info({tag()}).c_str()); return InferResult::FAILED; } return InferResult::UNCHANGED; } bool succ = m_desc.infer_func(m_cur_value, inp); if (!succ) { mgb_assert( is_mutable_src(), "infer failed for non-mutable src tag: var: %s", cg::dump_var_info({tag()}).c_str()); return InferResult::FAILED; } return update_value(); } /* ===================== StaticInferManagerImpl ===================== */ StaticInferManagerImpl::~StaticInferManagerImpl() noexcept { m_mem_pool_shape_trait.disable_freelist(); m_mem_pool_value_trait.disable_freelist(); for (auto&& i : m_dtor_callbacks) i.second(); for (auto&& i : ComputingGraphImpl::downcast(m_owner_graph)->all_oprs()) { for (auto j : i->output()) { clear_tag_handler(j); } } } void StaticInferManagerImpl::clear_tag_handler(Tag tag) { auto&& container = get_tag_trait_container(tag); if (auto s = container.shape) { if (s->is_const()) { m_mem_pool_const_shape_trait.free(static_cast<TagConstShapeTrait*>(s)); } else { m_mem_pool_shape_trait.free(static_cast<TagShapeTrait*>(s)); } container.shape = nullptr; } if (container.value) { m_mem_pool_value_trait.free(container.value); container.value = nullptr; } } StaticInferManagerImpl::TagTraitContainer& StaticInferManagerImpl:: get_tag_trait_container(Tag tag) { static_assert( sizeof(tag->m_static_infer_trait) == sizeof(TagTraitContainer) && alignof(std::remove_reference< decltype(tag->m_static_infer_trait)>::type) == alignof(TagTraitContainer), "bad size"); return *aliased_ptr<TagTraitContainer>(&tag->m_static_infer_trait); } void StaticInferManagerImpl::register_shape_infer( Tag dest, const ShapeInferDesc& desc) { mgb_assert(dest->owner_opr() == m_register_allowed_opr); for (auto&& i : desc.deps) mgb_assert(dest->owner_graph() == i.dest->owner_graph()); auto&& t = get_tag_trait_container(dest); mgb_assert(!t.shape, "shape desc already inserted"); auto ptr = m_mem_pool_shape_trait.alloc_unique(dest); ptr->init(desc, this); if (ptr->infer_type() == InferType::CONST && !dest->contain_flag(VarNode::Flag::VOLATILE_CONTENT)) { // infer const shapes immediately auto r = ptr->infer(false, false); mgb_assert(r && r->m_shape); dest->shape(r->shape()); dest->m_allow_shape_change = false; t.shape = m_mem_pool_const_shape_trait.alloc(dest); } else { t.shape = ptr.release(); } } void StaticInferManagerImpl::register_value_infer( Tag dest, const ValueInferDesc& desc) { mgb_assert(dest->owner_opr() == m_register_allowed_opr); for (auto&& i : desc.deps) mgb_assert(dest->owner_graph() == i.dest->owner_graph()); auto&& t = get_tag_trait_container(dest); mgb_assert(t.shape, "shape desc not inserted before value desc"); mgb_assert(!t.value, "value infer already registered"); t.value = m_mem_pool_value_trait.alloc(dest); t.value->init(desc, this); } InferType StaticInferManagerImpl::get_infer_type(Tag dest) { return get_tag_trait_container(dest).get_infer_type(); } const TensorShape& StaticInferManagerImpl::infer_shape(Tag dest) { return *do_infer_shape(dest, false); } const TensorShape* StaticInferManagerImpl::infer_shape_fallible(Tag dest) { return do_infer_shape(dest, true); } const DeviceTensorND& StaticInferManagerImpl::infer_value(Tag dest) { return *do_infer_value(dest, false); } const DeviceTensorND* StaticInferManagerImpl::infer_value_fallible(Tag dest) { return do_infer_value(dest, true); } const StaticInferManagerImpl::TagHandlerSet& StaticInferManagerImpl::get_missing_inp( TagHandler* dest_) { auto dest = static_cast<TagTraitBase*>(dest_)->as_mutable_safe(); mgb_assert(dest->infer_type() & (InferType::NO_DESC | InferType::MISSING_INP)); auto ptr = dest->missing_inp().get(); mgb_assert(ptr); return *ptr; } StaticInferManagerImpl::TagHandler* StaticInferManagerImpl::get_tag_handler_for_shape( Tag tag) { auto&& c = get_tag_trait_container(tag); if (!c.shape) { c.shape = m_mem_pool_shape_trait.alloc(tag); } return c.shape; } StaticInferManagerImpl::TagHandler* StaticInferManagerImpl::get_tag_handler_for_value( Tag tag) { auto&& c = get_tag_trait_container(tag); if (!c.value) { c.value = m_mem_pool_value_trait.alloc(tag); } return c.value; } StaticInferManagerImpl::TagTraitBase* StaticInferManagerImpl::get_tag_trait_for_dep( const DepElement& dep) { TagHandler* ret; switch (dep.type) { case DepType::SHAPE: ret = get_tag_handler_for_shape(dep.dest); break; case DepType::VALUE: ret = get_tag_handler_for_value(dep.dest); break; default: mgb_assert(0, "bad dep type"); } return static_cast<TagTraitBase*>(ret); } DepVal StaticInferManagerImpl::get_rt_static_source_deps(const DepElement& dest) { auto trait_base = get_tag_trait_container(dest.dest).select(dest.type); if (!trait_base || trait_base->is_const()) return {}; auto trait = static_cast<TagTraitMutableBase*>(trait_base); mgb_assert(is_static_infer_type(trait->infer_type())); DepVal result; auto cb_pre = [&](TagTraitDepIter::VisitedSet& visited, TagTraitBase* trait) { if (!trait->is_const() && visited.insert(trait).second) { if (trait->deps().empty() && trait->infer_type() == InferType::RT_STATIC) { result.push_back({trait->tag(), trait->handler_type()}); return false; } return true; } return false; }; TagTraitDepIter iter{cb_pre, {}}; iter.add(trait); return result; } const TensorShape* StaticInferManagerImpl::do_infer_shape(Tag dest, bool allow_fail) { MGB_LOCK_GUARD(m_mtx); MGB_TRY { auto&& container = get_tag_trait_container(dest); mgb_assert( container.shape, "infer desc for var has not been added for infer_shape: %s", cg::dump_var_info({dest}).c_str()); auto ret = container.shape->infer(false, allow_fail); if (!ret) { mgb_assert(allow_fail); return nullptr; } return &ret->shape(); } MGB_CATCH(MegBrainError & exc, { update_rethrow_exc(dest, exc); }) } const DeviceTensorND* StaticInferManagerImpl::do_infer_value( Tag dest, bool allow_fail) { MGB_LOCK_GUARD(m_mtx); MGB_TRY { auto&& container = get_tag_trait_container(dest); mgb_assert( container.value, "infer desc for var has not been added for infer_value: %s", cg::dump_var_info({dest}).c_str()); auto ret = container.value->infer(false, allow_fail); if (!ret) { mgb_assert(allow_fail); return nullptr; } return &ret->value(); } MGB_CATCH(MegBrainError & exc, { update_rethrow_exc(dest, exc); }) } void StaticInferManagerImpl::update_mutable_src_shape(Tag dest) { MGB_LOCK_GUARD(m_mtx); MGB_TRY { auto&& container = get_tag_trait_container(dest); auto handle = container.shape; if (handle && handle->infer_type() == InferType::RT_STATIC && handle->deps().empty()) { dest->shape(handle->infer(true, false)->shape()); } } MGB_CATCH(MegBrainError & exc, { update_rethrow_exc(dest, exc); }) } DepVal StaticInferManagerImpl::get_deps(const DepElement& elem) { auto trait_base = get_tag_trait_container(elem.dest).select(elem.type); if (!trait_base || trait_base->is_const()) return {}; return trait_base->as_mutable_safe()->raw_deps(); } /* ===================== CompSeqManager ===================== */ class CompSeqManager::VersionedTagTrait { TagTraitBase* const m_trait; size_t m_version = 0; public: VersionedTagTrait(TagTraitBase* trait) : m_trait{trait} {} /*! * \brief re-infer and assign shape * \return <whether version changed, whether shape changed> */ std::pair<bool, bool> update(bool recomp_mutable_srcnode); TagTraitBase* trait() const { return m_trait; } }; std::pair<bool, bool> CompSeqManager::VersionedTagTrait::update( bool recomp_mutable_srcnode) { auto rst = m_trait->infer(recomp_mutable_srcnode, false); auto version = m_trait->infer_result_version(); if (version != m_version) { bool shp = false; if (m_trait->handler_type() == TagHandlerType::SHAPE) { m_trait->tag()->shape(rst->shape()); shp = true; } m_version = version; return {true, shp}; } return {false, false}; } CompSeqManager::CompSeqManager(ComputingGraph* graph) : m_owner_graph(graph) {} CompSeqManager::~CompSeqManager() noexcept = default; void CompSeqManager::add_dest(CompSeqExtraInfo& info, TagTraitBase* dest) { if (!m_added.insert(dest).second) return; auto&& queue = m_add_dest_queue; queue.clear(); queue.push_back(dest); while (!queue.empty()) { auto qh = queue.front(); queue.pop_front(); mgb_assert(qh->tag()->owner_graph() == m_owner_graph); for (auto i : qh->deps()) { if (m_added.insert(i).second) queue.push_back(i); } switch (qh->infer_type()) { case InferType::CONST: if (!qh->is_const()) { // shape already updated for qh being const m_static_infer_const_needed.emplace_back(qh); } break; case InferType::NO_DESC: // record this as a missing input if (qh->handler_type() == TagHandlerType::SHAPE) info.missing_for_shape.insert(qh->tag()); else { mgb_assert(qh->handler_type() == TagHandlerType::VALUE); info.missing_for_value.insert(qh->tag()); } break; case InferType::RT_STATIC: if (qh->deps().empty()) { m_static_srcnode.emplace_back(qh); } else { m_static_mid.emplace_back(qh); } case InferType::MISSING_INP: // its missing inputs have been recorded, and this tag would be // inferred on demand when the operator asks for its value break; default: mgb_throw(MegBrainError, "bad infer type"); } } } void CompSeqManager::reset_dest(CompSeqExtraInfo& info) { m_static_first_run = true; m_added.clear(); m_static_infer_const_needed.clear(); m_static_srcnode.clear(); m_static_mid.clear(); info.missing_for_shape.clear(); info.missing_for_value.clear(); for (auto&& i : info.infer_dest) { mgb_assert(i->tag()->owner_graph() == m_owner_graph); add_dest(info, static_cast<TagTraitBase*>(i)); } info.rt_static_infer_src.clear(); for (auto&& i : m_static_srcnode) { auto trait = i.trait(); if (trait->infer_type() & InferType::RT_STATIC) { info.rt_static_infer_src.push_back({trait->tag(), trait->handler_type()}); } } } bool CompSeqManager::update_static_check_shape_change() { if (m_static_first_run) { for (auto&& i : m_static_infer_const_needed) i.update(false); } bool src_changed = false, shape_changed = false; for (auto&& i : m_static_srcnode) { auto cur = i.update(true); src_changed |= cur.first; shape_changed |= cur.second; } if (!src_changed && !m_static_first_run) return false; for (auto&& i : m_static_mid) { shape_changed |= i.update(false).second; } m_static_first_run = false; return shape_changed; } /* ===================== SubgraphStaticInferHelperImpl ===================== */ /* * The basic idea is to manage deps of vars in subgraph by this helper class, * and the deps would NOT be known by StaticInferManagerImpl (so the tags appear * as MUTABLE or CONST sources in their corresponding graphs). * * This helper is necessary (i.e. static infer manager could be shared by parent * and sub graphs) because a trait may be statically inferable in sub graph but * not so in parent graph. */ class StaticInferManagerImpl::SubgraphStaticInferHelperImpl final : public SubgraphStaticInferHelper { using TagTraitArray = TagTraitBase::TagTraitArray; using RegisterSubgrahInferCallback = thin_function<TagTraitBase*( StaticInferManagerImpl& mgr, SourceType src_type, const TagTraitArray& par_deps)>; typedef bool (SubgraphStaticInferHelperImpl::*RegisterHelperPtr)( Tag, const DepVal&, RegisterSubgrahInferCallback); //! par graph dependency traits of a subgraph trait struct SubgraphTraitDepInPar { bool only_static_dep = false; SharedSet<TagTraitBase*> static_deps; }; bool m_par_destructed = false; //! traits registered as extra receiver in parent graph; used deregstering //! the sub graph std::vector<std::pair<TagTraitMutableBase*, TagTraitMutableBase*>> m_registered_in_par_graph_receiver; ComputingGraphImpl *m_sub_graph = nullptr, *m_par_graph = nullptr; ThinHashMap<TagTraitBase*, SubgraphTraitDepInPar> m_sub_trait_dep_in_par; void check_graph_par(VarNode* var) { if (mgb_unlikely(!m_par_graph)) { m_par_graph = ComputingGraphImpl::downcast(var->owner_graph()); mgb_assert(m_par_graph != m_sub_graph); auto cb = [this]() { m_par_destructed = true; }; auto ins = m_par_graph->static_infer_manager_impl().m_dtor_callbacks.insert( {this, cb}); mgb_assert(ins.second); } else { mgb_assert(m_par_graph == var->owner_graph()); } } void check_graph_sub(VarNode* var) { if (mgb_unlikely(!m_sub_graph)) { m_sub_graph = ComputingGraphImpl::downcast(var->owner_graph()); mgb_assert(m_sub_graph != m_par_graph); } else { mgb_assert(m_sub_graph == var->owner_graph()); } } /*! * \brief helper to implement registering infer func for a var in subgraph * \param user_deps deps given by user * \param callback register proxy infer func in sub manager, and should * return tag trait for dest * \return true */ bool helper_register_infer_sub( Tag dest, const DepVal& user_deps, RegisterSubgrahInferCallback callback); /*! * \brief helper to implement registering infer func for a var in par graph * * The infer func would be registered only if all deps are statically * inferable from par. * * See helper_register_infer_sub for more details. * * \return whether infer func is registered */ bool helper_register_infer_par( Tag dest, const DepVal& user_deps, RegisterSubgrahInferCallback callback); bool call_register_for_shape( Tag dest, const ShapeInferDesc& desc, RegisterHelperPtr helper); bool call_register_for_value( Tag dest, const ValueInferDesc& desc, RegisterHelperPtr helper); /*! * \brief check whether a trait in subgraph only has static deps in par * graph */ const SubgraphTraitDepInPar& get_sub_trait_dep_in_par(TagTraitBase* trait); static InpVal prepare_inp_val(const TagTraitArray& deps); static bool infer_shape_raw( const TagTraitArray& deps, const ShapeInferDesc::infer_func_t& func, TensorShape& dest, const InpVal&); static bool infer_value_raw( const TagTraitArray& deps, const ValueInferDesc::infer_func_t& func, DeviceTensorND& dest, const InpVal&); public: ~SubgraphStaticInferHelperImpl() { if (m_par_destructed || !m_par_graph) return; for (auto&& i : m_registered_in_par_graph_receiver) i.first->remove_extra_receiver(i.second); auto cnt = m_par_graph->static_infer_manager_impl().m_dtor_callbacks.erase(this); mgb_assert(cnt == 1); } void register_shape_infer_sub(Tag dest, const ShapeInferDesc& desc) override { call_register_for_shape( dest, desc, &SubgraphStaticInferHelperImpl::helper_register_infer_sub); } void register_value_infer_sub(Tag dest, const ValueInferDesc& desc) override { call_register_for_value( dest, desc, &SubgraphStaticInferHelperImpl::helper_register_infer_sub); } bool register_shape_infer_par(Tag dest, const ShapeInferDesc& desc) override { return call_register_for_shape( dest, desc, &SubgraphStaticInferHelperImpl::helper_register_infer_par); } bool register_value_infer_par(Tag dest, const ValueInferDesc& desc) override { return call_register_for_value( dest, desc, &SubgraphStaticInferHelperImpl::helper_register_infer_par); } }; bool StaticInferManagerImpl::SubgraphStaticInferHelperImpl::helper_register_infer_sub( Tag dest, const DepVal& user_deps, RegisterSubgrahInferCallback callback) { check_graph_sub(dest); mgb_assert(!user_deps.empty()); bool is_const = true, is_static = true; TagTraitArray deps; // dependency in par graph for (auto&& i : user_deps) { check_graph_par(i.dest); auto&& par_mgr = m_par_graph->static_infer_manager_impl(); InferType::Flag infer_type; { auto t = par_mgr.get_infer_type(i.dest); if (i.type == DepType::SHAPE) { infer_type = t.shape; } else { mgb_assert(i.type == DepType::VALUE); infer_type = t.value; } } is_static &= is_static_infer_type(infer_type); is_const &= ((infer_type & InferType::CONST) != 0); deps.push_back(par_mgr.get_tag_trait_for_dep(i)); } auto&& sub_mgr = m_sub_graph->static_infer_manager_impl(); auto dest_trait = callback( sub_mgr, is_const ? SourceType::CONSTANT : SourceType::MUTABLE, deps); auto&& dep_info = m_sub_trait_dep_in_par[dest_trait]; dep_info.only_static_dep = is_static; if (is_static) { for (auto i : deps) dep_info.static_deps.insert(i); } if (!is_const) { auto non_const_dt = dest_trait->as_mutable_safe(); for (auto i0 : deps) { if (auto i = i0->as_mutable()) { i->add_extra_receiver(non_const_dt); m_registered_in_par_graph_receiver.emplace_back(i, non_const_dt); } } } return true; } bool StaticInferManagerImpl::SubgraphStaticInferHelperImpl::helper_register_infer_par( Tag dest, const DepVal& user_deps, RegisterSubgrahInferCallback callback) { mgb_assert(m_sub_graph && m_par_graph); check_graph_par(dest); auto&& sub_mgr = m_sub_graph->static_infer_manager_impl(); auto&& par_mgr = m_par_graph->static_infer_manager_impl(); TagTraitArray deps; bool is_const = true; TagTraitArray extra_par_deps; // deps in user_deps in par graph for (auto&& i : user_deps) { auto iog = i.dest->owner_graph(); mgb_assert(iog == m_sub_graph || iog == m_par_graph); TagTraitBase* cur_trait; if (iog == m_sub_graph) { cur_trait = sub_mgr.get_tag_trait_for_dep(i); auto&& dep_info = get_sub_trait_dep_in_par(cur_trait); if (!dep_info.only_static_dep) return false; for (auto i : dep_info.static_deps) extra_par_deps.push_back(i); } else { cur_trait = par_mgr.get_tag_trait_for_dep(i); extra_par_deps.push_back(cur_trait); } is_const &= ((cur_trait->infer_type() & InferType::CONST) != 0); deps.push_back(cur_trait); } auto dest_trait = callback( par_mgr, is_const ? SourceType::CONSTANT : SourceType::MUTABLE, deps); if (!is_const) { auto non_const_dt = dest_trait->as_mutable_safe(); for (auto i0 : extra_par_deps) { if (auto i = i0->as_mutable()) { i->add_extra_receiver(non_const_dt); m_registered_in_par_graph_receiver.emplace_back(i, non_const_dt); non_const_dt->add_extra_dep(i); } } } return true; } bool StaticInferManagerImpl::SubgraphStaticInferHelperImpl::call_register_for_shape( Tag dest, const ShapeInferDesc& desc, RegisterHelperPtr helper) { mgb_assert(desc.src_type == SourceType::DEP); auto callback = [&](StaticInferManagerImpl& mgr, SourceType src_type, const TagTraitArray& deps) -> TagTraitBase* { using namespace std::placeholders; auto f = std::bind( &SubgraphStaticInferHelperImpl::infer_shape_raw, deps, desc.infer_func, _1, _2); mgr.register_shape_infer(dest, {src_type, {}, f}); return mgr.get_tag_trait_container(dest).shape; }; return (this->*helper)(dest, desc.deps, callback); } bool StaticInferManagerImpl::SubgraphStaticInferHelperImpl::call_register_for_value( Tag dest, const ValueInferDesc& desc, RegisterHelperPtr helper) { mgb_assert(desc.src_type == SourceType::DEP); auto callback = [&](StaticInferManagerImpl& mgr, SourceType src_type, const TagTraitArray& deps) -> TagTraitBase* { using namespace std::placeholders; auto f = std::bind( &SubgraphStaticInferHelperImpl::infer_value_raw, deps, desc.infer_func, _1, _2); mgr.register_value_infer(dest, {src_type, {}, f}); return mgr.get_tag_trait_container(dest).value; }; return (this->*helper)(dest, desc.deps, callback); } InpVal StaticInferManagerImpl::SubgraphStaticInferHelperImpl::prepare_inp_val( const TagTraitArray& deps) { mgb_assert(!deps.empty()); InpVal finp; for (auto i : deps) { auto t = i->infer(false, true); if (!t) { finp.val.clear(); return finp; } finp.val.push_back(*t); finp.run_id += i->infer_result_version(); } return finp; } bool StaticInferManagerImpl::SubgraphStaticInferHelperImpl::infer_shape_raw( const TagTraitArray& deps, const ShapeInferDesc::infer_func_t& func, TensorShape& dest, const InpVal&) { auto finp = prepare_inp_val(deps); if (finp.val.empty()) return false; auto succ = func(dest, finp); mgb_assert(succ); return succ; } bool StaticInferManagerImpl::SubgraphStaticInferHelperImpl::infer_value_raw( const TagTraitArray& deps, const ValueInferDesc::infer_func_t& func, DeviceTensorND& dest, const InpVal&) { auto finp = prepare_inp_val(deps); if (finp.val.empty()) return false; auto succ = func(dest, finp); mgb_assert(succ); return succ; } const StaticInferManagerImpl::SubgraphStaticInferHelperImpl::SubgraphTraitDepInPar& StaticInferManagerImpl::SubgraphStaticInferHelperImpl::get_sub_trait_dep_in_par( TagTraitBase* trait) { auto iter = m_sub_trait_dep_in_par.find(trait); if (iter != m_sub_trait_dep_in_par.end()) return iter->second; auto&& rst = m_sub_trait_dep_in_par[trait]; if (trait->deps().empty()) { rst.only_static_dep = trait->infer_type() == InferType::CONST; } else { rst.only_static_dep = true; for (auto i : trait->deps()) { if (!get_sub_trait_dep_in_par(i).only_static_dep) { rst.only_static_dep = false; break; } } if (rst.only_static_dep) { for (auto i : trait->deps()) { auto&& t = m_sub_trait_dep_in_par.at(i); rst.static_deps.merge_from(t.static_deps); } } } return rst; } std::unique_ptr<SubgraphStaticInferHelper> SubgraphStaticInferHelper::make() { return std::unique_ptr<SubgraphStaticInferHelper>( new StaticInferManagerImpl::SubgraphStaticInferHelperImpl); } /* ===================== StaticInferUpdaterImpl ===================== */ class StaticInferManagerImpl::StaticInferUpdaterImpl final : public StaticInferUpdater { StaticInferManagerImpl* m_mgr = nullptr; bool m_build_done = false; SmallVector<TagTraitMutableBase*> m_src, m_dst; void build() { auto cb_pre = [this](TagTraitDepIter::VisitedSet& visited, TagTraitBase* trait) { if (!trait->is_const() && visited.insert(trait).second) { if (trait->deps().empty() && trait->infer_type() == InferType::RT_STATIC) { m_src.push_back(static_cast<TagTraitMutableBase*>(trait)); return false; } return true; } return false; }; TagTraitDepIter dep_iter{cb_pre, {}}; for (auto i : m_dst) { dep_iter.add(i); } } public: StaticInferUpdater& add_dest(const DepElement& dest) override { mgb_throw_if( m_build_done, GraphError, "add_dest() can not be called after update()"); auto mgr = static_cast<StaticInferManagerImpl*>( &dest.dest->owner_graph()->static_infer_manager()); if (!m_mgr) { m_mgr = mgr; } else { mgb_throw_if( m_mgr != mgr, GraphError, "computing graph in StaticInferUpdater changes"); } auto trait_base = mgr->get_tag_trait_container(dest.dest).select(dest.type); if (trait_base && trait_base->is_const()) { // ignore const infer types return *this; } mgb_throw_if( !trait_base || trait_base->infer_type() != InferType::RT_STATIC, GraphError, "StaticInferUpdater dest is not RT_STATIC type"); m_dst.push_back(trait_base->as_mutable_safe()); return *this; } void update() override { if (!m_build_done) { build(); m_build_done = true; } for (auto i : m_src) { i->infer(true, false); } for (auto i : m_dst) { i->infer(false, false); } } }; std::unique_ptr<StaticInferUpdater> StaticInferUpdater::make() { return std::make_unique<StaticInferManagerImpl::StaticInferUpdaterImpl>(); } /* ===================== others ===================== */ ShapeInferDesc ShapeInferDesc::make_identity(VarNode* src) { auto infer_shape = [](TensorShape& dest, const InpVal& inp) { dest = inp.val.at(0).shape(); return true; }; return {SourceType::DEP, {{src, DepType::SHAPE}}, infer_shape}; } ShapeInferDesc ShapeInferDesc::make_const(const TensorShape& shp) { auto infer_shape = [shp](TensorShape& dest, const InpVal&) { dest = shp; return true; }; return {SourceType::CONSTANT, {}, infer_shape}; } ValueInferDesc ValueInferDesc::make_identity(VarNode* src) { auto infer_value = [](DeviceTensorND& dest, const InpVal& inp) { dest = inp.val.at(0).value(); return true; }; return {SourceType::DEP, {{src, DepType::VALUE}}, infer_value}; } // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
33.486968
89
0.628306
[ "shape", "vector" ]
047c442ba62d2792d7cdeb91a5ad535c740cc7aa
1,456
cpp
C++
leetcode/number-of-islands/NumberOfIslands.cpp
giwankim/algo
8dd1cf8aed6e89db54e753c7ce5821019628c47f
[ "MIT" ]
null
null
null
leetcode/number-of-islands/NumberOfIslands.cpp
giwankim/algo
8dd1cf8aed6e89db54e753c7ce5821019628c47f
[ "MIT" ]
null
null
null
leetcode/number-of-islands/NumberOfIslands.cpp
giwankim/algo
8dd1cf8aed6e89db54e753c7ce5821019628c47f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; int m, n; vector<vector<int>> check; void bfs(int i, int j, vector<vector<char>> &grid) { queue<pair<int, int>> q; q.emplace(i, j); check[i][j] = 1; while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for (int k = 0; k < 4; ++k) { int nx = x + dx[k]; int ny = y + dy[k]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; if (grid[nx][ny] == '1' && check[nx][ny] == 0) { q.emplace(nx, ny); check[nx][ny] = 1; } } } } int numIslands(vector<vector<char>> &grid) { if (grid.empty()) return 0; n = (int)grid.size(); m = (int)grid[0].size(); check.resize(n, vector<int>(m)); int nc = 0; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == '1' && check[i][j] == 0) { bfs(i, j, grid); nc += 1; } } } return nc; } int main(int argc, char const *argv[]) { vector<vector<char>> grid = { {'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'}, {'0', '0', '0', '0', '0'}}; cout << numIslands(grid) << "\n"; return 0; }
22.4
58
0.371566
[ "vector" ]
047f408a0f4762f35cac78e89c8542603f8bdf71
19,274
cc
C++
headless/app/headless_shell.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
headless/app/headless_shell.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
headless/app/headless_shell.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <sstream> #include <string> #include "base/base64.h" #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/files/file_path.h" #include "base/json/json_writer.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/memory/ref_counted.h" #include "base/memory/weak_ptr.h" #include "base/numerics/safe_conversions.h" #include "base/strings/string_number_conversions.h" #include "content/public/common/content_switches.h" #include "headless/app/headless_shell_switches.h" #include "headless/public/devtools/domains/emulation.h" #include "headless/public/devtools/domains/inspector.h" #include "headless/public/devtools/domains/page.h" #include "headless/public/devtools/domains/runtime.h" #include "headless/public/headless_browser.h" #include "headless/public/headless_devtools_client.h" #include "headless/public/headless_devtools_target.h" #include "headless/public/headless_web_contents.h" #include "headless/public/util/deterministic_dispatcher.h" #include "headless/public/util/deterministic_http_protocol_handler.h" #include "net/base/file_stream.h" #include "net/base/io_buffer.h" #include "net/base/ip_address.h" #include "net/base/net_errors.h" #include "ui/gfx/geometry/size.h" namespace headless { namespace { // Address where to listen to incoming DevTools connections. const char kDevToolsHttpServerAddress[] = "127.0.0.1"; // Default file name for screenshot. Can be overriden by "--screenshot" switch. const char kDefaultScreenshotFileName[] = "screenshot.png"; bool ParseWindowSize(std::string window_size, gfx::Size* parsed_window_size) { int width, height = 0; if (sscanf(window_size.c_str(), "%d%*[x,]%d", &width, &height) >= 2 && width >= 0 && height >= 0) { parsed_window_size->set_width(width); parsed_window_size->set_height(height); return true; } return false; } } // namespace // An application which implements a simple headless browser. class HeadlessShell : public HeadlessWebContents::Observer, emulation::ExperimentalObserver, inspector::ExperimentalObserver, page::Observer { public: HeadlessShell() : browser_(nullptr), devtools_client_(HeadlessDevToolsClient::Create()), web_contents_(nullptr), processed_page_ready_(false), browser_context_(nullptr), weak_factory_(this) {} ~HeadlessShell() override {} void OnStart(HeadlessBrowser* browser) { browser_ = browser; HeadlessBrowserContext::Builder context_builder = browser_->CreateBrowserContextBuilder(); // TODO(eseckler): These switches should also affect BrowserContexts that // are created via DevTools later. if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kDeterministicFetch)) { deterministic_dispatcher_.reset( new DeterministicDispatcher(browser_->BrowserIOThread())); ProtocolHandlerMap protocol_handlers; protocol_handlers[url::kHttpScheme] = base::MakeUnique<DeterministicHttpProtocolHandler>( deterministic_dispatcher_.get(), browser->BrowserIOThread()); protocol_handlers[url::kHttpsScheme] = base::MakeUnique<DeterministicHttpProtocolHandler>( deterministic_dispatcher_.get(), browser->BrowserIOThread()); context_builder.SetProtocolHandlers(std::move(protocol_handlers)); } if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kHideScrollbars)) { context_builder.SetOverrideWebPreferencesCallback( base::Bind([](WebPreferences* preferences) { preferences->hide_scrollbars = true; })); } browser_context_ = context_builder.Build(); browser_->SetDefaultBrowserContext(browser_context_); HeadlessWebContents::Builder builder( browser_context_->CreateWebContentsBuilder()); base::CommandLine::StringVector args = base::CommandLine::ForCurrentProcess()->GetArgs(); // TODO(alexclarke): Should we navigate to about:blank first if using // virtual time? if (args.empty()) args.push_back("about:blank"); for (auto it = args.rbegin(); it != args.rend(); ++it) { GURL url(*it); HeadlessWebContents* web_contents = builder.SetInitialURL(url).Build(); if (!web_contents) { LOG(ERROR) << "Navigation to " << url << " failed"; browser_->Shutdown(); return; } if (!web_contents_ && !RemoteDebuggingEnabled()) { // TODO(jzfeng): Support observing multiple targets. url_ = url; web_contents_ = web_contents; web_contents_->AddObserver(this); } } } void Shutdown() { if (!web_contents_) return; if (!RemoteDebuggingEnabled()) { devtools_client_->GetEmulation()->GetExperimental()->RemoveObserver(this); devtools_client_->GetInspector()->GetExperimental()->RemoveObserver(this); devtools_client_->GetPage()->RemoveObserver(this); if (web_contents_->GetDevToolsTarget()) { web_contents_->GetDevToolsTarget()->DetachClient( devtools_client_.get()); } } web_contents_->RemoveObserver(this); web_contents_ = nullptr; browser_context_->Close(); browser_->Shutdown(); } // HeadlessWebContents::Observer implementation: void DevToolsTargetReady() override { web_contents_->GetDevToolsTarget()->AttachClient(devtools_client_.get()); devtools_client_->GetInspector()->GetExperimental()->AddObserver(this); devtools_client_->GetPage()->AddObserver(this); devtools_client_->GetPage()->Enable(); // Check if the document had already finished loading by the time we // attached. devtools_client_->GetEmulation()->GetExperimental()->AddObserver(this); if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kVirtualTimeBudget)) { std::string budget_ms_ascii = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kVirtualTimeBudget); int budget_ms; CHECK(base::StringToInt(budget_ms_ascii, &budget_ms)) << "Expected an integer value for --virtual-time-budget="; devtools_client_->GetEmulation()->GetExperimental()->SetVirtualTimePolicy( emulation::SetVirtualTimePolicyParams::Builder() .SetPolicy(emulation::VirtualTimePolicy:: PAUSE_IF_NETWORK_FETCHES_PENDING) .SetBudget(budget_ms) .Build()); } else { PollReadyState(); } if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kTimeout)) { std::string timeout_ms_ascii = base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII( switches::kTimeout); int timeout_ms; CHECK(base::StringToInt(timeout_ms_ascii, &timeout_ms)) << "Expected an integer value for --timeout="; browser_->BrowserMainThread()->PostDelayedTask( FROM_HERE, base::Bind(&HeadlessShell::FetchTimeout, weak_factory_.GetWeakPtr()), base::TimeDelta::FromMilliseconds(timeout_ms)); } // TODO(skyostil): Implement more features to demonstrate the devtools API. } void FetchTimeout() { LOG(INFO) << "Timeout."; devtools_client_->GetPage()->GetExperimental()->StopLoading( page::StopLoadingParams::Builder().Build()); } void OnTargetCrashed(const inspector::TargetCrashedParams& params) override { LOG(ERROR) << "Abnormal renderer termination."; // NB this never gets called if remote debugging is enabled. Shutdown(); } void PollReadyState() { // We need to check the current location in addition to the ready state to // be sure the expected page is ready. devtools_client_->GetRuntime()->Evaluate( "document.readyState + ' ' + document.location.href", base::Bind(&HeadlessShell::OnReadyState, weak_factory_.GetWeakPtr())); } void OnReadyState(std::unique_ptr<runtime::EvaluateResult> result) { std::string ready_state_and_url; if (result->GetResult()->GetValue()->GetAsString(&ready_state_and_url)) { std::stringstream stream(ready_state_and_url); std::string ready_state; std::string url; stream >> ready_state; stream >> url; if (ready_state == "complete" && (url_.spec() == url || url != "about:blank")) { OnPageReady(); return; } } } // emulation::Observer implementation: void OnVirtualTimeBudgetExpired( const emulation::VirtualTimeBudgetExpiredParams& params) override { OnPageReady(); } // page::Observer implementation: void OnLoadEventFired(const page::LoadEventFiredParams& params) override { if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kVirtualTimeBudget)) { return; } OnPageReady(); } void OnPageReady() { if (processed_page_ready_) return; processed_page_ready_ = true; if (base::CommandLine::ForCurrentProcess()->HasSwitch(switches::kDumpDom)) { FetchDom(); } else if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kRepl)) { LOG(INFO) << "Type a Javascript expression to evaluate or \"quit\" to exit."; InputExpression(); } else if (base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kScreenshot)) { CaptureScreenshot(); } else { Shutdown(); } } void FetchDom() { devtools_client_->GetRuntime()->Evaluate( "document.body.innerHTML", base::Bind(&HeadlessShell::OnDomFetched, weak_factory_.GetWeakPtr())); } void OnDomFetched(std::unique_ptr<runtime::EvaluateResult> result) { if (result->HasExceptionDetails()) { LOG(ERROR) << "Failed to evaluate document.body.innerHTML: " << result->GetExceptionDetails()->GetText(); } else { std::string dom; if (result->GetResult()->GetValue()->GetAsString(&dom)) { printf("%s\n", dom.c_str()); } } Shutdown(); } void InputExpression() { // Note that a real system should read user input asynchronously, because // otherwise all other browser activity is suspended (e.g., page loading). printf(">>> "); std::stringstream expression; while (true) { int c = fgetc(stdin); if (c == EOF || c == '\n') { break; } expression << c; } if (expression.str() == "quit") { Shutdown(); return; } devtools_client_->GetRuntime()->Evaluate( expression.str(), base::Bind(&HeadlessShell::OnExpressionResult, weak_factory_.GetWeakPtr())); } void OnExpressionResult(std::unique_ptr<runtime::EvaluateResult> result) { std::unique_ptr<base::Value> value = result->Serialize(); std::string result_json; base::JSONWriter::Write(*value, &result_json); printf("%s\n", result_json.c_str()); InputExpression(); } void CaptureScreenshot() { devtools_client_->GetPage()->GetExperimental()->CaptureScreenshot( page::CaptureScreenshotParams::Builder().Build(), base::Bind(&HeadlessShell::OnScreenshotCaptured, weak_factory_.GetWeakPtr())); } void OnScreenshotCaptured( std::unique_ptr<page::CaptureScreenshotResult> result) { base::FilePath file_name = base::CommandLine::ForCurrentProcess()->GetSwitchValuePath( switches::kScreenshot); if (file_name.empty()) { file_name = base::FilePath().AppendASCII(kDefaultScreenshotFileName); } screenshot_file_stream_.reset( new net::FileStream(browser_->BrowserFileThread())); const int open_result = screenshot_file_stream_->Open( file_name, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE | base::File::FLAG_ASYNC, base::Bind(&HeadlessShell::OnScreenshotFileOpened, weak_factory_.GetWeakPtr(), base::Passed(std::move(result)), file_name)); if (open_result != net::ERR_IO_PENDING) { // Operation could not be started. OnScreenshotFileOpened(nullptr, file_name, open_result); } } void OnScreenshotFileOpened( std::unique_ptr<page::CaptureScreenshotResult> result, const base::FilePath file_name, const int open_result) { if (open_result != net::OK) { LOG(ERROR) << "Writing screenshot to file " << file_name.value() << " was unsuccessful, could not open file: " << net::ErrorToString(open_result); return; } std::string decoded_png; base::Base64Decode(result->GetData(), &decoded_png); scoped_refptr<net::IOBufferWithSize> buf = new net::IOBufferWithSize(decoded_png.size()); memcpy(buf->data(), decoded_png.data(), decoded_png.size()); const int write_result = screenshot_file_stream_->Write( buf.get(), buf->size(), base::Bind(&HeadlessShell::OnScreenshotFileWritten, weak_factory_.GetWeakPtr(), file_name, buf->size())); if (write_result != net::ERR_IO_PENDING) { // Operation may have completed successfully or failed. OnScreenshotFileWritten(file_name, buf->size(), write_result); } } void OnScreenshotFileWritten(const base::FilePath file_name, const int length, const int write_result) { if (write_result < length) { // TODO(eseckler): Support recovering from partial writes. LOG(ERROR) << "Writing screenshot to file " << file_name.value() << " was unsuccessful: " << net::ErrorToString(write_result); } else { LOG(INFO) << "Screenshot written to file " << file_name.value() << "." << std::endl; } int close_result = screenshot_file_stream_->Close(base::Bind( &HeadlessShell::OnScreenshotFileClosed, weak_factory_.GetWeakPtr())); if (close_result != net::ERR_IO_PENDING) { // Operation could not be started. OnScreenshotFileClosed(close_result); } } void OnScreenshotFileClosed(const int close_result) { Shutdown(); } bool RemoteDebuggingEnabled() const { const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); return command_line.HasSwitch(::switches::kRemoteDebuggingPort); } private: GURL url_; HeadlessBrowser* browser_; // Not owned. std::unique_ptr<HeadlessDevToolsClient> devtools_client_; HeadlessWebContents* web_contents_; bool processed_page_ready_; std::unique_ptr<net::FileStream> screenshot_file_stream_; HeadlessBrowserContext* browser_context_; std::unique_ptr<DeterministicDispatcher> deterministic_dispatcher_; base::WeakPtrFactory<HeadlessShell> weak_factory_; DISALLOW_COPY_AND_ASSIGN(HeadlessShell); }; bool ValidateCommandLine(const base::CommandLine& command_line) { if (!command_line.HasSwitch(::switches::kRemoteDebuggingPort)) { if (command_line.GetArgs().size() <= 1) return true; LOG(ERROR) << "Open multiple tabs is only supported when the " << "remote debug port is set."; return false; } if (command_line.HasSwitch(switches::kDumpDom)) { LOG(ERROR) << "Dump DOM is disabled when remote debugging is enabled."; return false; } if (command_line.HasSwitch(switches::kRepl)) { LOG(ERROR) << "Evaluate Javascript is disabled " << "when remote debugging is enabled."; return false; } if (command_line.HasSwitch(switches::kScreenshot)) { LOG(ERROR) << "Capture screenshot is disabled " << "when remote debugging is enabled."; return false; } if (command_line.HasSwitch(switches::kTimeout)) { LOG(ERROR) << "Navigation timeout is disabled " << "when remote debugging is enabled."; return false; } if (command_line.HasSwitch(switches::kVirtualTimeBudget)) { LOG(ERROR) << "Virtual time budget is disabled " << "when remote debugging is enabled."; return false; } return true; } int HeadlessShellMain(int argc, const char** argv) { RunChildProcessIfNeeded(argc, argv); HeadlessShell shell; HeadlessBrowser::Options::Builder builder(argc, argv); // Enable devtools if requested. base::CommandLine command_line(argc, argv); if (!ValidateCommandLine(command_line)) return EXIT_FAILURE; if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) { std::string address = kDevToolsHttpServerAddress; if (command_line.HasSwitch(switches::kRemoteDebuggingAddress)) { address = command_line.GetSwitchValueASCII(switches::kRemoteDebuggingAddress); net::IPAddress parsed_address; if (!net::ParseURLHostnameToAddress(address, &parsed_address)) { LOG(ERROR) << "Invalid devtools server address"; return EXIT_FAILURE; } } int parsed_port; std::string port_str = command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort); if (!base::StringToInt(port_str, &parsed_port) || !base::IsValueInRangeForNumericType<uint16_t>(parsed_port)) { LOG(ERROR) << "Invalid devtools server port"; return EXIT_FAILURE; } net::IPAddress devtools_address; bool result = devtools_address.AssignFromIPLiteral(address); DCHECK(result); builder.EnableDevToolsServer(net::IPEndPoint( devtools_address, base::checked_cast<uint16_t>(parsed_port))); } if (command_line.HasSwitch(switches::kProxyServer)) { std::string proxy_server = command_line.GetSwitchValueASCII(switches::kProxyServer); net::HostPortPair parsed_proxy_server = net::HostPortPair::FromString(proxy_server); if (parsed_proxy_server.host().empty() || !parsed_proxy_server.port()) { LOG(ERROR) << "Malformed proxy server url"; return EXIT_FAILURE; } builder.SetProxyServer(parsed_proxy_server); } if (command_line.HasSwitch(::switches::kHostResolverRules)) { builder.SetHostResolverRules( command_line.GetSwitchValueASCII(::switches::kHostResolverRules)); } if (command_line.HasSwitch(switches::kUseGL)) { builder.SetGLImplementation( command_line.GetSwitchValueASCII(switches::kUseGL)); } if (command_line.HasSwitch(switches::kUserDataDir)) { builder.SetUserDataDir( command_line.GetSwitchValuePath(switches::kUserDataDir)); builder.SetIncognitoMode(false); } if (command_line.HasSwitch(switches::kWindowSize)) { std::string window_size = command_line.GetSwitchValueASCII(switches::kWindowSize); gfx::Size parsed_window_size; if (!ParseWindowSize(window_size, &parsed_window_size)) { LOG(ERROR) << "Malformed window size"; return EXIT_FAILURE; } builder.SetWindowSize(parsed_window_size); } return HeadlessBrowserMain( builder.Build(), base::Bind(&HeadlessShell::OnStart, base::Unretained(&shell))); } } // namespace headless
36.573055
80
0.674691
[ "geometry" ]
048131e8eb52c67fa6db8dd5c5f6aad3bda21c2a
21,526
hh
C++
Includes/live/includes/liveMedia/include/RTSPServer.hh
HectorTa1989/FFMPEG-Live555-H264-H265-VideoStreaming
90914d31dae00110278601787646222ff3139e26
[ "MIT" ]
null
null
null
Includes/live/includes/liveMedia/include/RTSPServer.hh
HectorTa1989/FFMPEG-Live555-H264-H265-VideoStreaming
90914d31dae00110278601787646222ff3139e26
[ "MIT" ]
null
null
null
Includes/live/includes/liveMedia/include/RTSPServer.hh
HectorTa1989/FFMPEG-Live555-H264-H265-VideoStreaming
90914d31dae00110278601787646222ff3139e26
[ "MIT" ]
null
null
null
/********** This library 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 (at your option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.) This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA **********/ // "liveMedia" // Copyright (c) 1996-2015 Live Networks, Inc. All rights reserved. // A RTSP server // C++ header #ifndef _RTSP_SERVER_HH #define _RTSP_SERVER_HH #ifndef _SERVER_MEDIA_SESSION_HH #include "ServerMediaSession.hh" #endif #ifndef _NET_ADDRESS_HH #include <NetAddress.hh> #endif #ifndef _DIGEST_AUTHENTICATION_HH #include "DigestAuthentication.hh" #endif // A data structure used for optional user/password authentication: class UserAuthenticationDatabase { public: UserAuthenticationDatabase(char const* realm = NULL, Boolean passwordsAreMD5 = False); // If "passwordsAreMD5" is True, then each password stored into, or removed from, // the database is actually the value computed // by md5(<username>:<realm>:<actual-password>) virtual ~UserAuthenticationDatabase(); virtual void addUserRecord(char const* username, char const* password); virtual void removeUserRecord(char const* username); virtual char const* lookupPassword(char const* username); // returns NULL if the user name was not present char const* realm() { return fRealm; } Boolean passwordsAreMD5() { return fPasswordsAreMD5; } protected: HashTable* fTable; char* fRealm; Boolean fPasswordsAreMD5; }; #ifndef RTSP_BUFFER_SIZE #define RTSP_BUFFER_SIZE 20000 // for incoming requests, and outgoing responses #endif class RTSPServer: public Medium { public: static RTSPServer* createNew(UsageEnvironment& env, Port ourPort = 554, UserAuthenticationDatabase* authDatabase = NULL, unsigned reclamationTestSeconds = 65); // If ourPort.num() == 0, we'll choose the port number // Note: The caller is responsible for reclaiming "authDatabase" // If "reclamationTestSeconds" > 0, then the "RTSPClientSession" state for // each client will get reclaimed (and the corresponding RTP stream(s) // torn down) if no RTSP commands - or RTCP "RR" packets - from the // client are received in at least "reclamationTestSeconds" seconds. static Boolean lookupByName(UsageEnvironment& env, char const* name, RTSPServer*& resultServer); void addServerMediaSession(ServerMediaSession* serverMediaSession); virtual ServerMediaSession* lookupServerMediaSession(char const* streamName, Boolean isFirstLookupInSession = True); void removeServerMediaSession(ServerMediaSession* serverMediaSession); // Removes the "ServerMediaSession" object from our lookup table, so it will no longer be accessible by new RTSP clients. // (However, any *existing* RTSP client sessions that use this "ServerMediaSession" object will continue streaming. // The "ServerMediaSession" object will not get deleted until all of these RTSP client sessions have closed.) // (To both delete the "ServerMediaSession" object *and* close all RTSP client sessions that use it, // call "deleteServerMediaSession(serverMediaSession)" instead.) void removeServerMediaSession(char const* streamName); // ditto void closeAllClientSessionsForServerMediaSession(ServerMediaSession* serverMediaSession); // Closes (from the server) all RTSP client sessions that are currently using this "ServerMediaSession" object. // Note, however, that the "ServerMediaSession" object remains accessible by new RTSP clients. void closeAllClientSessionsForServerMediaSession(char const* streamName); // ditto void deleteServerMediaSession(ServerMediaSession* serverMediaSession); // Equivalent to: // "closeAllClientSessionsForServerMediaSession(serverMediaSession); removeServerMediaSession(serverMediaSession);" void deleteServerMediaSession(char const* streamName); // Equivalent to: // "closeAllClientSessionsForServerMediaSession(streamName); removeServerMediaSession(streamName); typedef void (responseHandlerForREGISTER)(RTSPServer* rtspServer, unsigned requestId, int resultCode, char* resultString); unsigned registerStream(ServerMediaSession* serverMediaSession, char const* remoteClientNameOrAddress, portNumBits remoteClientPortNum, responseHandlerForREGISTER* responseHandler, char const* username = NULL, char const* password = NULL, Boolean receiveOurStreamViaTCP = False, char const* proxyURLSuffix = NULL); // 'Register' the stream represented by "serverMediaSession" with the given remote client (specifed by name and port number). // This is done using our custom "REGISTER" RTSP command. // The function returns a unique number that can be used to identify the request; this number is also passed to "responseHandler". // When a response is received from the remote client (or the "REGISTER" request fails), the specified response handler // (if non-NULL) is called. (Note that the "resultString" passed to the handler was dynamically allocated, // and should be delete[]d by the handler after use.) // If "receiveOurStreamViaTCP" is True, then we're requesting that the remote client access our stream using RTP/RTCP-over-TCP. // (Otherwise, the remote client may choose regular RTP/RTCP-over-UDP streaming.) // "proxyURLSuffix" (optional) is used only when the remote client is also a proxy server. // It tells the proxy server the suffix that it should use in its "rtsp://" URL (when front-end clients access the stream) char* rtspURL(ServerMediaSession const* serverMediaSession, int clientSocket = -1) const; // returns a "rtsp://" URL that could be used to access the // specified session (which must already have been added to // us using "addServerMediaSession()". // This string is dynamically allocated; caller should delete[] // (If "clientSocket" is non-negative, then it is used (by calling "getsockname()") to determine // the IP address to be used in the URL.) char* rtspURLPrefix(int clientSocket = -1) const; // like "rtspURL()", except that it returns just the common prefix used by // each session's "rtsp://" URL. // This string is dynamically allocated; caller should delete[] UserAuthenticationDatabase* setAuthenticationDatabase(UserAuthenticationDatabase* newDB); // Changes the server's authentication database to "newDB", returning a pointer to the old database (if there was one). // "newDB" may be NULL (you can use this to disable authentication at runtime, if desired). void disableStreamingRTPOverTCP() { fAllowStreamingRTPOverTCP = False; } Boolean setUpTunnelingOverHTTP(Port httpPort); // (Attempts to) enable RTSP-over-HTTP tunneling on the specified port. // Returns True iff the specified port can be used in this way (i.e., it's not already being used for a separate HTTP server). // Note: RTSP-over-HTTP tunneling is described in http://developer.apple.com/quicktime/icefloe/dispatch028.html portNumBits httpServerPortNum() const; // in host byte order. (Returns 0 if not present.) protected: RTSPServer(UsageEnvironment& env, int ourSocket, Port ourPort, UserAuthenticationDatabase* authDatabase, unsigned reclamationTestSeconds); // called only by createNew(); virtual ~RTSPServer(); static int setUpOurSocket(UsageEnvironment& env, Port& ourPort); virtual char const* allowedCommandNames(); // used to implement "RTSPClientConnection::handleCmd_OPTIONS()" virtual Boolean weImplementREGISTER(char const* proxyURLSuffix, char*& responseStr); // used to implement "RTSPClientConnection::handleCmd_REGISTER()" // Note: "responseStr" is dynamically allocated (or NULL), and should be delete[]d after the call virtual void implementCmd_REGISTER(char const* url, char const* urlSuffix, int socketToRemoteServer, Boolean deliverViaTCP, char const* proxyURLSuffix); // used to implement "RTSPClientConnection::handleCmd_REGISTER()" virtual UserAuthenticationDatabase* getAuthenticationDatabaseForCommand(char const* cmdName); virtual Boolean specialClientAccessCheck(int clientSocket, struct sockaddr_in& clientAddr, char const* urlSuffix); // a hook that allows subclassed servers to do server-specific access checking // on each client (e.g., based on client IP address), without using digest authentication. virtual Boolean specialClientUserAccessCheck(int clientSocket, struct sockaddr_in& clientAddr, char const* urlSuffix, char const *username); // another hook that allows subclassed servers to do server-specific access checking // - this time after normal digest authentication has already taken place (and would otherwise allow access). // (This test can only be used to further restrict access, not to grant additional access.) private: // redefined virtual functions virtual Boolean isRTSPServer() const; public: // should be protected, but some old compilers complain otherwise class RTSPClientSession; // forward // The state of a TCP connection used by a RTSP client: class RTSPClientConnection { public: // A data structure that's used to implement the "REGISTER" command: class ParamsForREGISTER { public: ParamsForREGISTER(RTSPClientConnection* ourConnection, char const* url, char const* urlSuffix, Boolean reuseConnection, Boolean deliverViaTCP, char const* proxyURLSuffix); virtual ~ParamsForREGISTER(); private: friend class RTSPClientConnection; RTSPClientConnection* fOurConnection; char* fURL; char* fURLSuffix; Boolean fReuseConnection, fDeliverViaTCP; char* fProxyURLSuffix; }; protected: RTSPClientConnection(RTSPServer& ourServer, int clientSocket, struct sockaddr_in clientAddr); virtual ~RTSPClientConnection(); friend class RTSPServer; friend class RTSPClientSession; // Make the handler functions for each command virtual, to allow subclasses to reimplement them, if necessary: virtual void handleCmd_OPTIONS(); // You probably won't need to subclass/reimplement this function; reimplement "RTSPServer::allowedCommandNames()" instead. virtual void handleCmd_GET_PARAMETER(char const* fullRequestStr); // when operating on the entire server virtual void handleCmd_SET_PARAMETER(char const* fullRequestStr); // when operating on the entire server virtual void handleCmd_DESCRIBE(char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr); virtual void handleCmd_REGISTER(char const* url, char const* urlSuffix, char const* fullRequestStr, Boolean reuseConnection, Boolean deliverViaTCP, char const* proxyURLSuffix); // You probably won't need to subclass/reimplement this function; // reimplement "RTSPServer::weImplementREGISTER()" and "RTSPServer::implementCmd_REGISTER()" instead. virtual void handleCmd_bad(); virtual void handleCmd_notSupported(); virtual void handleCmd_notFound(); virtual void handleCmd_sessionNotFound(); virtual void handleCmd_unsupportedTransport(); // Support for optional RTSP-over-HTTP tunneling: virtual Boolean parseHTTPRequestString(char* resultCmdName, unsigned resultCmdNameMaxSize, char* urlSuffix, unsigned urlSuffixMaxSize, char* sessionCookie, unsigned sessionCookieMaxSize, char* acceptStr, unsigned acceptStrMaxSize); virtual void handleHTTPCmd_notSupported(); virtual void handleHTTPCmd_notFound(); virtual void handleHTTPCmd_OPTIONS(); virtual void handleHTTPCmd_TunnelingGET(char const* sessionCookie); virtual Boolean handleHTTPCmd_TunnelingPOST(char const* sessionCookie, unsigned char const* extraData, unsigned extraDataSize); virtual void handleHTTPCmd_StreamingGET(char const* urlSuffix, char const* fullRequestStr); protected: UsageEnvironment& envir() { return fOurServer.envir(); } void resetRequestBuffer(); void closeSockets(); static void incomingRequestHandler(void*, int /*mask*/); void incomingRequestHandler1(); static void handleAlternativeRequestByte(void*, u_int8_t requestByte); void handleAlternativeRequestByte1(u_int8_t requestByte); void handleRequestBytes(int newBytesRead); Boolean authenticationOK(char const* cmdName, char const* urlSuffix, char const* fullRequestStr); void changeClientInputSocket(int newSocketNum, unsigned char const* extraData, unsigned extraDataSize); // used to implement RTSP-over-HTTP tunneling static void continueHandlingREGISTER(ParamsForREGISTER* params); virtual void continueHandlingREGISTER1(ParamsForREGISTER* params); // Shortcuts for setting up a RTSP response (prior to sending it): void setRTSPResponse(char const* responseStr); void setRTSPResponse(char const* responseStr, u_int32_t sessionId); void setRTSPResponse(char const* responseStr, char const* contentStr); void setRTSPResponse(char const* responseStr, u_int32_t sessionId, char const* contentStr); RTSPServer& fOurServer; Boolean fIsActive; int fClientInputSocket, fClientOutputSocket; struct sockaddr_in fClientAddr; unsigned char fRequestBuffer[RTSP_BUFFER_SIZE]; unsigned fRequestBytesAlreadySeen, fRequestBufferBytesLeft; unsigned char* fLastCRLF; unsigned char fResponseBuffer[RTSP_BUFFER_SIZE]; unsigned fRecursionCount; char const* fCurrentCSeq; Authenticator fCurrentAuthenticator; // used if access control is needed char* fOurSessionCookie; // used for optional RTSP-over-HTTP tunneling unsigned fBase64RemainderCount; // used for optional RTSP-over-HTTP tunneling (possible values: 0,1,2,3) }; // The state of an individual client session (using one or more sequential TCP connections) handled by a RTSP server: class RTSPClientSession { protected: RTSPClientSession(RTSPServer& ourServer, u_int32_t sessionId); virtual ~RTSPClientSession(); friend class RTSPServer; friend class RTSPClientConnection; // Make the handler functions for each command virtual, to allow subclasses to redefine them: virtual void handleCmd_SETUP(RTSPClientConnection* ourClientConnection, char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr); virtual void handleCmd_withinSession(RTSPClientConnection* ourClientConnection, char const* cmdName, char const* urlPreSuffix, char const* urlSuffix, char const* fullRequestStr); virtual void handleCmd_TEARDOWN(RTSPClientConnection* ourClientConnection, ServerMediaSubsession* subsession); virtual void handleCmd_PLAY(RTSPClientConnection* ourClientConnection, ServerMediaSubsession* subsession, char const* fullRequestStr); virtual void handleCmd_PAUSE(RTSPClientConnection* ourClientConnection, ServerMediaSubsession* subsession); virtual void handleCmd_GET_PARAMETER(RTSPClientConnection* ourClientConnection, ServerMediaSubsession* subsession, char const* fullRequestStr); virtual void handleCmd_SET_PARAMETER(RTSPClientConnection* ourClientConnection, ServerMediaSubsession* subsession, char const* fullRequestStr); protected: UsageEnvironment& envir() { return fOurServer.envir(); } void deleteStreamByTrack(unsigned trackNum); void reclaimStreamStates(); Boolean isMulticast() const { return fIsMulticast; } void noteLiveness(); static void noteClientLiveness(RTSPClientSession* clientSession); static void livenessTimeoutTask(RTSPClientSession* clientSession); // Shortcuts for setting up a RTSP response (prior to sending it): void setRTSPResponse(RTSPClientConnection* ourClientConnection, char const* responseStr) { ourClientConnection->setRTSPResponse(responseStr); } void setRTSPResponse(RTSPClientConnection* ourClientConnection, char const* responseStr, u_int32_t sessionId) { ourClientConnection->setRTSPResponse(responseStr, sessionId); } void setRTSPResponse(RTSPClientConnection* ourClientConnection, char const* responseStr, char const* contentStr) { ourClientConnection->setRTSPResponse(responseStr, contentStr); } void setRTSPResponse(RTSPClientConnection* ourClientConnection, char const* responseStr, u_int32_t sessionId, char const* contentStr) { ourClientConnection->setRTSPResponse(responseStr, sessionId, contentStr); } protected: RTSPServer& fOurServer; u_int32_t fOurSessionId; ServerMediaSession* fOurServerMediaSession; Boolean fIsMulticast, fStreamAfterSETUP; unsigned char fTCPStreamIdCount; // used for (optional) RTP/TCP Boolean usesTCPTransport() const { return fTCPStreamIdCount > 0; } TaskToken fLivenessCheckTask; unsigned fNumStreamStates; struct streamState { ServerMediaSubsession* subsession; int tcpSocketNum; void* streamToken; } * fStreamStates; }; protected: // If you subclass "RTSPClientConnection", then you must also redefine this virtual function in order // to create new objects of your subclass: virtual RTSPClientConnection* createNewClientConnection(int clientSocket, struct sockaddr_in clientAddr); // If you subclass "RTSPClientSession", then you must also redefine this virtual function in order // to create new objects of your subclass: virtual RTSPClientSession* createNewClientSession(u_int32_t sessionId); // An iterator over our "ServerMediaSession" objects: class ServerMediaSessionIterator { public: ServerMediaSessionIterator(RTSPServer& server); virtual ~ServerMediaSessionIterator(); ServerMediaSession* next(); private: HashTable::Iterator* fOurIterator; }; private: static void incomingConnectionHandlerRTSP(void*, int /*mask*/); void incomingConnectionHandlerRTSP1(); static void incomingConnectionHandlerHTTP(void*, int /*mask*/); void incomingConnectionHandlerHTTP1(); void incomingConnectionHandler(int serverSocket); void noteTCPStreamingOnSocket(int socketNum, RTSPClientSession* clientSession, unsigned trackNum); void unnoteTCPStreamingOnSocket(int socketNum, RTSPClientSession* clientSession, unsigned trackNum); void stopTCPStreamingOnSocket(int socketNum); protected: Port fRTSPServerPort; private: friend class RTSPClientConnection; friend class RTSPClientSession; friend class ServerMediaSessionIterator; friend class RegisterRequestRecord; int fRTSPServerSocket; int fHTTPServerSocket; // for optional RTSP-over-HTTP tunneling Port fHTTPServerPort; // ditto HashTable* fServerMediaSessions; // maps 'stream name' strings to "ServerMediaSession" objects HashTable* fClientConnections; // the "ClientConnection" objects that we're using HashTable* fClientConnectionsForHTTPTunneling; // maps client-supplied 'session cookie' strings to "RTSPClientConnection"s // (used only for optional RTSP-over-HTTP tunneling) HashTable* fClientSessions; // maps 'session id' strings to "RTSPClientSession" objects HashTable* fTCPStreamingDatabase; // maps TCP socket numbers to ids of sessions that are streaming over it (RTP/RTCP-over-TCP) HashTable* fPendingRegisterRequests; unsigned fRegisterRequestCounter; UserAuthenticationDatabase* fAuthDB; unsigned fReclamationTestSeconds; Boolean fAllowStreamingRTPOverTCP; // by default, True }; ////////// A subclass of "RTSPServer" that implements the "REGISTER" command to set up proxying on the specified URL ////////// class RTSPServerWithREGISTERProxying: public RTSPServer { public: static RTSPServerWithREGISTERProxying* createNew(UsageEnvironment& env, Port ourPort = 554, UserAuthenticationDatabase* authDatabase = NULL, UserAuthenticationDatabase* authDatabaseForREGISTER = NULL, unsigned reclamationTestSeconds = 65, Boolean streamRTPOverTCP = False, int verbosityLevelForProxying = 0); protected: RTSPServerWithREGISTERProxying(UsageEnvironment& env, int ourSocket, Port ourPort, UserAuthenticationDatabase* authDatabase, UserAuthenticationDatabase* authDatabaseForREGISTER, unsigned reclamationTestSeconds, Boolean streamRTPOverTCP, int verbosityLevelForProxying); // called only by createNew(); virtual ~RTSPServerWithREGISTERProxying(); protected: // redefined virtual functions virtual char const* allowedCommandNames(); virtual Boolean weImplementREGISTER(char const* proxyURLSuffix, char*& responseStr); virtual void implementCmd_REGISTER(char const* url, char const* urlSuffix, int socketToRemoteServer, Boolean deliverViaTCP, char const* proxyURLSuffix); virtual UserAuthenticationDatabase* getAuthenticationDatabaseForCommand(char const* cmdName); private: Boolean fStreamRTPOverTCP; int fVerbosityLevelForProxying; unsigned fRegisteredProxyCounter; char* fAllowedCommandNames; UserAuthenticationDatabase* fAuthDBForREGISTER; }; #endif
51.252381
215
0.766283
[ "object" ]
0488ab613ec2323eb25f3599323fc2de23f3a661
14,433
cc
C++
source/Host.test.cc
piperwelch/SymbulationEmp
36a69154f46bddfbc75712bf39becfa56d49ad02
[ "BSL-1.0" ]
3
2022-02-01T20:29:10.000Z
2022-02-03T21:10:23.000Z
source/Host.test.cc
piperwelch/SymbulationEmp
36a69154f46bddfbc75712bf39becfa56d49ad02
[ "BSL-1.0" ]
null
null
null
source/Host.test.cc
piperwelch/SymbulationEmp
36a69154f46bddfbc75712bf39becfa56d49ad02
[ "BSL-1.0" ]
1
2022-03-31T14:37:49.000Z
2022-03-31T14:37:49.000Z
#include "Host.h" #include "Symbiont.h" #include <set> TEST_CASE("Host SetIntVal, GetIntVal") { emp::Ptr<emp::Random> random = new emp::Random(-1); SymConfigBase config; SymWorld w(*random); double int_val = 1; Host * h1 = new Host(random, &w, &config); double default_int_val = 0.0; REQUIRE(h1->GetIntVal() == default_int_val); Host * h2 = new Host(random, &w, &config, int_val); double expected_int_val = 1; REQUIRE(h2->GetIntVal() == expected_int_val); int_val = -0.7; h2->SetIntVal(int_val); expected_int_val = -0.7; REQUIRE(h2->GetIntVal() == expected_int_val); int_val = -1.3; REQUIRE_THROWS(new Host(random, &w, &config, int_val)); int_val = 1.8; REQUIRE_THROWS(new Host(random, &w, &config, int_val)); } TEST_CASE("SetPoints, AddPoints, GetPoints") { emp::Ptr<emp::Random> random = new emp::Random(-1); SymConfigBase config; SymWorld w(*random); double int_val = 1; Host * h = new Host(random, &w, &config, int_val); double points = 50; h->SetPoints(points); double expected_points = 50; REQUIRE(h->GetPoints() == expected_points); points = 76; h->AddPoints(points); expected_points = 126; REQUIRE(h->GetPoints() == expected_points); } TEST_CASE("SetResTypes, GetResTypes") { emp::Ptr<emp::Random> random = new emp::Random(-1); SymConfigBase config; SymWorld w(*random); double int_val = 1; emp::vector<emp::Ptr<Organism>> syms = {}; emp::vector<emp::Ptr<Organism>> repro_syms = {}; std::set<int> res_types {1,3,5,9,2}; Host * h = new Host(random, &w, &config, int_val, syms, repro_syms, res_types); std::set<int> expected_res_types = h->GetResTypes(); for (int number : res_types) { // Tests if each integer from res_types is in expected_res_types REQUIRE(expected_res_types.find(number) != expected_res_types.end()); } res_types = {0,1}; h->SetResTypes(res_types); expected_res_types = h->GetResTypes(); for (int number : res_types) { // Tests if each integer from res_types is in expected_res_types REQUIRE(expected_res_types.find(number) != expected_res_types.end()); } } TEST_CASE("HasSym") { emp::Ptr<emp::Random> random = new emp::Random(-1); SymConfigBase config; SymWorld w(*random); double int_val = 1; WHEN("Host has no symbionts") { Host * h = new Host(random, &w, &config, int_val); THEN("HasSym is false") { bool expected = false; REQUIRE(h->HasSym() == expected); } } } TEST_CASE("Host Mutate") { //TODO: put in tests for mutation size and mutation rate separately emp::Ptr<emp::Random> random = new emp::Random(3); SymConfigBase config; SymWorld w(*random); double int_val = -0.31; //MUTATION RATE WHEN("Host mutation rate is -1"){ THEN("Normal mutation rate is used"){ config.HOST_MUTATION_RATE(-1); config.MUTATION_RATE(1); Host * h = new Host(random, &w, &config, int_val); REQUIRE(h->GetIntVal() == int_val); h->mutate(); REQUIRE(h->GetIntVal() != int_val); REQUIRE(h->GetIntVal() <= 1); REQUIRE(h->GetIntVal() >= -1); } } WHEN("Host mutation rate is not -1"){ THEN("Host mutation rate is used"){ config.HOST_MUTATION_RATE(1); config.MUTATION_RATE(0); Host * h = new Host(random, &w, &config, int_val); REQUIRE(h->GetIntVal() == int_val); h->mutate(); REQUIRE(h->GetIntVal() != int_val); REQUIRE(h->GetIntVal() <= 1); REQUIRE(h->GetIntVal() >= -1); } } //MUTATION SIZE WHEN("Host mutation size is -1"){ THEN("Normal mutation size is used"){ config.HOST_MUTATION_SIZE(-1); config.MUTATION_RATE(1); Host * h = new Host(random, &w, &config, int_val); REQUIRE(h->GetIntVal() == int_val); h->mutate(); REQUIRE(h->GetIntVal() != int_val); REQUIRE(h->GetIntVal() <= 1); REQUIRE(h->GetIntVal() >= -1); } } WHEN("Host mutation size is not -1"){ THEN("Host mutation size is used"){ config.HOST_MUTATION_SIZE(1); config.MUTATION_SIZE(0); Host * h = new Host(random, &w, &config, int_val); REQUIRE(h->GetIntVal() == int_val); h->mutate(); REQUIRE(h->GetIntVal() != int_val); REQUIRE(h->GetIntVal() <= 1); REQUIRE(h->GetIntVal() >= -1); } } } TEST_CASE("DistributeResources") { emp::Ptr<emp::Random> random = new emp::Random(-1); SymConfigBase config; SymWorld w(*random); WHEN("There are no symbionts and interaction value is between 0 and 1") { double int_val = 0.6; double resources = 80; double orig_points = 0; // call this default_points instead? (i'm not setting this val) config.SYNERGY(5); Host * h = new Host(random, &w, &config, int_val); h->DistribResources(resources); THEN("Points increase") { double expected_points = resources - (resources * int_val); // 48 double points = h->GetPoints(); REQUIRE(points == expected_points); REQUIRE(points > orig_points); } } WHEN("There are no symbionts and interaction value is 0") { double int_val = 0; double resources = 10; double orig_points = 0; config.SYNERGY(5); Host * h = new Host(random, &w, &config, int_val); h->DistribResources(resources); THEN("Resources are added to points") { double expected_points = orig_points + resources; // 0 double points = h->GetPoints(); REQUIRE(points == expected_points); } } WHEN("There are no symbionts and interaction value is between -1 and 0") { double int_val = -0.4; double resources = 30; double orig_points = 27; config.SYNERGY(5); Host * h = new Host(random, &w, &config, int_val); h->AddPoints(orig_points); h->DistribResources(resources); THEN("Points increase") { double host_defense = -1.0 * int_val * resources; // the resources spent on defense double add_points = resources - host_defense; double expected_points = orig_points + add_points; double points = h->GetPoints(); REQUIRE(points == expected_points); REQUIRE(points > orig_points); } } } TEST_CASE("Phage Exclude") { emp::Ptr<emp::Random> random = new emp::Random(3); SymWorld w(*random); SymConfigBase config; int sym_limit = 4; config.SYM_LIMIT(sym_limit); double int_val = 0; WHEN("Phage exclude is set to false"){ bool phage_exclude = 0; config.PHAGE_EXCLUDE(phage_exclude); Host * h = new Host(random, &w, &config, int_val); THEN("syms are added without issue"){ for(int i = 0; i < sym_limit; i++){ h->AddSymbiont(new Symbiont(random, &w, &config, int_val)); } int num_syms = (h->GetSymbionts()).size(); REQUIRE(num_syms==sym_limit); //with random seed 3 and phage exclusion on, //num_syms not reach the sym_limit (would be 2 not 4) } } WHEN("Phage exclude is set to true"){ bool phage_exclude = 1; config.PHAGE_EXCLUDE(phage_exclude); THEN("syms have a decreasing change of entering the host"){ int goal_num_syms[] = {3,3,3,3}; for(int i = 0; i < 4; i ++){ emp::Ptr<emp::Random> random = new emp::Random(i+1); SymWorld w(*random); Host * h = new Host(random, &w, &config, int_val); for(double i = 0; i < 10; i++){ h->AddSymbiont(new Symbiont(random, &w, &config, int_val)); } int host_num_syms = (h->GetSymbionts()).size(); REQUIRE(goal_num_syms[i] == host_num_syms); } } } } TEST_CASE("SetResInProcess, GetResInProcess") { emp::Ptr<emp::Random> random = new emp::Random(-1); SymConfigBase config; SymWorld w(*random); double int_val = 1; Host * h = new Host(random, &w, &config, int_val); double expected_res_in_process = 0; REQUIRE(h->GetResInProcess() == expected_res_in_process); h->SetResInProcess(126); expected_res_in_process = 126; REQUIRE(h->GetResInProcess() == expected_res_in_process); } TEST_CASE("Steal resources unit test"){ emp::Ptr<emp::Random> random = new emp::Random(-1); SymWorld w(*random); SymConfigBase config; WHEN ("sym_int_val < host_int_val"){ double sym_int_val = -0.6; WHEN("host_int_val > 0"){ double host_int_val = 0.2; Host * h = new Host(random, &w, &config, host_int_val); h->SetResInProcess(100); double expected_stolen = 60; // sym_int_val * res_in_process * -1 double expected_res_in_process = 40; // res_in_process - expected_stolen THEN("Amount stolen is dependent only on sym_int_val"){ REQUIRE(h->StealResources(sym_int_val) == expected_stolen); REQUIRE(h->GetResInProcess() == expected_res_in_process); } } WHEN("host_int_val < 0"){ double host_int_val = -0.2; Host * h = new Host(random, &w, &config, host_int_val); h->SetResInProcess(100); double expected_stolen = 40; // (host_int_val - sym_int_val) * res_in_process double expected_res_in_process = 60; // res_in_process - expected_stolen THEN("Amount stolen is dependent on both sym_int_val and host_int_val"){ REQUIRE(h->StealResources(sym_int_val) == expected_stolen); REQUIRE(h->GetResInProcess() == expected_res_in_process); } } } WHEN("host_int_val > sym_int_val"){ double sym_int_val = -0.3; double host_int_val = -0.5; Host * h = new Host(random, &w, &config, host_int_val); h->SetResInProcess(100); double expected_stolen = 0; double expected_res_in_process = 100; THEN("Symbiont fails to steal resources"){ REQUIRE(h->StealResources(sym_int_val) == expected_stolen); REQUIRE(h->GetResInProcess() == expected_res_in_process); } } } TEST_CASE("GetDoEctosymbiosis"){ GIVEN("A world"){ emp::Ptr<emp::Random> random = new emp::Random(17); SymWorld w(*random); SymConfigBase config; w.Resize(2,2); double int_val = 0.5; size_t host_pos = 0; WHEN("Ectosymbiosis is off but other conditions are met"){ config.ECTOSYMBIOSIS(0); emp::Ptr<Host> host = new Host(random, &w, &config, int_val); emp::Ptr<Organism> sym = new Symbiont(random, &w, &config, int_val); w.AddOrgAt(host, host_pos); w.AddOrgAt(sym, host_pos); THEN("Returns false"){ REQUIRE(host->GetDoEctosymbiosis(host_pos) == false); } } WHEN("There is no parallel sym but other conditions are met"){ config.ECTOSYMBIOSIS(1); emp::Ptr<Host> host = new Host(random, &w, &config, int_val); emp::Ptr<Organism> sym = new Symbiont(random, &w, &config, int_val); w.AddOrgAt(host, host_pos); w.AddOrgAt(sym, host_pos + 1); THEN("Returns false"){ REQUIRE(host->GetDoEctosymbiosis(host_pos) == false); } } WHEN("There is a parallel sym but it is dead, and other conditions are met"){ config.ECTOSYMBIOSIS(1); emp::Ptr<Host> host = new Host(random, &w, &config, int_val); emp::Ptr<Organism> sym = new Symbiont(random, &w, &config, int_val); sym->SetDead(); w.AddOrgAt(host, host_pos); w.AddOrgAt(sym, host_pos + 1); THEN("Returns false"){ REQUIRE(host->GetDoEctosymbiosis(host_pos) == false); } } WHEN("Ectosymbiotic immunity is on and the host has a sym, but other conditions are met"){ config.ECTOSYMBIOSIS(1); config.ECTOSYMBIOTIC_IMMUNITY(1); emp::Ptr<Host> host = new Host(random, &w, &config, int_val); emp::Ptr<Organism> sym = new Symbiont(random, &w, &config, int_val); emp::Ptr<Organism> hosted_sym = new Symbiont(random, &w, &config, int_val); w.AddOrgAt(host, host_pos); w.AddOrgAt(sym, host_pos); host->AddSymbiont(hosted_sym); THEN("Returns false"){ REQUIRE(host->GetDoEctosymbiosis(host_pos) == false); } } WHEN("Ectosymbiosis is on, there is a parallel sym, ectosymbiotic immunity is off, and the host has a sym"){ config.ECTOSYMBIOSIS(1); config.ECTOSYMBIOTIC_IMMUNITY(0); emp::Ptr<Host> host = new Host(random, &w, &config, int_val); emp::Ptr<Organism> sym = new Symbiont(random, &w, &config, int_val); emp::Ptr<Organism> hosted_sym = new Symbiont(random, &w, &config, int_val); w.AddOrgAt(host, host_pos); w.AddOrgAt(sym, host_pos); host->AddSymbiont(hosted_sym); THEN("Returns true"){ REQUIRE(host->GetDoEctosymbiosis(host_pos) == true); } } WHEN("Ectosymbiosis is on, there is a parallel sym, ectosymbiotic immunity is on, and the host does not have a sym"){ config.ECTOSYMBIOSIS(1); config.ECTOSYMBIOTIC_IMMUNITY(1); emp::Ptr<Host> host = new Host(random, &w, &config, int_val); emp::Ptr<Organism> sym = new Symbiont(random, &w, &config, int_val); emp::Ptr<Organism> hosted_sym = new Symbiont(random, &w, &config, int_val); w.AddOrgAt(host, host_pos); w.AddOrgAt(sym, host_pos); THEN("Returns true"){ REQUIRE(host->GetDoEctosymbiosis(host_pos) == true); } } } } TEST_CASE("Host growOlder"){ emp::Ptr<emp::Random> random = new emp::Random(-1); SymWorld w(*random); SymConfigBase config; config.HOST_AGE_MAX(2); WHEN ("A host reaches its maximum age"){ Host * h = new Host(random, &w, &config, 1); w.AddOrgAt(h, 1); THEN("The host dies and is removed from the world"){ REQUIRE(h->GetDead() == false); REQUIRE(w.GetNumOrgs() == 1); REQUIRE(h->GetAge() == 0); w.Update(); REQUIRE(h->GetAge() == 1); w.Update(); REQUIRE(h->GetAge() == 2); w.Update(); REQUIRE(w.GetNumOrgs() == 0); } } }
32.144766
121
0.59648
[ "vector" ]
048be8a11dfd45d178940cb575276192af6c42d1
69,059
cc
C++
src/btree/leaf_node.cc
sauter-hq/rethinkdb
f34541d501bcf109c2825a7a1b67cf8fd39b9133
[ "Apache-2.0" ]
null
null
null
src/btree/leaf_node.cc
sauter-hq/rethinkdb
f34541d501bcf109c2825a7a1b67cf8fd39b9133
[ "Apache-2.0" ]
null
null
null
src/btree/leaf_node.cc
sauter-hq/rethinkdb
f34541d501bcf109c2825a7a1b67cf8fd39b9133
[ "Apache-2.0" ]
null
null
null
// Copyright 2010-2014 RethinkDB, all rights reserved. #include "btree/leaf_node.hpp" #include <inttypes.h> #include <algorithm> #include <set> #include "errors.hpp" #include <boost/optional.hpp> #include "btree/node.hpp" #include "repli_timestamp.hpp" #include "utils.hpp" namespace leaf { // A leaf node is a set of key/value, key/value/modification_time, and // key/deletion_time tuples with distinct keys, where modification // time or deletion time is omitted for sufficiently old entries. A // key/deletion_time entry says that the key was recently deleted. // // In particular, all the modification times and deletions after a // certain time are recorded, and those before a certain time are // omitted. You'll note that we don't have deletion entries that omit // a timestamp. // Leaf nodes support efficient key lookup and efficient key-order // iteration, and efficient iteration in order of descending // modification time. The details of implementation are described // later. // These codes can appear as the first byte of a leaf node entry (see // below) (values 250 or smaller are just key sizes for key/value // pairs). // Means we have a deletion entry. const int DELETE_ENTRY_CODE = 255; // Means we have a skipped entry exactly one byte long. const int SKIP_ENTRY_CODE_ONE = 254; // Means we have a skipped entry exactly two bytes long. const int SKIP_ENTRY_CODE_TWO = 253; // Means we have a skipped entry exactly N bytes long, of form { uint8_t 252; uint16_t N; char garbage[]; } const int SKIP_ENTRY_CODE_MANY = 252; // A reserved meaningless value. const int SKIP_ENTRY_RESERVED = 251; // Entries are contiguously connected to the end of a btree // block. Here's what a full leaf node looks like. // // [magic][num_pairs][live_size][frontmost][tstamp_cutpoint][off0][off1][off2]...[offN-1]........[tstamp][entry][tstamp][entry][tstamp][entry][tstamp][entry][entry][entry][entry][entry][entry][entry] // \___________________________/ ^ ^ ^ // N = num_pairs frontmost tstamp_cutpoint (block size) // // [tstamp] in [tstamp][entry] pairs are non-increasing (when you look at them // from frontmost to tstamp_cutpoint). This is true even of skip entries. // // Here's what an "[entry]" may look like: // // [btree key][btree value] -- a live entry // [255][btree key] -- a deletion entry // [254] -- a skip entry of size one // [253][byte] -- a skip entry of size two // [252][uint16_t sz][byte][byte]...[byte] -- a skip entry of size "sz + 3" // \___________________/ // sz bytes // // The extra byte(s) in a skip entry are filled with `SKIP_ENTRY_RESERVED`. // // The reason why we special-case skip entries that are only one or two bytes // long is that we the header we use for a skip entry of size three or more is // itself three bytes, so it can't fit in a slot of size one or two. We don't // expect to actually see many entries of size one or two, but it pays to be // thorough. struct entry_t; struct value_t; bool entry_is_deletion(const entry_t *p) { uint8_t x = *reinterpret_cast<const uint8_t *>(p); rassert(x != SKIP_ENTRY_RESERVED); return x == DELETE_ENTRY_CODE; } bool entry_is_live(const entry_t *p) { uint8_t x = *reinterpret_cast<const uint8_t *>(p); rassert(x != SKIP_ENTRY_RESERVED); rassert(MAX_KEY_SIZE == 250); return x <= MAX_KEY_SIZE; } bool entry_is_skip(const entry_t *p) { return !entry_is_deletion(p) && !entry_is_live(p); } const btree_key_t *entry_key(const entry_t *p) { if (entry_is_deletion(p)) { return reinterpret_cast<const btree_key_t *>(1 + reinterpret_cast<const char *>(p)); } else { return reinterpret_cast<const btree_key_t *>(p); } } const void *entry_value(const entry_t *p) { if (entry_is_deletion(p)) { return nullptr; } else { return reinterpret_cast<const char *>(p) + entry_key(p)->full_size(); } } int entry_size(value_sizer_t *sizer, const entry_t *p) { uint8_t code = *reinterpret_cast<const uint8_t *>(p); switch (code) { case DELETE_ENTRY_CODE: return 1 + entry_key(p)->full_size(); case SKIP_ENTRY_CODE_ONE: return 1; case SKIP_ENTRY_CODE_TWO: return 2; case SKIP_ENTRY_CODE_MANY: return 3 + *reinterpret_cast<const uint16_t *>(1 + reinterpret_cast<const char *>(p)); default: rassert(code <= MAX_KEY_SIZE); return entry_key(p)->full_size() + sizer->size(entry_value(p)); } } const entry_t *get_entry(const leaf_node_t *node, int offset) { return reinterpret_cast<const entry_t *>(reinterpret_cast<const char *>(node) + offset + (offset < node->tstamp_cutpoint ? sizeof(repli_timestamp_t) : 0)); } entry_t *get_entry(leaf_node_t *node, int offset) { return reinterpret_cast<entry_t *>(reinterpret_cast<char *>(node) + offset + (offset < node->tstamp_cutpoint ? sizeof(repli_timestamp_t) : 0)); } char *get_at_offset(leaf_node_t *node, int offset) { return reinterpret_cast<char *>(node) + offset; } repli_timestamp_t get_timestamp(const leaf_node_t *node, int offset) { return *reinterpret_cast<const repli_timestamp_t *>(reinterpret_cast<const char *>(node) + offset); } struct entry_iter_t { int offset; void step(value_sizer_t *sizer, const leaf_node_t *node) { rassert(!done(sizer)); offset += entry_size(sizer, get_entry(node, offset)) + (offset < node->tstamp_cutpoint ? sizeof(repli_timestamp_t) : 0); } bool done(value_sizer_t *sizer) const { int bs = sizer->block_size().value(); rassert(offset <= bs, "offset=%d, bs=%d", offset, bs); return offset == bs; } static entry_iter_t make(const leaf_node_t *node) { entry_iter_t ret; ret.offset = node->frontmost; return ret; } }; void strprint_entry(std::string *out, value_sizer_t *sizer, const entry_t *entry) { if (entry_is_live(entry)) { const btree_key_t *key = entry_key(entry); *out += strprintf("%.*s:", static_cast<int>(key->size), key->contents); *out += strprintf("[entry size=%d]", entry_size(sizer, entry)); *out += strprintf("[value size=%d]", sizer->size(entry_value(entry))); } else if (entry_is_deletion(entry)) { const btree_key_t *key = entry_key(entry); *out += strprintf("%.*s:[deletion]", static_cast<int>(key->size), key->contents); } else if (entry_is_skip(entry)) { *out += strprintf("[skip %d]", entry_size(sizer, entry)); } else { *out += strprintf("[code %d]", *reinterpret_cast<const uint8_t *>(entry)); } } std::string strprint_leaf(value_sizer_t *sizer, const leaf_node_t *node) { std::string out; out += strprintf("Leaf(magic='%4.4s', num_pairs=%u, live_size=%u, frontmost=%u, tstamp_cutpoint=%u)\n", node->magic.bytes, node->num_pairs, node->live_size, node->frontmost, node->tstamp_cutpoint); out += strprintf(" Offsets:"); for (int i = 0; i < node->num_pairs; ++i) { out += strprintf(" %d", node->pair_offsets[i]); } out += strprintf("\n"); out += strprintf(" By Key:"); for (int i = 0; i < node->num_pairs; ++i) { out += strprintf(" %d:", node->pair_offsets[i]); strprint_entry(&out, sizer, get_entry(node, node->pair_offsets[i])); } out += strprintf("\n"); out += strprintf(" By Offset:"); entry_iter_t iter = entry_iter_t::make(node); while (out += strprintf(" %d", iter.offset), !iter.done(sizer)) { out += strprintf(":"); if (iter.offset < node->tstamp_cutpoint) { repli_timestamp_t tstamp = get_timestamp(node, iter.offset); out += strprintf("[t=%" PRIu64 "]", tstamp.longtime); } strprint_entry(&out, sizer, get_entry(node, iter.offset)); iter.step(sizer, node); } out += strprintf("\n"); return out; } void print_entry(FILE *fp, value_sizer_t *sizer, const entry_t *entry) { if (entry_is_live(entry)) { const btree_key_t *key = entry_key(entry); fprintf(fp, "%.*s:", static_cast<int>(key->size), key->contents); fprintf(fp, "[entry size=%d]", entry_size(sizer, entry)); fprintf(fp, "[value size=%d]", sizer->size(entry_value(entry))); } else if (entry_is_deletion(entry)) { const btree_key_t *key = entry_key(entry); fprintf(fp, "%.*s:[deletion]", static_cast<int>(key->size), key->contents); } else if (entry_is_skip(entry)) { fprintf(fp, "[skip %d]", entry_size(sizer, entry)); } else { fprintf(fp, "[code %d]", *reinterpret_cast<const uint8_t *>(entry)); } fflush(fp); } void print(FILE *fp, value_sizer_t *sizer, const leaf_node_t *node) { fprintf(fp, "Leaf(magic='%4.4s', num_pairs=%u, live_size=%u, frontmost=%u, tstamp_cutpoint=%u)\n", node->magic.bytes, node->num_pairs, node->live_size, node->frontmost, node->tstamp_cutpoint); fprintf(fp, " Offsets:"); for (int i = 0; i < node->num_pairs; ++i) { fprintf(fp, " %d", node->pair_offsets[i]); } fprintf(fp, "\n"); fflush(fp); fprintf(fp, " By Key:"); for (int i = 0; i < node->num_pairs; ++i) { fprintf(fp, " %d:", node->pair_offsets[i]); print_entry(fp, sizer, get_entry(node, node->pair_offsets[i])); } fprintf(fp, "\n"); fprintf(fp, " By Offset:"); fflush(fp); entry_iter_t iter = entry_iter_t::make(node); while (fprintf(fp, " %d", iter.offset), fflush(fp), !iter.done(sizer)) { fprintf(fp, ":"); fflush(fp); if (iter.offset < node->tstamp_cutpoint) { repli_timestamp_t tstamp = get_timestamp(node, iter.offset); fprintf(fp, "[t=%" PRIu64 "]", tstamp.longtime); fflush(fp); } print_entry(fp, sizer, get_entry(node, iter.offset)); iter.step(sizer, node); } fprintf(fp, "\n"); fflush(fp); } class do_nothing_fscker_t : public key_value_fscker_t { bool fsck(UNUSED value_sizer_t *sizer, UNUSED const btree_key_t *key, UNUSED const void *value, UNUSED std::string *msg_out) { return true; } }; bool fsck(value_sizer_t *sizer, const btree_key_t *left_exclusive_or_null, const btree_key_t *right_inclusive_or_null, const leaf_node_t *node, key_value_fscker_t *fscker, std::string *msg_out) { struct { std::string *msg_out; bool operator()(bool test, const char *msg) { if (!test) *msg_out = msg; return !test; } } failed; failed.msg_out = msg_out; // We check that all offsets are contiguous (with interspersed // skip entries) between frontmost and block_size, that frontmost // is the smallest offset, that live_size is correct, that we have // correct magic, that the keys are in order, that there are no // deletion entries after tstamp_cutpoint, and that // tstamp_cutpoint lies on an entry boundary, and that frontmost // is not before the end of pair_offsets // Basic sanity checks on fields' values. if (failed(node->magic == sizer->btree_leaf_magic(), "bad leaf magic") || failed(node->frontmost >= offsetof(leaf_node_t, pair_offsets) + node->num_pairs * sizeof(uint16_t), "frontmost offset is before the end of pair_offsets") || failed(node->live_size <= (sizer->block_size().value() - node->frontmost) + sizeof(uint16_t) * node->num_pairs, "live_size is impossibly large") || failed(node->tstamp_cutpoint >= node->frontmost, "timestamp cut offset below frontmost offset") || failed(node->tstamp_cutpoint <= sizer->block_size().value(), "timestamp cut offset larger than block size") ) { return false; } // sizeof(offs) is guaranteed to be less than the block_size() thanks to assertions above. scoped_array_t<uint16_t> offs(node->num_pairs); memcpy(offs.data(), node->pair_offsets, node->num_pairs * sizeof(uint16_t)); std::sort(offs.data(), offs.data() + node->num_pairs); if (failed(node->num_pairs == 0 || node->frontmost <= offs[0], "smallest pair offset is before frontmost offset") || failed(node->num_pairs == 0 || offs[node->num_pairs - 1] < sizer->block_size().value(), "largest pair offset is larger than block size") ) { return false; } entry_iter_t iter = entry_iter_t::make(node); int observed_live_size = 0; int i = 0; bool seen_tstamp_cutpoint = false; static_assert(std::is_same<uint64_t, decltype(repli_timestamp_t::longtime)>::value, "This code assumes repli_timestamp_t is a uint64_t."); uint64_t earliest_so_far = UINT64_MAX; while (!iter.done(sizer)) { int offset = iter.offset; // tstamp_cutpoint is supposed to be on some entry's offset. if (offset >= node->tstamp_cutpoint && !seen_tstamp_cutpoint) { if (failed(offset == node->tstamp_cutpoint, "misaligned tstamp_cutpoint")) { return false; } seen_tstamp_cutpoint = true; } if (failed(offset + (offset < node->tstamp_cutpoint ? sizeof(repli_timestamp_t) : 0) < sizer->block_size().value(), "offset would be past block size after accounting for the timestamp")) { return false; } if (offset < node->tstamp_cutpoint) { repli_timestamp_t tstamp = get_timestamp(node, offset); if (tstamp.longtime > earliest_so_far) { *msg_out = strprintf("timestamps out of order (%" PRIu64 " after %" PRIu64 ")\n", tstamp.longtime, earliest_so_far); return false; } earliest_so_far = tstamp.longtime; } const entry_t *ent = get_entry(node, offset); if (entry_is_live(ent)) { const void *value = entry_value(ent); int space = sizer->block_size().value() - (reinterpret_cast<const char *>(value) - reinterpret_cast<const char *>(node)); if (!sizer->fits(value, space)) { *msg_out = strprintf("problem with key %.*s: value does not fit\n", entry_key(ent)->size, entry_key(ent)->contents); return false; } std::string fscker_msg; if (!fscker->fsck(sizer, entry_key(ent), value, &fscker_msg)) { *msg_out = strprintf("Problem with key %.*s: %s\n", entry_key(ent)->size, entry_key(ent)->contents, fscker_msg.c_str()); return false; } observed_live_size += sizeof(uint16_t) + entry_size(sizer, ent); if (failed(i < node->num_pairs, "missing entry offsets")) { return false; } if (offset != offs[i]) { *msg_out = strprintf("missing live entries or entry offsets (next " "offset in offsets table is %d, but in node is %d)", offs[i], offset); return false; } ++i; } else if (entry_is_deletion(ent)) { if (failed(!seen_tstamp_cutpoint, "deletion entry after tstamp_cutpoint") || failed(i < node->num_pairs, "missing entry offsets") || failed(offset == offs[i], "missing deletion entries or entry offsets")) { return false; } ++i; } // It's safe to step (because we just checked that the entry // is valid). iter.step(sizer, node); } if (failed(i == node->num_pairs, "missing entries") || failed(node->live_size == observed_live_size, "incorrect live_size recorded")) { return false; } // Entries look valid, check key ordering. const btree_key_t *last = left_exclusive_or_null; for (int k = 0; k < node->num_pairs; ++k) { const btree_key_t *key = entry_key(get_entry(node, node->pair_offsets[k])); if (failed(last == nullptr || btree_key_cmp(last, key) < 0, "keys out of order")) { return false; } last = key; } if (failed(last == nullptr || right_inclusive_or_null == nullptr || btree_key_cmp(last, right_inclusive_or_null) <= 0, "keys out of order (with right_inclusive key)")) { return false; } return true; } void validate(DEBUG_VAR value_sizer_t *sizer, DEBUG_VAR const leaf_node_t *node) { #ifndef NDEBUG do_nothing_fscker_t fits; std::string msg; bool fscked_successfully = fsck(sizer, nullptr, nullptr, node, &fits, &msg); rassert(fscked_successfully, "%s", msg.c_str()); #endif } void init(value_sizer_t *sizer, leaf_node_t *node) { node->magic = sizer->btree_leaf_magic(); node->num_pairs = 0; node->live_size = 0; node->frontmost = sizer->block_size().value(); node->tstamp_cutpoint = node->frontmost; } int free_space(value_sizer_t *sizer) { return sizer->block_size().value() - offsetof(leaf_node_t, pair_offsets); } // Returns the mandatory storage cost of the node, returning a value // in the closed interval [0, free_space(sizer)]. Outputs the offset // of the first entry for which storing a timestamp is not mandatory. int mandatory_cost(value_sizer_t *sizer, const leaf_node_t *node, int required_timestamps, int *tstamp_back_offset_out) { int size = node->live_size; // node->live_size does not include deletion entries, deletion // entries' timestamps, and live entries' timestamps. We add that // to size. entry_iter_t iter = entry_iter_t::make(node); int count = 0; int deletions_cost = 0; int max_deletions_cost = free_space(sizer) / DELETION_RESERVE_FRACTION; while (!(count == required_timestamps || iter.done(sizer) || iter.offset >= node->tstamp_cutpoint)) { const entry_t *ent = get_entry(node, iter.offset); if (entry_is_deletion(ent)) { if (deletions_cost >= max_deletions_cost) { break; } int this_entry_cost = sizeof(uint16_t) + sizeof(repli_timestamp_t) + entry_size(sizer, ent); deletions_cost += this_entry_cost; size += this_entry_cost; ++count; } else if (entry_is_live(ent)) { ++count; size += sizeof(repli_timestamp_t); } iter.step(sizer, node); } *tstamp_back_offset_out = iter.offset; return size; } int mandatory_cost(value_sizer_t *sizer, const leaf_node_t *node, int required_timestamps) { int ignored; return mandatory_cost(sizer, node, required_timestamps, &ignored); } int leaf_epsilon(value_sizer_t *sizer) { // Returns the maximum possible entry size, i.e. the key cost plus // the value cost plus pair_offsets plus timestamp cost. int key_cost = sizeof(uint8_t) + MAX_KEY_SIZE; // If the value is always empty, the DELETE_ENTRY_CODE byte needs to be considered. int n = std::max(sizer->max_possible_size(), 1); int pair_offsets_cost = sizeof(uint16_t); int timestamp_cost = sizeof(repli_timestamp_t); return key_cost + n + pair_offsets_cost + timestamp_cost; } bool is_empty(const leaf_node_t *node) { return node->num_pairs == 0; } bool is_full(value_sizer_t *sizer, const leaf_node_t *node, const btree_key_t *key, const void *value) { // Upon an insertion, we preserve `MANDATORY_TIMESTAMPS - 1` // timestamps and add our own (accounted for below) // // Notice this is the site of some bullshit XXX, the line below used to // consider that we would need to preserve MANDATORY_TIMESTAMPS - 1 // timestamps. However this is incorrect because the key that we're // inserting may overwrite one of the timestamped keys. This means that a // key which mandatory cost had assumed was safe to garbage collect won't // be which allows us to get into a situation where is_full returns false // but when we call prepare_space_for_new_entry we fail with an insertion // because it doesn't actually fit. int size = mandatory_cost(sizer, node, MANDATORY_TIMESTAMPS); // Add the space we'll need for the new key/value pair we would // insert. We conservatively assume the key is not already // contained in the node. size += sizeof(uint16_t) + sizeof(repli_timestamp_t) + key->full_size() + sizer->size(value); // The node is full if we can't fit all that data within the free space. return size > free_space(sizer); } bool is_underfull(value_sizer_t *sizer, const leaf_node_t *node) { // An underfull node is one whose mandatory fields' cost // constitutes significantly less than half the free space, where // "significantly" is enough to prevent a split-then-merge. // (Note that x / y is indeed taken to mean floor(x / y) below.) // A split node's size S is always within leaf_epsilon of // free_space and then is split as evenly as possible. This means // the two resultant nodes' sizes are both no less than S / 2 - // leaf_epsilon / 2, which is no less than (free_space - // leaf_epsilon) / 2 - leaf_epsilon / 2. Which is no less than is // free_space / 2 - leaf_epsilon. We don't want an immediately // split node to be underfull, hence the threshold used below. return mandatory_cost(sizer, node, MANDATORY_TIMESTAMPS) < free_space(sizer) / 2 - leaf_epsilon(sizer); } // Compares indices by looking at values in another array. class indirect_index_comparator_t { public: explicit indirect_index_comparator_t(const uint16_t *array) : array_(array) { } bool operator()(uint16_t x, uint16_t y) { return array_[x] < array_[y]; } private: const uint16_t *array_; }; void garbage_collect( value_sizer_t *sizer, leaf_node_t *node, int num_tstamped, int *preserved_index, boost::optional<int> tstamp_cutoff_upper_bound = boost::optional<int>()) { scoped_array_t<uint16_t> indices(node->num_pairs); for (int i = 0; i < node->num_pairs; ++i) { indices[i] = i; } std::sort(indices.data(), indices.data() + node->num_pairs, indirect_index_comparator_t(node->pair_offsets)); int mand_offset; UNUSED int cost = mandatory_cost(sizer, node, num_tstamped, &mand_offset); if (tstamp_cutoff_upper_bound) { /* If we have an upper bound for the timestamp cutoff point, make sure that we cut off at least that many timestamps. */ mand_offset = std::min(*tstamp_cutoff_upper_bound, mand_offset); } int w = sizer->block_size().value(); int i = node->num_pairs - 1; for (; i >= 0; --i) { int offset = node->pair_offsets[indices[i]]; if (offset < mand_offset) { break; } entry_t *ent = get_entry(node, offset); if (entry_is_live(ent)) { int sz = entry_size(sizer, ent); w -= sz; memmove(get_at_offset(node, w), ent, sz); node->pair_offsets[indices[i]] = w; } else { node->pair_offsets[indices[i]] = 0; } } // Either i < 0 or node->pair_offsets[indices[i]] < mand_offset. node->tstamp_cutpoint = w; for (; i >= 0; --i) { int offset = node->pair_offsets[indices[i]]; entry_t *ent = get_entry(node, offset); rassert(!entry_is_skip(ent)); // Preserve the timestamp. int sz = sizeof(repli_timestamp_t) + entry_size(sizer, ent); w -= sz; memmove(get_at_offset(node, w), get_at_offset(node, offset), sz); node->pair_offsets[indices[i]] = w; } node->frontmost = w; // Now squash dead indices. int j = 0, k = 0; for (; k < node->num_pairs; ++k) { if (*preserved_index == k) { *preserved_index = j; } if (node->pair_offsets[k] != 0) { node->pair_offsets[j] = node->pair_offsets[k]; j += 1; } } if (*preserved_index == node->num_pairs) { *preserved_index = j; } node->num_pairs = j; validate(sizer, node); } void garbage_collect(value_sizer_t *sizer, leaf_node_t *node, int num_tstamped) { int ignore = 0; garbage_collect(sizer, node, num_tstamped, &ignore); rassert(ignore == 0); } void clean_entry(void *p, int sz) { rassert(sz > 0); uint8_t *q = reinterpret_cast<uint8_t *>(p); if (sz == 1) { q[0] = SKIP_ENTRY_CODE_ONE; } else if (sz == 2) { q[0] = SKIP_ENTRY_CODE_TWO; q[1] = SKIP_ENTRY_RESERVED; } else if (sz > 2) { q[0] = SKIP_ENTRY_CODE_MANY; rassert(sz < 65536); *reinterpret_cast<uint16_t *>(q + 1) = sz - 3; // Some memset implementations are broken for nonzero values. for (int i = 3; i < sz; ++i) { q[i] = SKIP_ENTRY_RESERVED; } } } // Moves entries with pair_offsets indices in the clopen range [beg, // end) from fro to tow. void move_elements(value_sizer_t *sizer, leaf_node_t *fro, int beg, int end, int wpoint, leaf_node_t *tow, int fro_copysize, int fro_mand_offset, std::vector<const void *> *moved_values_out) { rassert(is_underfull(sizer, tow)); rassert(end >= beg); // This assertion is a bit loose. rassert(fro_copysize + mandatory_cost(sizer, tow, MANDATORY_TIMESTAMPS) <= free_space(sizer)); // Make tow have a nice big region we can copy entries to. Also, // this means we have no "skip" entries in tow. garbage_collect(sizer, tow, MANDATORY_TIMESTAMPS, &wpoint); // Now resize and move tow's pair_offsets. memmove(tow->pair_offsets + wpoint + (end - beg), tow->pair_offsets + wpoint, sizeof(uint16_t) * (tow->num_pairs - wpoint)); tow->num_pairs += end - beg; // pos a // Now we're going to do something crazy. Fill the new hole in // the pair offsets with the numbers in [0, end - beg). for (int i = 0; i < end - beg; ++i) { tow->pair_offsets[wpoint + i] = i; } // We treat these numbers as indices into [beg, end) in fro, and // sort them so that we can access [beg, end) in order by // increasing offset. std::sort(tow->pair_offsets + wpoint, tow->pair_offsets + wpoint + (end - beg), indirect_index_comparator_t(fro->pair_offsets + beg)); int tow_offset = tow->frontmost; // The offset we read from (indirectly pointing to fro's [beg, // end)) in tow->pair_offsets, and the offset at which we stop. int fro_index = wpoint; int fro_index_end = wpoint + (end - beg); const int new_frontmost = tow->frontmost - fro_copysize; int wri_offset = new_frontmost; int adjustable_tow_offsets[MANDATORY_TIMESTAMPS]; int num_adjustable_tow_offsets = 0; // To detect bugs in the code int actually_copied = 0; // We will gradually compute the live size. int livesize = tow->live_size; for (int i = 0; i < wpoint; ++i) { if (tow->pair_offsets[i] < tow->tstamp_cutpoint) { rassert(num_adjustable_tow_offsets < MANDATORY_TIMESTAMPS); adjustable_tow_offsets[num_adjustable_tow_offsets] = i; ++num_adjustable_tow_offsets; } } for (int i = wpoint + (end - beg); i < tow->num_pairs; ++i) { if (tow->pair_offsets[i] < tow->tstamp_cutpoint) { rassert(num_adjustable_tow_offsets < MANDATORY_TIMESTAMPS); adjustable_tow_offsets[num_adjustable_tow_offsets] = i; ++num_adjustable_tow_offsets; } } int fro_live_size_adjustment = 0; for (;;) { rassert(tow_offset <= tow->tstamp_cutpoint); if (tow_offset == tow->tstamp_cutpoint || fro_index == fro_index_end) { // We have no more timestamped information to push. break; } int fro_offset = fro->pair_offsets[beg + tow->pair_offsets[fro_index]]; if (fro_offset >= fro_mand_offset) { // We have no more timestamped information to push. break; } repli_timestamp_t fro_tstamp = get_timestamp(fro, fro_offset); repli_timestamp_t tow_tstamp = get_timestamp(tow, tow_offset); // Greater timestamps go first. if (tow_tstamp < fro_tstamp) { entry_t *ent = get_entry(fro, fro_offset); int entsz = entry_size(sizer, ent); int sz = sizeof(repli_timestamp_t) + entsz; memmove(get_at_offset(tow, wri_offset), get_at_offset(fro, fro_offset), sz); if (entry_is_live(ent)) { livesize += entsz + sizeof(uint16_t); fro_live_size_adjustment -= entsz + sizeof(uint16_t); } clean_entry(ent, entsz); // Update the pair offset in fro to be the offset in tow // -- we'll never use the old value again and we'll copy // the newer values to tow later. fro->pair_offsets[beg + tow->pair_offsets[fro_index]] = wri_offset; wri_offset += sz; actually_copied += sz; fro_index++; } else { int sz = sizeof(repli_timestamp_t) + entry_size(sizer, get_entry(tow, tow_offset)); memmove(get_at_offset(tow, wri_offset), get_at_offset(tow, tow_offset), sz); // Update the pair offset of the entry we've moved. int i; for (i = 0; i < num_adjustable_tow_offsets; ++i) { int j = adjustable_tow_offsets[i]; if (tow->pair_offsets[j] == tow_offset) { tow->pair_offsets[j] = wri_offset; break; } } // Make sure we updated something. rassert(i != num_adjustable_tow_offsets); wri_offset += sz; tow_offset += sz; } } uint16_t new_tstamp_cutpoint = wri_offset; // Now we have some untimestamped entries to write. for (; fro_index < fro_index_end; ++fro_index) { int fro_offset = fro->pair_offsets[beg + tow->pair_offsets[fro_index]]; entry_t *ent = get_entry(fro, fro_offset); if (entry_is_live(ent)) { int sz = entry_size(sizer, ent); memmove(get_at_offset(tow, wri_offset), ent, sz); clean_entry(ent, sz); fro_live_size_adjustment -= sz + sizeof(uint16_t); fro->pair_offsets[beg + tow->pair_offsets[fro_index]] = wri_offset; wri_offset += sz; livesize += sz + sizeof(uint16_t); actually_copied += sz; rassert(wri_offset <= tow_offset); } else { rassert(entry_is_deletion(ent)); // This is a dead entry. We'll need to squash this dead entry later. fro->pair_offsets[beg + tow->pair_offsets[fro_index]] = 0; int sz = entry_size(sizer, ent); clean_entry(ent, sz); } } guarantee(actually_copied <= fro_copysize); rassert(wri_offset <= tow_offset); // tow may have some timestamped entries that need to become // un-timestamped. while (tow_offset < tow->tstamp_cutpoint) { rassert(wri_offset <= tow_offset); entry_t *ent = get_entry(tow, tow_offset); int sz = entry_size(sizer, ent); if (entry_is_live(ent)) { memmove(get_at_offset(tow, wri_offset), ent, sz); // Update the pair offset of the entry we've moved. int i; for (i = 0; i < num_adjustable_tow_offsets; ++i) { int j = adjustable_tow_offsets[i]; if (tow->pair_offsets[j] == tow_offset) { tow->pair_offsets[j] = wri_offset; break; } } // Make sure we updated something. rassert(i != num_adjustable_tow_offsets); wri_offset += sz; } else { // Update the pair offset of the entry we've deleted, so // that it gets squashed later. int i; for (i = 0; i < num_adjustable_tow_offsets; ++i) { int j = adjustable_tow_offsets[i]; if (tow->pair_offsets[j] == tow_offset) { tow->pair_offsets[j] = 0; } } } tow_offset += sizeof(repli_timestamp_t) + sz; } guarantee(wri_offset <= tow_offset); // If we needed to untimestamp any tow entries, we'll need a skip // entry for the open space. if (wri_offset < tow_offset) { // printf("wri_offset = %d, tow_offset = %d\n", wri_offset, tow_offset); clean_entry(get_at_offset(tow, wri_offset), tow_offset - wri_offset); } // We don't need to do anything else for tow entries because we // did a garbage collection in tow so they are contiguous through // the end of the buffer (and the rest don't have timestamps). // Copy the valid tow offsets from [beg, end) to the wpoint point // in tow, and move fro entries. memcpy(tow->pair_offsets + wpoint, fro->pair_offsets + beg, sizeof(uint16_t) * (end - beg)); memmove(fro->pair_offsets + beg, fro->pair_offsets + end, sizeof(uint16_t) * (fro->num_pairs - end)); fro->num_pairs -= end - beg; tow->frontmost = new_frontmost; tow->live_size = livesize; tow->tstamp_cutpoint = new_tstamp_cutpoint; fro->live_size += fro_live_size_adjustment; if (moved_values_out != nullptr) { // Collect value pointers of the moved values moved_values_out->clear(); moved_values_out->reserve(end - beg); for (int pair_idx = wpoint; pair_idx < wpoint + (end - beg); ++pair_idx) { const int offset = tow->pair_offsets[pair_idx]; // Skip dead entries if (offset != 0) { const entry_t *entry = get_entry(tow, offset); // Skip deletions if (entry_is_live(entry)) { moved_values_out->push_back(entry_value(entry)); } } } } { // Squash dead entries that we copied pair_offsets from fro, // for, and that we removed from tow, as well. int j, k; for (j = 0, k = 0; k < tow->num_pairs; ++k) { if (tow->pair_offsets[k] != 0) { tow->pair_offsets[j] = tow->pair_offsets[k]; j += 1; } } tow->num_pairs = j; } validate(sizer, fro); validate(sizer, tow); } void split(value_sizer_t *sizer, leaf_node_t *node, leaf_node_t *rnode, btree_key_t *median_out) { int tstamp_back_offset; int mandatory = mandatory_cost(sizer, node, MANDATORY_TIMESTAMPS, &tstamp_back_offset); guarantee(mandatory >= free_space(sizer) - leaf_epsilon(sizer)); // We shall split the mandatory cost of this node as evenly as possible. int num_mandatories = 0; int i = node->num_pairs - 1; int prev_rcost = 0; int rcost = 0; while (i >= 0 && rcost < mandatory / 2) { int offset = node->pair_offsets[i]; entry_t *ent = get_entry(node, offset); // We only take mandatory entries' costs into consideration, // which guarantees correct behavior (in that neither node nor // can become underfull after a split). If we didn't do this, // it would be possible to bias one node with a bunch of // deletions that makes its mandatory_cost artificially small. if (entry_is_live(ent)) { prev_rcost = rcost; rcost += entry_size(sizer, ent) + sizeof(uint16_t) + (offset < tstamp_back_offset ? sizeof(repli_timestamp_t) : 0); ++num_mandatories; } else { rassert(entry_is_deletion(ent)); if (offset < tstamp_back_offset) { prev_rcost = rcost; rcost += entry_size(sizer, ent) + sizeof(uint16_t) + sizeof(repli_timestamp_t); ++num_mandatories; } } --i; } // Since the mandatory_cost is at least free_space - leaf_epsilon there's no way i can equal num_pairs or zero. guarantee(i < node->num_pairs); guarantee(i > 0); // Now prev_rcost and rcost envelope mandatory / 2. guarantee(prev_rcost < mandatory / 2); guarantee(rcost >= mandatory / 2, "rcost = %d, mandatory / 2 = %d, i = %d", rcost, mandatory / 2, i); int s; int end_rcost; if ((mandatory - prev_rcost) - prev_rcost < rcost - (mandatory - rcost)) { end_rcost = prev_rcost; s = i + 2; --num_mandatories; } else { end_rcost = rcost; s = i + 1; } // If our math was right, neither node can be underfull just // considering the split of the mandatory costs. guarantee(end_rcost >= free_space(sizer) / 2 - leaf_epsilon(sizer)); guarantee(mandatory - end_rcost >= free_space(sizer) / 2 - leaf_epsilon(sizer)); // Now we wish to move the elements at indices [s, num_pairs) to rnode. init(sizer, rnode); int node_copysize = end_rcost - num_mandatories * sizeof(uint16_t); move_elements(sizer, node, s, node->num_pairs, 0, rnode, node_copysize, tstamp_back_offset, nullptr); keycpy(median_out, entry_key(get_entry(node, node->pair_offsets[s - 1]))); } void merge(value_sizer_t *sizer, leaf_node_t *left, leaf_node_t *right) { rassert(left != right); rassert(is_underfull(sizer, left)); rassert(is_underfull(sizer, right)); int tstamp_back_offset; int mandatory = mandatory_cost(sizer, left, MANDATORY_TIMESTAMPS, &tstamp_back_offset); int left_copysize = mandatory; // Uncount the uint16_t cost of mandatory entries. Sigh. // This includes deletion entries *before* the `tstamp_back_offset`, as well // as all non-deletion entries. for (int i = 0; i < left->num_pairs; ++i) { if (left->pair_offsets[i] < tstamp_back_offset || !entry_is_deletion(get_entry(left, left->pair_offsets[i]))) { left_copysize -= sizeof(uint16_t); } } move_elements(sizer, left, 0, left->num_pairs, 0, right, left_copysize, tstamp_back_offset, nullptr); } // We move keys out of sibling and into node. bool level(value_sizer_t *sizer, int nodecmp_node_with_sib, leaf_node_t *node, leaf_node_t *sibling, btree_key_t *replacement_key_out, std::vector<const void *> *moved_values_out) { rassert(node != sibling); // If sibling were underfull, we'd just merge the nodes. rassert(is_underfull(sizer, node)); rassert(!is_underfull(sizer, sibling)); // First figure out the inclusive range [beg, end] of elements we want to move // from sibling. int beg, end, *w, wstep; int node_weight = mandatory_cost(sizer, node, MANDATORY_TIMESTAMPS); int tstamp_back_offset; int sibling_weight = mandatory_cost(sizer, sibling, MANDATORY_TIMESTAMPS, &tstamp_back_offset); guarantee(node_weight < sibling_weight); if (nodecmp_node_with_sib < 0) { // node is to the left of sibling, so we want to move elements // [0, k) from sibling. beg = 0; end = 0; w = &end; wstep = 1; } else { // node is to the right of sibling, so we want to move // elements [num_pairs - k, num_pairs) from sibling. beg = sibling->num_pairs - 1; end = sibling->num_pairs - 1; w = &beg; wstep = -1; } guarantee(end - beg != sibling->num_pairs - 1); int prev_weight_movement = 0; int weight_movement = 0; int num_mandatories = 0; int prev_diff = sizer->block_size().value(); // some impossibly large value for (;;) { int offset = sibling->pair_offsets[*w]; entry_t *ent = get_entry(sibling, offset); // We only take mandatory entries' costs into consideration. if (entry_is_live(ent)) { int sz = entry_size(sizer, ent) + sizeof(uint16_t) + (offset < tstamp_back_offset ? sizeof(repli_timestamp_t) : 0); prev_diff = sibling_weight - node_weight; prev_weight_movement = weight_movement; weight_movement += sz; node_weight += sz; sibling_weight -= sz; ++num_mandatories; } else { rassert(entry_is_deletion(ent)); if (offset < tstamp_back_offset) { int sz = entry_size(sizer, ent) + sizeof(uint16_t) + sizeof(repli_timestamp_t); prev_diff = sibling_weight - node_weight; prev_weight_movement = weight_movement; weight_movement += sz; node_weight += sz; sibling_weight -= sz; ++num_mandatories; } } if (end - beg == sibling->num_pairs - 1 || node_weight >= sibling_weight) { break; } *w += wstep; } guarantee(end - beg < sibling->num_pairs - 1); if (prev_diff <= sibling_weight - node_weight) { *w -= wstep; --num_mandatories; weight_movement = prev_weight_movement; } if (end < beg) { // Alas, there is no actual leveling to do. guarantee(end + 1 == beg); return false; } int sib_copysize = weight_movement - num_mandatories * sizeof(uint16_t); move_elements(sizer, sibling, beg, end + 1, nodecmp_node_with_sib < 0 ? node->num_pairs : 0, node, sib_copysize, tstamp_back_offset, moved_values_out); guarantee(node->num_pairs > 0); guarantee(sibling->num_pairs > 0); if (nodecmp_node_with_sib < 0) { keycpy(replacement_key_out, entry_key(get_entry(node, node->pair_offsets[node->num_pairs - 1]))); } else { keycpy(replacement_key_out, entry_key(get_entry(sibling, sibling->pair_offsets[sibling->num_pairs - 1]))); } return true; } bool is_mergable(value_sizer_t *sizer, const leaf_node_t *node, const leaf_node_t *sibling) { return is_underfull(sizer, node) && is_underfull(sizer, sibling); } // Sets *index_out to the index for the live entry or deletion entry // for the key, or to the index the key would have if it were // inserted. Returns true if the key at said index is actually equal. bool find_key(const leaf_node_t *node, const btree_key_t *key, int *index_out) { int beg = 0; int end = node->num_pairs; // beg == 0 or key > *(beg - 1). // end == num_pairs or key < *end. while (beg < end) { // when (end - beg) > 0, (end - beg) / 2 is always less than (end - beg). So beg <= test_point < end. int test_point = beg + (end - beg) / 2; const btree_key_t *ek = entry_key(get_entry(node, node->pair_offsets[test_point])); int res = btree_key_cmp(key, ek); if (res < 0) { // key < *test_point. end = test_point; } else if (res > 0) { // key > *test_point. Since test_point < end, we have test_point + 1 <= end. beg = test_point + 1; } else { // We found the key! *index_out = test_point; return true; } } // (Since beg == end, then *(beg - 1) < key < *beg (with appropriate // provisions for beg == 0 or beg == num_pairs) and index_out // should be set to beg, and false should be returned. *index_out = beg; return false; } bool lookup(value_sizer_t *sizer, const leaf_node_t *node, const btree_key_t *key, void *value_out) { int index; if (find_key(node, key, &index)) { const entry_t *ent = get_entry(node, node->pair_offsets[index]); if (entry_is_live(ent)) { const void *val = entry_value(ent); memcpy(value_out, val, sizer->size(val)); return true; } } return false; } /* `insert()` and `remove()` call this to insert a new entry into the leaf node. First it removes any existing entry for `key`; then it makes room in the leaf node for a new entry and fills `*space_out` with a pointer to the beginning of where the new entry should go. `prepare_space_for_new_entry()` takes care of updating `pair_offsets` and `num_pairs`, moving around other entries as needed to maintain timestamp ordering, putting a timestamp on the new entry if appropriate, and maintaining `frontmost` and `tstamp_cutpoint`. The caller is responsible for writing the actual entry itself (including the key) and for updating `live_size` if the newly created entry is live. `new_entry_size` is the total size of the new entry, including key, value, and/or code byte, but not including repli timestamp. It is an error to put a deletion entry after `tstamp_cutpoint`. If the caller intends to insert a deletion entry, it should pass `false` for `allow_after_tstamp_cutpoint`. If the entry would go after `tstamp_cutpoint` and `allow_after_tstamp_cutpoint` is false, then instead of making room for the entry, `prepare_space_for_new_entry()` will return false. It will still remove any preexisting entry that was in the leaf node. If the entry would go before `tstamp_cutpoint` or `allow_after_tstamp_cutpoint` is true, then the return value will be true. */ MUST_USE bool prepare_space_for_new_entry( value_sizer_t *sizer, leaf_node_t *node, const btree_key_t *key, int new_entry_size, repli_timestamp_t tstamp, /* Used to derive the highest possible timestamp that non-timestamped entries might have. Usually the recency of the buf_t that node is in. */ repli_timestamp_t maximum_existing_tstamp, bool allow_after_tstamp_cutpoint, char **space_out) { /* Get an upper bound for the timestamp cutoff point in case we later call `garbage_collect()`. We want to make sure that garbage collection cleans up *at least* as much space as it would clean up now. This is crucial, because our caller (in particular `insert()`) might have used `is_full()` in order to check that the leaf node has enough space for a given entry. If the key already exists, we are going to call `clear_entry()` on it below, before we call `garbage_collect()`. However this can have the unwanted side effect that `mandatory_cost` in `garbage_collect()` no longer exceeds the `max_deletions_cost`, or exceeds it only at a later offset (this is true in particular if the existing entry is a deletion entry). As a consequence of that, `garbage_collect()` might clean up slightly less space than was originally assumed. We avoid this problem by getting the cutoff point now, and having `garbage_collect()` pick the lower of the two. */ int gc_tstamp_cutoff_upper_bound; mandatory_cost(sizer, node, MANDATORY_TIMESTAMPS - 1, &gc_tstamp_cutoff_upper_bound); /* Figure out where in `pair_offsets` to put the offset of the new entry, and simultaneously check for an existing entry for this key. If the entry already exists, clean it. */ int index; bool found = find_key(node, key, &index); if (found) { int offset = node->pair_offsets[index]; entry_t *ent = get_entry(node, offset); int sz = entry_size(sizer, ent); if (entry_is_live(ent)) { node->live_size -= sizeof(uint16_t) + sz; } clean_entry(ent, sz); /* We'll re-use the now open slot in `pair_offsets`. If it turns out that we aren't actually creating a new entry, like if we're deleting a key which has no timestamp, then we'll close up this space in `pair_offsets` later. */ } else { /* Later, once we've confirmed that we actually want to create an entry in the leaf node, we'll open up some space in `pair_offsets`. */ } /* Garbage collect if appropriate. We do it after cleaning up any existing entry so that adding a deletion entry *almost* always works no matter how full the node is. If the existing entry is smaller than the new deletion entry that we're trying to add, we might not have enough space for it even after garbage collection. This can happen if the previous entry didn't have a timestamp and had a very small value size (in practice this should be really rare). We check for this condition further down, and recover from it by dropping all existing timestamps and discarding the delete entry by returning `false`. */ if (offsetof(leaf_node_t, pair_offsets) + sizeof(uint16_t) * (node->num_pairs + (found ? 0 : 1)) + sizeof(repli_timestamp_t) + new_entry_size > node->frontmost) { if (found) { /* We can't re-use an existing index if we're garbage collecting. */ found = false; memmove( node->pair_offsets + index, node->pair_offsets + index + 1, sizeof(uint16_t) * (node->num_pairs - index - 1)); --node->num_pairs; } /* Passing `&index` as a parameter to `garbage_collect()` guarantees that it will remain valid even as `pair_offsets` entries are moved around. */ garbage_collect(sizer, node, MANDATORY_TIMESTAMPS - 1, &index, boost::make_optional(gc_tstamp_cutoff_upper_bound)); /* Make sure that `index` still refers to where the new key should be inserted. */ DEBUG_VAR int index2; rassert(!find_key(node, key, &index2)); rassert(index == index2, "garbage_collect() failed to preserve index"); } /* Compute where in the node to put the new entry */ uint16_t end_of_where_new_entry_should_go; bool new_entry_should_have_timestamp; if (node->frontmost == sizer->block_size().value() || (node->frontmost < node->tstamp_cutpoint && get_timestamp(node, node->frontmost) <= tstamp)) { /* In the most common case, the new value will go right at `node->frontmost` and will get a timestamp. For performance reasons, we check for this case specially and short-circuit. If a cosmic ray were to strike the computer and make us take the second branch of this `if` when we should have taken the first branch, the result should be the same. */ end_of_where_new_entry_should_go = node->frontmost; new_entry_should_have_timestamp = true; } else { entry_iter_t iter = entry_iter_t::make(node); while (!iter.done(sizer) && iter.offset < node->tstamp_cutpoint && get_timestamp(node, iter.offset) > tstamp) { iter.step(sizer, node); } end_of_where_new_entry_should_go = iter.offset; if (end_of_where_new_entry_should_go == node->tstamp_cutpoint && node->tstamp_cutpoint != sizer->block_size().value()) { /* We are after all of the timestamped entries, but before at least one non-timestamped entry. We know that the non-timestamped entries have a timestamp of at most maximum_existing_tstamp. If our own timestamp is higher than that, we can put a timestamp on ourself. Otherwise, we don't know what the timestamp would have been on the non-timestamped entry, so we mustn't put a timestamp on ourself. */ new_entry_should_have_timestamp = tstamp > maximum_existing_tstamp; } else { new_entry_should_have_timestamp = true; } } /* If a deletion would go after `tstamp_cutpoint`, instead we want to just discard it entirely (deletions have `allow_after_tstamp_cutpoint == false`). */ bool actually_create_entry = new_entry_should_have_timestamp || allow_after_tstamp_cutpoint; /* As mentioned above, it can theoretically happen that we're trying to replace an entry by a deletion entry and we don't have enough space to write the deletion entry. We check for this here, and shift the timestamp cutoff point in order to maintain correctness. This will be very rare in practice, since values are usually larger than deletion entries. */ bool drop_timestamps = false; if (actually_create_entry && !allow_after_tstamp_cutpoint && offsetof(leaf_node_t, pair_offsets) + sizeof(uint16_t) * (node->num_pairs + (found ? 0 : 1)) + new_entry_size + sizeof(repli_timestamp_t) > node->frontmost) { actually_create_entry = false; drop_timestamps = true; } if (!actually_create_entry) { if (found) { /* We're deleting the previous entry for this key, but not inserting a new one; close the gap in `pair_offsets`. `index` is the location of the open slot. */ memmove( node->pair_offsets + index, node->pair_offsets + index + 1, sizeof(uint16_t) * (node->num_pairs - index - 1)); --node->num_pairs; } if (drop_timestamps) { erase_deletions(sizer, node, boost::optional<repli_timestamp_t>()); } return false; } /* There was no previous entry for this key, but we're creating a new entry; make some room in `pair_offsets`. `index` is where the open slot should go. We didn't do this before because we weren't sure if we were actually gonna create a new entry or not. */ if (!found) { memmove( node->pair_offsets + index + 1, node->pair_offsets + index, sizeof(uint16_t) * (node->num_pairs - index)); ++node->num_pairs; } /* Now that we know where in the leaf node to write our entry, make space if necessary. */ int total_space_for_new_entry = new_entry_size + (new_entry_should_have_timestamp ? sizeof(repli_timestamp_t) : 0); if (end_of_where_new_entry_should_go == node->frontmost) { /* This is the common case. Just like before, we check for this case specially and short-circuit, even though the algorithm in the `else` branch is a no-op if `end_of_where_new_entry_should_go` is `node->frontmost`. */ } else { /* Move the entries themselves */ memmove( get_at_offset(node, node->frontmost - total_space_for_new_entry), get_at_offset(node, node->frontmost), end_of_where_new_entry_should_go - node->frontmost); /* Update the `pair_offsets` table so it points to the new locations of the entries */ for (int i = 0; i < node->num_pairs; ++i) { if (i == index) continue; if (node->pair_offsets[i] < end_of_where_new_entry_should_go) { node->pair_offsets[i] -= total_space_for_new_entry; } } } node->frontmost -= total_space_for_new_entry; guarantee(offsetof(leaf_node_t, pair_offsets) + sizeof(uint16_t) * node->num_pairs <= node->frontmost); /* Write the timestamp if we need one, and update `node->tstamp_cutpoint` if we don't. */ uint16_t start_of_where_new_entry_should_go = end_of_where_new_entry_should_go - total_space_for_new_entry; if (new_entry_should_have_timestamp) { *reinterpret_cast<repli_timestamp_t *>(get_at_offset(node, start_of_where_new_entry_should_go)) = tstamp; } else { rassert(end_of_where_new_entry_should_go == node->tstamp_cutpoint); node->tstamp_cutpoint = start_of_where_new_entry_should_go; } /* Record the offset in `pair_offsets` */ node->pair_offsets[index] = start_of_where_new_entry_should_go; /* Fill output variable */ if (new_entry_should_have_timestamp) { *space_out = get_at_offset(node, start_of_where_new_entry_should_go + sizeof(repli_timestamp_t)); } else { *space_out = get_at_offset(node, start_of_where_new_entry_should_go); } guarantee(end_of_where_new_entry_should_go <= sizer->block_size().value()); return true; } // Inserts a key/value pair into the node. Hopefully you've already // cleaned up the old value, if there is one. void insert( value_sizer_t *sizer, leaf_node_t *node, const btree_key_t *key, const void *value, repli_timestamp_t tstamp, repli_timestamp_t maximum_existing_tstamp, UNUSED key_modification_proof_t km_proof) { rassert(!is_full(sizer, node, key, value)); /* Make space for the entry itself */ char *location_to_write_data; bool should_write = prepare_space_for_new_entry(sizer, node, key, key->full_size() + sizer->size(value), tstamp, maximum_existing_tstamp, true, &location_to_write_data); guarantee(should_write); /* Now copy the data into the node itself */ memcpy(location_to_write_data, key, key->full_size()); location_to_write_data += key->full_size(); memcpy(location_to_write_data, value, sizer->size(value)); node->live_size += sizeof(uint16_t) + key->full_size() + sizer->size(value); validate(sizer, node); } void remove( value_sizer_t *sizer, leaf_node_t *node, const btree_key_t *key, repli_timestamp_t tstamp, repli_timestamp_t maximum_existing_tstamp, UNUSED key_modification_proof_t km_proof) { /* If the deletion entry would fall after `tstamp_cutpoint`, then it shouldn't be written at all. If that's the case, then `prepare_space_for_new_entry()` will return false because we pass false for `allow_after_tstamp_cutpoint`. */ char *location_to_write_data; if (prepare_space_for_new_entry(sizer, node, key, 1 + key->full_size(), /* 1 for `DELETE_ENTRY_CODE` */ tstamp, maximum_existing_tstamp, false, &location_to_write_data)) { *location_to_write_data = static_cast<char>(DELETE_ENTRY_CODE); ++location_to_write_data; memcpy(location_to_write_data, key, key->full_size()); } validate(sizer, node); } // Erases the entry for the given key, leaving behind no trace. void erase_presence(value_sizer_t *sizer, leaf_node_t *node, const btree_key_t *key, UNUSED key_modification_proof_t km_proof) { int index; bool found = find_key(node, key, &index); if (found) { int offset = node->pair_offsets[index]; entry_t *ent = get_entry(node, offset); int sz = entry_size(sizer, ent); if (entry_is_live(ent)) { node->live_size -= sizeof(uint16_t) + sz; } clean_entry(ent, sz); memmove(node->pair_offsets + index, node->pair_offsets + index + 1, (node->num_pairs - (index + 1)) * sizeof(uint16_t)); node->num_pairs -= 1; } validate(sizer, node); } repli_timestamp_t min_deletion_timestamp( value_sizer_t *sizer, const leaf_node_t *node, repli_timestamp_t maximum_existing_timestamp) { repli_timestamp_t earliest_so_far = maximum_existing_timestamp; entry_iter_t iter = entry_iter_t::make(node); while (!iter.done(sizer) && iter.offset < node->tstamp_cutpoint) { repli_timestamp_t tstamp = get_timestamp(node, iter.offset); rassert(earliest_so_far >= tstamp, "asserted earliest_so_far (%" PRIu64 ") >= tstamp (%" PRIu64 ")", earliest_so_far.longtime, tstamp.longtime); earliest_so_far = tstamp; iter.step(sizer, node); } /* It's possible for us to forget a deletion with timestamp equal to the oldest timestamped entry, so the min deletion timestamp is one time unit newer than the oldest timestamped entry. */ return earliest_so_far.next(); } void erase_deletions( value_sizer_t *sizer, leaf_node_t *node, boost::optional<repli_timestamp_t> min_del_timestamp) { int old_tstamp_cutpoint = node->tstamp_cutpoint; entry_iter_t iter = entry_iter_t::make(node); if (min_del_timestamp) { /* Advance `iter` to the first entry with a timestamp that's lower than `min_del_timestamp - 1`. */ while (true) { if (iter.done(sizer) || iter.offset >= old_tstamp_cutpoint) { return; } if (get_timestamp(node, iter.offset).next() < *min_del_timestamp) { break; } iter.step(sizer, node); } } /* We'll remove timestamps from all of the entries between `old_tstamp_cutpoint` and `new_tstamp_cutpoint`. But we won't update `leaf->tstamp_cutpoint` until the end of the function because we want `iter` to continue iterating according to the old value. */ int new_tstamp_cutpoint = iter.offset; /* Step until we reach `old_tstamp_cutpoint`, erasing timestamps and deletions as we go. Make a note of each deletion's offset so we can remove them from the `pair_offsets` array later. */ std::set<int> deletion_offsets; while (!iter.done(sizer) && iter.offset != old_tstamp_cutpoint) { int off = iter.offset; guarantee(off >= new_tstamp_cutpoint && off < old_tstamp_cutpoint); const entry_t *ent = get_entry(node, off); /* Move `iter` before we modify `ent`, to avoid confusion */ iter.step(sizer, node); if (entry_is_deletion(ent)) { clean_entry( get_at_offset(node, off), sizeof(repli_timestamp_t) + entry_size(sizer, ent)); deletion_offsets.insert(off); } else { /* This is the code path for both skip entries and live entries, because skip entries have timestamps too. */ clean_entry(get_at_offset(node, off), sizeof(repli_timestamp_t)); } } /* If a pointer in `pair_offsets` was pointing to a timestamp that's been erased on a key-value pair, we need to move it forward by `sizeof(repli_timestamp_t)`. If it was pointing to a deletion entry that's been erased, we need to remove that entry from `pair_offsets`. */ int src = 0, dst = 0; int num_deleted = deletion_offsets.size(); for (; src < node->num_pairs; ++src) { uint16_t off = node->pair_offsets[src]; auto it = deletion_offsets.find(off); if (it == deletion_offsets.end()) { if (off >= new_tstamp_cutpoint && off < old_tstamp_cutpoint) { off += sizeof(repli_timestamp_t); } node->pair_offsets[dst++] = off; } else { guarantee(off >= new_tstamp_cutpoint && off < old_tstamp_cutpoint); deletion_offsets.erase(it); } } guarantee(deletion_offsets.empty()); node->num_pairs -= num_deleted; /* Finally, update `node->tstamp_cutpoint` */ node->tstamp_cutpoint = new_tstamp_cutpoint; } /* Calls `cb` on every entry in the node, whether a real entry or a deletion. The calls will be in order from most recent to least recent. For entries with no timestamp, the callback will get `min_deletion_timestamp() - 1`. */ continue_bool_t visit_entries( value_sizer_t *sizer, const leaf_node_t *node, repli_timestamp_t maximum_existing_timestamp, const std::function<continue_bool_t( const btree_key_t *key, repli_timestamp_t timestamp, const void *value /* null for deletion */ )> &cb) { repli_timestamp_t earliest_so_far = maximum_existing_timestamp; for (entry_iter_t iter = entry_iter_t::make(node); !iter.done(sizer); iter.step(sizer, node)) { repli_timestamp_t tstamp; if (iter.offset < node->tstamp_cutpoint) { tstamp = get_timestamp(node, iter.offset); } else { tstamp = earliest_so_far; } earliest_so_far = tstamp; const entry_t *ent = get_entry(node, iter.offset); if (entry_is_skip(ent)) { continue; } if (continue_bool_t::ABORT == cb(entry_key(ent), tstamp, entry_value(ent))) { return continue_bool_t::ABORT; } } return continue_bool_t::CONTINUE; } iterator::iterator() : node_(nullptr), index_(-1) { } iterator::iterator(const leaf_node_t *node, int index) : node_(node), index_(index) { } std::pair<const btree_key_t *, const void *> iterator::operator*() const { guarantee(index_ < static_cast<int>(node_->num_pairs)); guarantee(index_ >= 0); const entry_t *entree = get_entry(node_, node_->pair_offsets[index_]); return std::make_pair(entry_key(entree), entry_value(entree)); } iterator &iterator::operator++() { guarantee(index_ < static_cast<int>(node_->num_pairs), "Trying to increment past the end of an iterator."); do { ++index_; } while (index_ < node_->num_pairs && !entry_is_live(get_entry(node_, node_->pair_offsets[index_]))); return *this; } iterator &iterator::operator--() { guarantee(index_ > -1, "Trying to decrement past the beginning of an iterator."); do { --index_; } while (index_ >= 0 && !entry_is_live(get_entry(node_, node_->pair_offsets[index_]))); return *this; } bool iterator::operator==(const iterator &other) const { return cmp(other) == 0; } bool iterator::operator!=(const iterator &other) const { return cmp(other) != 0; } bool iterator::operator<(const iterator &other) const { return cmp(other) < 0; } bool iterator::operator>(const iterator &other) const { return cmp(other) > 0; } bool iterator::operator<=(const iterator &other) const { return cmp(other) <= 0; } bool iterator::operator>=(const iterator &other) const { return cmp(other) >= 0; } int iterator::cmp(const iterator &other) const { guarantee(node_ == other.node_); return index_ - other.index_; } reverse_iterator::reverse_iterator() { } reverse_iterator::reverse_iterator(const leaf_node_t *node, int index) : inner_(node, index) { } std::pair<const btree_key_t *, const void *> reverse_iterator::operator*() const { return *inner_; } reverse_iterator &reverse_iterator::operator++() { --inner_; return *this; } reverse_iterator &reverse_iterator::operator--() { ++inner_; return *this; } bool reverse_iterator::operator==(const reverse_iterator &other) const { return inner_ == other.inner_; } bool reverse_iterator::operator!=(const reverse_iterator &other) const { return inner_ != other.inner_; } bool reverse_iterator::operator<(const reverse_iterator &other) const { return inner_ > other.inner_; } bool reverse_iterator::operator>(const reverse_iterator &other) const { return inner_ < other.inner_; } bool reverse_iterator::operator<=(const reverse_iterator &other) const { return inner_ >= other.inner_; } bool reverse_iterator::operator>=(const reverse_iterator &other) const { return inner_ <= other.inner_; } leaf_node_t::iterator begin(const leaf_node_t &leaf_node) { return ++leaf_node_t::iterator(&leaf_node, -1); } leaf_node_t::iterator end(const leaf_node_t &leaf_node) { return leaf_node_t::iterator(&leaf_node, leaf_node.num_pairs); } leaf_node_t::reverse_iterator rbegin(const leaf_node_t &leaf_node) { return ++leaf_node_t::reverse_iterator(&leaf_node, leaf_node.num_pairs); } leaf_node_t::reverse_iterator rend(const leaf_node_t &leaf_node) { return leaf_node_t::reverse_iterator(&leaf_node, -1); } leaf::iterator inclusive_lower_bound(const btree_key_t *key, const leaf_node_t &leaf_node) { int index; leaf::find_key(&leaf_node, key, &index); if (index == leaf_node.num_pairs || entry_is_live(leaf::get_entry(&leaf_node, leaf_node.pair_offsets[index]))) { return leaf_node_t::iterator(&leaf_node, index); } else { return ++leaf_node_t::iterator(&leaf_node, index); } } leaf::reverse_iterator exclusive_upper_bound(const btree_key_t *key, const leaf_node_t &leaf_node) { int index; leaf::find_key(&leaf_node, key, &index); if (index < leaf_node.num_pairs) { const leaf::entry_t *entry = leaf::get_entry(&leaf_node, leaf_node.pair_offsets[index]); const btree_key_t *ekey = leaf::entry_key(entry); if (entry_is_live(entry) && btree_key_cmp(ekey, key) == 0) { // We have to skip this entry to make the iterator exclusive, // hence the ++. return ++leaf_node_t::reverse_iterator(&leaf_node, index); } } return ++leaf_node_t::reverse_iterator(&leaf_node, index); } } // namespace leaf
37.778446
205
0.6302
[ "vector" ]
048f69021b8b70ec268a1973e5ce00e9c3de2ab0
24,341
cpp
C++
Source/EMsoftWorkbench/Workbench/Modules/PatternDisplayModule/PatternDisplayController.cpp
josephtessmer/EMsoft
b6f73c76c52ff7bfa432119b91d3981c8e97fd11
[ "Intel", "Unlicense", "MIT-CMU", "BSD-3-Clause" ]
37
2019-02-11T15:39:55.000Z
2022-03-15T10:37:23.000Z
Source/EMsoftWorkbench/Workbench/Modules/PatternDisplayModule/PatternDisplayController.cpp
hhoward22/EMsoft
97daa26978c42d5f569f4588a9991393c157d509
[ "Intel", "BSD-3-Clause", "MIT-CMU", "Unlicense" ]
83
2018-08-30T10:30:30.000Z
2022-03-31T09:27:33.000Z
Source/EMsoftWorkbench/Workbench/Modules/PatternDisplayModule/PatternDisplayController.cpp
hhoward22/EMsoft
97daa26978c42d5f569f4588a9991393c157d509
[ "Intel", "BSD-3-Clause", "MIT-CMU", "Unlicense" ]
71
2018-08-21T14:19:22.000Z
2022-03-30T19:50:54.000Z
/* ============================================================================ * Copyright (c) 2009-2017 BlueQuartz Software, LLC * * 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 BlueQuartz Software, the US Air Force, 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 HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE * USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The code contained herein was partially funded by the followig contracts: * United States Air Force Prime Contract FA8650-07-D-5800 * United States Air Force Prime Contract FA8650-10-D-5210 * United States Prime Contract Navy N00173-07-C-2068 * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ #include "PatternDisplayController.h" #include <initializer_list> #include <QtConcurrent> #include <QtCore/QFileInfo> #include "Common/ImageGenerator.hpp" #include "Common/PatternTools.h" #include "Common/ProjectionConversions.hpp" #include "Modules/PatternDisplayModule/PatternListModel.h" // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- PatternDisplayController::PatternDisplayController(QObject* parent) : QObject(parent) , m_Observer(nullptr) , m_NumOfFinishedPatternsLock(1) , m_CurrentOrderLock(1) , m_MasterLPNHImageGenLock(1) , m_MasterLPSHImageGenLock(1) , m_MasterCircleImageGenLock(1) , m_MasterStereoImageGenLock(1) , m_MCSquareImageGenLock(1) , m_MCCircleImageGenLock(1) , m_MCStereoImageGenLock(1) { // Connection to allow the pattern list to redraw itself PatternListModel* model = PatternListModel::Instance(); connect(this, SIGNAL(rowDataChanged(QModelIndex,QModelIndex)), model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), Qt::QueuedConnection); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- PatternDisplayController::~PatternDisplayController() = default; // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::setMasterFilePath(const QString& masterFilePath) { m_MasterFilePath = masterFilePath; QFileInfo fi(masterFilePath); emit stdOutputMessageGenerated("Full Path: " + masterFilePath); emit stdOutputMessageGenerated("Path: " + fi.path()); emit stdOutputMessageGenerated("Data File: " + fi.fileName()); emit stdOutputMessageGenerated("Suffix: " + fi.completeSuffix() + "\n"); MasterPatternFileReader reader(masterFilePath, m_Observer); m_MP_Data = reader.readMasterPatternData(); if(m_MP_Data.ekevs.empty()) { return; } emit minMaxEnergyLevelsChanged(m_MP_Data.ekevs); createMasterPatternImageGenerators(); createMonteCarloImageGenerators(); checkImageGenerationCompletion(); emit mpInitializationFinished(); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::createMasterPatternImageGenerators() { m_MasterLPNHImageGenerators.clear(); m_MasterLPSHImageGenerators.clear(); m_MasterCircleImageGenerators.clear(); m_MasterStereoImageGenerators.clear(); hsize_t mp_zDim = m_MP_Data.mLPNH_dims[1]; size_t currentCount = 1; size_t totalItems = 4; // Read Master Pattern lambert square projection data emit stdOutputMessageGenerated(tr("File generated by program '%1'").arg(m_MP_Data.mpProgramName)); emit stdOutputMessageGenerated(tr("Version Identifier: %1").arg(m_MP_Data.mpVersionId)); emit stdOutputMessageGenerated(tr("Number Of Energy Bins: %1\n").arg(QString::number(m_MP_Data.numMPEnergyBins))); QString mpDimStr = ""; for(size_t i = 0; i < m_MP_Data.mLPNH_dims.size(); i++) { mpDimStr.append(QString::number(m_MP_Data.mLPNH_dims[i])); if(i < m_MP_Data.mLPNH_dims.size() - 1) { mpDimStr.append(" x "); } } emit stdOutputMessageGenerated(tr("Size of mLPNH data array: %1").arg(mpDimStr)); // Create the master pattern northern hemisphere generators m_MasterLPNHImageGenerators.resize(mp_zDim); emit stdOutputMessageGenerated(tr("Reading Master Pattern data sets (%1/%2)...").arg(currentCount).arg(totalItems)); createImageGeneratorTasks<float>(m_MP_Data.masterLPNHData, m_MP_Data.mLPNH_dims[3], m_MP_Data.mLPNH_dims[2], mp_zDim, m_MasterLPNHImageGenerators, m_MasterLPNHImageGenLock); currentCount++; // Create the master pattern southern hemisphere generators m_MasterLPSHImageGenerators.resize(mp_zDim); emit stdOutputMessageGenerated(tr("Reading Master Pattern data sets (%1/%2)...").arg(currentCount).arg(totalItems)); createImageGeneratorTasks<float>(m_MP_Data.masterLPSHData, m_MP_Data.mLPSH_dims[3], m_MP_Data.mLPSH_dims[2], mp_zDim, m_MasterLPSHImageGenerators, m_MasterLPSHImageGenLock); currentCount++; // Convert to Master Pattern Lambert Circle projection data and create generators m_MasterCircleImageGenerators.resize(mp_zDim); emit stdOutputMessageGenerated(tr("Reading Master Pattern data sets (%1/%2)...").arg(currentCount).arg(totalItems)); createProjectionConversionTasks<float, float>(m_MP_Data.masterLPNHData, m_MP_Data.mLPNH_dims[3], m_MP_Data.mLPNH_dims[2], mp_zDim, m_MP_Data.mLPNH_dims[3], 1, ModifiedLambertProjection::Square::NorthSquare, m_MasterCircleImageGenerators, m_MasterCircleImageGenLock); currentCount++; // Create the master pattern stereographic projection generators m_MasterStereoImageGenerators.resize(mp_zDim); emit stdOutputMessageGenerated(tr("Reading Master Pattern data sets (%1/%2)...").arg(currentCount).arg(totalItems)); createImageGeneratorTasks<float>(m_MP_Data.masterSPNHData, m_MP_Data.masterSPNH_dims[2], m_MP_Data.masterSPNH_dims[1], mp_zDim, m_MasterStereoImageGenerators, m_MasterStereoImageGenLock); emit stdOutputMessageGenerated(tr("Reading Master Pattern data sets complete!\n")); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::createMonteCarloImageGenerators() { m_MCSquareImageGenerators.clear(); m_MCCircleImageGenerators.clear(); m_MCStereoImageGenerators.clear(); size_t currentCount = 1; size_t totalItems = 3; size_t mc_zDim = m_MP_Data.monteCarlo_dims[2]; // Read Monte Carlo lambert square projection data emit stdOutputMessageGenerated(tr("File generated by program '%1'").arg(m_MP_Data.mcProgramName)); emit stdOutputMessageGenerated(tr("Version Identifier: %1").arg(m_MP_Data.mcVersionId)); emit stdOutputMessageGenerated(tr("Dehyperslabbing Monte Carlo square data...")); std::vector<int32_t> monteCarloSquare_data = deHyperSlabData<int32_t>(m_MP_Data.monteCarloSquareData, m_MP_Data.monteCarlo_dims[0], m_MP_Data.monteCarlo_dims[1], m_MP_Data.monteCarlo_dims[2]); // Generate Monte Carlo square projection data m_MCSquareImageGenerators.resize(static_cast<size_t>(mc_zDim)); emit stdOutputMessageGenerated(tr("Reading Monte Carlo data sets (%1/%2)...").arg(currentCount).arg(totalItems)); createImageGeneratorTasks<int32_t>(monteCarloSquare_data, static_cast<size_t>(m_MP_Data.monteCarlo_dims[0]), static_cast<size_t>(m_MP_Data.monteCarlo_dims[1]), mc_zDim, m_MCSquareImageGenerators, m_MCSquareImageGenLock); currentCount++; // Generate Monte Carlo circular projection data m_MCCircleImageGenerators.resize(static_cast<size_t>(mc_zDim)); emit stdOutputMessageGenerated(tr("Reading Monte Carlo data sets (%1/%2)...").arg(currentCount).arg(totalItems)); createProjectionConversionTasks<int32_t, float>(monteCarloSquare_data, m_MP_Data.monteCarlo_dims[0], m_MP_Data.monteCarlo_dims[1], mc_zDim, m_MP_Data.monteCarlo_dims[0], 1, ModifiedLambertProjection::Square::NorthSquare, m_MCCircleImageGenerators, m_MCCircleImageGenLock, false, true); currentCount++; // Generate Monte Carlo stereographic projection data m_MCStereoImageGenerators.resize(static_cast<size_t>(mc_zDim)); emit stdOutputMessageGenerated(tr("Reading Monte Carlo data sets (%1/%2)...").arg(currentCount).arg(totalItems)); createProjectionConversionTasks<int32_t, float>(monteCarloSquare_data, m_MP_Data.monteCarlo_dims[0], m_MP_Data.monteCarlo_dims[1], mc_zDim, m_MP_Data.monteCarlo_dims[0], 0, ModifiedLambertProjection::Square::NorthSquare, m_MCStereoImageGenerators, m_MCStereoImageGenLock, false, true); QString mcDimStr = ""; for(size_t i = 0; i < m_MP_Data.monteCarlo_dims.size(); i++) { mcDimStr.append(QString::number(m_MP_Data.monteCarlo_dims[i])); if(i < m_MP_Data.monteCarlo_dims.size() - 1) { mcDimStr.append(" x "); } } emit stdOutputMessageGenerated(tr("Reading Monte Carlo data sets complete!\n")); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::checkImageGenerationCompletion() const { if(QThreadPool::globalInstance()->activeThreadCount() > 0) { QTimer::singleShot(100, this, SLOT(checkImageGenerationCompletion())); } else { // Set the default range of the images to be displayed (masterLPNH is always displayed first by default) emit imageRangeChanged(1, static_cast<int32_t>(m_MasterLPNHImageGenerators.size())); emit mpmcGenerationFinished(); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::generatePatternImagesUsingThread(const SimulatedPatternDisplayWidget::PatternDisplayData& patternData, const PatternDisplayController::DetectorData& detectorData) { PatternListModel* model = PatternListModel::Instance(); while(!m_CurrentOrder.empty()) { if(m_Cancel) { return; } // Load the next image if(m_CurrentOrderLock.tryAcquire()) { size_t index; if(!m_PriorityOrder.empty()) { // An index in this thread has been given priority index = m_PriorityOrder.front(); m_PriorityOrder.pop_front(); m_CurrentOrder.removeAll(index); } else { index = m_CurrentOrder.front(); m_CurrentOrder.pop_front(); } m_CurrentOrderLock.release(); QModelIndex modelIndex = model->index(static_cast<int32_t>(index), PatternListItem::DefaultColumn); model->setPatternStatus(static_cast<int32_t>(index), PatternListItem::PatternStatus::Loading); emit rowDataChanged(modelIndex, modelIndex); // Build up the iParValues object PatternTools::IParValues iParValues; iParValues.numsx = m_MP_Data.numsx; iParValues.numset = m_MP_Data.numset; iParValues.incidentBeamVoltage = static_cast<float>(m_MP_Data.incidentBeamVoltage); iParValues.minEnergy = static_cast<float>(m_MP_Data.minEnergy); iParValues.energyBinSize = static_cast<float>(m_MP_Data.energyBinSize); iParValues.npx = m_MP_Data.npx; iParValues.numOfPixelsX = detectorData.numOfPixelsX; iParValues.numOfPixelsY = detectorData.numOfPixelsY; iParValues.detectorBinningValue = static_cast<int32_t>(patternData.detectorBinningValue); iParValues.numberOfOrientations = 1; // Build up the fParValues object PatternTools::FParValues fParValues; fParValues.omega = static_cast<float>(m_MP_Data.omega); fParValues.sigma = static_cast<float>(m_MP_Data.sigma); fParValues.pcPixelsX = detectorData.patternCenterX; fParValues.pcPixelsY = detectorData.patternCenterY; fParValues.scintillatorPixelSize = detectorData.scintillatorPixelSize; fParValues.scintillatorDist = detectorData.scintillatorDist; fParValues.detectorTiltAngle = detectorData.detectorTiltAngle; fParValues.beamCurrent = detectorData.beamCurrent; fParValues.dwellTime = detectorData.dwellTime; fParValues.gammaValue = patternData.gammaValue; std::vector<float> pattern = PatternTools::GeneratePattern(iParValues, fParValues, m_MP_Data.masterLPNHData, m_MP_Data.masterLPSHData, m_MP_Data.monteCarloSquareData, patternData.angles, static_cast<int32_t>(index), m_Cancel); hsize_t xDim = static_cast<hsize_t>(iParValues.numOfPixelsX / iParValues.detectorBinningValue); hsize_t yDim = static_cast<hsize_t>(iParValues.numOfPixelsY / iParValues.detectorBinningValue); PatternImageViewer::ImageData imageData; bool success = generatePatternImage(imageData, pattern, xDim, yDim, 0); m_PatternDisplayWidget->loadImage(static_cast<int32_t>(index), imageData); if(success) { model->setPatternStatus(static_cast<int32_t>(index), PatternListItem::PatternStatus::Loaded); } else { model->setPatternStatus(static_cast<int32_t>(index), PatternListItem::PatternStatus::Error); } m_NumOfFinishedPatternsLock.acquire(); m_NumOfFinishedPatterns++; emit newProgressBarValue(static_cast<int32_t>(m_NumOfFinishedPatterns)); m_NumOfFinishedPatternsLock.release(); emit rowDataChanged(modelIndex, modelIndex); } } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- bool PatternDisplayController::generatePatternImage(PatternImageViewer::ImageData& imageData, const std::vector<float> &pattern, hsize_t xDim, hsize_t yDim, hsize_t zValue) const { AbstractImageGenerator::Pointer imgGen = ImageGenerator<float>::New(pattern, xDim, yDim, static_cast<int32_t>(zValue)); imgGen->createImage(); imageData.image = imgGen->getGeneratedImage(); VariantPair variantPair = imgGen->getMinMaxPair(); imageData.minValue = variantPair.first.toFloat(); imageData.maxValue = variantPair.second.toFloat(); return true; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::generatePatternImages(SimulatedPatternDisplayWidget::PatternDisplayData patternData, const PatternDisplayController::DetectorData& detectorData) { m_NumOfFinishedPatterns = 0; m_NumOfFinishedPatternThreads = 0; m_CurrentOrder.clear(); m_PriorityOrder.clear(); m_PatternWatchers.clear(); m_Cancel = false; std::vector<float> eulerAngles = patternData.angles; size_t angleCount = eulerAngles.size() / 3; emit newProgressBarMaximumValue(static_cast<int32_t>(angleCount)); PatternListModel* model = PatternListModel::Instance(); for(size_t i = 0; i < angleCount; i++) { model->setPatternStatus(static_cast<int32_t>(i), PatternListItem::PatternStatus::WaitingToLoad); if(i == patternData.currentRow) { // We want to render the current index first m_CurrentOrder.push_front(i); } else { m_CurrentOrder.push_back(i); } } int32_t threads = 1; // QThreadPool::globalInstance()->maxThreadCount(); for(int32_t i = 0; i < threads; i++) { std::unique_ptr<QFutureWatcher<void>> watcher = std::make_unique<QFutureWatcher<void>>(new QFutureWatcher<void>()); connect(watcher.get(), &QFutureWatcher<void>::finished, this, [=] { patternThreadFinished(threads); }); QFuture<void> future = QtConcurrent::run(this, &PatternDisplayController::generatePatternImagesUsingThread, patternData, detectorData); watcher->setFuture(future); m_PatternWatchers.push_back(std::move(watcher)); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::addPriorityIndex(size_t index) { m_PriorityOrder.push_back(index); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::updateMPImage(MPMCDisplayWidget::MPMCData mpData) const { QImage image; VariantPair variantPair; MPMCDisplayWidget::ProjectionMode mode = mpData.mode; size_t energyBin = static_cast<size_t>(mpData.energyBin); float keV; // If any of the arrays are going to go out of bounds, set a blank image with blank data if((mode == MPMCDisplayWidget::ProjectionMode::Lambert_Square && energyBin > m_MasterLPNHImageGenerators.size()) || (mode == MPMCDisplayWidget::ProjectionMode::Lambert_Circle && energyBin > m_MasterCircleImageGenerators.size()) || (mode == MPMCDisplayWidget::ProjectionMode::Stereographic && energyBin > m_MasterStereoImageGenerators.size())) { image = QImage(); variantPair.first = 0; variantPair.second = 0; keV = 0; } else { if(mode == MPMCDisplayWidget::ProjectionMode::Lambert_Square) { AbstractImageGenerator::Pointer imageGen = m_MasterLPNHImageGenerators[energyBin - 1]; image = imageGen->getGeneratedImage(); variantPair = imageGen->getMinMaxPair(); } else if(mode == MPMCDisplayWidget::ProjectionMode::Lambert_Circle) { AbstractImageGenerator::Pointer imageGen = m_MasterCircleImageGenerators[energyBin - 1]; image = imageGen->getGeneratedImage(); variantPair = imageGen->getMinMaxPair(); } else if(mode == MPMCDisplayWidget::ProjectionMode::Stereographic) { AbstractImageGenerator::Pointer imageGen = m_MasterStereoImageGenerators[energyBin - 1]; image = imageGen->getGeneratedImage(); variantPair = imageGen->getMinMaxPair(); } keV = m_MP_Data.ekevs.at(energyBin - 1); } PatternImageViewer::ImageData imageData; imageData.image = image; imageData.minValue = variantPair.first.toFloat(); imageData.maxValue = variantPair.second.toFloat(); imageData.keVValue = keV; emit mpImageNeedsDisplayed(imageData); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::updateMCImage(MPMCDisplayWidget::MPMCData mcData) const { QImage image; VariantPair variantPair; MPMCDisplayWidget::ProjectionMode mode = mcData.mode; size_t energyBin = static_cast<size_t>(mcData.energyBin); float keV; // If any of the arrays are going to go out of bounds, set a blank image with blank data if((mode == MPMCDisplayWidget::ProjectionMode::Lambert_Square && energyBin > m_MCSquareImageGenerators.size()) || (mode == MPMCDisplayWidget::ProjectionMode::Lambert_Circle && energyBin > m_MCCircleImageGenerators.size()) || (mode == MPMCDisplayWidget::ProjectionMode::Stereographic && energyBin > m_MCStereoImageGenerators.size())) { image = QImage(); variantPair.first = 0; variantPair.second = 0; keV = 0; } else { if(mode == MPMCDisplayWidget::ProjectionMode::Lambert_Square) { AbstractImageGenerator::Pointer imageGen = m_MCSquareImageGenerators[energyBin - 1]; image = imageGen->getGeneratedImage(); variantPair = imageGen->getMinMaxPair(); } else if(mode == MPMCDisplayWidget::ProjectionMode::Lambert_Circle) { AbstractImageGenerator::Pointer imageGen = m_MCCircleImageGenerators[energyBin - 1]; image = imageGen->getGeneratedImage(); variantPair = imageGen->getMinMaxPair(); } else if(mode == MPMCDisplayWidget::ProjectionMode::Stereographic) { AbstractImageGenerator::Pointer imageGen = m_MCStereoImageGenerators[energyBin - 1]; image = imageGen->getGeneratedImage(); variantPair = imageGen->getMinMaxPair(); } keV = m_MP_Data.ekevs.at(energyBin - 1); } PatternImageViewer::ImageData imageData; imageData.image = image; imageData.minValue = variantPair.first.toFloat(); imageData.maxValue = variantPair.second.toFloat(); imageData.keVValue = keV; emit mcImageNeedsDisplayed(imageData); } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::patternThreadFinished(int maxThreadCount) { m_NumOfFinishedPatternThreads++; if(m_NumOfFinishedPatternThreads == maxThreadCount) { m_Cancel = false; emit patternGenerationFinished(); } } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- bool PatternDisplayController::validateDetectorValues(PatternDisplayController::DetectorData data) const { if(data.masterFilePath.isEmpty()) { QString ss = QObject::tr("The master file path must be set."); emit errorMessageGenerated(ss); return false; } QFileInfo fi(data.masterFilePath); if(!fi.exists()) { QString ss = QObject::tr("The master file path '%1' does not exist.").arg(data.masterFilePath); emit errorMessageGenerated(ss); return false; } QString suffix = fi.completeSuffix(); if(suffix != "h5" && suffix != "dream3d") { QString ss = QObject::tr("The master file path '%1' is not an HDF5 file.").arg(data.masterFilePath); emit errorMessageGenerated(ss); return false; } return true; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::cancelGeneration() { m_Cancel = true; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::setPatternDisplayWidget(SimulatedPatternDisplayWidget* value) { m_PatternDisplayWidget = value; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- SimulatedPatternDisplayWidget* PatternDisplayController::getPatternDisplayWidget() const { return m_PatternDisplayWidget; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- void PatternDisplayController::setObserver(IObserver* value) { m_Observer = value; } // ----------------------------------------------------------------------------- // // ----------------------------------------------------------------------------- IObserver* PatternDisplayController::getObserver() const { return m_Observer; }
41.608547
197
0.646892
[ "render", "object", "vector", "model" ]
048fa151e72b184ca331726d27a5416ed8008128
7,787
cpp
C++
src/common/optionstructure.cpp
chinsp/KiT-RT
d4465d55b2d623b840a9a5696e3aad46d9fb158d
[ "MIT" ]
null
null
null
src/common/optionstructure.cpp
chinsp/KiT-RT
d4465d55b2d623b840a9a5696e3aad46d9fb158d
[ "MIT" ]
null
null
null
src/common/optionstructure.cpp
chinsp/KiT-RT
d4465d55b2d623b840a9a5696e3aad46d9fb158d
[ "MIT" ]
null
null
null
/*! * \file config.cpp * \brief Classes for different Optiontypes in rtsn * \author S. Schotthoefer * * Disclaimer: This class structure was copied and modifed with open source permission from SU2 v7.0.3 https://su2code.github.io/ */ #include "common/optionstructure.h" // --- Members of OptionBase ---- OptionBase::~OptionBase() {} std::vector<std::string> OptionBase::GetValue() { return _value; } std::string OptionBase::SetValue( std::vector<std::string> value ) { this->_value = value; return ""; } std::string OptionBase::OptionCheckMultipleValues( std::vector<std::string>& option_value, std::string type_id, std::string option_name ) { if( option_value.size() != 1 ) { std::string newString; newString.append( option_name ); newString.append( ": multiple values for type " ); newString.append( type_id ); return newString; } return ""; } std::string OptionBase::BadValue( std::vector<std::string>& option_value, std::string type_id, std::string option_name ) { std::string newString; newString.append( option_name ); newString.append( ": improper option value for type " ); newString.append( type_id ); newString.append( ". Value chosen: " ); for( unsigned i = 0; i < option_value.size(); i++ ) { newString.append( option_value[i] ); } return newString; } // ---- Memebers of OptionDouble OptionDouble::OptionDouble( std::string option_field_name, double& option_field, double default_value ) : _field( option_field ) { this->_def = default_value; this->_name = option_field_name; } std::string OptionDouble::SetValue( std::vector<std::string> option_value ) { OptionBase::SetValue( option_value ); // check if there is more than one value std::string out = OptionCheckMultipleValues( option_value, "double", this->_name ); if( out.compare( "" ) != 0 ) { return out; } std::istringstream is( option_value[0] ); double val; if( is >> val ) { this->_field = val; return ""; } return BadValue( option_value, "double", this->_name ); } void OptionDouble::SetDefault() { this->_field = this->_def; } // ---- Members of OptionString OptionString::OptionString( std::string option_field_name, std::string& option_field, std::string default_value ) : _field( option_field ) { this->_def = default_value; this->_name = option_field_name; } std::string OptionString::SetValue( std::vector<std::string> option_value ) { OptionBase::SetValue( option_value ); // check if there is more than one value std::string out = OptionCheckMultipleValues( option_value, "double", this->_name ); if( out.compare( "" ) != 0 ) { return out; } this->_field.assign( option_value[0] ); return ""; } void OptionString::SetDefault() { this->_field = this->_def; } // --- Members of OptionInt OptionInt::OptionInt( std::string option_field_name, int& option_field, int default_value ) : _field( option_field ) { this->_def = default_value; this->_name = option_field_name; } std::string OptionInt::SetValue( std::vector<std::string> option_value ) { OptionBase::SetValue( option_value ); std::string out = OptionCheckMultipleValues( option_value, "int", this->_name ); if( out.compare( "" ) != 0 ) { return out; } std::istringstream is( option_value[0] ); int val; if( is >> val ) { this->_field = val; return ""; } return BadValue( option_value, "int", this->_name ); } void OptionInt::SetDefault() { this->_field = this->_def; } // ---- Members of OptionULong OptionULong::OptionULong( std::string option_field_name, unsigned long& option_field, unsigned long default_value ) : _field( option_field ) { this->_def = default_value; this->_name = option_field_name; } std::string OptionULong::SetValue( std::vector<std::string> option_value ) { OptionBase::SetValue( option_value ); std::string out = OptionCheckMultipleValues( option_value, "unsigned long", this->_name ); if( out.compare( "" ) != 0 ) { return out; } std::istringstream is( option_value[0] ); unsigned long val; if( is >> val ) { this->_field = val; return ""; } return BadValue( option_value, "unsigned long", this->_name ); } void OptionULong::SetDefault() { this->_field = this->_def; } // ---- Members of OptionUShort OptionUShort::OptionUShort( std::string option_field_name, unsigned short& option_field, unsigned short default_value ) : _field( option_field ) { this->_def = default_value; this->_name = option_field_name; } std::string OptionUShort::SetValue( std::vector<std::string> option_value ) { OptionBase::SetValue( option_value ); std::string out = OptionCheckMultipleValues( option_value, "unsigned short", this->_name ); if( out.compare( "" ) != 0 ) { return out; } std::istringstream is( option_value[0] ); unsigned short val; if( is >> val ) { this->_field = val; return ""; } return BadValue( option_value, "unsigned short", this->_name ); } void OptionUShort::SetDefault() { this->_field = this->_def; } // ---- Members of OptionLong OptionLong::OptionLong( std::string option_field_name, long& option_field, long default_value ) : _field( option_field ) { this->_def = default_value; this->_name = option_field_name; } std::string OptionLong::SetValue( std::vector<std::string> option_value ) { OptionBase::SetValue( option_value ); std::string out = OptionCheckMultipleValues( option_value, "long", this->_name ); if( out.compare( "" ) != 0 ) { return out; } std::istringstream is( option_value[0] ); long val; if( is >> val ) { this->_field = val; return ""; } return BadValue( option_value, "long", this->_name ); } void OptionLong::SetDefault() { this->_field = this->_def; } // ---- Members of OptionBool OptionBool::OptionBool( std::string option_field_name, bool& option_field, bool default_value ) : _field( option_field ) { this->_def = default_value; this->_name = option_field_name; } std::string OptionBool::SetValue( std::vector<std::string> option_value ) { OptionBase::SetValue( option_value ); // check if there is more than one value std::string out = OptionCheckMultipleValues( option_value, "bool", this->_name ); if( out.compare( "" ) != 0 ) { return out; } if( option_value[0].compare( "YES" ) == 0 ) { this->_field = true; return ""; } if( option_value[0].compare( "NO" ) == 0 ) { this->_field = false; return ""; } return BadValue( option_value, "bool", this->_name ); } void OptionBool::SetDefault() { this->_field = this->_def; } // --- members of OptionStringList OptionStringList::OptionStringList( std::string option_field_name, unsigned short& list_size, std::vector<std::string>& option_field ) : _field( option_field ), _size( list_size ) { this->_name = option_field_name; } std::string OptionStringList::SetValue( std::vector<std::string> option_value ) { OptionBase::SetValue( option_value ); // The size is the length of option_value unsigned short option_size = option_value.size(); if( option_size == 1 && option_value[0].compare( "NONE" ) == 0 ) { this->_size = 0; return ""; } this->_size = option_size; // Parse all of the options this->_field.resize( this->_size ); for( unsigned long i = 0; i < option_size; i++ ) { this->_field.at( i ) = option_value[i]; } return ""; } void OptionStringList::SetDefault() { this->_size = 0; // There is no default value for list }
32.445833
146
0.649544
[ "vector" ]
04927876cde663765fe1bff8c0221902bc0e23a1
11,650
cpp
C++
src/Boring32/Crypto/boring32.crypto-functions.cpp
yottaawesome/Win32Common
cb5896bf68307d6eceddea78c7867b97ec020bc1
[ "MIT" ]
null
null
null
src/Boring32/Crypto/boring32.crypto-functions.cpp
yottaawesome/Win32Common
cb5896bf68307d6eceddea78c7867b97ec020bc1
[ "MIT" ]
null
null
null
src/Boring32/Crypto/boring32.crypto-functions.cpp
yottaawesome/Win32Common
cb5896bf68307d6eceddea78c7867b97ec020bc1
[ "MIT" ]
null
null
null
module; #include <vector> #include <stdexcept> #include <source_location> #include <string> #include <Windows.h> #include <dpapi.h> // not including this header causes symbol has already been defined error #include <Wincrypt.h> module boring32.crypto:functions; import boring32.error; namespace Boring32::Crypto { // See also a complete example on MSDN at: // https://docs.microsoft.com/en-us/windows/win32/seccrypto/example-c-program-using-cryptprotectdata std::vector<std::byte> Encrypt( const std::vector<std::byte>& data, const std::wstring& password, const std::wstring& description ) { DATA_BLOB dataIn; dataIn.pbData = reinterpret_cast<BYTE*>(const_cast<std::byte*>(&data[0])); dataIn.cbData = static_cast<DWORD>(data.size()); DATA_BLOB additionalEntropy{ 0 }; if (password.empty() == false) { additionalEntropy.pbData = reinterpret_cast<BYTE*>(const_cast<wchar_t*>(&password[0])); additionalEntropy.cbData = static_cast<DWORD>(password.size()*sizeof(wchar_t)); } // https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptprotectdata DATA_BLOB encryptedBlob{ 0 }; const wchar_t* descriptionCStr = description.empty() ? nullptr : description.c_str(); DATA_BLOB* const entropy = password.empty() ? nullptr : &additionalEntropy; const bool succeeded = CryptProtectData( &dataIn, // The data to encrypt. descriptionCStr, // An optional description string. entropy, // Optional additional entropy to // to encrypt the string with, e.g. // a password. nullptr, // Reserved. nullptr, // Pass a PromptStruct. 0, // Flags. &encryptedBlob // Receives the encrypted information. ); if (succeeded == false) throw Error::Win32Error("CryptProtectData() failed", GetLastError()); // Should we really return std::byte instead of Windows' BYTE? // Using std::byte means we'll need to cast at the API call. std::vector<std::byte> returnValue( (std::byte*)encryptedBlob.pbData, (std::byte*)encryptedBlob.pbData + encryptedBlob.cbData ); if (encryptedBlob.pbData) LocalFree(encryptedBlob.pbData); return returnValue; } std::vector<std::byte> Encrypt( const std::wstring& str, const std::wstring& password, const std::wstring& description ) { const std::byte* buffer = (std::byte*)&str[0]; return Encrypt( std::vector<std::byte>(buffer, buffer + str.size() * sizeof(wchar_t)), password, description ); } std::wstring DecryptString( const std::vector<std::byte>& encryptedData, const std::wstring& password, std::wstring& outDescription ) { DATA_BLOB encryptedBlob; encryptedBlob.pbData = (BYTE*)&encryptedData[0]; encryptedBlob.cbData = (DWORD)encryptedData.size(); DATA_BLOB additionalEntropy{ 0 }; if (password.empty() == false) { additionalEntropy.pbData = (BYTE*)&password[0]; additionalEntropy.cbData = (DWORD)password.size() * sizeof(wchar_t); } DATA_BLOB decryptedBlob; LPWSTR descrOut = nullptr; DATA_BLOB* const entropy = password.empty() ? nullptr : &additionalEntropy; // https://docs.microsoft.com/en-us/windows/win32/api/dpapi/nf-dpapi-cryptunprotectdata const bool succeeded = CryptUnprotectData( &encryptedBlob, // the encrypted data &descrOut, // Optional description entropy, // Optional additional entropy // used to encrypt the string // with, e.g. a password nullptr, // Reserved nullptr, // Optional prompt structure 0, // Flags &decryptedBlob // Receives the decrypted data ); if (succeeded == false) throw Error::Win32Error("CryptUnprotectData() failed", GetLastError()); if (descrOut) { outDescription = descrOut; LocalFree(descrOut); } std::wstring returnValue( reinterpret_cast<wchar_t*>(decryptedBlob.pbData), decryptedBlob.cbData / sizeof(wchar_t) ); if (decryptedBlob.pbData) LocalFree(decryptedBlob.pbData); return returnValue; } std::vector<std::byte> Encrypt( const DWORD blockByteLength, const CryptoKey& key, const std::vector<std::byte>& iv, const std::vector<std::byte>& plainText, const DWORD flags ) { if (key.GetHandle() == nullptr) throw std::invalid_argument(__FUNCSIG__ ": key is null"); // IV is optional PUCHAR pIV = nullptr; ULONG ivSize = 0; if (iv.empty() == false) { if (iv.size() != blockByteLength) throw std::invalid_argument(__FUNCSIG__ ": IV must be the same size as the AES block lenth"); pIV = (PUCHAR)&iv[0]; ivSize = (ULONG)iv.size(); } // Determine the byte size of the encrypted data DWORD cbData = 0; // https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptencrypt NTSTATUS status = BCryptEncrypt( key.GetHandle(), (PUCHAR)&plainText[0], (ULONG)plainText.size(), nullptr, pIV, ivSize, nullptr, 0, &cbData, flags ); if (BCRYPT_SUCCESS(status) == false) throw Error::NtStatusError("BCryptEncrypt() failed to count bytes", status); // Actually do the encryption std::vector<std::byte> cypherText(cbData, std::byte{ 0 }); status = BCryptEncrypt( key.GetHandle(), (PUCHAR)&plainText[0], (ULONG)plainText.size(), nullptr, pIV, ivSize, (PUCHAR)&cypherText[0], (ULONG)cypherText.size(), &cbData, flags ); if (BCRYPT_SUCCESS(status) == false) throw Error::NtStatusError("BCryptEncrypt() failed to encrypt", status); return cypherText; } std::vector<std::byte> Decrypt( const DWORD blockByteLength, const CryptoKey& key, const std::vector<std::byte>& iv, const std::vector<std::byte>& cypherText, const DWORD flags ) { if (key.GetHandle() == nullptr) throw std::invalid_argument(__FUNCSIG__ ": key is null"); // IV is optional PUCHAR pIV = nullptr; ULONG ivSize = 0; if (iv.empty() == false) { // Do all cipher algs require this? if (iv.size() != blockByteLength) throw std::invalid_argument(__FUNCSIG__ ": IV must be the same size as the AES block lenth"); pIV = (PUCHAR)&iv[0]; ivSize = (ULONG)iv.size(); } // Determine the byte size of the decrypted data DWORD cbData = 0; // https://docs.microsoft.com/en-us/windows/win32/api/bcrypt/nf-bcrypt-bcryptdecrypt NTSTATUS status = BCryptDecrypt( key.GetHandle(), (PUCHAR)&cypherText[0], (ULONG)cypherText.size(), nullptr, pIV, ivSize, nullptr, 0, &cbData, flags ); if (BCRYPT_SUCCESS(status) == false) throw Error::NtStatusError("BCryptDecrypt() failed to count bytes", status); // Actually do the decryption std::vector<std::byte> plainText(cbData, std::byte{ 0 }); status = BCryptDecrypt( key.GetHandle(), (PUCHAR)&cypherText[0], (ULONG)cypherText.size(), nullptr, pIV, ivSize, (PUCHAR)&plainText[0], (ULONG)plainText.size(), &cbData, flags ); if (BCRYPT_SUCCESS(status) == false) throw Error::NtStatusError("BCryptDecrypt() failed to decrypt", status); plainText.resize(cbData); return plainText; } std::string ToBase64String(const std::vector<std::byte>& bytes) { // Determine the required size -- this includes the null terminator DWORD size = 0; bool succeeded = CryptBinaryToStringA( (BYTE*)&bytes[0], (DWORD)bytes.size(), CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, nullptr, &size ); if (succeeded == false) throw Error::Win32Error("CryptBinaryToStringA() failed when calculating size"); if (size == 0) return ""; std::string returnVal(size, L'\0'); succeeded = CryptBinaryToStringA( (BYTE*)&bytes[0], (DWORD)bytes.size(), CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, (LPSTR)&returnVal[0], &size ); if (succeeded == false) throw Error::Win32Error("CryptBinaryToStringA() failed when encoding"); // Remove terminating null character if (returnVal.empty() == false) returnVal.pop_back(); return returnVal; } std::wstring ToBase64WString(const std::vector<std::byte>& bytes) { // Determine the required size -- this includes the null terminator DWORD size = 0; // https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptbinarytostringw bool succeeded = CryptBinaryToStringW( (BYTE*)&bytes[0], (DWORD)bytes.size(), CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, nullptr, &size ); if (succeeded == false) throw Error::Win32Error("CryptBinaryToStringW() failed when calculating size"); if (size == 0) return L""; std::wstring returnVal(size, L'\0'); succeeded = CryptBinaryToStringW( (BYTE*)&bytes[0], (DWORD)bytes.size(), CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, (LPWSTR)&returnVal[0], &size ); if (succeeded == false) throw Error::Win32Error("CryptBinaryToStringW() failed when encoding"); // Remove terminating null character if (returnVal.empty() == false) returnVal.pop_back(); return returnVal; } std::vector<std::byte> ToBinary(const std::wstring& base64) { DWORD byteSize = 0; bool succeeded = CryptStringToBinaryW( &base64[0], 0, CRYPT_STRING_BASE64, nullptr, &byteSize, nullptr, nullptr ); if (succeeded == false) throw Error::Win32Error("CryptStringToBinaryW() failed when calculating size"); std::vector<std::byte> returnVal(byteSize); succeeded = CryptStringToBinaryW( &base64[0], 0, CRYPT_STRING_BASE64, (BYTE*)&returnVal[0], &byteSize, nullptr, nullptr ); if (succeeded == false) throw Error::Win32Error("CryptStringToBinaryW() failed when decoding"); returnVal.resize(byteSize); return returnVal; } std::vector<std::byte> EncodeAsnString(const std::wstring& name) { DWORD encoded = 0; // CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG is required or the encoding // produces subtle differences in the encoded bytes (DC3 vs FF in // original buffer), which causes the match to fail // See https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certstrtonamew const DWORD flags = CERT_X500_NAME_STR | CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG; bool succeeded = CertStrToNameW( X509_ASN_ENCODING, name.c_str(), flags, nullptr, nullptr, &encoded, nullptr ); if (succeeded == false) throw Error::Win32Error("CertStrToNameW() failed", GetLastError()); std::vector<std::byte> byte(encoded); succeeded = CertStrToNameW( X509_ASN_ENCODING, name.c_str(), flags, nullptr, (BYTE*)&byte[0], &encoded, nullptr ); if (succeeded == false) throw Error::Win32Error("CertStrToNameW() failed", GetLastError()); byte.resize(encoded); return byte; } std::wstring FormatAsnNameBlob( const CERT_NAME_BLOB& certName, const DWORD format ) { // https://docs.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-certnametostrw DWORD characterSize = CertNameToStrW( X509_ASN_ENCODING, (CERT_NAME_BLOB*)&certName, format, nullptr, 0 ); if (characterSize == 0) return L""; std::wstring name(characterSize, '\0'); characterSize = CertNameToStrW( X509_ASN_ENCODING, (CERT_NAME_BLOB*)&certName, format, &name[0], (DWORD)name.size() ); name.pop_back(); // remove excess null character return name; } }
27.541371
102
0.658197
[ "vector" ]
049361e9101bf2733484c7ae8f09b4261b874315
8,038
cc
C++
content/worker/websharedworkerclient_proxy.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/worker/websharedworkerclient_proxy.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/worker/websharedworkerclient_proxy.cc
codenote/chromium-test
0637af0080f7e80bf7d20b29ce94c5edc817f390
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:25:45.000Z
2020-11-04T07:25:45.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/worker/websharedworkerclient_proxy.h" #include "base/bind.h" #include "base/command_line.h" #include "base/message_loop.h" #include "content/common/fileapi/file_system_dispatcher.h" #include "content/common/fileapi/webfilesystem_callback_dispatcher.h" #include "content/common/quota_dispatcher.h" #include "content/common/webmessageportchannel_impl.h" #include "content/common/worker_messages.h" #include "content/public/common/content_switches.h" #include "content/worker/shared_worker_devtools_agent.h" #include "content/worker/websharedworker_stub.h" #include "content/worker/worker_thread.h" #include "content/worker/worker_webapplicationcachehost_impl.h" #include "ipc/ipc_logging.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebString.h" #include "third_party/WebKit/Source/Platform/chromium/public/WebURL.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebDocument.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFileSystemCallbacks.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h" #include "third_party/WebKit/Source/WebKit/chromium/public/WebSecurityOrigin.h" using WebKit::WebApplicationCacheHost; using WebKit::WebFrame; using WebKit::WebMessagePortChannel; using WebKit::WebMessagePortChannelArray; using WebKit::WebSecurityOrigin; using WebKit::WebString; using WebKit::WebWorker; using WebKit::WebSharedWorkerClient; namespace content { // How long to wait for worker to finish after it's been told to terminate. #define kMaxTimeForRunawayWorkerSeconds 3 WebSharedWorkerClientProxy::WebSharedWorkerClientProxy( int route_id, WebSharedWorkerStub* stub) : route_id_(route_id), appcache_host_id_(0), stub_(stub), ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)), devtools_agent_(NULL) { } WebSharedWorkerClientProxy::~WebSharedWorkerClientProxy() { } void WebSharedWorkerClientProxy::postMessageToWorkerObject( const WebString& message, const WebMessagePortChannelArray& channels) { std::vector<int> message_port_ids(channels.size()); std::vector<int> routing_ids(channels.size()); for (size_t i = 0; i < channels.size(); ++i) { WebMessagePortChannelImpl* webchannel = static_cast<WebMessagePortChannelImpl*>(channels[i]); message_port_ids[i] = webchannel->message_port_id(); webchannel->QueueMessages(); DCHECK(message_port_ids[i] != MSG_ROUTING_NONE); routing_ids[i] = MSG_ROUTING_NONE; } Send(new WorkerMsg_PostMessage( route_id_, message, message_port_ids, routing_ids)); } void WebSharedWorkerClientProxy::postExceptionToWorkerObject( const WebString& error_message, int line_number, const WebString& source_url) { Send(new WorkerHostMsg_PostExceptionToWorkerObject( route_id_, error_message, line_number, source_url)); } void WebSharedWorkerClientProxy::postConsoleMessageToWorkerObject( int source, int type, int level, const WebString& message, int line_number, const WebString& source_url) { WorkerHostMsg_PostConsoleMessageToWorkerObject_Params params; params.source_identifier = source; params.message_type = type; params.message_level = level; params.message = message; params.line_number = line_number; params.source_url = source_url; Send(new WorkerHostMsg_PostConsoleMessageToWorkerObject(route_id_, params)); } void WebSharedWorkerClientProxy::confirmMessageFromWorkerObject( bool has_pending_activity) { Send(new WorkerHostMsg_ConfirmMessageFromWorkerObject( route_id_, has_pending_activity)); } void WebSharedWorkerClientProxy::reportPendingActivity( bool has_pending_activity) { Send(new WorkerHostMsg_ReportPendingActivity( route_id_, has_pending_activity)); } void WebSharedWorkerClientProxy::workerContextClosed() { Send(new WorkerHostMsg_WorkerContextClosed(route_id_)); } void WebSharedWorkerClientProxy::workerContextDestroyed() { Send(new WorkerHostMsg_WorkerContextDestroyed(route_id_)); // Tell the stub that the worker has shutdown - frees this object. if (stub_) stub_->Shutdown(); } WebKit::WebNotificationPresenter* WebSharedWorkerClientProxy::notificationPresenter() { // TODO(johnnyg): Notifications are not yet hooked up to workers. // Coming soon. NOTREACHED(); return NULL; } WebApplicationCacheHost* WebSharedWorkerClientProxy::createApplicationCacheHost( WebKit::WebApplicationCacheHostClient* client) { WorkerWebApplicationCacheHostImpl* host = new WorkerWebApplicationCacheHostImpl(stub_->appcache_init_info(), client); // Remember the id of the instance we create so we have access to that // value when creating nested dedicated workers in createWorker. appcache_host_id_ = host->host_id(); return host; } // TODO(abarth): Security checks should use WebDocument or WebSecurityOrigin, // not WebFrame as the context object because WebFrames can contain different // WebDocuments at different times. bool WebSharedWorkerClientProxy::allowDatabase(WebFrame* frame, const WebString& name, const WebString& display_name, unsigned long estimated_size) { WebSecurityOrigin origin = frame->document().securityOrigin(); if (origin.isUnique()) return false; bool result = false; Send(new WorkerProcessHostMsg_AllowDatabase( route_id_, GURL(origin.toString().utf8()), name, display_name, estimated_size, &result)); return result; } bool WebSharedWorkerClientProxy::allowFileSystem() { bool result = false; Send(new WorkerProcessHostMsg_AllowFileSystem( route_id_, stub_->url().GetOrigin(), &result)); return result; } void WebSharedWorkerClientProxy::openFileSystem( WebKit::WebFileSystemType type, long long size, bool create, WebKit::WebFileSystemCallbacks* callbacks) { ChildThread::current()->file_system_dispatcher()->OpenFileSystem( stub_->url().GetOrigin(), static_cast<fileapi::FileSystemType>(type), size, create, new WebFileSystemCallbackDispatcher(callbacks)); } bool WebSharedWorkerClientProxy::allowIndexedDB(const WebKit::WebString& name) { bool result = false; Send(new WorkerProcessHostMsg_AllowIndexedDB( route_id_, stub_->url().GetOrigin(), name, &result)); return result; } void WebSharedWorkerClientProxy::queryUsageAndQuota( WebKit::WebStorageQuotaType type, WebKit::WebStorageQuotaCallbacks* callbacks) { ChildThread::current()->quota_dispatcher()->QueryStorageUsageAndQuota( stub_->url().GetOrigin(), static_cast<quota::StorageType>(type), QuotaDispatcher::CreateWebStorageQuotaCallbacksWrapper(callbacks)); } void WebSharedWorkerClientProxy::dispatchDevToolsMessage( const WebString& message) { if (devtools_agent_) devtools_agent_->SendDevToolsMessage(message); } void WebSharedWorkerClientProxy::saveDevToolsAgentState( const WebKit::WebString& state) { if (devtools_agent_) devtools_agent_->SaveDevToolsAgentState(state); } bool WebSharedWorkerClientProxy::Send(IPC::Message* message) { return WorkerThread::current()->Send(message); } void WebSharedWorkerClientProxy::EnsureWorkerContextTerminates() { // This shuts down the process cleanly from the perspective of the browser // process, and avoids the crashed worker infobar from appearing to the new // page. It's ok to post several of theese, because the first executed task // will exit the message loop and subsequent ones won't be executed. MessageLoop::current()->PostDelayedTask(FROM_HERE, base::Bind( &WebSharedWorkerClientProxy::workerContextDestroyed, weak_factory_.GetWeakPtr()), base::TimeDelta::FromSeconds(kMaxTimeForRunawayWorkerSeconds)); } } // namespace content
36.87156
84
0.76325
[ "object", "vector" ]
0493d1927aa13107fd62b455538e431b1e83c7df
6,205
cc
C++
src/ui/lib/escher/scene/camera.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
1
2019-10-09T10:50:57.000Z
2019-10-09T10:50:57.000Z
src/ui/lib/escher/scene/camera.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
src/ui/lib/escher/scene/camera.cc
bootingman/fuchsia2
04012f0aa1edd1d4108a2ac647a65e59730fc4c2
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Fuchsia 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 "src/ui/lib/escher/scene/camera.h" #include "src/lib/fxl/logging.h" #include "src/ui/lib/escher/math/rotations.h" #include "src/ui/lib/escher/scene/viewing_volume.h" #include "src/ui/lib/escher/util/debug_print.h" namespace escher { static std::pair<float, float> ComputeNearAndFarPlanes( const ViewingVolume& volume, const mat4& camera_transform) { float width = volume.width(); float height = volume.height(); float bottom = volume.bottom(); float top = volume.top(); FXL_DCHECK(bottom > top); vec3 corners[] = {{0, 0, bottom}, {width, 0, bottom}, {0, 0, top}, {width, 0, top}, {0, height, bottom}, {width, height, bottom}, {0, height, top}, {width, height, top}}; // Transform the corners into eye space, throwing away everything except the // negated Z-coordinate. There are two reasons that we do this; both rely on // the fact that in Vulkan eye space, the view vector is the negative Z-axis: // - Z is constant for all planes perpendicular to the view vector, so we // can use these to obtain the near/far plane distances. // - A positive Z value is behind the camera, so a negative Z-value must be // negated to obtain the distance in front of the camera. // // The reason for computing these negated Z-coordinates is that the smallest // one can be directly used as the near plane distance, and the largest for // the far plane distance. float negated_z; float far = FLT_MIN; float near = FLT_MAX; for (int i = 0; i < 8; ++i) { negated_z = -(camera_transform * vec4(corners[i], 1)).z; near = negated_z < near ? negated_z : near; far = negated_z > far ? negated_z : far; } #ifndef NDEBUG // The viewing volume must be entirely in front of the camera. // We can relax this restriction later, but we'll need to develop some // heuristics. if (near < 0) { // Invert the camera matrix to obtain the camera space to world space // transform from which we can extract the camera position in world space. mat4 camera_inverse = glm::inverse(camera_transform); vec3 pos(camera_transform * vec4(0, 0, 0, 1)); vec3 dir(camera_transform * vec4(0, 0, -1, 0)); FXL_LOG(FATAL) << "ViewingVolume must be entirely in front of the " "camera\nCamera Position: " << pos << "\nCamera Direction: " << dir << "\n" << volume; } #endif return std::make_pair(near, far); } Camera::Camera(const mat4& transform, const mat4& projection) : transform_(transform), projection_(projection) {} Camera Camera::NewOrtho(const ViewingVolume& volume) { // The floor of the stage has (x, y) coordinates ranging from (0,0) to // (volume.width(), volume.height()); move the camera so that it is above the // center of the stage. Also, move the camera "upward"; since the Vulkan // camera points into the screen along the negative-Z axis, this is equivalent // to moving the entire stage by a negative amount in Z. mat4 transform = glm::translate( vec3(-volume.width() / 2, -volume.height() / 2, volume.top() - 10.f)); // This method does not take the transform of the camera as input so there is // no way to reorient the view matrix outside of this method, so we point it // down the -Z axis here. The reason we mirror here instead of rotating is // because glm::orthoRH() produces a "right handed" matrix only in the sense // that it projects a right handed view space into OpenGL's left handed NDC // space, and thus it also projects a left handed view space into Vulkan's // right handed NDC space. transform = glm::scale(transform, glm::vec3(1.f, 1.f, -1.f)); auto near_and_far = ComputeNearAndFarPlanes(volume, transform); mat4 projection = glm::orthoRH( -0.5f * volume.width(), 0.5f * volume.width(), -0.5f * volume.height(), 0.5f * volume.height(), near_and_far.first, near_and_far.second); return Camera(transform, projection); } Camera Camera::NewForDirectionalShadowMap(const ViewingVolume& volume, const glm::vec3& direction) { glm::mat4 transform; RotationBetweenVectors(direction, glm::vec3(0.f, 0.f, -1.f), &transform); BoundingBox box = transform * volume.bounding_box(); constexpr float kStageFloorFudgeFactor = 0.0001f; const float range = box.max().z - box.min().z; const float near = -box.max().z - (kStageFloorFudgeFactor * range); const float far = -box.min().z + (kStageFloorFudgeFactor * range); glm::mat4 projection = glm::ortho(box.min().x, box.max().x, box.min().y, box.max().y, near, far); return Camera(transform, projection); } Camera Camera::NewPerspective(const ViewingVolume& volume, const mat4& transform, float fovy) { auto near_and_far = ComputeNearAndFarPlanes(volume, transform); float aspect = volume.width() / volume.height(); mat4 projection = glm::perspectiveRH(fovy, aspect, near_and_far.first, near_and_far.second); // glm::perspectiveRH() generates "right handed" projection matrices but // since glm is intended to work with OpenGL, glm::perspectiveRH() generates // a matrix that projects a right handed space into OpenGL's left handed NDC // space. In order to make it project a right handed space into Vulkan's // right handed NDC space we must flip it again. Note that this is equivilent // to calling glm::perspectiveLH with the same arguments and rotating the // resulting matrix 180 degrees around the X axis. projection = glm::scale(projection, glm::vec3(1.f, -1.f, 1.f)); return Camera(transform, projection); } vk::Rect2D Camera::Viewport::vk_rect_2d(uint32_t fb_width, uint32_t fb_height) const { vk::Rect2D result; result.offset.x = x * fb_width; result.offset.y = y * fb_height; result.extent.width = width * fb_width; result.extent.height = height * fb_height; return result; } } // namespace escher
43.090278
80
0.675262
[ "vector", "transform" ]
0496e3fd95d560aa3ca1c724eb5cd3b2021c1484
4,922
cpp
C++
tests/src/test_AlignerBatchCPU.cpp
ahehn-nv/pancake
273a035d3b858256d0847f773f6fa4560c2d37f8
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
null
null
null
tests/src/test_AlignerBatchCPU.cpp
ahehn-nv/pancake
273a035d3b858256d0847f773f6fa4560c2d37f8
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
null
null
null
tests/src/test_AlignerBatchCPU.cpp
ahehn-nv/pancake
273a035d3b858256d0847f773f6fa4560c2d37f8
[ "BSD-3-Clause-Clear", "BSL-1.0", "BSD-3-Clause", "MIT" ]
null
null
null
#include <PancakeTestData.h> #include <gtest/gtest.h> #include <pacbio/pancake/AlignerBatchCPU.h> #include <pacbio/pancake/AlignerFactory.h> #include <pacbio/pancake/AlignmentParameters.h> #include <iostream> #include "TestHelperUtils.h" TEST(AlignerBatchCPU, ArrayOfTests_Small) { using namespace PacBio::Pancake; struct TestData { std::string testName; // Tuple: <query, target, isGlobal> std::vector<std::tuple<std::string, std::string, bool>> batchData; int32_t numThreads; std::vector<PacBio::Pancake::AlignmentResult> expectedAlns; }; // clang-format off std::vector<TestData> testData = { { "Batch of multiple query/target pairs.", { // Global alignment. {"ACTGACTGAC", "ACTGTCTGAC", true}, {"ACTG", "ACTG", true}, {"A", "T", true}, // Extension alignment. {"AAAAAAAAAAAAAAAAAAAACCCCCACCCCCCCCCCCCCCCCCCCCCCCCC", "AAAAAAAAAAAAAAAAAAAAGGGGGAGGGGGGGGGGGGGGGGGGGGGGGGG", false}, }, 4, // Expected results. { PacBio::Pancake::AlignmentResult{PacBio::BAM::Cigar("4=1X5="), 10, 10, 10, 10, true, 14, 14, false, Alignment::DiffCounts(9, 1, 0, 0)}, PacBio::Pancake::AlignmentResult{PacBio::BAM::Cigar("4="), 4, 4, 4, 4, true, 8, 8, false, Alignment::DiffCounts(4, 0, 0, 0)}, PacBio::Pancake::AlignmentResult{PacBio::BAM::Cigar("1X"), 1, 1, 1, 1, true, -4, -4, false, Alignment::DiffCounts(0, 1, 0, 0)}, PacBio::Pancake::AlignmentResult{PacBio::BAM::Cigar("20="), 20, 20, 19, 19, true, 40, 40, true, Alignment::DiffCounts(20, 0, 0, 0)}, }, }, { "Empty batch.", { }, 4, // Expected results. { }, }, { "Another batch of edge cases.", { // Global alignment. {"", "", true}, {"A", "", true}, {"", "A", true}, {"A", "T", true}, }, 4, // Expected results. { PacBio::Pancake::AlignmentResult{PacBio::BAM::Cigar(""), 0, 0, 0, 0, false, 0, 0, false, Alignment::DiffCounts(0, 0, 0, 0)}, PacBio::Pancake::AlignmentResult{PacBio::BAM::Cigar("1I"), 1, 0, 1, 0, true, -4, -4, false, Alignment::DiffCounts(0, 0, 1, 0)}, PacBio::Pancake::AlignmentResult{PacBio::BAM::Cigar("1D"), 0, 1, 0, 1, true, -4, -4, false, Alignment::DiffCounts(0, 0, 0, 1)}, PacBio::Pancake::AlignmentResult{PacBio::BAM::Cigar("1X"), 1, 1, 1, 1, true, -4, -4, false, Alignment::DiffCounts(0, 1, 0, 0)}, }, }, }; // clang-format on // Alignment parameters. PacBio::Pancake::AlignerType alignerTypeGlobal = AlignerType::EDLIB; PacBio::Pancake::AlignmentParameters alnParamsGlobal; PacBio::Pancake::AlignerType alignerTypeExt = AlignerType::KSW2; PacBio::Pancake::AlignmentParameters alnParamsExt; // These parameters are the same as current defaults, but they are specified here in case // the defaults ever change, so that the test doesn't have to be updated. alnParamsGlobal.zdrop = 100; alnParamsGlobal.zdrop2 = 500; alnParamsGlobal.alignBandwidth = 500; alnParamsGlobal.endBonus = 50; alnParamsGlobal.matchScore = 2; alnParamsGlobal.mismatchPenalty = 4; alnParamsGlobal.gapOpen1 = 4; alnParamsGlobal.gapExtend1 = 2; alnParamsGlobal.gapOpen2 = 24; alnParamsGlobal.gapExtend2 = 1; alnParamsExt = alnParamsGlobal; for (const auto& data : testData) { // Debug info. SCOPED_TRACE(data.testName); std::cerr << "testName = " << data.testName << "\n"; PacBio::Pancake::AlignerBatchCPU aligner(data.numThreads, alignerTypeGlobal, alnParamsGlobal, alignerTypeExt, alnParamsExt); for (const auto& seqPair : data.batchData) { const auto& query = std::get<0>(seqPair); const auto& target = std::get<1>(seqPair); const bool isGlobal = std::get<2>(seqPair); aligner.AddSequencePair(query.c_str(), query.size(), target.c_str(), target.size(), isGlobal); } // Run alignment. aligner.AlignAll(); const std::vector<PacBio::Pancake::AlignmentResult>& results = aligner.GetAlnResults(); // std::cerr << "results.size() = " << results.size() << "\n"; // for (size_t i = 0; i < results.size(); ++i) { // const auto& aln = results[i]; // std::cerr << "[result " << i << "] " << aln << "\n"; // } // Evaluate. ASSERT_EQ(data.expectedAlns, results); } }
40.01626
151
0.552011
[ "vector" ]
04977c93d0ea5eef41a7a524d90c7427230c027c
1,880
cpp
C++
liver/test/fill_liver_test.cpp
ncrookston/liver_source
9876ac4e9ea57d8e23767af9be061a9b10c6f1e5
[ "BSL-1.0" ]
null
null
null
liver/test/fill_liver_test.cpp
ncrookston/liver_source
9876ac4e9ea57d8e23767af9be061a9b10c6f1e5
[ "BSL-1.0" ]
null
null
null
liver/test/fill_liver_test.cpp
ncrookston/liver_source
9876ac4e9ea57d8e23767af9be061a9b10c6f1e5
[ "BSL-1.0" ]
null
null
null
#include "liver/fill_liver_volume.hpp" #include "shape/box.hpp" #define CATCH_CONFIG_MAIN #include <catch.hpp> #include <fmt/ostream.h> #include <range/v3/all.hpp> using namespace jhmi; TEST_CASE( "Lobules two ways", "[fill_liver_volume]" ) { auto shape = box{m3{}, dbl3{1,1,1} * 18_mm}; auto lob1 = std::vector<m3>{}; for_lobule(shape, [&](m3 const& pt, int3 const&) { lob1.push_back(pt); }); auto lob2 = lobules_in(shape); RANGES_FOR(auto z, ranges::view::zip(lob1, lob2)) REQUIRE(distance(z.first - z.second).value() < 1e-16); } #if 0 TEST_CASE( "Portal tracts two ways", "[fill_liver_volume]" ) { auto shape = box{m3{}, dbl3{1,1,1} * 18_mm}; auto tract1 = std::vector<m3>{}; for_portal_tract(shape, [&](m3 const& pt, int3 const&) { tract1.push_back(pt); }); auto tract2 = tracts_in(shape); RANGES_FOR(auto z, ranges::view::zip(tract1, tract2)) REQUIRE(distance(z.first - z.second).value() < 1e-16); } #endif TEST_CASE( "Lobule near", "[fill_liver_volume]") { auto shape = box{m3{}, dbl3{1,1,1} * 18_mm}; auto lobules = std::map<int3,m3>{}; for_lobule(shape, [&](m3 const& pt, int3 const& ipt) { lobules[ipt] = pt; }); auto pts = ranges::view::ints(2,35); RANGES_FOR(double i, pts) { auto near = find_near_lobule(shape, i * dbl3{1,1,1} * .5_mm); REQUIRE(near); REQUIRE(distance(near->first - lobules[near->second]).value() < 1e-16); } } TEST_CASE( "Tract near", "[fill_liver_volume]") { auto shape = box{m3{}, dbl3{1,1,1} * 18_mm}; auto tracts = std::map<int3,m3>{}; for_portal_tract(shape, [&](m3 const& pt, int3 const& ipt) { tracts[ipt] = pt; }); auto pts = ranges::view::ints(2,35); RANGES_FOR(double i, pts) { auto near = find_near_tract(shape, i * dbl3{1,1,1} * .5_mm); REQUIRE(near); REQUIRE(distance(near->first - tracts[near->second]).value() < 1e-16); } }
28.059701
75
0.632447
[ "shape", "vector" ]
049c0b63119ed1d3e0cd5400602c56a6ec6bb35f
8,359
cpp
C++
src/capture_checkerboard.cpp
hongtaowu67/checkerboard_ros
c58c1a939cb55e0ca6dc4e5ec6b54fba30182cd0
[ "MIT" ]
3
2020-06-02T19:50:54.000Z
2020-09-18T04:38:59.000Z
src/capture_checkerboard.cpp
hongtaowu67/checkerboard_ros
c58c1a939cb55e0ca6dc4e5ec6b54fba30182cd0
[ "MIT" ]
null
null
null
src/capture_checkerboard.cpp
hongtaowu67/checkerboard_ros
c58c1a939cb55e0ca6dc4e5ec6b54fba30182cd0
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <ros/ros.h> #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/calib3d.hpp> #include "capture_checkerboard.h" using namespace std; using namespace sensor_msgs; using namespace message_filters; using namespace cv; using std::vector; void CapturePoseCheckerboard::setCameraInfo(const CameraInfoConstPtr& cam_info) { if (use_rect) // rgb is rectified { intrinsic_matrix.at<double>(0,0) = cam_info->P[0]; intrinsic_matrix.at<double>(0,1) = cam_info->P[1]; intrinsic_matrix.at<double>(0,2) = cam_info->P[2]; intrinsic_matrix.at<double>(1,0) = cam_info->P[4]; intrinsic_matrix.at<double>(1,1) = cam_info->P[5]; intrinsic_matrix.at<double>(1,2) = cam_info->P[6]; intrinsic_matrix.at<double>(2,0) = cam_info->P[8]; intrinsic_matrix.at<double>(2,1) = cam_info->P[9]; intrinsic_matrix.at<double>(2,2) = cam_info->P[10]; dist_coeff = Mat::zeros ( 1,5,CV_32F ); } else // rgb is not raw { intrinsic_matrix.at<double>(0,0) = cam_info->K[0]; intrinsic_matrix.at<double>(0,1) = cam_info->K[1]; intrinsic_matrix.at<double>(0,2) = cam_info->K[2]; intrinsic_matrix.at<double>(1,0) = cam_info->K[3]; intrinsic_matrix.at<double>(1,1) = cam_info->K[4]; intrinsic_matrix.at<double>(1,2) = cam_info->K[5]; intrinsic_matrix.at<double>(2,0) = cam_info->K[6]; intrinsic_matrix.at<double>(2,1) = cam_info->K[7]; intrinsic_matrix.at<double>(2,2) = cam_info->K[8]; cam_model.fromCameraInfo ( cam_info ); dist_coeff = Mat ( cam_model.distortionCoeffs() ); } } void CapturePoseCheckerboard::callBack( const ImageConstPtr& rgb, const CameraInfoConstPtr& cam_info ) { if (ros::ok()) { setCameraInfo(cam_info); // set camera_info input_bridge = cv_bridge::toCvCopy( rgb, image_encodings::MONO8 ); image_grey = input_bridge->image; int flags = 0; if ( adaptive_thresh ) flags += CV_CALIB_CB_ADAPTIVE_THRESH; if ( normalize_image ) flags += CV_CALIB_CB_NORMALIZE_IMAGE; if ( filter_quads ) flags += CV_CALIB_CB_FILTER_QUADS; if ( fast_check ) flags += CALIB_CB_FAST_CHECK; bool patternfound = findChessboardCorners ( image_grey, patternsize, image_corners, flags ); if ( patternfound ) { cv::cornerSubPix( image_grey, image_corners, Size(subpixelfit_window_size, subpixelfit_window_size), Size(-1, -1), TermCriteria(CV_TERMCRIT_EPS + CV_TERMCRIT_ITER, 30, 0.1)); cv::solvePnP( object_corners, image_corners, cv::Mat( intrinsic_matrix, cv::Rect(0, 0, 3, 3) ), dist_coeff, rotation_vec, translation_vec ); extrinsic_matrix = cv::Mat_<double>::eye (4, 4); extrinsic_matrix(0, 3) = translation_vec(0); extrinsic_matrix(1, 3) = translation_vec(1); extrinsic_matrix(2, 3) = translation_vec(2); Rodrigues ( rotation_vec, cv::Mat( extrinsic_matrix, cv::Rect(0, 0, 3, 3)), noArray() ); projection_matrix = intrinsic_matrix * extrinsic_matrix; // generate tf model to camera R_check = tf::Matrix3x3 ( extrinsic_matrix( 0, 0 ), extrinsic_matrix( 0, 1 ), extrinsic_matrix( 0, 2 ), extrinsic_matrix( 1, 0 ), extrinsic_matrix( 1, 1 ), extrinsic_matrix( 1, 2 ), extrinsic_matrix( 2, 0 ), extrinsic_matrix( 2, 1 ), extrinsic_matrix( 2, 2 ) ); t_check = tf::Vector3 ( translation_vec ( 0 ), translation_vec ( 1 ), translation_vec ( 2 ) ); transform_check = tf::Transform ( R_check, t_check ); q_check = transform_check.getRotation(); // Publish check pose pose_check.header = rgb->header; pose_check.pose.orientation.x = q_check.x(); pose_check.pose.orientation.y = q_check.y(); pose_check.pose.orientation.z = q_check.z(); pose_check.pose.orientation.w = q_check.w(); pose_check.pose.position.x = t_check.x(); pose_check.pose.position.y = t_check.y(); pose_check.pose.position.z = t_check.z(); check_pose_pub.publish(pose_check); // Deubgging the output rotation matrix of the cam pose // std::cout << "Cam Rotation" << std::endl << R_cam[0][0] << " " << R_cam[0][1] << " " << R_cam[0][2] << std::endl // << R_cam[1][0] << " " << R_cam[1][1] << " " << R_cam[1][2] << std::endl // << R_cam[2][0] << " " << R_cam[2][1] << " " << R_cam[2][2] << std::endl; // std::cout << "Cam Translation" << std::endl << t_cam.x() << " " << t_cam.y() << " " << t_cam.z() << std::endl; double nr_of_square = std::max ( col_num, row_num ); double size = square_size * nr_of_square; int font = cv::FONT_HERSHEY_SIMPLEX; double fontScale = 1.0; double thickness = 1.0; double lineType = CV_AA; double lineThickness = 3; input_bridge = cv_bridge::toCvCopy( rgb, image_encodings::BGR8 ); // ROS_INFO("Finish converting to BGR...\n"); image_rgb = input_bridge->image; cv::Mat_<double> Pi0 = projection_matrix * ( cv::Mat_<double> ( 4,1 ) << 0, 0, 0, 1 ); cv::Point2d pi0 ( Pi0 ( 0,0 ) / Pi0 ( 0,2 ), Pi0 ( 0,1 ) / Pi0 ( 0,2 ) ); cv::circle ( image_rgb, pi0, 3, CV_RGB ( 255,255,255 ) ); cv::Mat_<double> Pi1 = projection_matrix * ( cv::Mat_<double> ( 4,1 ) << size, 0, 0, 1 );; cv::Point2d pi1 ( Pi1 ( 0,0 ) / Pi1 ( 0,2 ), Pi1 ( 0,1 ) / Pi1 ( 0,2 ) ); cv::circle ( image_rgb, pi1, 3, CV_RGB ( 255,0,0 ) ); putText ( image_rgb, "X", pi1, font, fontScale, CV_RGB ( 255,0,0 ), thickness, CV_AA ); cv::line ( image_rgb, pi0, pi1, CV_RGB ( 255,0,0 ), lineThickness ); cv::Mat_<double> Pi2 = projection_matrix * ( cv::Mat_<double> ( 4,1 ) << 0, size, 0, 1 ); cv::Point2d pi2 ( Pi2 ( 0,0 ) / Pi2 ( 0,2 ), Pi2 ( 0,1 ) / Pi2 ( 0,2 ) ); cv::circle ( image_rgb, pi2, 3, CV_RGB ( 0,255,0 ) ); putText ( image_rgb, "Y", pi2, font, fontScale, CV_RGB ( 0,255,0 ), thickness, CV_AA ); cv::line ( image_rgb, pi0, pi2, CV_RGB ( 0,255,0 ), lineThickness ); cv::Mat_<double> Pi3 = projection_matrix * ( cv::Mat_<double> ( 4,1 ) << 0, 0, size, 1 ); cv::Point2d pi3 ( Pi3 ( 0,0 ) / Pi3 ( 0,2 ), Pi3 ( 0,1 ) / Pi3 ( 0,2 ) ); cv::circle ( image_rgb, pi3, 3, CV_RGB ( 0,0,255 ) ); putText ( image_rgb, "Z", pi3, font, fontScale, CV_RGB ( 0,0,255 ) , thickness, CV_AA ); cv::line ( image_rgb, pi0, pi3, CV_RGB ( 0,0,255 ), lineThickness ); drawChessboardCorners ( image_rgb, patternsize, Mat ( image_corners ), patternfound ); // Publish pose estimation result pose_result_msg = cv_bridge::CvImage(std_msgs::Header(), "bgr8", image_rgb).toImageMsg(); pose_result_msg->header = rgb->header; pose_result_pub.publish(pose_result_msg); } else { ROS_INFO("Cannot find all the corners of the chessboard..."); } } } int main( int argc, char** argv ) { ros::init( argc, argv, "capture" ); string check_pose_topic = "/capture/pose_check"; string pose_result_topic = "/capture/pose_result"; // // PrimeSense // string rgb_topic = "/camera/rgb/image_rect_color"; // string rgb_cam_info_topic = "/camera/rgb/camera_info"; // Intel Realsense string rgb_topic = "/camera/color/image_raw"; string rgb_cam_info_topic = "/camera/color/camera_info"; bool use_rect = true; CapturePoseCheckerboard CPC(check_pose_topic, pose_result_topic, rgb_topic, rgb_cam_info_topic, use_rect); ros::spin(); return 0; }
45.429348
165
0.578179
[ "vector", "model", "transform" ]
049c6503f493af07032c274a6be2f493d5ec4074
952
cpp
C++
examples/example_or_get.cpp
alipha/streamer
5ce6e19ea517dd201a946bd83ba1732b769c84d3
[ "MIT" ]
null
null
null
examples/example_or_get.cpp
alipha/streamer
5ce6e19ea517dd201a946bd83ba1732b769c84d3
[ "MIT" ]
null
null
null
examples/example_or_get.cpp
alipha/streamer
5ce6e19ea517dd201a946bd83ba1732b769c84d3
[ "MIT" ]
null
null
null
#include "../streamer/streamer.hpp" #include "../streamer/optional.hpp" #include <cassert> #include <vector> /* * or_get(UnaryFunc) operates on a std::optional and returns either the value the * std::optional contains, or calls the UnaryFunc passed to or_default if the std::optional is * empty, and returns the UnaryFunc's result. */ void example_or_get() { using namespace streamer; std::vector<int> input = {15, 23, 4}; std::vector<int> empty_input = {}; int count = 0; int count2 = 0; int result = input >> first >> or_get([&count]() { count++; return 999; }); int result2 = input % first % or_get([&count]() { count++; return 999; }); int result3 = empty_input | first() | or_get([&count2]() { count2++; return 999; }); assert(result == 15); assert(result2 == 15); assert(result3 == 999); assert(count == 0); assert(count2 == 1); }
25.72973
94
0.595588
[ "vector" ]
049c900b95e22f0f1d7a9008d33dcbc5c729b2e8
8,033
cpp
C++
src/mbgl/annotation/annotation_manager.cpp
kravtsun/mapbox-gl-native
ea8ec38df156c6683c886253dbb1f6bc828686ff
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/annotation/annotation_manager.cpp
kravtsun/mapbox-gl-native
ea8ec38df156c6683c886253dbb1f6bc828686ff
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/annotation/annotation_manager.cpp
kravtsun/mapbox-gl-native
ea8ec38df156c6683c886253dbb1f6bc828686ff
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include <mbgl/annotation/annotation_manager.hpp> #include <mbgl/annotation/annotation_source.hpp> #include <mbgl/annotation/annotation_tile.hpp> #include <mbgl/annotation/symbol_annotation_impl.hpp> #include <mbgl/annotation/line_annotation_impl.hpp> #include <mbgl/annotation/fill_annotation_impl.hpp> #include <mbgl/annotation/style_sourced_annotation_impl.hpp> #include <mbgl/style/style.hpp> #include <mbgl/style/layers/symbol_layer.hpp> #include <mbgl/style/layers/symbol_layer_impl.hpp> #include <mbgl/storage/file_source.hpp> #include <boost/function_output_iterator.hpp> namespace mbgl { using namespace style; const std::string AnnotationManager::SourceID = "com.mapbox.annotations"; const std::string AnnotationManager::PointLayerID = "com.mapbox.annotations.points"; AnnotationManager::AnnotationManager(float pixelRatio) : spriteAtlas({ 1024, 1024 }, pixelRatio) { // This is a special atlas, holding only images added via addIcon, so we always treat it as // loaded. spriteAtlas.markAsLoaded(); } AnnotationManager::~AnnotationManager() = default; AnnotationID AnnotationManager::addAnnotation(const Annotation& annotation, const uint8_t maxZoom) { AnnotationID id = nextID++; Annotation::visit(annotation, [&] (const auto& annotation_) { this->add(id, annotation_, maxZoom); }); return id; } Update AnnotationManager::updateAnnotation(const AnnotationID& id, const Annotation& annotation, const uint8_t maxZoom) { return Annotation::visit(annotation, [&] (const auto& annotation_) { return this->update(id, annotation_, maxZoom); }); } void AnnotationManager::removeAnnotation(const AnnotationID& id) { if (symbolAnnotations.find(id) != symbolAnnotations.end()) { symbolTree.remove(symbolAnnotations.at(id)); symbolAnnotations.erase(id); } else if (shapeAnnotations.find(id) != shapeAnnotations.end()) { obsoleteShapeAnnotationLayers.insert(shapeAnnotations.at(id)->layerID); shapeAnnotations.erase(id); } else { assert(false); // Should never happen } } void AnnotationManager::add(const AnnotationID& id, const SymbolAnnotation& annotation, const uint8_t) { auto impl = std::make_shared<SymbolAnnotationImpl>(id, annotation); symbolTree.insert(impl); symbolAnnotations.emplace(id, impl); } void AnnotationManager::add(const AnnotationID& id, const LineAnnotation& annotation, const uint8_t maxZoom) { ShapeAnnotationImpl& impl = *shapeAnnotations.emplace(id, std::make_unique<LineAnnotationImpl>(id, annotation, maxZoom)).first->second; obsoleteShapeAnnotationLayers.erase(impl.layerID); } void AnnotationManager::add(const AnnotationID& id, const FillAnnotation& annotation, const uint8_t maxZoom) { ShapeAnnotationImpl& impl = *shapeAnnotations.emplace(id, std::make_unique<FillAnnotationImpl>(id, annotation, maxZoom)).first->second; obsoleteShapeAnnotationLayers.erase(impl.layerID); } void AnnotationManager::add(const AnnotationID& id, const StyleSourcedAnnotation& annotation, const uint8_t maxZoom) { ShapeAnnotationImpl& impl = *shapeAnnotations.emplace(id, std::make_unique<StyleSourcedAnnotationImpl>(id, annotation, maxZoom)).first->second; obsoleteShapeAnnotationLayers.erase(impl.layerID); } Update AnnotationManager::update(const AnnotationID& id, const SymbolAnnotation& annotation, const uint8_t maxZoom) { Update result = Update::Nothing; auto it = symbolAnnotations.find(id); if (it == symbolAnnotations.end()) { assert(false); // Attempt to update a non-existent symbol annotation return result; } const SymbolAnnotation& existing = it->second->annotation; if (existing.geometry != annotation.geometry) { result |= Update::AnnotationData; } if (existing.icon != annotation.icon) { result |= Update::AnnotationData | Update::AnnotationStyle; } if (result != Update::Nothing) { removeAndAdd(id, annotation, maxZoom); } return result; } Update AnnotationManager::update(const AnnotationID& id, const LineAnnotation& annotation, const uint8_t maxZoom) { auto it = shapeAnnotations.find(id); if (it == shapeAnnotations.end()) { assert(false); // Attempt to update a non-existent shape annotation return Update::Nothing; } removeAndAdd(id, annotation, maxZoom); return Update::AnnotationData | Update::AnnotationStyle; } Update AnnotationManager::update(const AnnotationID& id, const FillAnnotation& annotation, const uint8_t maxZoom) { auto it = shapeAnnotations.find(id); if (it == shapeAnnotations.end()) { assert(false); // Attempt to update a non-existent shape annotation return Update::Nothing; } removeAndAdd(id, annotation, maxZoom); return Update::AnnotationData | Update::AnnotationStyle; } Update AnnotationManager::update(const AnnotationID& id, const StyleSourcedAnnotation& annotation, const uint8_t maxZoom) { auto it = shapeAnnotations.find(id); if (it == shapeAnnotations.end()) { assert(false); // Attempt to update a non-existent shape annotation return Update::Nothing; } removeAndAdd(id, annotation, maxZoom); return Update::AnnotationData | Update::AnnotationStyle; } void AnnotationManager::removeAndAdd(const AnnotationID& id, const Annotation& annotation, const uint8_t maxZoom) { removeAnnotation(id); Annotation::visit(annotation, [&] (const auto& annotation_) { this->add(id, annotation_, maxZoom); }); } std::unique_ptr<AnnotationTileData> AnnotationManager::getTileData(const CanonicalTileID& tileID) { if (symbolAnnotations.empty() && shapeAnnotations.empty()) return nullptr; auto tileData = std::make_unique<AnnotationTileData>(); AnnotationTileLayer& pointLayer = tileData->layers.emplace(PointLayerID, PointLayerID).first->second; LatLngBounds tileBounds(tileID); symbolTree.query(boost::geometry::index::intersects(tileBounds), boost::make_function_output_iterator([&](const auto& val){ val->updateLayer(tileID, pointLayer); })); for (const auto& shape : shapeAnnotations) { shape.second->updateTileData(tileID, *tileData); } return tileData; } void AnnotationManager::updateStyle(Style& style) { // Create annotation source, point layer, and point bucket if (!style.getSource(SourceID)) { style.addSource(std::make_unique<AnnotationSource>()); std::unique_ptr<SymbolLayer> layer = std::make_unique<SymbolLayer>(PointLayerID, SourceID); layer->setSourceLayer(PointLayerID); layer->setIconImage({"{sprite}"}); layer->setIconAllowOverlap(true); layer->setIconIgnorePlacement(true); layer->impl->spriteAtlas = &spriteAtlas; style.addLayer(std::move(layer)); } for (const auto& shape : shapeAnnotations) { shape.second->updateStyle(style); } for (const auto& layer : obsoleteShapeAnnotationLayers) { if (style.getLayer(layer)) { style.removeLayer(layer); } } obsoleteShapeAnnotationLayers.clear(); } void AnnotationManager::updateData() { for (auto& tile : tiles) { tile->setData(getTileData(tile->id.canonical)); } } void AnnotationManager::addTile(AnnotationTile& tile) { tiles.insert(&tile); tile.setData(getTileData(tile.id.canonical)); } void AnnotationManager::removeTile(AnnotationTile& tile) { tiles.erase(&tile); } void AnnotationManager::addImage(const std::string& id, std::unique_ptr<style::Image> image) { spriteAtlas.addImage(id, std::move(image)); } void AnnotationManager::removeImage(const std::string& id) { spriteAtlas.removeImage(id); } double AnnotationManager::getTopOffsetPixelsForImage(const std::string& id) { const style::Image* image = spriteAtlas.getImage(id); return image ? -(image->image.size.height / image->pixelRatio) / 2 : 0; } } // namespace mbgl
35.702222
123
0.717789
[ "geometry", "shape" ]
049eaf46c3da602bd3490e6642862b6317449532
657
cpp
C++
Composite/Composite/Canvas.cpp
AlK2x/OOD
7ce78cfa7708978483f67642d93a8bc2873c2285
[ "MIT" ]
null
null
null
Composite/Composite/Canvas.cpp
AlK2x/OOD
7ce78cfa7708978483f67642d93a8bc2873c2285
[ "MIT" ]
5
2016-03-20T20:28:52.000Z
2016-06-30T18:17:42.000Z
Composite/Composite/Canvas.cpp
AlK2x/OOD
7ce78cfa7708978483f67642d93a8bc2873c2285
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Canvas.h" CCanvas::CCanvas() { } void CCanvas::DrawLine(SPoint a, SPoint b) { std::cout << "Line: " << a << " - " << b << std::endl; } void CCanvas::DrawEllipse(int l, int t, int w, int h) { std::cout << "Draw Ellipse" << std::endl; } void CCanvas::FillEllipse(int l, int t, int w, int h, SColor color) { std::cout << "Fill Ellipse" << std::endl; } void CCanvas::FillPolygon(const std::vector<SPoint>& points, SColor color) { std::cout << "Fill Polygon" << std::endl; } void CCanvas::SetPenColor(SColor color) { } void CCanvas::SetPenThickness(unsigned thinckness) { } void CCanvas::SetFillColor(SColor color) { }
16.425
74
0.649924
[ "vector" ]
049eb24957d39917a5393763369b11a7e1e982a9
4,217
cpp
C++
src/Game/Things/Thing.cpp
CronosTs/phobos3d
c0336456d946f3a9e62fb9b7815831ad32820da5
[ "Zlib" ]
2
2015-01-14T20:20:51.000Z
2015-09-08T15:49:18.000Z
src/Game/Things/Thing.cpp
CronosTs/phobos3d
c0336456d946f3a9e62fb9b7815831ad32820da5
[ "Zlib" ]
null
null
null
src/Game/Things/Thing.cpp
CronosTs/phobos3d
c0336456d946f3a9e62fb9b7815831ad32820da5
[ "Zlib" ]
1
2015-11-03T13:58:58.000Z
2015-11-03T13:58:58.000Z
/* Phobos 3d May 2011 Copyright (c) 2005-2011 Bruno Sanches http://code.google.com/p/phobos3d This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "Phobos/Game/Things/Thing.h" #include <Phobos/Exception.h> #include "Phobos/Game/WorldManager.h" #include "Phobos/Game/Things/SignalManager.h" namespace Phobos { namespace Game { namespace Things { Thing::Thing(const String_t &name, UInt32_t flags): Node(name, flags), fFixedUpdateEnabled(false), fUpdateEnabled(false) { } Thing::Thing(const Char_t *name, UInt32_t flags): Node(name, flags), fFixedUpdateEnabled(false), fUpdateEnabled(false) { } Thing::~Thing() { SignalManager::GetInstance().CancelEvents(*this); if(fFixedUpdateEnabled || fUpdateEnabled) { WorldManager &world = WorldManager::GetInstance(); if(fFixedUpdateEnabled) world.RemoveFromFixedUpdateList(*this); if(fUpdateEnabled) world.RemoveFromUpdateList(*this); } } void Thing::FixedUpdate() { this->OnFixedUpdate(); } void Thing::Update() { this->OnUpdate(); } void Thing::EnableFixedUpdate() { if(fFixedUpdateEnabled) return; WorldManager::GetInstance().AddToFixedUpdateList(*this); fFixedUpdateEnabled = true; } void Thing::EnableUpdate() { if(fUpdateEnabled) return; WorldManager::GetInstance().AddToUpdateList(*this); fUpdateEnabled = true; } void Thing::DisableFixedUpdate() { if(!fFixedUpdateEnabled) return; WorldManager::GetInstance().RemoveFromFixedUpdateList(*this); fFixedUpdateEnabled = false; } void Thing::DisableUpdate() { if(!fUpdateEnabled) return; WorldManager::GetInstance().RemoveFromUpdateList(*this); fUpdateEnabled = false; } #if 0 EntityOutputManager::EntityOutputManager() { //empty } void EntityOutputManager::AddConnector(const String_t &name, OutputProcConnector_t proc) { ConnectorsMap_t::iterator it = mapConnectors.lower_bound(name); if((it != mapConnectors.end()) && (!mapConnectors.key_comp()(name, it->first))) { std::stringstream stream; stream << "Output " << name << " already exists."; PH_RAISE(OBJECT_ALREADY_EXISTS_EXCEPTION, "[EntityOutputManager::AddConnector]", stream.str()); } mapConnectors.insert(it, std::make_pair(name, proc)); } void EntityOutputManager::Connect(EntityIO &outputOwner, const std::string &outputName, EntityIO &inputOwner, InputProc_t input) { ConnectorsMap_t::iterator it = mapConnectors.find(outputName); if(it == mapConnectors.end()) { std::stringstream stream; stream << "Output " << outputName << " not found."; PH_RAISE(OBJECT_NOT_FOUND_EXCEPTION, "[EntityOutputManager::Connect]", stream.str()); } (outputOwner.*(it->second))(inputOwner, input); } EntityInputManager::EntityInputManager() { //empty } void EntityInputManager::AddSlot(const String_t &name, InputProc_t proc) { InputMap_t::iterator it = mapInputs.lower_bound(name); if((it != mapInputs.end()) && (!mapInputs.key_comp()(name, it->first))) { std::stringstream stream; stream << "Output " << name << " already exists."; PH_RAISE(OBJECT_ALREADY_EXISTS_EXCEPTION, "[EntityInputManager::AddSlot]", stream.str()); } mapInputs.insert(it, std::make_pair(name, proc)); } #endif } } }
26.522013
243
0.691487
[ "3d" ]
04a5cad3c0c67a116a756204eeb8576951e4cf98
83,769
cpp
C++
catboost/libs/fstr/shap_values.cpp
LordProtoss/catboost
fc196e25b67a4aacaffc89e23475c4fc4de324d4
[ "Apache-2.0" ]
null
null
null
catboost/libs/fstr/shap_values.cpp
LordProtoss/catboost
fc196e25b67a4aacaffc89e23475c4fc4de324d4
[ "Apache-2.0" ]
null
null
null
catboost/libs/fstr/shap_values.cpp
LordProtoss/catboost
fc196e25b67a4aacaffc89e23475c4fc4de324d4
[ "Apache-2.0" ]
null
null
null
#include "shap_values.h" #include "util.h" #include "shap_exact.h" #include <catboost/private/libs/algo/features_data_helpers.h> #include <catboost/private/libs/algo/index_calcer.h> #include <catboost/libs/data/features_layout.h> #include <catboost/libs/helpers/exception.h> #include <catboost/libs/loggers/logger.h> #include <catboost/libs/logging/profile_info.h> #include <catboost/private/libs/options/restrictions.h> #include <util/generic/algorithm.h> #include <util/generic/cast.h> #include <util/generic/utility.h> #include <util/generic/ymath.h> #include <catboost/libs/model/cpu/quantization.h> using namespace NCB; namespace { struct TFeaturePathElement { int Feature; double ZeroPathsFraction; double OnePathsFraction; double Weight; TFeaturePathElement() = default; TFeaturePathElement(int feature, double zeroPathsFraction, double onePathsFraction, double weight) : Feature(feature) , ZeroPathsFraction(zeroPathsFraction) , OnePathsFraction(onePathsFraction) , Weight(weight) { } }; } //anonymous static TVector<TFeaturePathElement> ExtendFeaturePath( const TVector<TFeaturePathElement>& oldFeaturePath, double zeroPathsFraction, double onePathsFraction, int feature ) { const size_t pathLength = oldFeaturePath.size(); TVector<TFeaturePathElement> newFeaturePath(pathLength + 1); Copy(oldFeaturePath.begin(), oldFeaturePath.begin() + pathLength, newFeaturePath.begin()); const double weight = pathLength == 0 ? 1.0 : 0.0; newFeaturePath[pathLength] = TFeaturePathElement(feature, zeroPathsFraction, onePathsFraction, weight); for (int elementIdx = pathLength - 1; elementIdx >= 0; --elementIdx) { newFeaturePath[elementIdx + 1].Weight += onePathsFraction * newFeaturePath[elementIdx].Weight * (elementIdx + 1) / (pathLength + 1); newFeaturePath[elementIdx].Weight = zeroPathsFraction * newFeaturePath[elementIdx].Weight * (pathLength - elementIdx) / (pathLength + 1); } return newFeaturePath; } static TVector<TFeaturePathElement> UnwindFeaturePath( const TVector<TFeaturePathElement>& oldFeaturePath, size_t eraseElementIdx) { const size_t pathLength = oldFeaturePath.size(); CB_ENSURE(pathLength > 0, "Path to unwind must have at least one element"); TVector<TFeaturePathElement> newFeaturePath( oldFeaturePath.begin(), oldFeaturePath.begin() + pathLength - 1); for (size_t elementIdx = eraseElementIdx; elementIdx < pathLength - 1; ++elementIdx) { newFeaturePath[elementIdx].Feature = oldFeaturePath[elementIdx + 1].Feature; newFeaturePath[elementIdx].ZeroPathsFraction = oldFeaturePath[elementIdx + 1].ZeroPathsFraction; newFeaturePath[elementIdx].OnePathsFraction = oldFeaturePath[elementIdx + 1].OnePathsFraction; } const double onePathsFraction = oldFeaturePath[eraseElementIdx].OnePathsFraction; const double zeroPathsFraction = oldFeaturePath[eraseElementIdx].ZeroPathsFraction; double weightDiff = oldFeaturePath[pathLength - 1].Weight; if (!FuzzyEquals(1 + onePathsFraction, 1 + 0.0)) { for (int elementIdx = pathLength - 2; elementIdx >= 0; --elementIdx) { double oldWeight = newFeaturePath[elementIdx].Weight; newFeaturePath[elementIdx].Weight = weightDiff * pathLength / (onePathsFraction * (elementIdx + 1)); weightDiff = oldWeight - newFeaturePath[elementIdx].Weight * zeroPathsFraction * (pathLength - elementIdx - 1) / pathLength; } } else { for (int elementIdx = pathLength - 2; elementIdx >= 0; --elementIdx) { newFeaturePath[elementIdx].Weight *= pathLength / (zeroPathsFraction * (pathLength - elementIdx - 1)); } } return newFeaturePath; } static void UpdateShapByFeaturePath( const TVector<TFeaturePathElement>& featurePath, const double* leafValuesPtr, size_t leafId, int approxDimension, bool isOblivious, double averageTreeApprox, double conditionFeatureFraction, TVector<TShapValue>* shapValuesInternal ) { const int approxDimOffset = isOblivious ? approxDimension : 1; for (size_t elementIdx = 1; elementIdx < featurePath.size(); ++elementIdx) { const TVector<TFeaturePathElement> unwoundPath = UnwindFeaturePath(featurePath, elementIdx); double weightSum = 0.0; for (const TFeaturePathElement& unwoundPathElement : unwoundPath) { weightSum += unwoundPathElement.Weight; } const TFeaturePathElement& element = featurePath[elementIdx]; const auto sameFeatureShapValue = FindIf( shapValuesInternal->begin(), shapValuesInternal->end(), [element](const TShapValue& shapValue) { return shapValue.Feature == element.Feature; } ); const double coefficient = conditionFeatureFraction * weightSum * (element.OnePathsFraction - element.ZeroPathsFraction); if (sameFeatureShapValue == shapValuesInternal->end()) { shapValuesInternal->emplace_back(element.Feature, approxDimension); for (int dimension = 0; dimension < approxDimension; ++dimension) { double value = coefficient * (leafValuesPtr[leafId * approxDimOffset + dimension] - averageTreeApprox); shapValuesInternal->back().Value[dimension] = value; } } else { for (int dimension = 0; dimension < approxDimension; ++dimension) { double addValue = coefficient * (leafValuesPtr[leafId * approxDimOffset + dimension] - averageTreeApprox); sameFeatureShapValue->Value[dimension] += addValue; } } } } TConditionsFeatureFraction::TConditionsFeatureFraction( const TMaybe<TFixedFeatureParams>& fixedFeatureParams, int combinationClass, double conditionFeatureFraction, double hotCoefficient, double coldCoefficient ) { HotConditionFeatureFraction = conditionFeatureFraction; ColdConditionFeatureFraction = conditionFeatureFraction; if (fixedFeatureParams.Defined() && combinationClass == fixedFeatureParams->Feature) { switch (fixedFeatureParams->FixedFeatureMode) { case TFixedFeatureParams::EMode::FixedOn: { ColdConditionFeatureFraction = 0; break; } case TFixedFeatureParams::EMode::FixedOff: { HotConditionFeatureFraction *= hotCoefficient; ColdConditionFeatureFraction *= coldCoefficient; break; } default: { Y_UNREACHABLE(); } } } } static void ExtendFeaturePathIfFeatureNotFixed( const TMaybe<TFixedFeatureParams>& fixedFeatureParams, const TVector<TFeaturePathElement>& oldFeaturePath, double zeroPathsFraction, double onePathsFraction, int feature, TVector<TFeaturePathElement>* featurePath ) { if (!fixedFeatureParams.Defined() || (fixedFeatureParams->FixedFeatureMode == TFixedFeatureParams::EMode::NotFixed || fixedFeatureParams->Feature != feature)) { *featurePath = ExtendFeaturePath( oldFeaturePath, zeroPathsFraction, onePathsFraction, feature); } else { const size_t pathLength = oldFeaturePath.size(); *featurePath = TVector<TFeaturePathElement>(oldFeaturePath.begin(), oldFeaturePath.begin() + pathLength); } } static void CalcObliviousInternalShapValuesForLeafRecursive( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, size_t documentLeafIdx, size_t treeIdx, int depth, const TVector<TVector<double>>& subtreeWeights, size_t nodeIdx, const TVector<TFeaturePathElement>& oldFeaturePath, double zeroPathsFraction, double onePathsFraction, int feature, bool calcInternalValues, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, const double conditionFeatureFraction, TVector<TShapValue>* shapValuesInternal, double averageTreeApprox ) { if (FuzzyEquals(1.0 + conditionFeatureFraction, 1.0 + 0.0)) { return; } TVector<TFeaturePathElement> featurePath; ExtendFeaturePathIfFeatureNotFixed( fixedFeatureParams, oldFeaturePath, zeroPathsFraction, onePathsFraction, feature, &featurePath ); if (depth == forest.GetTreeSizes()[treeIdx]) { UpdateShapByFeaturePath( featurePath, forest.GetFirstLeafPtrForTree(treeIdx), nodeIdx, forest.GetDimensionsCount(), /*isOblivious*/ true, averageTreeApprox, conditionFeatureFraction, shapValuesInternal ); } else { double newZeroPathsFraction = 1.0; double newOnePathsFraction = 1.0; const size_t remainingDepth = forest.GetTreeSizes()[treeIdx] - depth - 1; const int combinationClass = binFeatureCombinationClass[ forest.GetTreeSplits()[forest.GetTreeStartOffsets()[treeIdx] + remainingDepth] ]; const auto sameFeatureElement = FindIf( featurePath.begin(), featurePath.end(), [combinationClass](const TFeaturePathElement& element) { return element.Feature == combinationClass; } ); if (sameFeatureElement != featurePath.end()) { const size_t sameFeatureIndex = sameFeatureElement - featurePath.begin(); newZeroPathsFraction = featurePath[sameFeatureIndex].ZeroPathsFraction; newOnePathsFraction = featurePath[sameFeatureIndex].OnePathsFraction; featurePath = UnwindFeaturePath(featurePath, sameFeatureIndex); } const bool isGoRight = (documentLeafIdx >> remainingDepth) & 1; const size_t goNodeIdx = nodeIdx * 2 + isGoRight; const size_t skipNodeIdx = nodeIdx * 2 + !isGoRight; const double hotCoefficient = subtreeWeights[depth + 1][goNodeIdx] / subtreeWeights[depth][nodeIdx]; const double coldCoefficient = subtreeWeights[depth + 1][skipNodeIdx] / subtreeWeights[depth][nodeIdx]; TConditionsFeatureFraction conditionsFeatureFraction{ fixedFeatureParams, combinationClass, conditionFeatureFraction, hotCoefficient, coldCoefficient }; if (!FuzzyEquals(1 + subtreeWeights[depth + 1][goNodeIdx], 1 + 0.0)) { double newZeroPathsFractionGoNode = newZeroPathsFraction * hotCoefficient; CalcObliviousInternalShapValuesForLeafRecursive( forest, binFeatureCombinationClass, documentLeafIdx, treeIdx, depth + 1, subtreeWeights, goNodeIdx, featurePath, newZeroPathsFractionGoNode, newOnePathsFraction, combinationClass, calcInternalValues, fixedFeatureParams, conditionsFeatureFraction.HotConditionFeatureFraction, shapValuesInternal, averageTreeApprox ); } if (!FuzzyEquals(1 + subtreeWeights[depth + 1][skipNodeIdx], 1 + 0.0)) { double newZeroPathsFractionSkipNode = newZeroPathsFraction * coldCoefficient; CalcObliviousInternalShapValuesForLeafRecursive( forest, binFeatureCombinationClass, documentLeafIdx, treeIdx, depth + 1, subtreeWeights, skipNodeIdx, featurePath, newZeroPathsFractionSkipNode, /*onePathFraction*/ 0, combinationClass, calcInternalValues, fixedFeatureParams, conditionsFeatureFraction.ColdConditionFeatureFraction, shapValuesInternal, averageTreeApprox ); } } } static void CalcNonObliviousInternalShapValuesForLeafRecursive( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, const TVector<bool>& mapNodeIdToIsGoRight, size_t treeIdx, int depth, const TVector<TVector<double>>& subtreeWeights, size_t nodeIdx, const TVector<TFeaturePathElement>& oldFeaturePath, double zeroPathsFraction, double onePathsFraction, int feature, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, const double conditionFeatureFraction, bool calcInternalValues, TVector<TShapValue>* shapValuesInternal, double averageTreeApprox ) { if (FuzzyEquals(1.0 + conditionFeatureFraction, 1.0 + 0.0)) { return; } TVector<TFeaturePathElement> featurePath; ExtendFeaturePathIfFeatureNotFixed( fixedFeatureParams, oldFeaturePath, zeroPathsFraction, onePathsFraction, feature, &featurePath ); const auto& node = forest.GetNonSymmetricStepNodes()[nodeIdx]; const size_t startOffset = forest.GetTreeStartOffsets()[treeIdx]; size_t goNodeIdx; size_t skipNodeIdx; if (mapNodeIdToIsGoRight[nodeIdx - startOffset]) { goNodeIdx = nodeIdx + node.RightSubtreeDiff; skipNodeIdx = nodeIdx + node.LeftSubtreeDiff; } else { goNodeIdx = nodeIdx + node.LeftSubtreeDiff; skipNodeIdx = nodeIdx + node.RightSubtreeDiff; } // goNodeIdx == nodeIdx mean that nodeIdx is a terminal node for // observed object. That's why we should update shap here. // Similary for skipNodeIdx. if (goNodeIdx == nodeIdx || skipNodeIdx == nodeIdx) { UpdateShapByFeaturePath( featurePath, &forest.GetLeafValues()[0], forest.GetNonSymmetricNodeIdToLeafId()[nodeIdx], forest.GetDimensionsCount(), /*isOblivious*/ false, averageTreeApprox, conditionFeatureFraction, shapValuesInternal ); } double newZeroPathsFraction = 1.0; double newOnePathsFraction = 1.0; const int combinationClass = binFeatureCombinationClass[ forest.GetTreeSplits()[nodeIdx] ]; const auto sameFeatureElement = FindIf( featurePath.begin(), featurePath.end(), [combinationClass](const TFeaturePathElement& element) { return element.Feature == combinationClass; } ); if (sameFeatureElement != featurePath.end()) { const size_t sameFeatureIndex = sameFeatureElement - featurePath.begin(); newZeroPathsFraction = featurePath[sameFeatureIndex].ZeroPathsFraction; newOnePathsFraction = featurePath[sameFeatureIndex].OnePathsFraction; featurePath = UnwindFeaturePath(featurePath, sameFeatureIndex); } const double hotCoefficient = goNodeIdx != nodeIdx ? subtreeWeights[0][goNodeIdx - startOffset] / subtreeWeights[0][nodeIdx - startOffset] : -1.0; const double coldCoefficient = skipNodeIdx != nodeIdx ? subtreeWeights[0][skipNodeIdx - startOffset] / subtreeWeights[0][nodeIdx - startOffset] : -1.0; TConditionsFeatureFraction conditionsFeatureFraction { fixedFeatureParams, combinationClass, conditionFeatureFraction, hotCoefficient, coldCoefficient }; if (goNodeIdx != nodeIdx && !FuzzyEquals(1 + subtreeWeights[0][goNodeIdx - startOffset], 1 + 0.0)) { double newZeroPathsFractionGoNode = newZeroPathsFraction * hotCoefficient; CalcNonObliviousInternalShapValuesForLeafRecursive( forest, binFeatureCombinationClass, mapNodeIdToIsGoRight, treeIdx, depth + 1, subtreeWeights, goNodeIdx, featurePath, newZeroPathsFractionGoNode, newOnePathsFraction, combinationClass, fixedFeatureParams, conditionsFeatureFraction.HotConditionFeatureFraction, calcInternalValues, shapValuesInternal, averageTreeApprox ); } if (skipNodeIdx != nodeIdx && !FuzzyEquals(1 + subtreeWeights[0][skipNodeIdx - startOffset], 1 + 0.0)) { double newZeroPathsFractionSkipNode = newZeroPathsFraction * coldCoefficient; CalcNonObliviousInternalShapValuesForLeafRecursive( forest, binFeatureCombinationClass, mapNodeIdToIsGoRight, treeIdx, depth + 1, subtreeWeights, skipNodeIdx, featurePath, newZeroPathsFractionSkipNode, /*onePathFraction*/ 0, combinationClass, fixedFeatureParams, conditionsFeatureFraction.ColdConditionFeatureFraction, calcInternalValues, shapValuesInternal, averageTreeApprox ); } } static void UnpackInternalShaps(const TVector<TShapValue>& shapValuesInternal, const TVector<TVector<int>>& combinationClassFeatures, TVector<TShapValue>* shapValues) { shapValues->clear(); if (shapValuesInternal.empty()) { return; } const int approxDimension = shapValuesInternal[0].Value.ysize(); for (const auto & shapValueInternal: shapValuesInternal) { const TVector<int> &flatFeatures = combinationClassFeatures[shapValueInternal.Feature]; for (int flatFeatureIdx : flatFeatures) { const auto sameFeatureShapValue = FindIf( shapValues->begin(), shapValues->end(), [flatFeatureIdx](const TShapValue &shapValue) { return shapValue.Feature == flatFeatureIdx; } ); double coefficient = flatFeatures.size(); if (sameFeatureShapValue == shapValues->end()) { shapValues->emplace_back(flatFeatureIdx, approxDimension); for (int dimension = 0; dimension < approxDimension; ++dimension) { double value = shapValueInternal.Value[dimension] / coefficient; shapValues->back().Value[dimension] = value; } } else { for (int dimension = 0; dimension < approxDimension; ++dimension) { double addValue = shapValueInternal.Value[dimension] / coefficient; sameFeatureShapValue->Value[dimension] += addValue; } } } } } static inline void CalcObliviousShapValuesForLeaf( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, const TVector<TVector<int>>& combinationClassFeatures, size_t documentLeafIdx, size_t treeIdx, const TVector<TVector<double>>& subtreeWeights, bool calcInternalValues, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, TVector<TShapValue>* shapValues, double averageTreeApprox ) { shapValues->clear(); if (calcInternalValues) { CalcObliviousInternalShapValuesForLeafRecursive( forest, binFeatureCombinationClass, documentLeafIdx, treeIdx, /*depth*/ 0, subtreeWeights, /*nodeIdx*/ 0, /*initialFeaturePath*/ {}, /*zeroPathFraction*/ 1, /*onePathFraction*/ 1, /*feature*/ -1, calcInternalValues, fixedFeatureParams, /*conditionFeatureFraction*/ 1, shapValues, averageTreeApprox ); } else { TVector<TShapValue> shapValuesInternal; CalcObliviousInternalShapValuesForLeafRecursive( forest, binFeatureCombinationClass, documentLeafIdx, treeIdx, /*depth*/ 0, subtreeWeights, /*nodeIdx*/ 0, /*initialFeaturePath*/ {}, /*zeroPathFraction*/ 1, /*onePathFraction*/ 1, /*feature*/ -1, calcInternalValues, fixedFeatureParams, /*conditionFeatureFraction*/ 1, &shapValuesInternal, averageTreeApprox ); UnpackInternalShaps(shapValuesInternal, combinationClassFeatures, shapValues); } } static void CalcObliviousApproximateShapValuesForLeafImplementation( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, size_t documentLeafIdx, size_t treeIdx, const TVector<TVector<TVector<double>>>& subtreeValues, TVector<TShapValue>* shapValues ) { const size_t approxDimension = forest.GetDimensionsCount(); size_t treeSize = forest.GetTreeSizes()[treeIdx]; size_t nodeIdx = 0; for (size_t depth = 0; depth < treeSize; ++depth) { size_t remainingDepth = treeSize - depth - 1; const bool isGoRight = (documentLeafIdx >> remainingDepth) & 1; const size_t goNodeIdx = nodeIdx * 2 + isGoRight; const int combinationClass = binFeatureCombinationClass[ forest.GetTreeSplits()[forest.GetTreeStartOffsets()[treeIdx] + remainingDepth] ]; const auto FeatureShapValue = FindIf( shapValues->begin(), shapValues->end(), [combinationClass](const TShapValue &shapValue) { return shapValue.Feature == combinationClass; } ); auto newFeatureShapValue = shapValues->end(); if (FeatureShapValue == shapValues->end()) { shapValues->emplace_back(combinationClass, approxDimension); newFeatureShapValue = shapValues->end() - 1; } else { newFeatureShapValue = FeatureShapValue; } for (size_t dimension = 0; dimension < approxDimension; ++dimension) { newFeatureShapValue->Value[dimension] += subtreeValues[depth + 1][goNodeIdx][dimension] - subtreeValues[depth][nodeIdx][dimension]; } nodeIdx = goNodeIdx; } } static inline void CalcObliviousApproximateShapValuesForLeaf( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, const TVector<TVector<int>>& combinationClassFeatures, size_t documentLeafIdx, size_t treeIdx, const TVector<TVector<TVector<double>>>& subtreeValues, bool calcInternalValues, TVector<TShapValue>* shapValues ) { shapValues->clear(); if (calcInternalValues) { CalcObliviousApproximateShapValuesForLeafImplementation( forest, binFeatureCombinationClass, documentLeafIdx, treeIdx, subtreeValues, shapValues ); } else { TVector<TShapValue> shapValuesInternal; CalcObliviousApproximateShapValuesForLeafImplementation( forest, binFeatureCombinationClass, documentLeafIdx, treeIdx, subtreeValues, &shapValuesInternal ); UnpackInternalShaps(shapValuesInternal, combinationClassFeatures, shapValues); } } static inline void CalcObliviousExactShapValuesForLeaf( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, const TVector<TVector<int>>& combinationClassFeatures, size_t documentLeafIdx, size_t treeIdx, const TVector<TVector<double>>& subtreeWeights, bool calcInternalValues, TVector<TShapValue>* shapValues ) { shapValues->clear(); if (calcInternalValues) { CalcObliviousExactShapValuesForLeafImplementation( forest, binFeatureCombinationClass, documentLeafIdx, treeIdx, subtreeWeights, shapValues ); } else { TVector<TShapValue> shapValuesInternal; CalcObliviousExactShapValuesForLeafImplementation( forest, binFeatureCombinationClass, documentLeafIdx, treeIdx, subtreeWeights, &shapValuesInternal ); UnpackInternalShaps(shapValuesInternal, combinationClassFeatures, shapValues); } } static inline void CalcNonObliviousShapValuesForLeaf( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, const TVector<TVector<int>>& combinationClassFeatures, const TVector<bool>& mapNodeIdToIsGoRight, size_t treeIdx, const TVector<TVector<double>>& subtreeWeights, bool calcInternalValues, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, TVector<TShapValue>* shapValues, double averageTreeApprox ) { shapValues->clear(); if (calcInternalValues) { CalcNonObliviousInternalShapValuesForLeafRecursive( forest, binFeatureCombinationClass, mapNodeIdToIsGoRight, treeIdx, /*depth*/ 0, subtreeWeights, /*nodeIdx*/ forest.GetTreeStartOffsets()[treeIdx], /*initialFeaturePath*/ {}, /*zeroPathFraction*/ 1, /*onePathFraction*/ 1, /*feature*/ -1, fixedFeatureParams, /*conditionFeatureFraction*/ 1.0, calcInternalValues, shapValues, averageTreeApprox ); } else { TVector<TShapValue> shapValuesInternal; CalcNonObliviousInternalShapValuesForLeafRecursive( forest, binFeatureCombinationClass, mapNodeIdToIsGoRight, treeIdx, /*depth*/ 0, subtreeWeights, /*nodeIdx*/ forest.GetTreeStartOffsets()[treeIdx], /*initialFeaturePath*/ {}, /*zeroPathFraction*/ 1, /*onePathFraction*/ 1, /*feature*/ -1, fixedFeatureParams, /*conditionFeatureFraction*/ 1.0, calcInternalValues, &shapValuesInternal, averageTreeApprox ); UnpackInternalShaps(shapValuesInternal, combinationClassFeatures, shapValues); } } static void CalcNonObliviousApproximateShapValuesForLeafImplementation( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, const TVector<bool>& mapNodeIdToIsGoRight, size_t treeIdx, const TVector<TVector<TVector<double>>>& subtreeValues, TVector<TShapValue>* shapValues ) { const size_t approxDimension = forest.GetDimensionsCount(); const size_t startOffset = forest.GetTreeStartOffsets()[treeIdx]; size_t nodeIdx = startOffset; size_t goNodeIdx; auto& node = forest.GetNonSymmetricStepNodes()[nodeIdx]; if (mapNodeIdToIsGoRight[nodeIdx - startOffset]) { goNodeIdx = nodeIdx + node.RightSubtreeDiff; } else { goNodeIdx = nodeIdx + node.LeftSubtreeDiff; } while (nodeIdx != goNodeIdx) { const int combinationClass = binFeatureCombinationClass[ forest.GetTreeSplits()[nodeIdx] ]; const auto FeatureShapValue = FindIf( shapValues->begin(), shapValues->end(), [combinationClass](const TShapValue &shapValue) { return shapValue.Feature == combinationClass; } ); auto newFeatureShapValue = shapValues->end(); if (FeatureShapValue == shapValues->end()) { shapValues->emplace_back(combinationClass, approxDimension); newFeatureShapValue = shapValues->end() - 1; } else { newFeatureShapValue = FeatureShapValue; } for (size_t dimension = 0; dimension < approxDimension; ++dimension) { newFeatureShapValue->Value[dimension] += subtreeValues[0][goNodeIdx - startOffset][dimension] - subtreeValues[0][nodeIdx - startOffset][dimension]; } nodeIdx = goNodeIdx; auto& node = forest.GetNonSymmetricStepNodes()[nodeIdx]; if (mapNodeIdToIsGoRight[nodeIdx - startOffset]) { goNodeIdx = nodeIdx + node.RightSubtreeDiff; } else { goNodeIdx = nodeIdx + node.LeftSubtreeDiff; } } } static inline void CalcNonObliviousApproximateShapValuesForLeaf( const TModelTrees& forest, const TVector<int>& binFeatureCombinationClass, const TVector<TVector<int>>& combinationClassFeatures, const TVector<bool>& mapNodeIdToIsGoRight, size_t treeIdx, const TVector<TVector<TVector<double>>>& subtreeValues, bool calcInternalValues, TVector<TShapValue>* shapValues ) { shapValues->clear(); if (calcInternalValues) { CalcNonObliviousApproximateShapValuesForLeafImplementation( forest, binFeatureCombinationClass, mapNodeIdToIsGoRight, treeIdx, subtreeValues, shapValues ); } else { TVector<TShapValue> shapValuesInternal; CalcNonObliviousApproximateShapValuesForLeafImplementation( forest, binFeatureCombinationClass, mapNodeIdToIsGoRight, treeIdx, subtreeValues, &shapValuesInternal ); UnpackInternalShaps(shapValuesInternal, combinationClassFeatures, shapValues); } } static TVector<double> CalcMeanValueForTree( const TModelTrees& forest, const TVector<TVector<double>>& subtreeWeights, size_t treeIdx ) { const int approxDimension = forest.GetDimensionsCount(); TVector<double> meanValue(approxDimension, 0.0); if (forest.IsOblivious()) { auto firstLeafPtr = forest.GetFirstLeafPtrForTree(treeIdx); const size_t maxDepth = forest.GetTreeSizes()[treeIdx]; for (size_t leafIdx = 0; leafIdx < (size_t(1) << maxDepth); ++leafIdx) { for (int dimension = 0; dimension < approxDimension; ++dimension) { meanValue[dimension] += firstLeafPtr[leafIdx * approxDimension + dimension] * subtreeWeights[maxDepth][leafIdx]; } } } else { const int totalNodesCount = forest.GetNonSymmetricNodeIdToLeafId().size(); const bool isLastTree = treeIdx == forest.GetTreeStartOffsets().size() - 1; const size_t startOffset = forest.GetTreeStartOffsets()[treeIdx]; const size_t endOffset = isLastTree ? totalNodesCount : forest.GetTreeStartOffsets()[treeIdx + 1]; for (size_t nodeIdx = startOffset; nodeIdx < endOffset; ++nodeIdx) { for (int dimension = 0; dimension < approxDimension; ++dimension) { size_t leafIdx = forest.GetNonSymmetricNodeIdToLeafId()[nodeIdx]; if (leafIdx < forest.GetLeafValues().size()) { meanValue[dimension] += forest.GetLeafValues()[leafIdx + dimension] * forest.GetLeafWeights()[leafIdx / forest.GetDimensionsCount()]; } } } } for (int dimension = 0; dimension < approxDimension; ++dimension) { meanValue[dimension] /= subtreeWeights[0][0]; } return meanValue; } // 'reversed' mean every child will become parent and vice versa static TVector<size_t> GetReversedSubtreeForNonObliviousTree( const TModelTrees& forest, int treeIdx ) { const int totalNodesCount = forest.GetTreeSplits().size(); const bool isLastTree = static_cast<size_t>(treeIdx + 1) == forest.GetTreeStartOffsets().size(); const int startOffset = forest.GetTreeStartOffsets()[treeIdx]; const int endOffset = isLastTree ? totalNodesCount : forest.GetTreeStartOffsets()[treeIdx + 1]; const int treeSize = endOffset - startOffset; TVector<size_t> reversedTree(treeSize, 0); for (int nodeIdx = startOffset; nodeIdx < endOffset; ++nodeIdx) { const int localIdx = nodeIdx - startOffset; const size_t leftDiff = forest.GetNonSymmetricStepNodes()[nodeIdx].LeftSubtreeDiff; const size_t rightDiff = forest.GetNonSymmetricStepNodes()[nodeIdx].RightSubtreeDiff; if (leftDiff != 0) { reversedTree[localIdx + leftDiff] = nodeIdx; } if (rightDiff != 0) { reversedTree[localIdx + rightDiff] = nodeIdx; } } return reversedTree; } // All calculations only for one docId static TVector<bool> GetDocumentPathToLeafForNonObliviousBlock( const TModelTrees& forest, const size_t docIdx, const size_t treeIdx, const NCB::NModelEvaluation::TCPUEvaluatorQuantizedData& block ) { const ui8* binFeatures = block.QuantizedData.data(); const size_t docCountInBlock = block.ObjectsCount; const TRepackedBin* treeSplitsPtr = forest.GetRepackedBins().data(); const auto firstLeafOffsets = forest.GetFirstLeafOffsets(); const int totalNodesCount = forest.GetTreeSplits().size(); const bool isLastTree = static_cast<size_t>(treeIdx + 1) == forest.GetTreeStartOffsets().size(); const size_t endOffset = isLastTree ? totalNodesCount : forest.GetTreeStartOffsets()[treeIdx + 1]; TVector<bool> mapNodeIdToIsGoRight; for (NCB::NModelEvaluation::TCalcerIndexType nodeIdx = forest.GetTreeStartOffsets()[treeIdx]; nodeIdx < endOffset; ++nodeIdx) { const TRepackedBin split = treeSplitsPtr[nodeIdx]; ui8 featureValue = binFeatures[split.FeatureIndex * docCountInBlock + docIdx]; if (!forest.GetOneHotFeatures().empty()) { featureValue ^= split.XorMask; } mapNodeIdToIsGoRight.push_back(featureValue >= split.SplitIdx); } return mapNodeIdToIsGoRight; } static TVector<bool> GetDocumentIsGoRightMapperForNodesInNonObliviousTree( const TModelTrees& forest, size_t treeIdx, const NCB::NModelEvaluation::IQuantizedData* binarizedFeaturesForBlock, size_t documentIdx ) { const NModelEvaluation::TCPUEvaluatorQuantizedData* dataPtr = reinterpret_cast<const NModelEvaluation::TCPUEvaluatorQuantizedData*>(binarizedFeaturesForBlock); Y_ASSERT(dataPtr); auto blockId = documentIdx / NModelEvaluation::FORMULA_EVALUATION_BLOCK_SIZE; auto subBlock = dataPtr->ExtractBlock(blockId); return GetDocumentPathToLeafForNonObliviousBlock( forest, documentIdx % NModelEvaluation::FORMULA_EVALUATION_BLOCK_SIZE, treeIdx, subBlock ); } static TVector<TVector<TVector<double>>> CalcSubtreeValuesForTree( const TModelTrees& forest, const TVector<TVector<double>>& subtreeWeights, const TVector<double>& leafWeights, size_t treeIdx ) { const size_t approxDimension = forest.GetDimensionsCount(); TVector<TVector<TVector<double>>> subtreeValues; if (forest.IsOblivious()) { auto firstLeafPtr = forest.GetFirstLeafPtrForTree(treeIdx); const size_t treeDepth = forest.GetTreeSizes()[treeIdx]; subtreeValues.resize(treeDepth + 1); size_t leafNum = size_t(1) << treeDepth; subtreeValues[treeDepth].resize(leafNum); for (size_t leafIdx = 0; leafIdx < leafNum; ++leafIdx) { subtreeValues[treeDepth][leafIdx].resize(approxDimension, 0.0); for (size_t dimension = 0; dimension < approxDimension; ++dimension) { subtreeValues[treeDepth][leafIdx][dimension] = firstLeafPtr[leafIdx * approxDimension + dimension]; } } for (int depth = treeDepth - 1; depth >= 0; --depth) { size_t subtreeNum = size_t(1) << depth; subtreeValues[depth].resize(subtreeNum); for (size_t subtreeIdx = 0; subtreeIdx < subtreeNum; ++subtreeIdx) { subtreeValues[depth][subtreeIdx].resize(approxDimension, 0.0); if (!FuzzyEquals(1 + subtreeWeights[depth][subtreeIdx], 1 + 0.0)) { for (size_t dimension = 0; dimension < approxDimension; ++dimension) { subtreeValues[depth][subtreeIdx][dimension] = subtreeValues[depth + 1][subtreeIdx * 2][dimension] * subtreeWeights[depth + 1][subtreeIdx * 2] + subtreeValues[depth + 1][subtreeIdx * 2 + 1][dimension] * subtreeWeights[depth + 1][subtreeIdx * 2 + 1]; subtreeValues[depth][subtreeIdx][dimension] /= subtreeWeights[depth][subtreeIdx]; } } } } } else { const size_t startOffset = forest.GetTreeStartOffsets()[treeIdx]; auto firstLeafPtr = &forest.GetLeafValues()[0]; TVector<size_t> reversedTree = GetReversedSubtreeForNonObliviousTree(forest, treeIdx); subtreeValues.resize(1); subtreeValues[0].resize(reversedTree.size(), TVector<double>(approxDimension, 0.0)); if (reversedTree.size() == 1) { size_t leafIdx = forest.GetNonSymmetricNodeIdToLeafId()[startOffset]; for (size_t dimension = 0; dimension < approxDimension; ++dimension) { subtreeValues[0][0][dimension] = firstLeafPtr[leafIdx + dimension]; } } else { for (size_t localIdx = reversedTree.size() - 1; localIdx > 0; --localIdx) { size_t leafIdx = forest.GetNonSymmetricNodeIdToLeafId()[startOffset + localIdx]; size_t leafWeightIdx = leafIdx / approxDimension; if (leafWeightIdx < leafWeights.size()) { if (!FuzzyEquals(1 + leafWeights[leafWeightIdx], 1 + 0.0)) { for (size_t dimension = 0; dimension < approxDimension; ++dimension) { subtreeValues[0][localIdx][dimension] += firstLeafPtr[leafIdx + dimension] * leafWeights[leafWeightIdx]; } } } if (!FuzzyEquals(1 + subtreeWeights[0][localIdx], 1 + 0.0)) { for (size_t dimension = 0; dimension < approxDimension; ++dimension) { subtreeValues[0][reversedTree[localIdx] - startOffset][dimension] += subtreeValues[0][localIdx][dimension]; } } } for (int localIdx = reversedTree.size() - 1; localIdx >= 0; --localIdx) { if (!FuzzyEquals(1 + subtreeWeights[0][localIdx], 1 + 0.0)) { for (size_t dimension = 0; dimension < approxDimension; ++dimension) { subtreeValues[0][localIdx][dimension] /= subtreeWeights[0][localIdx]; } } } } } return subtreeValues; } static TVector<TVector<double>> CalcSubtreeWeightsForTree( const TModelTrees& forest, const TVector<double>& leafWeights, int treeIdx ) { TVector<TVector<double>> subtreeWeights; if (forest.IsOblivious()) { const int treeDepth = forest.GetTreeSizes()[treeIdx]; subtreeWeights.resize(treeDepth + 1); subtreeWeights[treeDepth].resize(size_t(1) << treeDepth); const int weightOffset = forest.GetFirstLeafOffsets()[treeIdx] / forest.GetDimensionsCount(); for (size_t nodeIdx = 0; nodeIdx < size_t(1) << treeDepth; ++nodeIdx) { subtreeWeights[treeDepth][nodeIdx] = leafWeights[weightOffset + nodeIdx]; } for (int depth = treeDepth - 1; depth >= 0; --depth) { const size_t nodeCount = size_t(1) << depth; subtreeWeights[depth].resize(nodeCount); for (size_t nodeIdx = 0; nodeIdx < nodeCount; ++nodeIdx) { subtreeWeights[depth][nodeIdx] = subtreeWeights[depth + 1][nodeIdx * 2] + subtreeWeights[depth + 1][nodeIdx * 2 + 1]; } } } else { const int startOffset = forest.GetTreeStartOffsets()[treeIdx]; TVector<size_t> reversedTree = GetReversedSubtreeForNonObliviousTree(forest, treeIdx); subtreeWeights.resize(1); // with respect to NonSymmetric format of TObliviousTree subtreeWeights[0].resize(reversedTree.size(), 0); if (reversedTree.size() == 1) { subtreeWeights[0][0] = leafWeights[forest.GetNonSymmetricNodeIdToLeafId()[startOffset] / forest.GetDimensionsCount()]; } else { for (size_t localIdx = reversedTree.size() - 1; localIdx > 0; --localIdx) { size_t leafIdx = forest.GetNonSymmetricNodeIdToLeafId()[startOffset + localIdx] / forest.GetDimensionsCount(); if (leafIdx < leafWeights.size()) { subtreeWeights[0][localIdx] += leafWeights[leafIdx]; } subtreeWeights[0][reversedTree[localIdx] - startOffset] += subtreeWeights[0][localIdx]; } } } return subtreeWeights; } static void MapBinFeaturesToClasses( const TModelTrees& forest, TVector<int>* binFeatureCombinationClass, TVector<TVector<int>>* combinationClassFeatures ) { TConstArrayRef<TFloatFeature> floatFeatures = forest.GetFloatFeatures(); TConstArrayRef<TCatFeature> catFeatures = forest.GetCatFeatures(); const NCB::TFeaturesLayout layout( TVector<TFloatFeature>(floatFeatures.begin(), floatFeatures.end()), TVector<TCatFeature>(catFeatures.begin(), catFeatures.end())); TVector<TVector<int>> featuresCombinations; TVector<size_t> featureBucketSizes; for (const TFloatFeature& floatFeature : forest.GetFloatFeatures()) { if (!floatFeature.UsedInModel()) { continue; } featuresCombinations.emplace_back(); featuresCombinations.back() = { floatFeature.Position.FlatIndex }; featureBucketSizes.push_back(floatFeature.Borders.size()); } for (const TOneHotFeature& oneHotFeature: forest.GetOneHotFeatures()) { featuresCombinations.emplace_back(); featuresCombinations.back() = { (int)layout.GetExternalFeatureIdx(oneHotFeature.CatFeatureIndex, EFeatureType::Categorical) }; featureBucketSizes.push_back(oneHotFeature.Values.size()); } for (const TCtrFeature& ctrFeature : forest.GetCtrFeatures()) { const TFeatureCombination& combination = ctrFeature.Ctr.Base.Projection; featuresCombinations.emplace_back(); for (int catFeatureIdx : combination.CatFeatures) { featuresCombinations.back().push_back( layout.GetExternalFeatureIdx(catFeatureIdx, EFeatureType::Categorical)); } featureBucketSizes.push_back(ctrFeature.Borders.size()); } TVector<size_t> featureFirstBinBucket(featureBucketSizes.size(), 0); for (size_t i = 1; i < featureBucketSizes.size(); ++i) { featureFirstBinBucket[i] = featureFirstBinBucket[i - 1] + featureBucketSizes[i - 1]; } TVector<int> sortedBinFeatures(featuresCombinations.size()); Iota(sortedBinFeatures.begin(), sortedBinFeatures.end(), 0); Sort( sortedBinFeatures.begin(), sortedBinFeatures.end(), [featuresCombinations](int feature1, int feature2) { return featuresCombinations[feature1] < featuresCombinations[feature2]; } ); *binFeatureCombinationClass = TVector<int>(forest.GetBinaryFeaturesFullCount()); *combinationClassFeatures = TVector<TVector<int>>(); int equivalenceClassesCount = 0; for (ui32 featureIdx = 0; featureIdx < featuresCombinations.size(); ++featureIdx) { int currentFeature = sortedBinFeatures[featureIdx]; int previousFeature = featureIdx == 0 ? -1 : sortedBinFeatures[featureIdx - 1]; if (featureIdx == 0 || featuresCombinations[currentFeature] != featuresCombinations[previousFeature]) { combinationClassFeatures->push_back(featuresCombinations[currentFeature]); ++equivalenceClassesCount; } for (size_t binBucketId = featureFirstBinBucket[currentFeature]; binBucketId < featureFirstBinBucket[currentFeature] + featureBucketSizes[currentFeature]; ++binBucketId) { (*binFeatureCombinationClass)[binBucketId] = equivalenceClassesCount - 1; } } } void CalcShapValuesForDocumentMulti( const TFullModel& model, const TShapPreparedTrees& preparedTrees, const NCB::NModelEvaluation::IQuantizedData* binarizedFeaturesForBlock, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, int featuresCount, TConstArrayRef<NModelEvaluation::TCalcerIndexType> docIndices, size_t documentIdxInBlock, TVector<TVector<double>>* shapValues, ECalcTypeShapValues calcType ) { const int approxDimension = model.GetDimensionsCount(); shapValues->assign(approxDimension, TVector<double>(featuresCount + 1, 0.0)); const size_t treeCount = model.GetTreeCount(); for (size_t treeIdx = 0; treeIdx < treeCount; ++treeIdx) { if (preparedTrees.CalcShapValuesByLeafForAllTrees && model.IsOblivious()) { Y_ASSERT(docIndices[treeIdx] < preparedTrees.ShapValuesByLeafForAllTrees[treeIdx].size()); for (const TShapValue& shapValue : preparedTrees.ShapValuesByLeafForAllTrees[treeIdx][docIndices[treeIdx]]) { for (int dimension = 0; dimension < approxDimension; ++dimension) { (*shapValues)[dimension][shapValue.Feature] += shapValue.Value[dimension]; } } } else { TVector<TShapValue> shapValuesByLeaf; switch (calcType) { case ECalcTypeShapValues::Approximate: if (model.IsOblivious()) { CalcObliviousApproximateShapValuesForLeaf( *model.ModelTrees.Get(), preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, docIndices[treeIdx], treeIdx, preparedTrees.SubtreeValuesForAllTrees[treeIdx], preparedTrees.CalcInternalValues, &shapValuesByLeaf ); } else { TVector<bool> mapNodeIdToIsGoRight = GetDocumentIsGoRightMapperForNodesInNonObliviousTree( *model.ModelTrees.Get(), treeIdx, binarizedFeaturesForBlock, documentIdxInBlock ); CalcNonObliviousApproximateShapValuesForLeaf( *model.ModelTrees.Get(), preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, mapNodeIdToIsGoRight, treeIdx, preparedTrees.SubtreeValuesForAllTrees[treeIdx], preparedTrees.CalcInternalValues, &shapValuesByLeaf ); } break; case ECalcTypeShapValues::Regular: if (model.IsOblivious()) { CalcObliviousShapValuesForLeaf( *model.ModelTrees.Get(), preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, docIndices[treeIdx], treeIdx, preparedTrees.SubtreeWeightsForAllTrees[treeIdx], preparedTrees.CalcInternalValues, fixedFeatureParams, &shapValuesByLeaf, preparedTrees.AverageApproxByTree[treeIdx] ); } else { TVector<bool> mapNodeIdToIsGoRight = GetDocumentIsGoRightMapperForNodesInNonObliviousTree( *model.ModelTrees.Get(), treeIdx, binarizedFeaturesForBlock, documentIdxInBlock ); CalcNonObliviousShapValuesForLeaf( *model.ModelTrees.Get(), preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, mapNodeIdToIsGoRight, treeIdx, preparedTrees.SubtreeWeightsForAllTrees[treeIdx], preparedTrees.CalcInternalValues, fixedFeatureParams, &shapValuesByLeaf, preparedTrees.AverageApproxByTree[treeIdx] ); } break; case ECalcTypeShapValues::Exact: CB_ENSURE(model.IsOblivious(), "'Exact' calculation type is supported only for oblivious trees."); CalcObliviousExactShapValuesForLeaf( *model.ModelTrees.Get(), preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, docIndices[treeIdx], treeIdx, preparedTrees.SubtreeWeightsForAllTrees[treeIdx], preparedTrees.CalcInternalValues, &shapValuesByLeaf ); break; } for (const TShapValue& shapValue : shapValuesByLeaf) { for (int dimension = 0; dimension < approxDimension; ++dimension) { (*shapValues)[dimension][shapValue.Feature] += shapValue.Value[dimension]; } } } for (int dimension = 0; dimension < approxDimension; ++dimension) { (*shapValues)[dimension][featuresCount] += preparedTrees.MeanValuesForAllTrees[treeIdx][dimension]; } } if (approxDimension == 1) { (*shapValues)[0][featuresCount] += model.GetScaleAndBias().Bias; } } void CalcShapValuesForDocumentMulti( const TFullModel& model, const TShapPreparedTrees& preparedTrees, const NCB::NModelEvaluation::IQuantizedData* binarizedFeaturesForBlock, int featuresCount, TConstArrayRef<NModelEvaluation::TCalcerIndexType> docIndices, size_t documentIdxInBlock, TVector<TVector<double>>* shapValues, ECalcTypeShapValues calcType ) { CalcShapValuesForDocumentMulti( model, preparedTrees, binarizedFeaturesForBlock, /*fixedFeatureParams*/ Nothing(), featuresCount, docIndices, documentIdxInBlock, shapValues, calcType ); } static void CalcShapValuesForDocumentBlockMulti( const TFullModel& model, const IFeaturesBlockIterator& featuresBlockIterator, int flatFeatureCount, const TShapPreparedTrees& preparedTrees, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, size_t start, size_t end, NPar::TLocalExecutor* localExecutor, TVector<TVector<TVector<double>>>* shapValuesForAllDocuments, ECalcTypeShapValues calcType ) { CheckNonZeroApproxForZeroWeightLeaf(model); const size_t documentCount = end - start; auto binarizedFeaturesForBlock = MakeQuantizedFeaturesForEvaluator(model, featuresBlockIterator, start, end); TVector<NModelEvaluation::TCalcerIndexType> indices(binarizedFeaturesForBlock->GetObjectsCount() * model.GetTreeCount()); model.GetCurrentEvaluator()->CalcLeafIndexes(binarizedFeaturesForBlock.Get(), 0, model.GetTreeCount(), indices); const int oldShapValuesSize = shapValuesForAllDocuments->size(); shapValuesForAllDocuments->resize(oldShapValuesSize + end - start); NPar::TLocalExecutor::TExecRangeParams blockParams(0, documentCount); localExecutor->ExecRange([&] (size_t documentIdxInBlock) { TVector<TVector<double>>& shapValues = (*shapValuesForAllDocuments)[oldShapValuesSize + documentIdxInBlock]; CalcShapValuesForDocumentMulti( model, preparedTrees, binarizedFeaturesForBlock.Get(), fixedFeatureParams, flatFeatureCount, MakeArrayRef(indices.data() + documentIdxInBlock * model.GetTreeCount(), model.GetTreeCount()), documentIdxInBlock, &shapValues, calcType ); }, blockParams, NPar::TLocalExecutor::WAIT_COMPLETE); } static double CalcAverageApprox(const TVector<double>& averageApproxByClass) { double result = 0; for (double value : averageApproxByClass) { result += value; } return result / averageApproxByClass.size(); } static void CalcShapValuesByLeafForTreeBlock( const TModelTrees& forest, int start, int end, bool calcInternalValues, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, NPar::TLocalExecutor* localExecutor, TShapPreparedTrees* preparedTrees, ECalcTypeShapValues calcType ) { const auto& binFeatureCombinationClass = preparedTrees->BinFeatureCombinationClass; const auto& combinationClassFeatures = preparedTrees->CombinationClassFeatures; NPar::TLocalExecutor::TExecRangeParams blockParams(start, end); localExecutor->ExecRange([&] (size_t treeIdx) { const bool isOblivious = forest.GetNonSymmetricStepNodes().empty() && forest.GetNonSymmetricNodeIdToLeafId().empty(); if (preparedTrees->CalcShapValuesByLeafForAllTrees && isOblivious) { const size_t leafCount = (size_t(1) << forest.GetTreeSizes()[treeIdx]); TVector<TVector<TShapValue>>& shapValuesByLeaf = preparedTrees->ShapValuesByLeafForAllTrees[treeIdx]; shapValuesByLeaf.resize(leafCount); for (size_t leafIdx = 0; leafIdx < leafCount; ++leafIdx) { switch (calcType) { case ECalcTypeShapValues::Approximate: CalcObliviousApproximateShapValuesForLeaf( forest, binFeatureCombinationClass, combinationClassFeatures, leafIdx, treeIdx, preparedTrees->SubtreeValuesForAllTrees[treeIdx], calcInternalValues, &shapValuesByLeaf[leafIdx] ); break; case ECalcTypeShapValues::Regular: CalcObliviousShapValuesForLeaf( forest, binFeatureCombinationClass, combinationClassFeatures, leafIdx, treeIdx, preparedTrees->SubtreeWeightsForAllTrees[treeIdx], calcInternalValues, fixedFeatureParams, &shapValuesByLeaf[leafIdx], preparedTrees->AverageApproxByTree[treeIdx] ); break; case ECalcTypeShapValues::Exact: CalcObliviousExactShapValuesForLeaf( forest, binFeatureCombinationClass, combinationClassFeatures, leafIdx, treeIdx, preparedTrees->SubtreeWeightsForAllTrees[treeIdx], calcInternalValues, &shapValuesByLeaf[leafIdx] ); break; } } } }, blockParams, NPar::TLocalExecutor::WAIT_COMPLETE); } bool IsPrepareTreesCalcShapValues( const TFullModel& model, const TDataProvider* dataset, EPreCalcShapValues mode ) { switch (mode) { case EPreCalcShapValues::UsePreCalc: CB_ENSURE(model.IsOblivious(), "UsePreCalc mode can be used only for symmetric trees."); return true; case EPreCalcShapValues::NoPreCalc: return false; case EPreCalcShapValues::Auto: if (dataset==nullptr) { return true; } else { if (!model.IsOblivious()) { return false; } const size_t treeCount = model.GetTreeCount(); const TModelTrees& forest = *model.ModelTrees; double treesAverageLeafCount = forest.GetLeafValues().size() / treeCount; return treesAverageLeafCount < dataset->ObjectsGrouping->GetObjectCount(); } } Y_UNREACHABLE(); } static bool AreApproxesZeroForLastClass( const TModelTrees& forest, size_t treeIdx) { const int approxDimension = forest.GetDimensionsCount(); const double Eps = 1e-12; if (forest.IsOblivious()) { auto firstLeafPtr = forest.GetFirstLeafPtrForTree(treeIdx); const size_t maxDepth = forest.GetTreeSizes()[treeIdx]; for (size_t leafIdx = 0; leafIdx < (size_t(1) << maxDepth); ++leafIdx) { if (fabs(firstLeafPtr[leafIdx * approxDimension + approxDimension - 1]) > Eps){ return false; } } } else { const int totalNodesCount = forest.GetNonSymmetricNodeIdToLeafId().size(); const bool isLastTree = treeIdx == forest.GetTreeStartOffsets().size() - 1; const size_t startOffset = forest.GetTreeStartOffsets()[treeIdx]; const size_t endOffset = isLastTree ? totalNodesCount : forest.GetTreeStartOffsets()[treeIdx + 1]; for (size_t nodeIdx = startOffset; nodeIdx < endOffset; ++nodeIdx) { size_t leafIdx = forest.GetNonSymmetricNodeIdToLeafId()[nodeIdx]; if (leafIdx < forest.GetLeafValues().size() && fabs(forest.GetLeafValues()[leafIdx + approxDimension]) > Eps) { return false; } } } return true; } static bool IsMultiClass(const TFullModel& model) { return model.ModelTrees->GetDimensionsCount() > 1; } TMaybe<ELossFunction> TryGuessModelMultiClassLoss(const TFullModel& model) { TString lossFunctionName = model.GetLossFunctionName(); if (lossFunctionName) { return FromString<ELossFunction>(lossFunctionName); } else { const auto& forest = *model.ModelTrees; bool approxesAreZeroForLastClass = true; for (size_t treeIdx = 0; treeIdx < model.GetTreeCount(); ++treeIdx) { approxesAreZeroForLastClass &= AreApproxesZeroForLastClass(forest, treeIdx); } return approxesAreZeroForLastClass ? TMaybe<ELossFunction>(ELossFunction::MultiClass) : Nothing(); } } static void CalcTreeStats( const TModelTrees& forest, const TVector<double>& leafWeights, bool isMultiClass, TShapPreparedTrees* preparedTrees, ECalcTypeShapValues calcType ) { const size_t treeCount = forest.GetTreeCount(); for (size_t treeIdx = 0; treeIdx < treeCount; ++treeIdx) { preparedTrees->SubtreeWeightsForAllTrees[treeIdx] = CalcSubtreeWeightsForTree(forest, leafWeights, treeIdx); preparedTrees->MeanValuesForAllTrees[treeIdx] = CalcMeanValueForTree(forest, preparedTrees->SubtreeWeightsForAllTrees[treeIdx], treeIdx); if (calcType == ECalcTypeShapValues::Approximate) { preparedTrees->SubtreeValuesForAllTrees[treeIdx] = CalcSubtreeValuesForTree(forest, preparedTrees->SubtreeWeightsForAllTrees[treeIdx], leafWeights, treeIdx); } preparedTrees->AverageApproxByTree[treeIdx] = isMultiClass ? CalcAverageApprox(preparedTrees->MeanValuesForAllTrees[treeIdx]) : 0; } } static void InitPreparedTrees( const TFullModel& model, const TDataProvider* dataset, // can be nullptr if model has LeafWeights EPreCalcShapValues mode, bool calcInternalValues, NPar::TLocalExecutor* localExecutor, TShapPreparedTrees* preparedTrees, ECalcTypeShapValues calcType ) { const size_t treeCount = model.GetTreeCount(); // use only if model.ModelTrees->LeafWeights is empty TVector<double> leafWeights; if (model.ModelTrees->GetLeafWeights().empty()) { CB_ENSURE( dataset, "PrepareTrees requires either non-empty LeafWeights in model or provided dataset" ); CB_ENSURE(dataset->ObjectsGrouping->GetObjectCount() != 0, "To calculate shap values, dataset must contain objects."); CB_ENSURE(dataset->MetaInfo.GetFeatureCount() > 0, "To calculate shap values, dataset must contain features."); leafWeights = CollectLeavesStatistics(*dataset, model, localExecutor); } preparedTrees->CalcShapValuesByLeafForAllTrees = IsPrepareTreesCalcShapValues(model, dataset, mode); if (!preparedTrees->CalcShapValuesByLeafForAllTrees) { TVector<double> modelLeafWeights(model.ModelTrees->GetLeafWeights().begin(), model.ModelTrees->GetLeafWeights().end()); preparedTrees->LeafWeightsForAllTrees = modelLeafWeights.empty() ? leafWeights : modelLeafWeights; } preparedTrees->ShapValuesByLeafForAllTrees.resize(treeCount); preparedTrees->SubtreeWeightsForAllTrees.resize(treeCount); preparedTrees->MeanValuesForAllTrees.resize(treeCount); if (calcType == ECalcTypeShapValues::Approximate) { preparedTrees->SubtreeValuesForAllTrees.resize(treeCount); } preparedTrees->AverageApproxByTree.resize(treeCount); preparedTrees->CalcInternalValues = calcInternalValues; const TModelTrees& forest = *model.ModelTrees; MapBinFeaturesToClasses( forest, &preparedTrees->BinFeatureCombinationClass, &preparedTrees->CombinationClassFeatures ); } static void InitLeafWeights( const TFullModel& model, const TDataProvider* dataset, NPar::TLocalExecutor* localExecutor, TVector<double>* leafWeights ) { const auto& leafWeightsOfModels = model.ModelTrees->GetLeafWeights(); if (leafWeightsOfModels.empty()) { CB_ENSURE( dataset, "To calculate shap values, either a model with leaf weights, or a dataset are required." ); CB_ENSURE(dataset->ObjectsGrouping->GetObjectCount() != 0, "To calculate shap values, dataset must contain objects."); CB_ENSURE(dataset->MetaInfo.GetFeatureCount() > 0, "To calculate shap values, dataset must contain features."); *leafWeights = CollectLeavesStatistics(*dataset, model, localExecutor); } else { leafWeights->assign(leafWeightsOfModels.begin(), leafWeightsOfModels.end()); } } static inline bool IsMultiClassification(const TFullModel& model) { ELossFunction modelLoss = ELossFunction::RMSE; if (IsMultiClass(model)) { TMaybe<ELossFunction> loss = TryGuessModelMultiClassLoss(model); if (loss) { modelLoss = *loss.Get(); } else { CATBOOST_WARNING_LOG << "There is no loss_function parameter in the model, so it is considered as MultiClass" << Endl; modelLoss = ELossFunction::MultiClass; } } return (modelLoss == ELossFunction::MultiClass); } void CalcShapValuesByLeaf( const TFullModel& model, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, int logPeriod, bool calcInternalValues, NPar::TLocalExecutor* localExecutor, TShapPreparedTrees* preparedTrees, ECalcTypeShapValues calcType ) { const size_t treeCount = model.GetTreeCount(); const size_t treeBlockSize = CB_THREAD_LIMIT; // least necessary for threading TProfileInfo processTreesProfile(treeCount); TImportanceLogger treesLogger(treeCount, "trees processed", "Processing trees...", logPeriod); for (size_t start = 0; start < treeCount; start += treeBlockSize) { size_t end = Min(start + treeBlockSize, treeCount); processTreesProfile.StartIterationBlock(); CalcShapValuesByLeafForTreeBlock( *model.ModelTrees, start, end, calcInternalValues, fixedFeatureParams, localExecutor, preparedTrees, calcType ); processTreesProfile.FinishIterationBlock(end - start); auto profileResults = processTreesProfile.GetProfileResults(); treesLogger.Log(profileResults); } } TShapPreparedTrees PrepareTrees( const TFullModel& model, const TDataProvider* dataset, // can be nullptr if model has LeafWeights EPreCalcShapValues mode, NPar::TLocalExecutor* localExecutor, bool calcInternalValues, ECalcTypeShapValues calcType ) { TVector<double> leafWeights; InitLeafWeights(model, dataset, localExecutor, &leafWeights); TShapPreparedTrees preparedTrees; InitPreparedTrees(model, dataset, mode, calcInternalValues, localExecutor, &preparedTrees, calcType); const bool isMultiClass = IsMultiClassification(model); CalcTreeStats(*model.ModelTrees, leafWeights, isMultiClass, &preparedTrees, calcType); return preparedTrees; } TShapPreparedTrees PrepareTrees( const TFullModel& model, NPar::TLocalExecutor* localExecutor, ECalcTypeShapValues calcType ) { CB_ENSURE( !model.ModelTrees->GetLeafWeights().empty(), "Model must have leaf weights or sample pool must be provided" ); TShapPreparedTrees preparedTrees = PrepareTrees( model, nullptr, EPreCalcShapValues::Auto, localExecutor, /*calcInternalValues*/ false, calcType ); CalcShapValuesByLeaf( model, /*fixedFeatureParams*/ Nothing(), /*logPeriod*/ 0, preparedTrees.CalcInternalValues, localExecutor, &preparedTrees, calcType ); return preparedTrees; } void CalcShapValuesInternalForFeature( const TShapPreparedTrees& preparedTrees, const TFullModel& model, int /*logPeriod*/, ui32 start, ui32 end, ui32 featuresCount, const NCB::TObjectsDataProvider& objectsData, TVector<TVector<TVector<double>>>* shapValues, // [docIdx][featureIdx][dim] NPar::TLocalExecutor* localExecutor, ECalcTypeShapValues calcType ) { CB_ENSURE(start <= end && end <= objectsData.GetObjectCount()); const TModelTrees& forest = *model.ModelTrees; shapValues->clear(); const ui32 documentCount = end - start; shapValues->resize(documentCount); THolder<IFeaturesBlockIterator> featuresBlockIterator = CreateFeaturesBlockIterator(model, objectsData, start, end); const ui32 documentBlockSize = NModelEvaluation::FORMULA_EVALUATION_BLOCK_SIZE; TVector<NModelEvaluation::TCalcerIndexType> indices(documentBlockSize * forest.GetTreeCount()); for (ui32 startIdx = 0; startIdx < documentCount; startIdx += documentBlockSize) { NPar::TLocalExecutor::TExecRangeParams blockParams(startIdx, startIdx + Min(documentBlockSize, documentCount - startIdx)); featuresBlockIterator->NextBlock(blockParams.LastId - blockParams.FirstId); auto binarizedFeaturesForBlock = MakeQuantizedFeaturesForEvaluator(model, *featuresBlockIterator, blockParams.FirstId, blockParams.LastId); model.GetCurrentEvaluator()->CalcLeafIndexes( binarizedFeaturesForBlock.Get(), 0, forest.GetTreeCount(), MakeArrayRef(indices.data(), binarizedFeaturesForBlock->GetObjectsCount() * forest.GetTreeCount()) ); localExecutor->ExecRange([&](ui32 documentIdx) { TVector<TVector<double>> &docShapValues = (*shapValues)[documentIdx]; docShapValues.assign(featuresCount, TVector<double>(forest.GetDimensionsCount() + 1, 0.0)); auto docIndices = MakeArrayRef(indices.data() + forest.GetTreeCount() * (documentIdx - startIdx), forest.GetTreeCount()); for (size_t treeIdx = 0; treeIdx < forest.GetTreeCount(); ++treeIdx) { if (preparedTrees.CalcShapValuesByLeafForAllTrees && model.IsOblivious()) { for (const TShapValue& shapValue : preparedTrees.ShapValuesByLeafForAllTrees[treeIdx][docIndices[treeIdx]]) { for (int dimension = 0; dimension < (int)forest.GetDimensionsCount(); ++dimension) { docShapValues[shapValue.Feature][dimension] += shapValue.Value[dimension]; } } } else { TVector<TShapValue> shapValuesByLeaf; switch (calcType) { case ECalcTypeShapValues::Approximate: if (model.IsOblivious()) { CalcObliviousApproximateShapValuesForLeaf( forest, preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, docIndices[treeIdx], treeIdx, preparedTrees.SubtreeValuesForAllTrees[treeIdx], preparedTrees.CalcInternalValues, &shapValuesByLeaf ); } else { const TVector<bool> docPathIndexes = GetDocumentIsGoRightMapperForNodesInNonObliviousTree( *model.ModelTrees.Get(), treeIdx, binarizedFeaturesForBlock.Get(), documentIdx - startIdx ); CalcNonObliviousApproximateShapValuesForLeaf( forest, preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, docPathIndexes, treeIdx, preparedTrees.SubtreeValuesForAllTrees[treeIdx], preparedTrees.CalcInternalValues, &shapValuesByLeaf ); } break; case ECalcTypeShapValues::Regular: if (model.IsOblivious()) { CalcObliviousShapValuesForLeaf( forest, preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, docIndices[treeIdx], treeIdx, preparedTrees.SubtreeWeightsForAllTrees[treeIdx], preparedTrees.CalcInternalValues, /*fixedFeatureParams*/ Nothing(), &shapValuesByLeaf, preparedTrees.AverageApproxByTree[treeIdx] ); } else { const TVector<bool> docPathIndexes = GetDocumentIsGoRightMapperForNodesInNonObliviousTree( *model.ModelTrees.Get(), treeIdx, binarizedFeaturesForBlock.Get(), documentIdx - startIdx ); CalcNonObliviousShapValuesForLeaf( forest, preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, docPathIndexes, treeIdx, preparedTrees.SubtreeWeightsForAllTrees[treeIdx], preparedTrees.CalcInternalValues, /*fixedFeatureParams*/ Nothing(), &shapValuesByLeaf, preparedTrees.AverageApproxByTree[treeIdx] ); } break; case ECalcTypeShapValues::Exact: CB_ENSURE(model.IsOblivious(), "'Exact' calculation type is supported only for oblivious trees."); CalcObliviousExactShapValuesForLeaf( forest, preparedTrees.BinFeatureCombinationClass, preparedTrees.CombinationClassFeatures, docIndices[treeIdx], treeIdx, preparedTrees.SubtreeWeightsForAllTrees[treeIdx], preparedTrees.CalcInternalValues, &shapValuesByLeaf ); break; } for (const TShapValue& shapValue : shapValuesByLeaf) { for (int dimension = 0; dimension < (int)forest.GetDimensionsCount(); ++dimension) { docShapValues[shapValue.Feature][dimension] += shapValue.Value[dimension]; } } } } }, blockParams, NPar::TLocalExecutor::WAIT_COMPLETE); } } static TVector<TVector<TVector<double>>> CalcShapValuesWithPreparedTrees( const TFullModel& model, const TDataProvider& dataset, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, int logPeriod, TShapPreparedTrees* preparedTrees, NPar::TLocalExecutor* localExecutor, ECalcTypeShapValues calcType ) { const size_t documentCount = dataset.ObjectsGrouping->GetObjectCount(); const size_t documentBlockSize = CB_THREAD_LIMIT; // least necessary for threading const int flatFeatureCount = SafeIntegerCast<int>(dataset.MetaInfo.GetFeatureCount()); TImportanceLogger documentsLogger(documentCount, "documents processed", "Processing documents...", logPeriod); TVector<TVector<TVector<double>>> shapValues; shapValues.reserve(documentCount); TProfileInfo processDocumentsProfile(documentCount); THolder<IFeaturesBlockIterator> featuresBlockIterator = CreateFeaturesBlockIterator(model, *dataset.ObjectsData, 0, documentCount); for (size_t start = 0; start < documentCount; start += documentBlockSize) { size_t end = Min(start + documentBlockSize, documentCount); processDocumentsProfile.StartIterationBlock(); featuresBlockIterator->NextBlock(end - start); CalcShapValuesForDocumentBlockMulti( model, *featuresBlockIterator, flatFeatureCount, *preparedTrees, fixedFeatureParams, start, end, localExecutor, &shapValues, calcType ); processDocumentsProfile.FinishIterationBlock(end - start); auto profileResults = processDocumentsProfile.GetProfileResults(); documentsLogger.Log(profileResults); } return shapValues; } TVector<TVector<TVector<double>>> CalcShapValuesMulti( const TFullModel& model, const TDataProvider& dataset, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, int logPeriod, EPreCalcShapValues mode, NPar::TLocalExecutor* localExecutor, ECalcTypeShapValues calcType ) { TShapPreparedTrees preparedTrees = PrepareTrees( model, &dataset, mode, localExecutor, /*calcInternalValues*/ false, calcType ); CalcShapValuesByLeaf( model, fixedFeatureParams, logPeriod, preparedTrees.CalcInternalValues, localExecutor, &preparedTrees, calcType ); return CalcShapValuesWithPreparedTrees( model, dataset, fixedFeatureParams, logPeriod, &preparedTrees, localExecutor, calcType ); } TVector<TVector<double>> CalcShapValues( const TFullModel& model, const TDataProvider& dataset, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, int logPeriod, EPreCalcShapValues mode, NPar::TLocalExecutor* localExecutor, ECalcTypeShapValues calcType ) { CB_ENSURE(model.ModelTrees->GetDimensionsCount() == 1, "Model must not be trained for multiclassification."); TVector<TVector<TVector<double>>> shapValuesMulti = CalcShapValuesMulti( model, dataset, fixedFeatureParams, logPeriod, mode, localExecutor, calcType ); size_t documentsCount = dataset.ObjectsGrouping->GetObjectCount(); TVector<TVector<double>> shapValues(documentsCount); for (size_t documentIdx = 0; documentIdx < documentsCount; ++documentIdx) { shapValues[documentIdx] = std::move(shapValuesMulti[documentIdx][0]); } return shapValues; } static TVector<TVector<TVector<double>>> SwapFeatureAndDocumentAxes(const TVector<TVector<TVector<double>>>& shapValues) { const size_t approxDimension = shapValues[0].size(); const size_t documentCount = shapValues.size(); const size_t featuresCount = shapValues[0][0].size(); TVector<TVector<TVector<double>>> swapedShapValues(featuresCount); for (size_t featureIdx = 0; featureIdx < featuresCount; ++featureIdx) { swapedShapValues[featureIdx].resize(approxDimension); for (size_t dimension = 0; dimension < approxDimension; ++dimension) { swapedShapValues[featureIdx][dimension].resize(documentCount); for (size_t documentIdx = 0; documentIdx < documentCount; ++documentIdx) { swapedShapValues[featureIdx][dimension][documentIdx] = shapValues[documentIdx][dimension][featureIdx]; } } } return swapedShapValues; } // returned: ShapValues[featureIdx][dim][documentIdx] TVector<TVector<TVector<double>>> CalcShapValueWithQuantizedData( const TFullModel& model, const TVector<TIntrusivePtr<NModelEvaluation::IQuantizedData>>& quantizedFeatures, const TVector<TVector<NModelEvaluation::TCalcerIndexType>>& indices, const TMaybe<TFixedFeatureParams>& fixedFeatureParams, const size_t documentCount, int logPeriod, TShapPreparedTrees* preparedTrees, NPar::TLocalExecutor* localExecutor, ECalcTypeShapValues calcType ) { CalcShapValuesByLeaf( model, fixedFeatureParams, logPeriod, preparedTrees->CalcInternalValues, localExecutor, preparedTrees, calcType ); const TModelTrees& forest = *model.ModelTrees; TVector<TVector<TVector<double>>> shapValues(documentCount); const int featuresCount = preparedTrees->CombinationClassFeatures.size(); const size_t documentBlockSize = CB_THREAD_LIMIT; for (ui32 startIdx = 0, blockIdx = 0; startIdx < documentCount; startIdx += documentBlockSize, ++blockIdx) { NPar::TLocalExecutor::TExecRangeParams blockParams(startIdx, startIdx + Min(documentBlockSize, documentCount - startIdx)); auto quantizedFeaturesBlock = quantizedFeatures[blockIdx]; auto& indicesForBlock = indices[blockIdx]; localExecutor->ExecRange([&](ui32 documentIdx) { const size_t documentIdxInBlock = documentIdx - startIdx; auto docIndices = MakeArrayRef(indicesForBlock.data() + forest.GetTreeCount() * documentIdxInBlock, forest.GetTreeCount()); CalcShapValuesForDocumentMulti( model, *preparedTrees, quantizedFeaturesBlock.Get(), fixedFeatureParams, featuresCount, docIndices, documentIdxInBlock, &shapValues[documentIdx], calcType ); }, blockParams, NPar::TLocalExecutor::WAIT_COMPLETE); } const auto& swapedShapValues = SwapFeatureAndDocumentAxes(shapValues); return swapedShapValues; } static void OutputShapValuesMulti(const TVector<TVector<TVector<double>>>& shapValues, TFileOutput& out) { for (const auto& shapValuesForDocument : shapValues) { for (const auto& shapValuesForClass : shapValuesForDocument) { int valuesCount = shapValuesForClass.size(); for (int valueIdx = 0; valueIdx < valuesCount; ++valueIdx) { out << shapValuesForClass[valueIdx] << (valueIdx + 1 == valuesCount ? '\n' : '\t'); } } } } void CalcAndOutputShapValues( const TFullModel& model, const TDataProvider& dataset, const TString& outputPath, int logPeriod, EPreCalcShapValues mode, NPar::TLocalExecutor* localExecutor, ECalcTypeShapValues calcType ) { TShapPreparedTrees preparedTrees = PrepareTrees( model, &dataset, mode, localExecutor, /*calcInternalValues*/ false, calcType ); CalcShapValuesByLeaf( model, /*fixedFeatureParams*/ Nothing(), logPeriod, preparedTrees.CalcInternalValues, localExecutor, &preparedTrees, calcType ); CB_ENSURE_SCALE_IDENTITY(model.GetScaleAndBias(), "SHAP values"); const int flatFeatureCount = SafeIntegerCast<int>(dataset.MetaInfo.GetFeatureCount()); const size_t documentCount = dataset.ObjectsGrouping->GetObjectCount(); const size_t documentBlockSize = CB_THREAD_LIMIT; // least necessary for threading TImportanceLogger documentsLogger(documentCount, "documents processed", "Processing documents...", logPeriod); TProfileInfo processDocumentsProfile(documentCount); THolder<IFeaturesBlockIterator> featuresBlockIterator = CreateFeaturesBlockIterator(model, *dataset.ObjectsData, 0, documentCount); TFileOutput out(outputPath); for (size_t start = 0; start < documentCount; start += documentBlockSize) { size_t end = Min(start + documentBlockSize, documentCount); processDocumentsProfile.StartIterationBlock(); TVector<TVector<TVector<double>>> shapValuesForBlock; shapValuesForBlock.reserve(end - start); featuresBlockIterator->NextBlock(end - start); CalcShapValuesForDocumentBlockMulti( model, *featuresBlockIterator, flatFeatureCount, preparedTrees, /*fixedFeatureParams*/ Nothing(), start, end, localExecutor, &shapValuesForBlock, calcType ); OutputShapValuesMulti(shapValuesForBlock, out); processDocumentsProfile.FinishIterationBlock(end - start); auto profileResults = processDocumentsProfile.GetProfileResults(); documentsLogger.Log(profileResults); } }
41.063235
169
0.626198
[ "object", "model" ]
04b280e355a03e50310854842520aa030bba21d5
7,381
cpp
C++
src/runtime_src/core/tools/common/XBUtilitiesCore.cpp
mariodruiz/XRT
c2fe15ff3c3b3d329645d40073cf9f71b8222e15
[ "Apache-2.0" ]
null
null
null
src/runtime_src/core/tools/common/XBUtilitiesCore.cpp
mariodruiz/XRT
c2fe15ff3c3b3d329645d40073cf9f71b8222e15
[ "Apache-2.0" ]
null
null
null
src/runtime_src/core/tools/common/XBUtilitiesCore.cpp
mariodruiz/XRT
c2fe15ff3c3b3d329645d40073cf9f71b8222e15
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2019-2022 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located at * * http://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. */ // ------ I N C L U D E F I L E S ------------------------------------------- // Local - Include Files #include "XBUtilitiesCore.h" // 3rd Party Library - Include Files #include <boost/property_tree/json_parser.hpp> #include <boost/tokenizer.hpp> #include <boost/format.hpp> #include <boost/algorithm/string/split.hpp> // System - Include Files #include <iostream> #include <map> #include <regex> // ------ N A M E S P A C E --------------------------------------------------- using namespace XBUtilities; // ------ S T A T I C V A R I A B L E S ------------------------------------- static bool m_bVerbose = false; static bool m_bTrace = false; static bool m_disableEscapeCodes = false; static bool m_bShowHidden = false; static bool m_bForce = false; // ------ F U N C T I O N S --------------------------------------------------- void XBUtilities::setVerbose(bool _bVerbose) { bool prevVerbose = m_bVerbose; if ((prevVerbose == true) && (_bVerbose == false)) verbose("Disabling Verbosity"); m_bVerbose = _bVerbose; if ((prevVerbose == false) && (_bVerbose == true)) verbose("Enabling Verbosity"); } bool XBUtilities::getVerbose() { return m_bVerbose; } void XBUtilities::setTrace(bool _bTrace) { if (_bTrace) trace("Enabling Tracing"); else trace("Disabling Tracing"); m_bTrace = _bTrace; } void XBUtilities::setShowHidden(bool _bShowHidden) { if (_bShowHidden) trace("Hidden commands and options will be shown."); else trace("Hidden commands and options will be hidden"); m_bShowHidden = _bShowHidden; } bool XBUtilities::getShowHidden() { return m_bShowHidden; } void XBUtilities::setForce(bool _bForce) { m_bForce = _bForce; if (m_bForce) trace("Enabling force option"); else trace("Disabling force option"); } bool XBUtilities::getForce() { return m_bForce; } void XBUtilities::disable_escape_codes(bool _disable) { m_disableEscapeCodes = _disable; } bool XBUtilities::is_escape_codes_disabled() { return m_disableEscapeCodes; } void XBUtilities::message_(MessageType _eMT, const std::string& _msg, bool _endl, std::ostream & _ostream) { static std::map<MessageType, std::string> msgPrefix = { { MT_MESSAGE, "" }, { MT_INFO, "Info: " }, { MT_WARNING, "Warning: " }, { MT_ERROR, "Error: " }, { MT_VERBOSE, "Verbose: " }, { MT_FATAL, "Fatal: " }, { MT_TRACE, "Trace: " }, { MT_UNKNOWN, "<type unknown>: " }, }; // A simple DRC check if (_eMT > MT_UNKNOWN) { _eMT = MT_UNKNOWN; } // Verbosity is not enabled if ((m_bVerbose == false) && (_eMT == MT_VERBOSE)) { return; } // Tracing is not enabled if ((m_bTrace == false) && (_eMT == MT_TRACE)) { return; } _ostream << msgPrefix[_eMT] << _msg; if (_endl == true) { _ostream << std::endl; } } void XBUtilities::message(const std::string& _msg, bool _endl, std::ostream & _ostream) { message_(MT_MESSAGE, _msg, _endl, _ostream); } void XBUtilities::info(const std::string& _msg, bool _endl) { message_(MT_INFO, _msg, _endl); } void XBUtilities::warning(const std::string& _msg, bool _endl) { message_(MT_WARNING, _msg, _endl); } void XBUtilities::error(const std::string& _msg, bool _endl) { message_(MT_ERROR, _msg, _endl); } void XBUtilities::verbose(const std::string& _msg, bool _endl) { message_(MT_VERBOSE, _msg, _endl); } void XBUtilities::fatal(const std::string& _msg, bool _endl) { message_(MT_FATAL, _msg, _endl); } void XBUtilities::trace(const std::string& _msg, bool _endl) { message_(MT_TRACE, _msg, _endl); } void XBUtilities::trace_print_tree(const std::string & _name, const boost::property_tree::ptree & _pt) { if (m_bTrace == false) { return; } XBUtilities::trace(_name + " (JSON Tree)"); std::ostringstream buf; boost::property_tree::write_json(buf, _pt, true /*Pretty print*/); XBUtilities::message(buf.str()); } std::string XBUtilities::wrap_paragraphs( const std::string & unformattedString, unsigned int indentWidth, unsigned int columnWidth, bool indentFirstLine) { std::vector<std::string> lines; // Process the string std::string workingString; for (const auto &entry : unformattedString) { // Do we have a new line added by the user if (entry == '\n') { lines.push_back(workingString); workingString.clear(); continue; } workingString += entry; // Check to see if this string is too long if (workingString.size() >= columnWidth) { // Find the beginning of the previous 'word' auto index = workingString.find_last_of(" "); // None found, keep on adding characters till we find a space if (index == std::string::npos) continue; // Add the line and populate the next line lines.push_back(workingString.substr(0, index)); workingString = workingString.substr(index + 1); } } if (!workingString.empty()) lines.push_back(workingString); // Early exit, nothing here if (lines.size() == 0) return std::string(); // -- Build the formatted string std::string formattedString; // Iterate over the lines building the formatted string const std::string indention(indentWidth, ' '); auto iter = lines.begin(); while (iter != lines.end()) { // Add an indention if (iter != lines.begin() || indentFirstLine) formattedString += indention; // Add formatted line formattedString += *iter; // Don't add a '\n' on the last line if (++iter != lines.end()) formattedString += "\n"; } return formattedString; } bool XBUtilities::can_proceed(bool force) { bool proceed = false; std::string input; std::cout << "Are you sure you wish to proceed? [Y/n]: "; if (force) std::cout << "Y (Force override)" << std::endl; else std::getline(std::cin, input); // Ugh, the std::transform() produces windows compiler warnings due to // conversions from 'int' to 'char' in the algorithm header file boost::algorithm::to_lower(input); //std::transform( input.begin(), input.end(), input.begin(), [](unsigned char c){ return std::tolower(c); }); //std::transform( input.begin(), input.end(), input.begin(), ::tolower); // proceeds for "y", "Y" and no input proceed = ((input.compare("y") == 0) || input.empty()); if (!proceed) std::cout << "Action canceled." << std::endl; return proceed; } void XBUtilities::sudo_or_throw_err() { #ifndef _WIN32 if ((getuid() == 0) || (geteuid() == 0)) return; std::cout << "ERROR: root privileges required." << std::endl; throw std::errc::operation_canceled; #endif }
23.137931
113
0.631893
[ "vector", "transform" ]
04bd3a15d22698ce4a69d257cdb399d34e8e8296
4,745
cpp
C++
src/step_function.cpp
cocteautwins/SIRIUS-develop
8ab09ca7cc69e9a7dc76475b7b562b20d56deea3
[ "BSD-2-Clause" ]
null
null
null
src/step_function.cpp
cocteautwins/SIRIUS-develop
8ab09ca7cc69e9a7dc76475b7b562b20d56deea3
[ "BSD-2-Clause" ]
null
null
null
src/step_function.cpp
cocteautwins/SIRIUS-develop
8ab09ca7cc69e9a7dc76475b7b562b20d56deea3
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2013-2016 Anton Kozhevnikov, Thomas Schulthess // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted provided that // the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the // following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions // and the following disclaimer in the documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. /** \file step_function.cpp * * \brief Contains remaining implementation of sirius::Step_function class. */ #include "step_function.h" namespace sirius { Step_function::Step_function(Unit_cell const& unit_cell__, FFT3D* fft__, Gvec_FFT_distribution const& gvec_fft_distr__, Communicator const& comm__) { PROFILE(); if (unit_cell__.num_atoms() == 0) { return; } auto& gvec = gvec_fft_distr__.gvec(); auto ffac = get_step_function_form_factors(gvec.num_shells(), unit_cell__, gvec, comm__); step_function_pw_.resize(gvec.num_gvec()); step_function_.resize(fft__->local_size()); std::vector<double_complex> f_pw = unit_cell__.make_periodic_function(ffac, gvec); for (int ig = 0; ig < gvec.num_gvec(); ig++) { step_function_pw_[ig] = -f_pw[ig]; } step_function_pw_[0] += 1.0; fft__->prepare(); fft__->transform<1>(gvec_fft_distr__, &step_function_pw_[gvec_fft_distr__.offset_gvec_fft()]); fft__->output(&step_function_[0]); fft__->dismiss(); double vit = 0.0; for (int i = 0; i < fft__->local_size(); i++) { vit += step_function_[i]; } vit *= (unit_cell__.omega() / fft__->size()); fft__->comm().allreduce(&vit, 1); if (std::abs(vit - unit_cell__.volume_it()) > 1e-10) { std::stringstream s; s << "step function gives a wrong volume for IT region" << std::endl << " difference with exact value : " << std::abs(vit - unit_cell__.volume_it()); WARNING(s); } #ifdef __PRINT_OBJECT_CHECKSUM //double_complex z1 = mdarray<double_complex, 1>(&step_function_pw_[0], fft__->local_size()).checksum(); double d1 = mdarray<double, 1>(&step_function_[0], fft__->local_size()).checksum(); comm__.allreduce(&d1, 1); DUMP("checksum(step_function): %18.10f", d1); //DUMP("checksum(step_function_pw): %18.10f %18.10f", std::real(z1), std::imag(z1)); #endif } mdarray<double, 2> Step_function::get_step_function_form_factors(int num_gsh, Unit_cell const& unit_cell__, Gvec const& gvec__, Communicator const& comm__) const { mdarray<double, 2> ffac(unit_cell__.num_atom_types(), num_gsh); splindex<block> spl_num_gvec_shells(num_gsh, comm__.size(), comm__.rank()); #pragma omp parallel for for (int igsloc = 0; igsloc < spl_num_gvec_shells.local_size(); igsloc++) { int igs = spl_num_gvec_shells[igsloc]; double G = gvec__.shell_len(igs); double g3inv = (igs) ? 1.0 / std::pow(G, 3) : 0.0; for (int iat = 0; iat < unit_cell__.num_atom_types(); iat++) { double R = unit_cell__.atom_type(iat).mt_radius(); double GR = G * R; ffac(iat, igs) = (igs) ? (std::sin(GR) - GR * std::cos(GR)) * g3inv : std::pow(R, 3) / 3.0; } } int ld = unit_cell__.num_atom_types(); comm__.allgather(ffac.at<CPU>(), ld * spl_num_gvec_shells.global_offset(), ld * spl_num_gvec_shells.local_size()); return ffac; } }
42.747748
118
0.633087
[ "vector", "transform" ]
04c885993a91b488e490b8e48fe020dd6a9cd60e
15,548
cpp
C++
src/SFML/Graphics/Shader.cpp
Luhrel/CSFML
a9df535b6b8adffb2bb585058caf5f6dd5c26d83
[ "Zlib" ]
null
null
null
src/SFML/Graphics/Shader.cpp
Luhrel/CSFML
a9df535b6b8adffb2bb585058caf5f6dd5c26d83
[ "Zlib" ]
null
null
null
src/SFML/Graphics/Shader.cpp
Luhrel/CSFML
a9df535b6b8adffb2bb585058caf5f6dd5c26d83
[ "Zlib" ]
null
null
null
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2018 Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <SFML/Graphics/Shader.h> #include <SFML/Graphics/ShaderStruct.h> #include <SFML/Graphics/TextureStruct.h> #include <SFML/Graphics/ConvertTransform.hpp> #include <SFML/Internal.h> #include <SFML/CallbackStream.h> //////////////////////////////////////////////////////////// sfShader* sfShader_createFromFile(const char* vertexShaderFilename, const char* geometryShaderFilename, const char* fragmentShaderFilename) { bool success = false; sfShader* shader = new sfShader; if (vertexShaderFilename || geometryShaderFilename || fragmentShaderFilename) { if (!geometryShaderFilename) { if (!vertexShaderFilename) { // fragment shader only success = shader->This.loadFromFile(fragmentShaderFilename, sf::Shader::Fragment); } else if (!fragmentShaderFilename) { // vertex shader only success = shader->This.loadFromFile(vertexShaderFilename, sf::Shader::Vertex); } else { // vertex + fragment shaders success = shader->This.loadFromFile(vertexShaderFilename, fragmentShaderFilename); } } else { if (!vertexShaderFilename && !fragmentShaderFilename) { // geometry shader only success = shader->This.loadFromFile(geometryShaderFilename, sf::Shader::Geometry); } else { // vertex + geometry + fragment shaders success = shader->This.loadFromFile(vertexShaderFilename, geometryShaderFilename, fragmentShaderFilename); } } } if (!success) { delete shader; shader = NULL; } return shader; } //////////////////////////////////////////////////////////// sfShader* sfShader_createFromMemory(const char* vertexShader, const char* geometryShader, const char* fragmentShader) { bool success = false; sfShader* shader = new sfShader; if (vertexShader || geometryShader || fragmentShader) { if (!geometryShader) { if (!vertexShader) { // fragment shader only success = shader->This.loadFromMemory(fragmentShader, sf::Shader::Fragment); } else if (!fragmentShader) { // vertex shader only success = shader->This.loadFromMemory(vertexShader, sf::Shader::Vertex); } else { // vertex + fragment shaders success = shader->This.loadFromMemory(vertexShader, fragmentShader); } } else { if (!vertexShader && !fragmentShader) { // geometry shader only success = shader->This.loadFromMemory(geometryShader, sf::Shader::Geometry); } else { // vertex + geometry + fragment shaders success = shader->This.loadFromMemory(vertexShader, geometryShader, fragmentShader); } } } if (!success) { delete shader; shader = NULL; } return shader; } //////////////////////////////////////////////////////////// sfShader* sfShader_createFromStream(sfInputStream* vertexShaderStream, sfInputStream* geometryShaderStream, sfInputStream* fragmentShaderStream) { bool success = false; sfShader* shader = new sfShader; if (vertexShaderStream || geometryShaderStream || fragmentShaderStream) { if (!geometryShaderStream) { if (!vertexShaderStream) { // fragment shader only CallbackStream stream(fragmentShaderStream); success = shader->This.loadFromStream(stream, sf::Shader::Fragment); } else if (!fragmentShaderStream) { // vertex shader only CallbackStream stream(vertexShaderStream); success = shader->This.loadFromStream(stream, sf::Shader::Vertex); } else { // vertex + fragment shaders CallbackStream vertexStream(vertexShaderStream); CallbackStream fragmentStream(fragmentShaderStream); success = shader->This.loadFromStream(vertexStream, fragmentStream); } } else { CallbackStream geometryStream(geometryShaderStream); if (!vertexShaderStream && !fragmentShaderStream) { // geometry shader only success = shader->This.loadFromStream(geometryStream, sf::Shader::Geometry); } else { // vertex + geometry + fragment shaders CallbackStream vertexStream(vertexShaderStream); CallbackStream fragmentStream(fragmentShaderStream); success = shader->This.loadFromStream(vertexStream, geometryStream, fragmentStream); } } } if (!success) { delete shader; shader = NULL; } return shader; } //////////////////////////////////////////////////////////// void sfShader_destroy(sfShader* shader) { delete shader; } //////////////////////////////////////////////////////////// void sfShader_setFloatUniform(sfShader* shader, const char* name, float x) { CSFML_CALL(shader, setUniform(name, x)); } //////////////////////////////////////////////////////////// void sfShader_setVec2Uniform(sfShader* shader, const char* name, sfGlslVec2 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Vec2(vector.x, vector.y))); } //////////////////////////////////////////////////////////// void sfShader_setVec3Uniform(sfShader* shader, const char* name, sfGlslVec3 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Vec3(vector.x, vector.y, vector.z))); } //////////////////////////////////////////////////////////// void sfShader_setVec4Uniform(sfShader* shader, const char* name, sfGlslVec4 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Vec4(vector.x, vector.y, vector.z, vector.w))); } //////////////////////////////////////////////////////////// void sfShader_setColorUniform(sfShader* shader, const char* name, sfColor color) { sfGlslVec4 vec4; vec4.x = color.r / 255.f; vec4.y = color.g / 255.f; vec4.z = color.b / 255.f; vec4.w = color.a / 255.f; sfShader_setVec4Uniform(shader, name, vec4); } //////////////////////////////////////////////////////////// void sfShader_setIntUniform(sfShader* shader, const char* name, int x) { CSFML_CALL(shader, setUniform(name, x)); } //////////////////////////////////////////////////////////// void sfShader_setIvec2Uniform(sfShader* shader, const char* name, sfGlslIvec2 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Ivec2(vector.x, vector.y))); } //////////////////////////////////////////////////////////// void sfShader_setIvec3Uniform(sfShader* shader, const char* name, sfGlslIvec3 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Ivec3(vector.x, vector.y, vector.z))); } //////////////////////////////////////////////////////////// void sfShader_setIvec4Uniform(sfShader* shader, const char* name, sfGlslIvec4 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Ivec4(vector.x, vector.y, vector.z, vector.w))); } //////////////////////////////////////////////////////////// void sfShader_setIntColorUniform(sfShader* shader, const char* name, sfColor color) { sfGlslIvec4 ivec4; ivec4.x = (int)color.r; ivec4.y = (int)color.g; ivec4.z = (int)color.b; ivec4.w = (int)color.a; sfShader_setIvec4Uniform(shader, name, ivec4); } //////////////////////////////////////////////////////////// void sfShader_setBoolUniform(sfShader* shader, const char* name, sfBool x) { CSFML_CALL(shader, setUniform(name, x != sfFalse)); } //////////////////////////////////////////////////////////// void sfShader_setBvec2Uniform(sfShader* shader, const char* name, sfGlslBvec2 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Bvec2(vector.x != sfFalse, vector.y != sfFalse))); } //////////////////////////////////////////////////////////// void sfShader_setBvec3Uniform(sfShader* shader, const char* name, sfGlslBvec3 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Bvec3(vector.x != sfFalse, vector.y != sfFalse, vector.z != sfFalse))); } //////////////////////////////////////////////////////////// void sfShader_setBvec4Uniform(sfShader* shader, const char* name, sfGlslBvec4 vector) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Bvec4(vector.x != sfFalse, vector.y != sfFalse, vector.z != sfFalse, vector.w != sfFalse))); } //////////////////////////////////////////////////////////// void sfShader_setMat3Uniform(sfShader* shader, const char* name, const sfGlslMat3* matrix) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Mat3(matrix->array))); } //////////////////////////////////////////////////////////// void sfShader_setMat4Uniform(sfShader* shader, const char* name, const sfGlslMat4* matrix) { CSFML_CALL(shader, setUniform(name, sf::Glsl::Mat4(matrix->array))); } //////////////////////////////////////////////////////////// void sfShader_setTextureUniform(sfShader* shader, const char* name, const sfTexture* texture) { CSFML_CALL(shader, setUniform(name, *texture->This)); } //////////////////////////////////////////////////////////// void sfShader_setCurrentTextureUniform(sfShader* shader, const char* name) { CSFML_CALL(shader, setUniform(name, sf::Shader::CurrentTexture)); } //////////////////////////////////////////////////////////// void sfShader_setFloatUniformArray(sfShader* shader, const char* name, const float* scalarArray, size_t length) { CSFML_CALL(shader, setUniformArray(name, scalarArray, length)); } //////////////////////////////////////////////////////////// void sfShader_setVec2UniformArray(sfShader* shader, const char* name, const sfGlslVec2* vectorArray, size_t length) { CSFML_CALL(shader, setUniformArray(name, reinterpret_cast<const sf::Glsl::Vec2*>(vectorArray), length)); } //////////////////////////////////////////////////////////// void sfShader_setVec3UniformArray(sfShader* shader, const char* name, const sfGlslVec3* vectorArray, size_t length) { CSFML_CALL(shader, setUniformArray(name, reinterpret_cast<const sf::Glsl::Vec3*>(vectorArray), length)); } //////////////////////////////////////////////////////////// void sfShader_setVec4UniformArray(sfShader* shader, const char* name, const sfGlslVec4* vectorArray, size_t length) { CSFML_CALL(shader, setUniformArray(name, reinterpret_cast<const sf::Glsl::Vec4*>(vectorArray), length)); } //////////////////////////////////////////////////////////// void sfShader_setMat3UniformArray(sfShader* shader, const char* name, const sfGlslMat3* matrixArray, size_t length) { CSFML_CALL(shader, setUniformArray(name, reinterpret_cast<const sf::Glsl::Mat3*>(matrixArray), length)); } //////////////////////////////////////////////////////////// void sfShader_setMat4UniformArray(sfShader* shader, const char* name, const sfGlslMat4* matrixArray, size_t length) { CSFML_CALL(shader, setUniformArray(name, reinterpret_cast<const sf::Glsl::Mat4*>(matrixArray), length)); } //////////////////////////////////////////////////////////// void sfShader_setFloatParameter(sfShader* shader, const char* name, float x) { CSFML_CALL(shader, setParameter(name, x)); } //////////////////////////////////////////////////////////// void sfShader_setFloat2Parameter(sfShader* shader, const char* name, float x, float y) { CSFML_CALL(shader, setParameter(name, x, y)); } //////////////////////////////////////////////////////////// void sfShader_setFloat3Parameter(sfShader* shader, const char* name, float x, float y, float z) { CSFML_CALL(shader, setParameter(name, x, y, z)); } //////////////////////////////////////////////////////////// void sfShader_setFloat4Parameter(sfShader* shader, const char* name, float x, float y, float z, float w) { CSFML_CALL(shader, setParameter(name, x, y, z, w)); } //////////////////////////////////////////////////////////// void sfShader_setVector2Parameter(sfShader* shader, const char* name, sfVector2f vector) { CSFML_CALL(shader, setParameter(name, sf::Vector2f(vector.x, vector.y))); } //////////////////////////////////////////////////////////// void sfShader_setVector3Parameter(sfShader* shader, const char* name, sfVector3f vector) { CSFML_CALL(shader, setParameter(name, sf::Vector3f(vector.x, vector.y, vector.z))); } //////////////////////////////////////////////////////////// void sfShader_setColorParameter(sfShader* shader, const char* name, sfColor color) { CSFML_CALL(shader, setParameter(name, sf::Color(color.r, color.g, color.b, color.a))); } //////////////////////////////////////////////////////////// void sfShader_setTransformParameter(sfShader* shader, const char* name, sfTransform transform) { CSFML_CALL(shader, setParameter(name, convertTransform(transform))); } //////////////////////////////////////////////////////////// void sfShader_setTextureParameter(sfShader* shader, const char* name, const sfTexture* texture) { CSFML_CHECK(texture); CSFML_CALL(shader, setParameter(name,*texture->This)); } //////////////////////////////////////////////////////////// void sfShader_setCurrentTextureParameter(sfShader* shader, const char* name) { CSFML_CALL(shader, setParameter(name, sf::Shader::CurrentTexture)); } //////////////////////////////////////////////////////////// unsigned int sfShader_getNativeHandle(const sfShader* shader) { CSFML_CALL_RETURN(shader, getNativeHandle(), 0); } //////////////////////////////////////////////////////////// void sfShader_bind(const sfShader* shader) { sf::Shader::bind(shader ? &shader->This : NULL); } //////////////////////////////////////////////////////////// sfBool sfShader_isAvailable(void) { return sf::Shader::isAvailable() ? sfTrue : sfFalse; } //////////////////////////////////////////////////////////// sfBool sfShader_isGeometryAvailable(void) { return sf::Shader::isGeometryAvailable() ? sfTrue : sfFalse; }
32.732632
144
0.554862
[ "geometry", "vector", "transform" ]
04cc292996b77e928cfbcc2cf1cf2d40c3bb10cf
7,381
cpp
C++
data/test/cpp/04cc292996b77e928cfbcc2cf1cf2d40c3bb10cfenvchunk.cpp
harshp8l/deep-learning-lang-detection
2a54293181c1c2b1a2b840ddee4d4d80177efb33
[ "MIT" ]
84
2017-10-25T15:49:21.000Z
2021-11-28T21:25:54.000Z
data/test/cpp/04cc292996b77e928cfbcc2cf1cf2d40c3bb10cfenvchunk.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
5
2018-03-29T11:50:46.000Z
2021-04-26T13:33:18.000Z
data/test/cpp/04cc292996b77e928cfbcc2cf1cf2d40c3bb10cfenvchunk.cpp
vassalos/deep-learning-lang-detection
cbb00b3e81bed3a64553f9c6aa6138b2511e544e
[ "MIT" ]
24
2017-11-22T08:31:00.000Z
2022-03-27T01:22:31.000Z
#include "chunk.hpp" #include "envchunk.hpp" //macro for helping to force inclusion of chunks when using libraries FORCE_CHUNK_INCLUDE_IMPLEMENT(envchunk) // Class Environment_Data_Chunk functions RIF_IMPLEMENT_DYNCREATE("REBENVDT",Environment_Data_Chunk) // constructor from buffer LOCKABLE_CHUNK_WITH_CHILDREN_LOADER("REBENVDT",Environment_Data_Chunk) /* Children for Enviornment_Data_Chunk : "ENVSDSCL" Environment_Scale_Chunk "GAMEMODE" Environment_Game_Mode_Chunk "ENVPALET" Environment_Palette_Chunk "ENVTXLIT" Environment_TLT_Chunk "TLTCONFG" TLT_Config_Chunk "CLRLOOKP" Coloured_Polygons_Lookup_Chunk "MATCHIMG" Matching_Images_Chunk "BMPNAMES" Global_BMP_Name_Chunk "BMNAMVER" BMP_Names_Version_Chunk "BMNAMEXT" BMP_Names_ExtraData_Chunk "RIFFNAME" RIF_Name_Chunk "ENDTHEAD" Environment_Data_Header_Chunk "LIGHTSET" Light_Set_Chunk "PRSETPAL" Preset_Palette_Chunk "SPECLOBJ" Special_Objects_Chunk "AVPEXSTR" AVP_External_Strategy_Chunk "BMPMD5ID" Bitmap_MD5_Chunk "GLOGENDC" Global_Generator_Data_Chunk "FRAGTYPE" Fragment_Type_Chunk "ENVACOUS" Environment_Acoustics_Chunk "AVPENVIR" AVP_Environment_Settings_Chunk "SOUNDDIR" Sound_Directory_Chunk "RANTEXID" Random_Texture_ID_Chunk */ // empty constructor Environment_Data_Chunk::Environment_Data_Chunk (Chunk_With_Children * parent) :Lockable_Chunk_With_Children (parent, "REBENVDT") { // as necessary, generated automatically new Environment_Data_Header_Chunk (this); } BOOL Environment_Data_Chunk::file_equals (HANDLE & /*rif_file*/) { return(TRUE); } Environment_Data_Header_Chunk * Environment_Data_Chunk::get_header() { return (Environment_Data_Header_Chunk *) this->lookup_single_child ("ENDTHEAD"); } const char * Environment_Data_Chunk::get_head_id() { Environment_Data_Header_Chunk * hdptr = get_header(); if (!hdptr) return (0); return(hdptr->identifier); } void Environment_Data_Chunk::set_lock_user (char * user) { Environment_Data_Header_Chunk * hdptr = get_header(); if (!hdptr) return; strncpy (hdptr->lock_user, user,16); hdptr->lock_user[16] = 0; } void Environment_Data_Chunk::post_input_processing() { if (get_header()) if (get_header()->flags & GENERAL_FLAG_LOCKED) external_lock = TRUE; Chunk_With_Children::post_input_processing(); } /////////////////////////////////////// // Class Environment_Data_Header_Chunk functions RIF_IMPLEMENT_DYNCREATE("ENDTHEAD",Environment_Data_Header_Chunk) // from buffer Environment_Data_Header_Chunk::Environment_Data_Header_Chunk (Chunk_With_Children * parent, const char * hdata, size_t /*hsize*/) : Chunk (parent, "ENDTHEAD"), flags (0), version_no (0) { flags = *((int *) hdata); strncpy (lock_user, (hdata + 4), 16); lock_user[16] = '\0'; version_no = *((int *) (hdata + 20)); } BOOL Environment_Data_Header_Chunk::output_chunk (HANDLE & hand) { unsigned long junk; BOOL ok; char * data_block; data_block = make_data_block_from_chunk(); ok = WriteFile (hand, (long *) data_block, (unsigned long) chunk_size, &junk, 0); delete [] data_block; if (!ok) return FALSE; return TRUE; } void Environment_Data_Header_Chunk::fill_data_block ( char * data_start) { strncpy (data_start, identifier, 8); data_start += 8; *((int *) data_start) = chunk_size; data_start += 4; *((int *) data_start) = flags; strncpy ((data_start + 4), lock_user, 16); *((int *) (data_start+20)) = version_no; } void Environment_Data_Header_Chunk::prepare_for_output() { version_no ++; } /////////////////////////////////////// // Class Environment_Scale_Chunk functions RIF_IMPLEMENT_DYNCREATE("ENVSDSCL",Environment_Scale_Chunk) void Environment_Scale_Chunk::fill_data_block ( char * data_start) { strncpy (data_start, identifier, 8); data_start += 8; *((int *) data_start) = chunk_size; data_start += 4; *((double *) data_start) = scale; } /////////////////////////////////////// RIF_IMPLEMENT_DYNCREATE("ENVACOUS",Environment_Acoustics_Chunk) Environment_Acoustics_Chunk::Environment_Acoustics_Chunk(Environment_Data_Chunk* parent) :Chunk(parent,"ENVACOUS") { env_index=0; reverb=2; spare=0; } Environment_Acoustics_Chunk::Environment_Acoustics_Chunk(Chunk_With_Children* parent,const char* data,size_t) :Chunk(parent,"ENVACOUS") { env_index=*(int*)data; data+=4; reverb=*(float*)data; data+=4; spare=*(int*)data; } void Environment_Acoustics_Chunk::fill_data_block(char* data_start) { strncpy (data_start, identifier, 8); data_start += 8; *((int *) data_start) = chunk_size; data_start += 4; *(int*)data_start=env_index; data_start+=4; *(float*)data_start=reverb; data_start+=4; *(int*)data_start=spare; } /////////////////////////////////////// RIF_IMPLEMENT_DYNCREATE("SOUNDDIR",Sound_Directory_Chunk) Sound_Directory_Chunk::Sound_Directory_Chunk(Environment_Data_Chunk* parent,const char* dir) :Chunk(parent,"SOUNDDIR") { directory=new char[strlen(dir)+1]; strcpy(directory,dir); } Sound_Directory_Chunk::Sound_Directory_Chunk(Chunk_With_Children * const parent, const char* data, size_t const ) :Chunk(parent,"SOUNDDIR") { directory=new char[strlen(data)+1]; strcpy(directory,data); } Sound_Directory_Chunk::~Sound_Directory_Chunk() { delete [] directory; } void Sound_Directory_Chunk::fill_data_block(char* data_start) { strncpy (data_start, identifier, 8); data_start += 8; *((int *) data_start) = chunk_size; data_start += 4; strcpy(data_start,directory); } /////////////////////////////////////// /////////////////////Available shape set collections//////////////////////////////////////// RIF_IMPLEMENT_DYNCREATE("RANTEXID",Random_Texture_ID_Chunk) Random_Texture_ID_Chunk::Random_Texture_ID_Chunk(Chunk_With_Children* parent,const char* _name) :Chunk(parent,"RANTEXID") { name=new char[strlen(_name)+1]; strcpy(name,_name); spare1=spare2=0; } Random_Texture_ID_Chunk::Random_Texture_ID_Chunk(Chunk_With_Children* parent,const char* data,size_t) :Chunk(parent,"RANTEXID") { CHUNK_EXTRACT_STRING(name); int num_types,type; CHUNK_EXTRACT(num_types,int); for(int i=0;i<num_types;i++) { CHUNK_EXTRACT(type,int); random_types.add_entry(type); } CHUNK_EXTRACT(spare1,int); CHUNK_EXTRACT(spare2,int); } Random_Texture_ID_Chunk::~Random_Texture_ID_Chunk() { delete [] name; } void Random_Texture_ID_Chunk::fill_data_block(char* data) { CHUNK_FILL_START CHUNK_FILL_STRING(name) CHUNK_FILL(random_types.size(),int); for(LIF<int> rlif(&random_types);!rlif.done();rlif.next()) { CHUNK_FILL(rlif(),int) } CHUNK_FILL(spare1,int) CHUNK_FILL(spare2,int) } size_t Random_Texture_ID_Chunk::size_chunk() { chunk_size=12+12+random_types.size()*4; chunk_size+=(strlen(name)+4)&~3; return chunk_size; } /////////////////////////////////////// //Class Special_Objects_Chunk : RIF_IMPLEMENT_DYNCREATE("SPECLOBJ",Special_Objects_Chunk) CHUNK_WITH_CHILDREN_LOADER("SPECLOBJ",Special_Objects_Chunk) /* Children for Special_Objects_Chunk : "AVPGENER" AVP_Generator_Chunk "SOUNDOB2" Sound_Object_Chunk "VIOBJECT" Virtual_Object_Chunk "AVPCABLE" AVP_Power_Cable_Chunk "AVPSTART" AVP_Player_Start_Chunk "AVPPATH2" AVP_Path_Chunk "AVPGENEX" AVP_Generator_Extra_Data_Chunk "SOUNDEXD" Sound_Object_Extra_Data_Chunk "PARGENER" AVP_Particle_Generator_Chunk "PLACHIER" Placed_Hierarchy_Chunk "CAMORIGN" Camera_Origin_Chunk "AVPDECAL" AVP_Decal_Chunk "R6WAYPNT" R6_Waypoint_Chunk */
22.641104
129
0.74204
[ "shape" ]
04cf5ba71a7472b58a2feb7092838357e7968639
20,458
cpp
C++
SymbolExtractorAndRenamer/swift/lib/Obfuscation/LayoutRenamer.cpp
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
SymbolExtractorAndRenamer/swift/lib/Obfuscation/LayoutRenamer.cpp
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
SymbolExtractorAndRenamer/swift/lib/Obfuscation/LayoutRenamer.cpp
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
#include "swift/Obfuscation/LayoutRenamer.h" namespace swift { namespace obfuscation { LayoutNodeRenaming::LayoutNodeRenaming(xmlNode* Node, const xmlChar* PropertyName, const std::string ObfuscatedName) : Node(Node), PropertyName(PropertyName), ObfuscatedName(ObfuscatedName) {}; BaseLayoutRenamingStrategy::BaseLayoutRenamingStrategy(xmlNode *RootNode) : RootNode(RootNode) {} xmlNode* BaseLayoutRenamingStrategy::findNodeWithAttributeValue( xmlNode *Node, const xmlChar *AttributeName, const xmlChar *AttributeValue, const TraversalDirection TraversalDirection) { if(Node == nullptr || AttributeName == nullptr) { return nullptr; } for (xmlNode *CurrentNode = Node; CurrentNode != nullptr; CurrentNode = CurrentNode->next) { if (CurrentNode->type == XML_ELEMENT_NODE) { for (xmlAttr *CurrentAttribute = CurrentNode->properties; CurrentAttribute != nullptr; CurrentAttribute = CurrentAttribute->next) { if(CurrentAttribute->type == XML_ATTRIBUTE_NODE) { if(xmlStrcmp(CurrentAttribute->name, AttributeName) == 0){ // if AttributeValue == nullptr then it means that we're interested // in finding only a Node with attribute that name is AttributeName if(AttributeValue == nullptr) { return CurrentNode; } else { // otherwise we need to pull attribute's value and compare it // with AttributeValue that was passed as a parameter xmlChar* value = xmlGetProp(CurrentNode, AttributeName); if(xmlStrcmp(value, AttributeValue) == 0){ return CurrentNode; } } } } } } // depending on the TraversalDirection we go down (children) // or up (parent) of the document xmlNode *NextNode = nullptr; if(TraversalDirection == Up) { NextNode = CurrentNode->parent; } else if(TraversalDirection == Down) { NextNode = CurrentNode->children; } if(NextNode != nullptr) { xmlNode *Found = findNodeWithAttributeValue(NextNode, AttributeName, AttributeValue, TraversalDirection); if(Found != nullptr) { return Found; } } } return nullptr; } class XCode9RenamingStrategy: public BaseLayoutRenamingStrategy { private: // Needed for type renaming const xmlChar * CustomClassAttributeName = reinterpret_cast<const xmlChar *>("customClass"); const xmlChar * CustomModuleAttributeName = reinterpret_cast<const xmlChar *>("customModule"); // Needed for outlet renaming const xmlChar * OutletNodeName = reinterpret_cast<const xmlChar *>("outlet"); const xmlChar * OutletPropertyAttributeName = reinterpret_cast<const xmlChar *>("property"); // Needed for action renaming const xmlChar * ActionNodeName = reinterpret_cast<const xmlChar *>("action"); const xmlChar * ActionSelectorAttributeName = reinterpret_cast<const xmlChar *>("selector"); //General const xmlChar * IdAttributeName = reinterpret_cast<const xmlChar *>("id"); const xmlChar * DestinationAttributeName = reinterpret_cast<const xmlChar *>("destination"); const xmlChar * TargetAttributeName = reinterpret_cast<const xmlChar *>("target"); TargetRuntime TargetRuntime; bool shouldRename(const SymbolRenaming &Symbol, const std::string &CustomClass, const std::string &CustomModule) { return CustomModule.empty() || CustomModule == Symbol.Module; } void extractCustomClassAndModule(xmlNode *Node, std::string &CustomClass, std::string &CustomModule) { for (xmlAttr *CurrentAttribute = Node->properties; CurrentAttribute != nullptr; CurrentAttribute = CurrentAttribute->next) { if(CurrentAttribute->type == XML_ATTRIBUTE_NODE) { if (xmlStrcmp(CurrentAttribute->name, CustomClassAttributeName) == 0) { CustomClass = std::string(reinterpret_cast<const char *>(xmlGetProp( Node, CurrentAttribute->name))); } if (xmlStrcmp(CurrentAttribute->name, CustomModuleAttributeName) == 0) { CustomModule = std::string(reinterpret_cast<const char *>(xmlGetProp( Node, CurrentAttribute->name))); } } } } // Determines if a SymbolIdentifier contains given ClassName and // ModuleName. It used to find proper SymbolRenaming for outlets and actions. bool identifierContainsModuleAndClass(const std::string SymbolIdentifier, const std::string ClassName, const std::string ModuleName) { auto HasClassName = SymbolIdentifier.find("."+ClassName+".") != std::string::npos; auto HasModuleName = ModuleName.empty() || (SymbolIdentifier.find("."+ModuleName+".") != std::string::npos); return HasClassName && HasModuleName; } public: XCode9RenamingStrategy(xmlNode *RootNode, enum TargetRuntime TargetRuntime) : BaseLayoutRenamingStrategy(RootNode) { this->TargetRuntime = TargetRuntime; } // Extracts Node information that is required to perform renaming. // Layout files are xmls, it looks for a specific attributes // such as "customClass" and retrieves their values. // These values are then used to look up RenamedSymbols map. // If a "customClass" value is present inside RenamedSymbols, then // it means that this symbol was renamed in the source code in previous step // and it should be renamed in layout file as well so it collects it in // NodesToRename vector. // "customModule" attribute is also taken into account - if it's present then // it's value is compared with // symbol's module value (the one found in RenamedSymbols) and // if it's not present then we assume that it's inherited from target project. void extractLayoutRenamingNodes( xmlNode *Node, const std::vector<SymbolRenaming> &RenamedSymbols, std::vector<LayoutNodeRenaming> &NodesToRename) { if(Node == nullptr){ return; } for (xmlNode *CurrentNode = Node; CurrentNode != nullptr; CurrentNode = CurrentNode->next) { if (CurrentNode->type == XML_ELEMENT_NODE) { auto CustomClassNode = extractCustomClassRenamingNode( CurrentNode, RenamedSymbols); if (CustomClassNode.hasValue()) { NodesToRename.push_back(CustomClassNode.getValue()); } auto ActionNode = extractActionRenamingNode(CurrentNode, RenamedSymbols); if (ActionNode.hasValue()) { NodesToRename.push_back(ActionNode.getValue()); } auto OutletNode = extractOutletRenamingNode(CurrentNode, RenamedSymbols); if (OutletNode.hasValue()) { NodesToRename.push_back(OutletNode.getValue()); } } xmlNode *ChildrenNode = CurrentNode->children; if(ChildrenNode != nullptr) { extractLayoutRenamingNodes(ChildrenNode, RenamedSymbols, NodesToRename); } } } llvm::Optional<LayoutNodeRenaming> extractCustomClassRenamingNode( xmlNode *Node, const std::vector<SymbolRenaming> &RenamedSymbols) { std::string CustomClass; std::string CustomModule; extractCustomClassAndModule(Node, CustomClass, CustomModule); if(!CustomClass.empty()) { // Find SymbolRenaming for given CustomClass and perform renaming for(auto SymbolRenaming: RenamedSymbols) { if(SymbolRenaming.OriginalName == CustomClass) { if(shouldRename(SymbolRenaming, CustomClass, CustomModule)) { return LayoutNodeRenaming(Node, CustomClassAttributeName, SymbolRenaming.ObfuscatedName); } } } } return llvm::None; } // actions look like this in xml for macos: // <action selector="customAction:" target="XfG-lQ-9wD" id="UKD-iL-45N"/> // // and like this in xml for ios: // <action selector="customAction:" destination="0Ct-JR-NLr" eventType="touchUpInside" id="s2s-A5-aG6"/> // // in order to obfuscate customAction the module name needs to be known // it looks for a node which id attribute's value is equal to // actions's node destination (or target if destination // is not present) attribute value // then it extracts CustomClass/CustomModule needed for check // if customAction should be obfuscated // it does the check and returns the node info that will be later renamed llvm::Optional<LayoutNodeRenaming> extractActionRenamingNode( xmlNode *Node, const std::vector<SymbolRenaming> &RenamedSymbols) { if (xmlStrcmp(Node->name, ActionNodeName) == 0) { std::string DestinationOrTarget; if(TargetRuntime == CocoaTouch) { DestinationOrTarget = std::string( reinterpret_cast<const char *>(xmlGetProp(Node, DestinationAttributeName))); } else if(TargetRuntime == Cocoa) { DestinationOrTarget = std::string(reinterpret_cast<const char *>( xmlGetProp(Node, TargetAttributeName))); } // find node with which id attribute value == DestinationOrTarget xmlNode *NodeWithDestinationAsId = findNodeWithAttributeValue( RootNode, IdAttributeName, reinterpret_cast<const xmlChar *> (DestinationOrTarget.c_str()), TraversalDirection::Down); if(NodeWithDestinationAsId != nullptr) { std::string CustomClass; std::string CustomModule; // Try to extract CustomClass and CustomModule extractCustomClassAndModule( NodeWithDestinationAsId, CustomClass, CustomModule); // Check if should rename and if yes then perform actual renaming if(!CustomClass.empty()) { std::string SelectorName = std::string( reinterpret_cast<const char *>( xmlGetProp( Node, ActionSelectorAttributeName))); std::vector<std::string> SplittedSelName = split(SelectorName, ':'); if(!SplittedSelName.empty()) { std::string SelectorFunctionName = SplittedSelName[0]; for(auto SymbolRenaming: RenamedSymbols) { if(SymbolRenaming.OriginalName == SelectorFunctionName && identifierContainsModuleAndClass(SymbolRenaming.Identifier, CustomClass, CustomModule)) { SelectorName.replace(0, SymbolRenaming.OriginalName.length(), SymbolRenaming.ObfuscatedName); if(shouldRename(SymbolRenaming, CustomClass, CustomModule)) { return LayoutNodeRenaming( Node, ActionSelectorAttributeName, SelectorName); } } } } } } } return llvm::None; } // outlets look like this in xml: // <outlet property="prop_name" destination="x0y-zc-UQE" id="IiG-Jc-DUb"/> // // in order to obfuscate prop_name the module name needs to be known // so it looks for the closest parent which has CustomClass attribute // then when it have CustomClass/CustomModule needed for check // if prop_name should be obfuscated // it does the check and returns the node info that will be later renamed llvm::Optional<LayoutNodeRenaming> extractOutletRenamingNode( xmlNode *Node, const std::vector<SymbolRenaming> &RenamedSymbols) { if (xmlStrcmp(Node->name, OutletNodeName) == 0) { std::string CustomClass; std::string CustomModule; // Search for closest parent Node with custom class xmlNode *Parent = findNodeWithAttributeValue( Node, CustomClassAttributeName, nullptr, TraversalDirection::Up); if(Parent != nullptr) { // Try to extract CustomClass and CustomModule extractCustomClassAndModule(Parent, CustomClass, CustomModule); // Check if should rename and if yes then perform actual renaming if(!CustomClass.empty()) { std::string PropertyName = std::string( reinterpret_cast<const char *>( xmlGetProp( Node, OutletPropertyAttributeName))); for(auto SymbolRenaming: RenamedSymbols) { if(SymbolRenaming.OriginalName == PropertyName && identifierContainsModuleAndClass(SymbolRenaming.Identifier, CustomClass, CustomModule)) { if(shouldRename(SymbolRenaming, CustomClass, CustomModule)) { return LayoutNodeRenaming( Node, OutletPropertyAttributeName, SymbolRenaming.ObfuscatedName); } } } } } } return llvm::None; } }; LayoutRenamer::LayoutRenamer(std::string FileName) { this->FileName = FileName; XmlDocument = xmlReadFile(FileName.c_str(), /* encoding */ "UTF-8", /* options */ 0); } LayoutRenamer::~LayoutRenamer() { if(XmlDocument != nullptr) { xmlFreeDoc(XmlDocument); } xmlCleanupParser(); } // For now we support layout files with root node that looks like this: // <document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" ... > // where type can be Cocoa or CocoaTouch .XIB or .Storyboard.XIB llvm::Expected<std::unique_ptr<BaseLayoutRenamingStrategy>> LayoutRenamer::createRenamingStrategy(xmlNode *RootNode) { const auto *RootNodeName = reinterpret_cast<const xmlChar *>("document"); if (xmlStrcmp(RootNode->name, RootNodeName) == 0) { const auto * RootNodeTypeAttributeName = reinterpret_cast<const xmlChar *>("type"); const auto * RootNodeVersionAttributeName = reinterpret_cast<const xmlChar *>("version"); const auto * TargetRuntimeAttributeName = reinterpret_cast<const xmlChar *> ("targetRuntime"); auto TypeAttributeValue = std::string( reinterpret_cast<const char *>(xmlGetProp( RootNode, RootNodeTypeAttributeName))); auto VersionAttributeValue = std::string( reinterpret_cast<const char *>(xmlGetProp( RootNode, RootNodeVersionAttributeName))); std::set<std::string> SupportedDocumentTypes = { "com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB", "com.apple.InterfaceBuilder3.Cocoa.Storyboard.XIB", "com.apple.InterfaceBuilder3.CocoaTouch.XIB", "com.apple.InterfaceBuilder3.Cocoa.XIB" }; if(SupportedDocumentTypes.find(TypeAttributeValue) != SupportedDocumentTypes.end() && VersionAttributeValue == "3.0") { // try to find out what the target platform is xmlChar* TargetRuntimeValue = xmlGetProp(RootNode, TargetRuntimeAttributeName); TargetRuntime TargetRuntime = Undefined; if(TargetRuntimeValue != nullptr) { std::string TargetRuntimeValueStr = std::string( reinterpret_cast<const char *>( TargetRuntimeValue)); if (TargetRuntimeValueStr.find("CocoaTouch") != std::string::npos) { TargetRuntime = CocoaTouch; } else if (TargetRuntimeValueStr.find("Cocoa") != std::string::npos) { TargetRuntime = Cocoa; } } if(TargetRuntime == Undefined) { return stringError("Could not parse target runtime in: " + FileName); } return llvm::make_unique<XCode9RenamingStrategy>(RootNode, TargetRuntime); } else { // Probably a new version of layout file came out // and it should be handled separately. // Create a new BaseLayoutRenamingStrategy implementation // and update this method so it returns correct Strategy for specific // version of the layout file. return stringError("Unknown layout file version for layout: " + FileName); } } else { return stringError("Unknown root node type in layout file: " + FileName); } } llvm::Expected<std::vector<LayoutNodeRenaming>> LayoutRenamer::extractLayoutRenamingNodes( std::vector<SymbolRenaming> RenamedSymbols) { std::vector<LayoutNodeRenaming> NodesToRename; if (XmlDocument == nullptr) { return stringError("Could not parse file: " + FileName); } xmlNode *RootNode = xmlDocGetRootElement(XmlDocument); auto RenamingStrategyOrError = createRenamingStrategy(RootNode); if (auto Error = RenamingStrategyOrError.takeError()) { return std::move(Error); } auto RenamingStrategy = std::move(RenamingStrategyOrError.get()); RenamingStrategy->extractLayoutRenamingNodes(RootNode, RenamedSymbols, NodesToRename); return NodesToRename; } void LayoutRenamer::performRenaming( const std::vector<LayoutNodeRenaming> LayoutNodesToRename, std::string OutputPath) { for (const auto &LayoutNodeToRename: LayoutNodesToRename) { xmlSetProp(LayoutNodeToRename.Node, LayoutNodeToRename.PropertyName, reinterpret_cast<const xmlChar *>( LayoutNodeToRename.ObfuscatedName.c_str())); } xmlSaveFileEnc(static_cast<const char *>(OutputPath.c_str()), XmlDocument, reinterpret_cast<const char *>(XmlDocument->encoding)); } } //namespace obfuscation } //namespace swift
38.026022
106
0.561443
[ "vector" ]
04d386dd8821e3af37ff7ff65414042941cc221c
6,749
cc
C++
CalibTracker/SiPixelConnectivity/src/PixelToFEDAssociateFromAscii.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
CalibTracker/SiPixelConnectivity/src/PixelToFEDAssociateFromAscii.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
CalibTracker/SiPixelConnectivity/src/PixelToFEDAssociateFromAscii.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "CalibTracker/SiPixelConnectivity/interface/PixelToFEDAssociateFromAscii.h" #include "DataFormats/SiPixelDetId/interface/PixelBarrelName.h" #include "DataFormats/SiPixelDetId/interface/PixelEndcapName.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include <ostream> #include <fstream> #include "FWCore/Utilities/interface/Exception.h" using namespace std; PixelToFEDAssociateFromAscii::PixelToFEDAssociateFromAscii(const string & fn) { init(fn); } std::string PixelToFEDAssociateFromAscii::version() const { return theVersion; } int PixelToFEDAssociateFromAscii::operator()(const PixelModuleName & id) const { return id.isBarrel() ? operator()(dynamic_cast<const PixelBarrelName & >(id)) : operator()(dynamic_cast<const PixelEndcapName & >(id)) ; } int PixelToFEDAssociateFromAscii::operator()(const PixelBarrelName & id) const { for (BarrelConnections::const_iterator ibc = theBarrel.begin(); ibc != theBarrel.end(); ibc++) { for (vector<Bdu>::const_iterator ibd = (*ibc).second.begin(); ibd != (*ibc).second.end(); ibd++) { if ( ibd->b == id.shell() && ibd->l.inside( id.layerName() ) && ibd->z.inside( id.moduleName() ) && ibd->f.inside( id.ladderName() ) ) return (*ibc).first; } } edm::LogError("** PixelToFEDAssociateFromAscii WARNING, name: ") << id.name()<<" not associated to FED"; return -1; } int PixelToFEDAssociateFromAscii::operator()(const PixelEndcapName & id) const { for (EndcapConnections::const_iterator iec = theEndcap.begin(); iec != theEndcap.end(); iec++) { for (vector<Edu>::const_iterator ied = (*iec).second.begin(); ied != (*iec).second.end(); ied++) { if ( ied->e == id.halfCylinder() && ied->d.inside( id.diskName() ) && ied->b.inside( id.bladeName() ) ) return iec->first; } } edm::LogError("** PixelToFEDAssociateFromAscii WARNING, name: ") << id.name()<<" not associated to FED"; return -1; } void PixelToFEDAssociateFromAscii::init(const string & cfg_name) { LogDebug("init, input file:") << cfg_name.c_str(); std::ifstream file( cfg_name.c_str() ); if ( !file ) { edm::LogError(" ** PixelToFEDAssociateFromAscii,init ** ") << " cant open data file: " << cfg_name; return; } else { edm::LogInfo("PixelToFEDAssociateFromAscii, read data from: ") <<cfg_name ; } string line; pair< int, vector<Bdu> > barCon; pair< int, vector<Edu> > endCon; try { while (getline(file,line)) { // // treat # lines // string::size_type pos = line.find("#"); if (pos != string::npos) line = line.erase(pos); string::size_type posF = line.find("FED:"); string::size_type posB = line.find("S:"); string::size_type posE = line.find("E:"); LogDebug ( "line read" ) << line; // // treat version lines, reset date // if ( line.compare(0,3,"VER") == 0 ) { edm::LogInfo("version: ")<<line; theVersion = line; send(barCon,endCon); theBarrel.clear(); theEndcap.clear(); } // // fed id line // else if ( posF != string::npos) { line = line.substr(posF+4); int id = atoi(line.c_str()); send(barCon,endCon); barCon.first = id; endCon.first = id; } // // barrel connections // else if ( posB != string::npos) { line = line.substr(posB+2); barCon.second.push_back( getBdu(line) ); } // // endcap connections // else if ( posE != string::npos) { line = line.substr(posE+2); endCon.second.push_back( getEdu(line) ); } } send(barCon,endCon); } catch(exception& err) { edm::LogError("**PixelToFEDAssociateFromAscii** exception")<<err.what(); theBarrel.clear(); theEndcap.clear(); } // // for debug // std::ostringstream str; str <<" **PixelToFEDAssociateFromAscii ** BARREL FED CONNECTIONS: "<< endl; for (BarrelConnections::const_iterator ibc = theBarrel.begin(); ibc != theBarrel.end(); ibc++) { str << "FED: " << ibc->first << endl; for (vector<Bdu>::const_iterator ibd = (*ibc).second.begin(); ibd != (*ibc).second.end(); ibd++) { str << "b: "<<ibd->b<<" l: "<<ibd->l<<" z: "<<ibd->z<<" f: "<<ibd->f<<endl; } } str <<" **PixelToFEDAssociateFromAscii ** ENDCAP FED CONNECTIONS: " << endl; for (EndcapConnections::const_iterator iec = theEndcap.begin(); iec != theEndcap.end(); iec++) { str << "FED: " << iec->first << endl; for (vector<Edu>::const_iterator ied = (*iec).second.begin(); ied != (*iec).second.end(); ied++) { str << " e: "<<ied->e<<" d: "<<ied->d<<" b: "<<ied->b<<endl; } } edm::LogInfo("PixelToFEDAssociateFromAscii")<<str.str(); } void PixelToFEDAssociateFromAscii::send( pair<int,vector<Bdu> > & b, pair<int,vector<Edu> > & e) { if (b.second.size() > 0) theBarrel.push_back(b); if (e.second.size() > 0) theEndcap.push_back(e); b.second.clear(); e.second.clear(); } PixelToFEDAssociateFromAscii::Bdu PixelToFEDAssociateFromAscii::getBdu( string line) const { Bdu result; string::size_type pos; result.b = readRange(line).first; pos = line.find("L:"); if (pos != string::npos) line = line.substr(pos+2); result.l = readRange(line); pos = line.find("Z:"); if (pos != string::npos) line = line.substr(pos+2); result.z = readRange(line); pos = line.find("F:"); if (pos != string::npos) line = line.substr(pos+2); result.f = readRange(line); return result; } PixelToFEDAssociateFromAscii::Edu PixelToFEDAssociateFromAscii::getEdu( string line) const { Edu result; string::size_type pos; result.e = readRange(line).first; pos = line.find("D:"); if (pos != string::npos) line = line.substr(pos+2); result.d = readRange(line); pos = line.find("B:"); if (pos != string::npos) line = line.substr(pos+2); result.b = readRange(line); return result; } PixelToFEDAssociateFromAscii::Range PixelToFEDAssociateFromAscii::readRange( const string & l) const { bool first = true; int num1 = -1; int num2 = -1; const char * line = l.c_str(); while (line) { char * evp = 0; int num = strtol(line, &evp, 10); { stringstream s; s<<"raad from line: "; s<<num; LogDebug(s.str()); } if (evp != line) { line = evp +1; if (first) { num1 = num; first = false; } num2 = num; } else line = 0; } if (first) { string s = "** PixelToFEDAssociateFromAscii, read data, cant intrpret: " ; edm::LogInfo(s) << endl << l << endl <<"=====> send exception " << endl; s += l; throw cms::Exception(s); } return Range(num1,num2); }
27.88843
90
0.605571
[ "vector" ]
3e20f3b6b3d7ba724a71d79dd095cd7842423d61
2,997
cpp
C++
inventory_dump.cpp
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
2
2020-03-12T19:11:56.000Z
2020-05-01T03:11:03.000Z
inventory_dump.cpp
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
null
null
null
inventory_dump.cpp
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
1
2021-06-22T22:05:56.000Z
2021-06-22T22:05:56.000Z
#include <iostream> #include <fstream> #include <vector> #include <algorithm> #include <stdlib.h> #include "bloom.h" #include "binary_io.h" using namespace std; int main(int argc, char *argv[]) { try{ if(argc != 2){ cerr << "Usage: " << argv[0] << " <binary metadata file>" << endl; return EXIT_SUCCESS; } ifstream fin(argv[1], ios::binary); if(!fin){ cerr << "Unable to open metadata file: " << argv[1] << endl; return EXIT_FAILURE; } FilterInfo info; size_t num_info; binary_read(fin, num_info); cout << "Metadata file contains " << num_info << " FilterInfo objects" << endl; for(size_t i = 0;i < num_info;++i){ binary_read(fin, info); if(info.run_accession == INVALID_ACCESSION){ cout << "Invalid run accession" << endl; } else{ cout << accession_to_str(info.run_accession) << endl; } cout << "\tspots : " << info.number_of_spots << endl; cout << "\tbases : " << info.number_of_bases << endl; cout << "\tdate_received : " << info.date_received << endl; if(info.experiment_accession == INVALID_ACCESSION){ cout << "\texperiment_accession : Invalid" << endl; } else{ cout << "\texperiment_accession : " << accession_to_str(info.experiment_accession) << endl; } cout << "\texperiment_title : " << info.experiment_title << endl; cout << "\texperiment_design_description : " << info.experiment_design_description << endl; cout << "\texperiment_library_name : " << info.experiment_library_name << endl; cout << "\texperiment_library_strategy : " << info.experiment_library_strategy << endl; cout << "\texperiment_library_source : " << info.experiment_library_source << endl; cout << "\texperiment_library_selection : " << info.experiment_library_selection << endl; cout << "\texperiment_instrument_model : " << info.experiment_instrument_model << endl; if(info.sample_accession == INVALID_ACCESSION){ cout << "\tsample_accession : Invalid" << endl; } else{ cout << "\tsample_accession : " << accession_to_str(info.sample_accession) << endl; } cout << "\tsample_taxa : " << info.sample_taxa << endl; if( !info.sample_attributes.empty() ){ cout << "\tsample_attributes :" << endl; for(MAP<string, string>::const_iterator j = info.sample_attributes.begin(); j != info.sample_attributes.end();++j){ cout << "\t\t" << j->first << " : " << j->second << endl; } } if(info.study_accession == INVALID_ACCESSION){ cout << "\tstudy_accession : Invalid" << endl; } else{ cout << "\tstudy_accession : " << accession_to_str(info.study_accession) << endl; } cout << "\tstudy_title : " << info.study_title << endl; cout << "\tstudy_abstract : " << info.study_abstract << endl; } } catch(const char *error){ cerr << "Caught the error: " << error << endl; return EXIT_FAILURE; } catch(...){ cerr << "Caught an unhandled error!" << endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
27
95
0.638639
[ "vector" ]
3e24eacef3303fb703ce6550617aa8fd265f8077
11,121
cc
C++
tools/toktx/pngimage.cc
kacprzak/KTX-Software
ebc4b205e32090665d375bd9bee8559a85294b33
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-1-Clause", "BSD-3-Clause" ]
null
null
null
tools/toktx/pngimage.cc
kacprzak/KTX-Software
ebc4b205e32090665d375bd9bee8559a85294b33
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-1-Clause", "BSD-3-Clause" ]
null
null
null
tools/toktx/pngimage.cc
kacprzak/KTX-Software
ebc4b205e32090665d375bd9bee8559a85294b33
[ "Apache-2.0", "BSD-2-Clause", "MIT", "BSD-1-Clause", "BSD-3-Clause" ]
null
null
null
// -*- tab-width: 4; -*- // vi: set sw=2 ts=4 expandtab: // Copyright 2010-2020 The Khronos Group Inc. // SPDX-License-Identifier: Apache-2.0 //! //! @internal //! @~English //! @file //! //! @brief Create Images from PNG format files. //! //! @author Mark Callow, HI Corporation. //! @author Jacob Str&ouml;m, Ericsson AB. //! #include "stdafx.h" #include <sstream> #include <stdexcept> #include "image.hpp" #include "lodepng.h" #include <KHR/khr_df.h> #include "dfd.h" void warning(const char *pFmt, ...); Image* Image::CreateFromPNG(FILE* src, bool transformOETF, Image::rescale_e rescale) { // Unfortunately LoadPNG doesn't believe in stdio plus // the function we need only reads from memory. To avoid // a potentially unnecessary read of the whole file check the // signature ourselves. uint8_t pngsig[8] = { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a }; uint8_t filesig[sizeof(pngsig)]; if (fseek(src, 0L, SEEK_SET) < 0) { std::stringstream message; message << "Could not seek. " << strerror(errno); throw std::runtime_error(message.str()); } if (fread(filesig, sizeof(pngsig), 1, src) != 1) { std::stringstream message; message << "Could not read. " << strerror(errno); throw std::runtime_error(message.str()); } if (memcmp(filesig, pngsig, sizeof(pngsig))) { throw Image::different_format(); } // It's a PNG file. // Find out the size. size_t fsz; fseek(src, 0L, SEEK_END); fsz = ftell(src); fseek(src, 0L, SEEK_SET); // Slurp it into memory so we can use lodepng_inspect, to determine // the data type, and lodepng_chunk_find. std::vector<uint8_t> png; png.resize(fsz); if (fread(png.data(), 1L, png.size(), src) != png.size()) { if (feof(src)) { throw std::runtime_error("Unexpected end of file."); } else { std::stringstream message; message << "Could not read. " << strerror(ferror(src)); throw std::runtime_error(message.str()); } } lodepng::State state; unsigned int lodepngError; uint32_t componentCount, componentBits; uint32_t w, h; // Find out the color type. As lodepng_inspect only reads the IHDR chunk, // we must also check for presence of a tRNS chunk as it affects the // target color type. This is so we can request the exact type we need // when decoding. What a palaver! Sigh! However this is probably faster // than telling the decoder to give us RGBA and potentially touching every // pixel to extract only what we need. lodepngError = lodepng_inspect(&w, &h, &state, png.data(), png.size()); if (lodepngError) { std::stringstream message; message << "PNG inspect error: " << lodepng_error_text(lodepngError) << "."; throw std::runtime_error(message.str()); } // Tell the decoder we want the same color type as the file. Exceptions // to this are made later. state.info_raw = state.info_png.color; // Is there a tRNS chunk? const unsigned char *pTrnsChunk = nullptr; const unsigned char* pFirstChunk = &png.data()[33]; // 1st after header pTrnsChunk = lodepng_chunk_find_const(pFirstChunk, &png.back(), "tRNS"); switch (state.info_png.color.colortype) { case LCT_GREY: componentCount = 1; // TODO: Create 4-bit color type and rescale 1- & 2-bpp to that. rescale = Image::eAlwaysRescaleTo8Bits; break; case LCT_RGB: if (pTrnsChunk != nullptr) { state.info_raw.colortype = LCT_RGBA; componentCount = 4; } else { state.info_raw.colortype = LCT_RGB; componentCount = 3; } break; case LCT_PALETTE: if (pTrnsChunk) { state.info_raw.colortype = LCT_RGBA; componentCount = 4; } else { state.info_raw.colortype = LCT_RGB; componentCount = 3; } state.info_raw.bitdepth = 8; // Palette values are 8 bit RGBA warning("Expanding %d-bit paletted image to %s", state.info_png.color.bitdepth, state.info_raw.colortype == LCT_RGBA ? "R8G8B8A8" : "R8G8B8"); break; case LCT_GREY_ALPHA: componentCount = 2; break; case LCT_RGBA: componentCount = 4; break; default: // To avoid potentially uninitialized variable warning. componentCount = 0; } if (rescale == eAlwaysRescaleTo8Bits || (rescale == eRescaleTo8BitsIfLess && state.info_png.color.bitdepth < 8)) { state.info_raw.bitdepth = 8; if (state.info_png.color.bitdepth != 8) { warning("Rescaling %d-bit image to 8 bits.", state.info_png.color.bitdepth); } componentBits = 8; } else { componentBits = state.info_png.color.bitdepth; } uint8_t* imageData; lodepngError = lodepng_decode(&imageData, &w, &h, &state, png.data(), png.size()); if (imageData && !lodepngError) { (void)lodepng_get_raw_size(w, h, &state.info_raw); } else { free(imageData); std::stringstream message; message << "PNG decode error. " << lodepng_error_text(lodepngError) << "."; throw std::runtime_error(message.str()); } Image* image = nullptr; if (componentBits == 16 ) { switch (componentCount) { case 1: { image = new r16image(w, h, (r16color*)imageData); break; } case 2: { image = new rg16image(w, h, (rg16color*)imageData); break; } case 3: { image = new rgb16image(w, h, (rgb16color*)imageData); break; } case 4: { image = new rgba16image(w, h, (rgba16color*)imageData); break; } } } else { switch (componentCount) { case 1: { image = new r8image(w, h, (r8color*)imageData); break; } case 2: { image = new rg8image(w, h, (rg8color*)imageData); break; } case 3: { image = new rgb8image(w, h, (rgb8color*)imageData); break; } case 4: { image = new rgba8image(w, h, (rgba8color*)imageData); break; } } } switch (componentCount) { case 1: image->colortype = Image::eLuminance; // Defined in PNG spec. break; case 2: image->colortype = Image::eLuminanceAlpha; // ditto break; case 3: image->colortype = Image::eRGB; break; case 4: image->colortype = Image::eRGBA; break; } // state will have been updated with the rest of the file info. // Here is the priority of the color space info in PNG: // // 1. No color-info chunks: assume sRGB default or 2.2 gamma // (up to the implementation). // 2. sRGB chunk: use sRGB intent specified in the chunk, ignore // all other color space information. // 3. iCCP chunk: use the provided ICC profile, ignore gamma and // primaries. // 4. gAMA and/or cHRM chunks: use provided gamma and primaries. // // A PNG image could signal linear transfer function with one // of these two options: // // 1. Provide an ICC profile in iCCP chunk. // 2. Use a gAMA chunk with a value that yields linear // function (100000). // // Using no. 1 above or setting transfer func & primaries from // the ICC profile would require parsing the ICC payload. if (state.info_png.srgb_defined) { // intent is a matter for the user when a color transform // is needed during rendering, especially when gamut // mapping. It does not affect the meaning or value of the // image pixels so there is nothing to do here. image->setOetf(KHR_DF_TRANSFER_SRGB); } else if (state.info_png.iccp_defined) { delete image; throw std::runtime_error("PNG file has an ICC profile chunk. " "These are not supported"); } else if (state.info_png.gama_defined) { if (state.info_png.gama_gamma == 100000) image->setOetf(KHR_DF_TRANSFER_LINEAR); else if (state.info_png.gama_gamma == 45455) image->setOetf(KHR_DF_TRANSFER_SRGB); else { if (state.info_png.gama_gamma == 0) { delete image; throw std::runtime_error("PNG file has gAMA of 0."); } if (transformOETF) { // What PNG calls gamma is the power to use for encoding. // Elsewhere gamma is commonly used for the power to use for // decoding. For example by spec. the value in the PNG file is // gamma * 100000 so gamma of 45455 is .45455. The power for // decoding is the inverse, i.e 1 / .45455 which is 2.2. // The variable gamma below is for decoding and is 1 / gAMA. float gamma = (float) 100000 / state.info_png.gama_gamma; // 1.6667 is a very arbitrary cutoff. if (componentBits == 8 && gamma > 1.6667f) { image->transformOETF(decode_gamma, encode_sRGB, gamma); image->setOetf(KHR_DF_TRANSFER_SRGB); if (gamma > 3.3333f) { warning("Transformed PNG image with gamma of %f to sRGB" " gamma (~2.2)", gamma); } } else { image->transformOETF(decode_gamma, encode_linear, gamma); image->setOetf(KHR_DF_TRANSFER_LINEAR); if (gamma > 1.3) { warning("Transformed PNG image with gamma of %f to" " linear", gamma); } } } else { // User is overriding color space info from file. image->setOetf(KHR_DF_TRANSFER_UNSPECIFIED); return image; } } } else { image->setOetf(KHR_DF_TRANSFER_SRGB); } if (state.info_png.chrm_defined && !state.info_png.srgb_defined && !state.info_png.iccp_defined) { Primaries primaries; primaries.Rx = (float)state.info_png.chrm_red_x / 100000; primaries.Ry = (float)state.info_png.chrm_red_y / 100000; primaries.Gx = (float)state.info_png.chrm_green_x / 100000; primaries.Gy = (float)state.info_png.chrm_green_y / 100000; primaries.Bx = (float)state.info_png.chrm_blue_x / 100000; primaries.By = (float)state.info_png.chrm_blue_y / 100000; primaries.Wx = (float)state.info_png.chrm_white_x / 100000; primaries.Wy = (float)state.info_png.chrm_white_y / 100000; image->setPrimaries(findMapping(&primaries, 0.002f)); } return image; }
35.990291
80
0.575398
[ "vector", "transform" ]
3e26bfdfd5db49aae493e3ac9428c2f0fe6d6025
11,063
cpp
C++
Plugins/PLCompositing/src/Shaders/Deferred/SRPDeferredAmbient.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
1
2019-11-09T16:54:04.000Z
2019-11-09T16:54:04.000Z
Plugins/PLCompositing/src/Shaders/Deferred/SRPDeferredAmbient.cpp
naetherm/pixelligh
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Plugins/PLCompositing/src/Shaders/Deferred/SRPDeferredAmbient.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
null
null
null
/*********************************************************\ * File: SRPDeferredAmbient.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLRenderer/RendererContext.h> #include <PLRenderer/Renderer/Program.h> #include <PLRenderer/Renderer/ProgramUniform.h> #include <PLRenderer/Renderer/ProgramAttribute.h> #include <PLRenderer/Renderer/TextureBufferRectangle.h> #include <PLRenderer/Effect/EffectManager.h> #include "PLCompositing/FullscreenQuad.h" #include "PLCompositing/Shaders/Deferred/SRPDeferredGBuffer.h" #include "PLCompositing/Shaders/Deferred/SRPDeferredAmbient.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; using namespace PLRenderer; using namespace PLScene; namespace PLCompositing { //[-------------------------------------------------------] //[ RTTI interface ] //[-------------------------------------------------------] pl_class_metadata(SRPDeferredAmbient, "PLCompositing", PLCompositing::SRPDeferred, "Scene renderer pass for deferred rendering ambient") // Constructors pl_constructor_0_metadata(DefaultConstructor, "Default constructor", "") // Attributes pl_attribute_metadata(ShaderLanguage, PLCore::String, "", ReadWrite, "Shader language to use (for example \"GLSL\" or \"Cg\"), if empty string, the default shader language of the renderer will be used", "") pl_attribute_metadata(AmbientColor, PLGraphics::Color3, PLGraphics::Color3(0.2f, 0.2f, 0.2f), ReadWrite, "Ambient color", "") // Overwritten PLScene::SceneRendererPass attributes pl_attribute_metadata(Flags, pl_flag_type_def3(SRPDeferredAmbient, EFlags), 0, ReadWrite, "Flags", "") pl_class_metadata_end(SRPDeferredAmbient) //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Default constructor */ SRPDeferredAmbient::SRPDeferredAmbient() : ShaderLanguage(this), AmbientColor(this), Flags(this), m_pProgramGenerator(nullptr) { } /** * @brief * Destructor */ SRPDeferredAmbient::~SRPDeferredAmbient() { // Destroy the program generator if (m_pProgramGenerator) delete m_pProgramGenerator; } //[-------------------------------------------------------] //[ Private virtual PLScene::SceneRendererPass functions ] //[-------------------------------------------------------] void SRPDeferredAmbient::Draw(Renderer &cRenderer, const SQCull &cCullQuery) { // Get the instance of the "PLCompositing::SRPDeferredGBuffer" scene renderer pass SRPDeferredGBuffer *pSRPDeferredGBuffer = GetGBuffer(); if (pSRPDeferredGBuffer) { // Get the fullscreen quad instance FullscreenQuad *pFullscreenQuad = pSRPDeferredGBuffer->GetFullscreenQuad(); if (pFullscreenQuad) { // Get the vertex buffer of the fullscreen quad VertexBuffer *pVertexBuffer = pFullscreenQuad->GetVertexBuffer(); if (pVertexBuffer) { // Get the texture buffer to use TextureBufferRectangle *pTextureBuffer = pSRPDeferredGBuffer->GetRenderTargetTextureBuffer(0); if (pTextureBuffer) { // Get the shader language to use String sShaderLanguage = ShaderLanguage; if (!sShaderLanguage.GetLength()) sShaderLanguage = cRenderer.GetDefaultShaderLanguage(); // Create the program generator if there's currently no instance of it if (!m_pProgramGenerator || m_pProgramGenerator->GetShaderLanguage() != sShaderLanguage) { // If there's an previous instance of the program generator, destroy it first if (m_pProgramGenerator) { delete m_pProgramGenerator; m_pProgramGenerator = nullptr; } // Choose the shader source codes depending on the requested shader language if (sShaderLanguage == "GLSL") { #include "SRPDeferredAmbient_GLSL.h" m_pProgramGenerator = new ProgramGenerator(cRenderer, sShaderLanguage, sDeferredAmbient_GLSL_VS, "110", sDeferredAmbient_GLSL_FS, "110"); // OpenGL 2.0 ("#version 110") } else if (sShaderLanguage == "Cg") { #include "SRPDeferredAmbient_Cg.h" m_pProgramGenerator = new ProgramGenerator(cRenderer, sShaderLanguage, sDeferredAmbient_Cg_VS, "arbvp1", sDeferredAmbient_Cg_FS, "arbfp1"); } } // If there's no program generator, we don't need to continue if (m_pProgramGenerator) { // Reset all render states to default cRenderer.GetRendererContext().GetEffectManager().Use(); // Use stencil buffer? if (!(GetFlags() & NoStencil)) { // Enable stencil test - ignore pixels tagged with 1 within the stencil buffer cRenderer.SetRenderState(RenderState::StencilEnable, true); cRenderer.SetRenderState(RenderState::StencilRef, 1); cRenderer.SetRenderState(RenderState::StencilFunc, Compare::NotEqual); } // Reset the program flags m_cProgramFlags.Reset(); // Albedo used? if (!(GetFlags() & NoAlbedo)) PL_ADD_FS_FLAG(m_cProgramFlags, FS_ALBEDO) // Ambient occlusion used? if (!(GetFlags() & NoAmbientOcclusion)) PL_ADD_FS_FLAG(m_cProgramFlags, FS_AMBIENTOCCLUSION) // Self illumination used? if (pSRPDeferredGBuffer->IsColorTarget3Used() && !(GetFlags() & NoSelfIllumination)) PL_ADD_FS_FLAG(m_cProgramFlags, FS_SELFILLUMINATION) // Get a program instance from the program generator using the given program flags ProgramGenerator::GeneratedProgram *pGeneratedProgram = m_pProgramGenerator->GetProgram(m_cProgramFlags); // Make our program to the current one if (pGeneratedProgram && cRenderer.SetProgram(pGeneratedProgram->pProgram)) { // Set pointers to uniforms & attributes of a generated program if they are not set yet GeneratedProgramUserData *pGeneratedProgramUserData = static_cast<GeneratedProgramUserData*>(pGeneratedProgram->pUserData); if (!pGeneratedProgramUserData) { pGeneratedProgram->pUserData = pGeneratedProgramUserData = new GeneratedProgramUserData; Program *pProgram = pGeneratedProgram->pProgram; // Vertex shader attributes static const String sVertexPosition = "VertexPosition"; pGeneratedProgramUserData->pVertexPosition = pProgram->GetAttribute(sVertexPosition); // Vertex shader uniforms static const String sTextureSize = "TextureSize"; pGeneratedProgramUserData->pTextureSize = pProgram->GetUniform(sTextureSize); // Fragment shader uniforms static const String sAmbientColor = "AmbientColor"; pGeneratedProgramUserData->pAmbientColor = pProgram->GetUniform(sAmbientColor); static const String sAlbedoMap = "AlbedoMap"; pGeneratedProgramUserData->pAlbedoMap = pProgram->GetUniform(sAlbedoMap); static const String sSelfIlluminationMap = "SelfIlluminationMap"; pGeneratedProgramUserData->pSelfIlluminationMap = pProgram->GetUniform(sSelfIlluminationMap); } // Set program vertex attributes, this creates a connection between "Vertex Buffer Attribute" and "Vertex Shader Attribute" if (pGeneratedProgramUserData->pVertexPosition) pGeneratedProgramUserData->pVertexPosition->Set(pVertexBuffer, PLRenderer::VertexBuffer::Position); // Set texture size if (pGeneratedProgramUserData->pTextureSize) pGeneratedProgramUserData->pTextureSize->Set(pTextureBuffer->GetSize()); // Ambient color if (pGeneratedProgramUserData->pAmbientColor) pGeneratedProgramUserData->pAmbientColor->Set(AmbientColor.Get()); // Albedo map if (pGeneratedProgramUserData->pAlbedoMap) { const int nTextureUnit = pGeneratedProgramUserData->pAlbedoMap->Set(pTextureBuffer); if (nTextureUnit >= 0) { cRenderer.SetSamplerState(nTextureUnit, Sampler::AddressU, TextureAddressing::Clamp); cRenderer.SetSamplerState(nTextureUnit, Sampler::AddressV, TextureAddressing::Clamp); cRenderer.SetSamplerState(nTextureUnit, Sampler::MagFilter, TextureFiltering::None); cRenderer.SetSamplerState(nTextureUnit, Sampler::MinFilter, TextureFiltering::None); cRenderer.SetSamplerState(nTextureUnit, Sampler::MipFilter, TextureFiltering::None); } } // Self illumination map if (pGeneratedProgramUserData->pSelfIlluminationMap) { const int nTextureUnit = pGeneratedProgramUserData->pSelfIlluminationMap->Set(pSRPDeferredGBuffer->GetRenderTargetTextureBuffer(3)); if (nTextureUnit >= 0) { cRenderer.SetSamplerState(nTextureUnit, Sampler::AddressU, TextureAddressing::Clamp); cRenderer.SetSamplerState(nTextureUnit, Sampler::AddressV, TextureAddressing::Clamp); cRenderer.SetSamplerState(nTextureUnit, Sampler::MagFilter, TextureFiltering::None); cRenderer.SetSamplerState(nTextureUnit, Sampler::MinFilter, TextureFiltering::None); cRenderer.SetSamplerState(nTextureUnit, Sampler::MipFilter, TextureFiltering::None); } } // Draw the fullscreen quad cRenderer.SetRenderState(RenderState::ScissorTestEnable, false); pFullscreenQuad->Draw(true); } } } } } } } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLCompositing
47.277778
224
0.657778
[ "render" ]
3e26d83ee430c59e587c33105047cb4393421356
2,383
hpp
C++
Support/Modules/UDLib/UDSettingsCombMainDialog.hpp
graphisoft-python/TextEngine
20c2ff53877b20fdfe2cd51ce7abdab1ff676a70
[ "Apache-2.0" ]
3
2019-07-15T10:54:54.000Z
2020-01-25T08:24:51.000Z
Support/Modules/UDLib/UDSettingsCombMainDialog.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
null
null
null
Support/Modules/UDLib/UDSettingsCombMainDialog.hpp
graphisoft-python/GSRoot
008fac2c6bf601ca96e7096705e25b10ba4d3e75
[ "Apache-2.0" ]
1
2020-09-26T03:17:22.000Z
2020-09-26T03:17:22.000Z
#ifndef SETTINGSCOMBMAINDIALOG_HPP #define SETTINGSCOMBMAINDIALOG_HPP #pragma once #include <memory> #include "UDRollDownDialogs.hpp" namespace UD { class SettingsCombHeaderTabPage; class SettingsCombListTabPage; class ISettingsCombCurrTabPage; class SettingsCombControl; class SettingsCombDialogState; } namespace UD { class UD_DLL_EXPORT SettingsCombMainDialog : public UD::RollDownModalDialog { public: class UD_DLL_EXPORT ISettingsCombDialogEnvironment : public DG::PanelObserver { public: virtual ~ISettingsCombDialogEnvironment (); virtual GS::UniString GetDialogTitle () const = 0; virtual USize GetTabPageCount () const { return 1; }; virtual bool IsHeaderPanelVisible () const {return true; }; virtual GS::Array<UD::ISettingsCombCurrTabPage*> CreateSettingsCombCurrTabPage (const GS::Array<UD::IRollPanel*>& rollPanelArray, std::shared_ptr<UD::SettingsCombControl> settingsCombControl) = 0; }; class UD_DLL_EXPORT ICustomBottomPanelCreator { public: virtual ~ICustomBottomPanelCreator (); virtual void CreateBottomPanel (UD::RollDownModalDialog& rollDownDialog) = 0; }; protected: GS::Array<GS::Ref<GS::Object>>& setsCombRefArr; GS::Ref<ISettingsCombDialogEnvironment> dialogEnvironment; std::shared_ptr<SettingsCombControl> settingsCombControl; public: SettingsCombMainDialog (GS::Ref<ISettingsCombDialogEnvironment> dialogEnvironment, GS::Array<GS::Ref<GS::Object> >& setsCombRefArr, std::shared_ptr<SettingsCombControl> settingsCombControl, const SettingsCombDialogState* dialogState, const GS::Guid& guid = GS::NULLGuid); SettingsCombMainDialog (GS::Ref<ISettingsCombDialogEnvironment> dialogEnvironment, GS::Array<GS::Ref<GS::Object> >& setsCombRefArr, std::shared_ptr<SettingsCombControl> settingsCombControl, const SettingsCombDialogState* dialogState, GS::Ref <ICustomBottomPanelCreator> customBottomPanelCreator, const GS::Guid& guid = GS::NULLGuid); ~SettingsCombMainDialog (); SettingsCombDialogState GetDialogState () const; private: void InitCustomBottomPanel (GS::Ref <ICustomBottomPanelCreator> customBottomPanelCreator); void InitMainTabPages (GS::Ref<ISettingsCombDialogEnvironment> settingsCombDialogEnvironment, const SettingsCombDialogState* dialogState); }; } //namespace UD #endif
31.355263
198
0.76794
[ "object" ]
3e2b08d459aecde78abc44b60543d45cffa7a6fc
498
hpp
C++
src/analysisgraph.hpp
medical-genomics-group/hydra
d352f1096d8397a36d6984ff7ea944bdb6c4e1d5
[ "MIT" ]
7
2020-09-09T08:35:24.000Z
2021-11-14T16:09:12.000Z
src/analysisgraph.hpp
medical-genomics-group/hydra
d352f1096d8397a36d6984ff7ea944bdb6c4e1d5
[ "MIT" ]
2
2020-12-09T14:48:15.000Z
2021-04-23T09:56:24.000Z
src/analysisgraph.hpp
medical-genomics-group/hydra
d352f1096d8397a36d6984ff7ea944bdb6c4e1d5
[ "MIT" ]
1
2020-10-11T12:33:25.000Z
2020-10-11T12:33:25.000Z
#ifndef ANALYSISGRAPH_H #define ANALYSISGRAPH_H #include <cstddef> #include <vector> class BayesRRmz; class AnalysisGraph { public: AnalysisGraph(BayesRRmz *bayes, size_t maxParallel = 12); virtual ~AnalysisGraph(); virtual void exec(unsigned int numInds, unsigned int numSnps, const std::vector<unsigned int> &markerIndices) = 0; protected: BayesRRmz *m_bayes = nullptr; size_t m_maxParallel = 12; }; #endif // ANALYSISGRAPH_H
19.92
74
0.674699
[ "vector" ]
3e314855a6b69fb1c435ede7d0597f9b81712ee6
2,215
cpp
C++
source/file/alignment/bed/BedFile.cpp
Frangou-Lab/libgene
28d11eea1489dd473f8376ff6475b53f12594fe6
[ "Apache-2.0" ]
null
null
null
source/file/alignment/bed/BedFile.cpp
Frangou-Lab/libgene
28d11eea1489dd473f8376ff6475b53f12594fe6
[ "Apache-2.0" ]
null
null
null
source/file/alignment/bed/BedFile.cpp
Frangou-Lab/libgene
28d11eea1489dd473f8376ff6475b53f12594fe6
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Frangou Lab * * 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 "BedFile.hpp" #include "../sam/SamRecord.hpp" namespace gene { BedFile::BedFile(const std::string& path, const std::unique_ptr<CommandLineFlags>& flags, OpenMode mode) : AlignmentFile(path, FileType::Bed, flags, mode) { switch (mode) { case OpenMode::Read: readHeader(); break; case OpenMode::Write: writeHeader(); break; } } void BedFile::readHeader() { } void BedFile::writeHeader() { out_file_->Write("chrom"); out_file_->Write(','); out_file_->Write("chromStart"); out_file_->Write(','); out_file_->Write("chromEnd"); out_file_->Write(','); out_file_->Write("name"); out_file_->WriteLine(); } void BedFile::write(const SamRecord& record) { out_file_->Write(record.chrom); out_file_->Write('\t'); out_file_->Write(std::to_string(record.chromStart)); out_file_->Write('\t'); out_file_->Write(std::to_string(record.chromEnd)); out_file_->Write('\t'); out_file_->Write(record.name); out_file_->WriteLine(); } SamRecord BedFile::read() { std::string line = in_file_->ReadLine(); return SamRecord(line); } int64_t BedFile::length() const { return IOFile::length(); } int64_t BedFile::position() const { return IOFile::position(); } bool BedFile::isValidAlignmentFile() const { return true; } std::string BedFile::strFileType() const { return "bed"; } std::string BedFile::defaultExtension() { return "bed"; } std::vector<std::string> BedFile::extensions() { return {"bed"}; } } // namespace gene
21.504854
75
0.651919
[ "vector" ]
3e31e2371dba294014f9558c24350667fd3e612f
1,265
cpp
C++
Cpp/DFS/DFSforReal/dfs.cpp
Manuel4131/CandCppFT
e88a8312db4b5fea44b5225809a6ba8059289d4e
[ "MIT" ]
null
null
null
Cpp/DFS/DFSforReal/dfs.cpp
Manuel4131/CandCppFT
e88a8312db4b5fea44b5225809a6ba8059289d4e
[ "MIT" ]
null
null
null
Cpp/DFS/DFSforReal/dfs.cpp
Manuel4131/CandCppFT
e88a8312db4b5fea44b5225809a6ba8059289d4e
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> #include <vector> void getNeighborsAndPush(std::stack <int> &s, int node); bool isVisited(std::vector<int> &visitedNode, int node); void printVector(std::vector <int> &v); int graph[][7]= { {0,1,1,1,0,0,0}, {1,0,0,0,0,1,0}, {1,0,0,1,1,0,1}, {1,0,1,0,1,0,0}, {0,0,1,1,0,0,1}, {0,1,0,0,0,0,0}, {0,0,1,0,1,0,0} }; int main() { std::stack <int> s; std::vector <int> nodes; int curNode= 0; std::vector <int> visitedNode; for(int i= 0; i < 7; i++) { nodes.push_back(i); } s.push( nodes[0] ); while( !s.empty() ) { curNode= s.top(); s.pop(); if (isVisited(visitedNode, curNode) ) continue; else { getNeighborsAndPush(s, curNode); visitedNode.push_back(curNode); } } printVector(visitedNode); return 0; } void getNeighborsAndPush(std::stack <int> &s, int node) { for(int i= 0; i < 7 ;i++) //You should use vector instead of array. { if( graph[ node ][i]== 1) s.push( i ); } } bool isVisited(std::vector<int> &visitedNode, int node) { for(int i=0; i < visitedNode.size();i++) { if(node == visitedNode[i]) return true; } return false; } void printVector(std::vector <int> &v) { for(int i= 0; i < v.size(); ++i) { std::cout<<" "<< v[i]; } std::cout<<'\n'; }
15.8125
69
0.58419
[ "vector" ]
3e3749e052587a8c8364da3e11b05fe0c4e95206
16,062
cc
C++
extensions/browser/updater/update_data_provider_unittest.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
extensions/browser/updater/update_data_provider_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
extensions/browser/updater/update_data_provider_unittest.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2017 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 "extensions/browser/updater/update_data_provider.h" #include <map> #include <memory> #include <set> #include <string> #include <vector> #include "base/bind.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/threading/thread_task_runner_handle.h" #include "components/update_client/update_client.h" #include "extensions/browser/disable_reason.h" #include "extensions/browser/extension_prefs.h" #include "extensions/browser/extension_registry.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/extensions_test.h" #include "extensions/browser/test_extensions_browser_client.h" #include "extensions/browser/updater/extension_installer.h" #include "extensions/common/extension_builder.h" namespace extensions { namespace { class UpdateDataProviderExtensionsBrowserClient : public TestExtensionsBrowserClient { public: explicit UpdateDataProviderExtensionsBrowserClient( content::BrowserContext* context) : TestExtensionsBrowserClient(context) {} ~UpdateDataProviderExtensionsBrowserClient() override {} bool IsExtensionEnabled(const std::string& id, content::BrowserContext* context) const override { return enabled_ids_.find(id) != enabled_ids_.end(); } void AddEnabledExtension(const std::string& id) { enabled_ids_.insert(id); } private: std::set<std::string> enabled_ids_; DISALLOW_COPY_AND_ASSIGN(UpdateDataProviderExtensionsBrowserClient); }; class UpdateDataProviderTest : public ExtensionsTest { public: using UpdateClientCallback = UpdateDataProvider::UpdateClientCallback; UpdateDataProviderTest() {} ~UpdateDataProviderTest() override {} void SetUp() override { SetExtensionsBrowserClient( std::make_unique<UpdateDataProviderExtensionsBrowserClient>( browser_context())); ExtensionsTest::SetUp(); } protected: ExtensionSystem* extension_system() { return ExtensionSystem::Get(browser_context()); } ExtensionRegistry* extension_registry() { return ExtensionRegistry::Get(browser_context()); } // Helper function that creates a file at |relative_path| within |directory| // and fills it with |content|. bool AddFileToDirectory(const base::FilePath& directory, const base::FilePath& relative_path, const std::string& content) const { const base::FilePath full_path = directory.Append(relative_path); if (!base::CreateDirectory(full_path.DirName())) return false; int result = base::WriteFile(full_path, content.data(), content.size()); return (static_cast<size_t>(result) == content.size()); } void AddExtension(const std::string& extension_id, const std::string& version, bool enabled, int disable_reasons, Manifest::Location location) { base::ScopedTempDir temp_dir; ASSERT_TRUE(temp_dir.CreateUniqueTempDir()); ASSERT_TRUE(base::PathExists(temp_dir.GetPath())); base::FilePath foo_js(FILE_PATH_LITERAL("foo.js")); base::FilePath bar_html(FILE_PATH_LITERAL("bar/bar.html")); ASSERT_TRUE(AddFileToDirectory(temp_dir.GetPath(), foo_js, "hello")) << "Failed to write " << temp_dir.GetPath().value() << "/" << foo_js.value(); ASSERT_TRUE(AddFileToDirectory(temp_dir.GetPath(), bar_html, "world")); ExtensionBuilder builder; builder.SetManifest(DictionaryBuilder() .Set("name", "My First Extension") .Set("version", version) .Set("manifest_version", 2) .Build()); builder.SetID(extension_id); builder.SetPath(temp_dir.GetPath()); builder.SetLocation(location); auto* test_browser_client = static_cast<UpdateDataProviderExtensionsBrowserClient*>( extensions_browser_client()); if (enabled) { extension_registry()->AddEnabled(builder.Build()); test_browser_client->AddEnabledExtension(extension_id); } else { extension_registry()->AddDisabled(builder.Build()); ExtensionPrefs::Get(browser_context()) ->AddDisableReasons(extension_id, disable_reasons); } const Extension* extension = extension_registry()->GetInstalledExtension(extension_id); ASSERT_NE(nullptr, extension); ASSERT_EQ(version, extension->VersionString()); } const std::string kExtensionId1 = "adbncddmehfkgipkidpdiheffobcpfma"; const std::string kExtensionId2 = "ldnnhddmnhbkjipkidpdiheffobcpfmf"; }; TEST_F(UpdateDataProviderTest, GetData_NoDataAdded) { scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(nullptr); const auto data = data_provider->GetData(ExtensionUpdateDataMap(), {kExtensionId1}); EXPECT_EQ(0UL, data.size()); } TEST_F(UpdateDataProviderTest, GetData_EnabledExtension) { scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version = "0.1.2.3"; AddExtension(kExtensionId1, version, true, disable_reason::DisableReason::DISABLE_NONE, Manifest::INTERNAL); ExtensionUpdateDataMap update_data; update_data[kExtensionId1] = {}; std::vector<std::string> ids({kExtensionId1}); const auto data = data_provider->GetData(update_data, ids); ASSERT_EQ(1UL, data.size()); EXPECT_EQ(version, data[0]->version.GetString()); EXPECT_NE(nullptr, data[0]->installer.get()); EXPECT_EQ(0UL, data[0]->disabled_reasons.size()); EXPECT_EQ("internal", data[0]->install_location); } TEST_F(UpdateDataProviderTest, GetData_EnabledExtensionWithData) { scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version = "0.1.2.3"; AddExtension(kExtensionId1, version, true, disable_reason::DisableReason::DISABLE_NONE, Manifest::EXTERNAL_PREF); ExtensionUpdateDataMap update_data; auto& info = update_data[kExtensionId1]; info.is_corrupt_reinstall = true; info.install_source = "webstore"; const auto data = data_provider->GetData(update_data, {kExtensionId1}); ASSERT_EQ(1UL, data.size()); EXPECT_EQ("0.0.0.0", data[0]->version.GetString()); EXPECT_EQ("webstore", data[0]->install_source); EXPECT_EQ("external", data[0]->install_location); EXPECT_NE(nullptr, data[0]->installer.get()); EXPECT_EQ(0UL, data[0]->disabled_reasons.size()); } TEST_F(UpdateDataProviderTest, GetData_DisabledExtension_WithNoReason) { scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version = "0.1.2.3"; AddExtension(kExtensionId1, version, false, disable_reason::DisableReason::DISABLE_NONE, Manifest::EXTERNAL_REGISTRY); ExtensionUpdateDataMap update_data; update_data[kExtensionId1] = {}; const auto data = data_provider->GetData(update_data, {kExtensionId1}); ASSERT_EQ(1UL, data.size()); EXPECT_EQ(version, data[0]->version.GetString()); EXPECT_NE(nullptr, data[0]->installer.get()); ASSERT_EQ(1UL, data[0]->disabled_reasons.size()); EXPECT_EQ(disable_reason::DisableReason::DISABLE_NONE, data[0]->disabled_reasons[0]); EXPECT_EQ("external", data[0]->install_location); } TEST_F(UpdateDataProviderTest, GetData_DisabledExtension_UnknownReason) { scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version = "0.1.2.3"; AddExtension(kExtensionId1, version, false, disable_reason::DisableReason::DISABLE_REASON_LAST, Manifest::COMMAND_LINE); ExtensionUpdateDataMap update_data; update_data[kExtensionId1] = {}; const auto data = data_provider->GetData(update_data, {kExtensionId1}); ASSERT_EQ(1UL, data.size()); EXPECT_EQ(version, data[0]->version.GetString()); EXPECT_NE(nullptr, data[0]->installer.get()); ASSERT_EQ(1UL, data[0]->disabled_reasons.size()); EXPECT_EQ(disable_reason::DisableReason::DISABLE_NONE, data[0]->disabled_reasons[0]); EXPECT_EQ("other", data[0]->install_location); } TEST_F(UpdateDataProviderTest, GetData_DisabledExtension_WithReasons) { scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version = "0.1.2.3"; AddExtension(kExtensionId1, version, false, disable_reason::DisableReason::DISABLE_USER_ACTION | disable_reason::DisableReason::DISABLE_CORRUPTED, Manifest::EXTERNAL_POLICY_DOWNLOAD); ExtensionUpdateDataMap update_data; update_data[kExtensionId1] = {}; const auto data = data_provider->GetData(update_data, {kExtensionId1}); ASSERT_EQ(1UL, data.size()); EXPECT_EQ(version, data[0]->version.GetString()); EXPECT_NE(nullptr, data[0]->installer.get()); ASSERT_EQ(2UL, data[0]->disabled_reasons.size()); EXPECT_EQ(disable_reason::DisableReason::DISABLE_USER_ACTION, data[0]->disabled_reasons[0]); EXPECT_EQ(disable_reason::DisableReason::DISABLE_CORRUPTED, data[0]->disabled_reasons[1]); EXPECT_EQ("policy", data[0]->install_location); } TEST_F(UpdateDataProviderTest, GetData_DisabledExtension_WithReasonsAndUnknownReason) { scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version = "0.1.2.3"; AddExtension(kExtensionId1, version, false, disable_reason::DisableReason::DISABLE_USER_ACTION | disable_reason::DisableReason::DISABLE_CORRUPTED | disable_reason::DisableReason::DISABLE_REASON_LAST, Manifest::EXTERNAL_PREF_DOWNLOAD); ExtensionUpdateDataMap update_data; update_data[kExtensionId1] = {}; const auto data = data_provider->GetData(update_data, {kExtensionId1}); ASSERT_EQ(1UL, data.size()); EXPECT_EQ(version, data[0]->version.GetString()); EXPECT_NE(nullptr, data[0]->installer.get()); ASSERT_EQ(3UL, data[0]->disabled_reasons.size()); EXPECT_EQ(disable_reason::DisableReason::DISABLE_NONE, data[0]->disabled_reasons[0]); EXPECT_EQ(disable_reason::DisableReason::DISABLE_USER_ACTION, data[0]->disabled_reasons[1]); EXPECT_EQ(disable_reason::DisableReason::DISABLE_CORRUPTED, data[0]->disabled_reasons[2]); EXPECT_EQ("external", data[0]->install_location); } TEST_F(UpdateDataProviderTest, GetData_MultipleExtensions) { // GetData with more than 1 extension. scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version1 = "0.1.2.3"; const std::string version2 = "9.8.7.6"; AddExtension(kExtensionId1, version1, true, disable_reason::DisableReason::DISABLE_NONE, Manifest::EXTERNAL_REGISTRY); AddExtension(kExtensionId2, version2, true, disable_reason::DisableReason::DISABLE_NONE, Manifest::UNPACKED); ExtensionUpdateDataMap update_data; update_data[kExtensionId1] = {}; update_data[kExtensionId2] = {}; const auto data = data_provider->GetData(update_data, {kExtensionId1, kExtensionId2}); ASSERT_EQ(2UL, data.size()); EXPECT_EQ(version1, data[0]->version.GetString()); EXPECT_NE(nullptr, data[0]->installer.get()); EXPECT_EQ(0UL, data[0]->disabled_reasons.size()); EXPECT_EQ("external", data[0]->install_location); EXPECT_EQ(version2, data[1]->version.GetString()); EXPECT_NE(nullptr, data[1]->installer.get()); EXPECT_EQ(0UL, data[1]->disabled_reasons.size()); EXPECT_EQ("other", data[1]->install_location); } TEST_F(UpdateDataProviderTest, GetData_MultipleExtensions_DisabledExtension) { // One extension is disabled. scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version1 = "0.1.2.3"; const std::string version2 = "9.8.7.6"; AddExtension(kExtensionId1, version1, false, disable_reason::DisableReason::DISABLE_CORRUPTED, Manifest::INTERNAL); AddExtension(kExtensionId2, version2, true, disable_reason::DisableReason::DISABLE_NONE, Manifest::EXTERNAL_PREF_DOWNLOAD); ExtensionUpdateDataMap update_data; update_data[kExtensionId1] = {}; update_data[kExtensionId2] = {}; const auto data = data_provider->GetData(update_data, {kExtensionId1, kExtensionId2}); ASSERT_EQ(2UL, data.size()); EXPECT_EQ(version1, data[0]->version.GetString()); EXPECT_NE(nullptr, data[0]->installer.get()); ASSERT_EQ(1UL, data[0]->disabled_reasons.size()); EXPECT_EQ(disable_reason::DisableReason::DISABLE_CORRUPTED, data[0]->disabled_reasons[0]); EXPECT_EQ("internal", data[0]->install_location); EXPECT_EQ(version2, data[1]->version.GetString()); EXPECT_NE(nullptr, data[1]->installer.get()); EXPECT_EQ(0UL, data[1]->disabled_reasons.size()); EXPECT_EQ("external", data[1]->install_location); } TEST_F(UpdateDataProviderTest, GetData_MultipleExtensions_NotInstalledExtension) { // One extension is not installed. scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version = "0.1.2.3"; AddExtension(kExtensionId1, version, true, disable_reason::DisableReason::DISABLE_NONE, Manifest::COMPONENT); ExtensionUpdateDataMap update_data; update_data[kExtensionId1] = {}; update_data[kExtensionId2] = {}; const auto data = data_provider->GetData(update_data, {kExtensionId1, kExtensionId2}); ASSERT_EQ(2UL, data.size()); ASSERT_NE(nullptr, data[0]); EXPECT_EQ(version, data[0]->version.GetString()); EXPECT_NE(nullptr, data[0]->installer.get()); EXPECT_EQ(0UL, data[0]->disabled_reasons.size()); EXPECT_EQ("other", data[0]->install_location); EXPECT_EQ(nullptr, data[1]); } TEST_F(UpdateDataProviderTest, GetData_MultipleExtensions_CorruptExtension) { // With non-default data, one extension is corrupted: // is_corrupt_reinstall=true. scoped_refptr<UpdateDataProvider> data_provider = base::MakeRefCounted<UpdateDataProvider>(browser_context()); const std::string version1 = "0.1.2.3"; const std::string version2 = "9.8.7.6"; const std::string initial_version = "0.0.0.0"; AddExtension(kExtensionId1, version1, true, disable_reason::DisableReason::DISABLE_NONE, Manifest::EXTERNAL_COMPONENT); AddExtension(kExtensionId2, version2, true, disable_reason::DisableReason::DISABLE_NONE, Manifest::EXTERNAL_POLICY); ExtensionUpdateDataMap update_data; auto& info1 = update_data[kExtensionId1]; auto& info2 = update_data[kExtensionId2]; info1.install_source = "webstore"; info2.is_corrupt_reinstall = true; info2.install_source = "sideload"; const auto data = data_provider->GetData(update_data, {kExtensionId1, kExtensionId2}); ASSERT_EQ(2UL, data.size()); EXPECT_EQ(version1, data[0]->version.GetString()); EXPECT_EQ("webstore", data[0]->install_source); EXPECT_EQ("other", data[0]->install_location); EXPECT_NE(nullptr, data[0]->installer.get()); EXPECT_EQ(0UL, data[0]->disabled_reasons.size()); EXPECT_EQ(initial_version, data[1]->version.GetString()); EXPECT_EQ("sideload", data[1]->install_source); EXPECT_EQ("policy", data[1]->install_location); EXPECT_NE(nullptr, data[1]->installer.get()); EXPECT_EQ(0UL, data[1]->disabled_reasons.size()); } } // namespace } // namespace extensions
37.353488
80
0.717532
[ "vector" ]
3e378c347f34ecd6597246ee8149b64de80834e6
12,229
cpp
C++
spoj/ACPC10G.cpp
tuket/challenges
456979020c78dfcae2f8681245000bb64a6aaf38
[ "Unlicense" ]
null
null
null
spoj/ACPC10G.cpp
tuket/challenges
456979020c78dfcae2f8681245000bb64a6aaf38
[ "Unlicense" ]
null
null
null
spoj/ACPC10G.cpp
tuket/challenges
456979020c78dfcae2f8681245000bb64a6aaf38
[ "Unlicense" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <bitset> using namespace std; typedef int64_t i64; typedef int8_t i8; typedef uint8_t u8; typedef int32_t i32; typedef uint32_t u32; struct P { i64 x, y; }; static constexpr i64 LU_SIZE = 10; static const i64 LU[LU_SIZE][LU_SIZE] = { {0, 3, 2, 3, 2, 3, 4, 5, 4, 5}, {3, 2, 1, 2, 3, 4, 3, 4, 5, 6}, {2, 1, 4, 3, 2, 3, 4, 5, 4, 5}, {3, 2, 3, 2, 3, 4, 3, 4, 5, 6}, {2, 3, 2, 3, 4, 3, 4, 5, 4, 5}, {3, 4, 3, 4, 3, 4, 5, 4, 5, 6}, {4, 3, 4, 3, 4, 5, 4, 5, 6, 5}, {5, 4, 5, 4, 5, 4, 5, 6, 5, 6}, {4, 5, 4, 5, 4, 5, 6, 5, 6, 7}, {5, 6, 5, 6, 5, 6, 5, 6, 7, 6}, }; static constexpr i64 TABLE_SIZE = 100; static i64 table[TABLE_SIZE+4][TABLE_SIZE+4]; i64 testTableHelper() { for(int y = 0; y < TABLE_SIZE+4; y++) for(int x = 0; x < TABLE_SIZE+4; x++) table[y][x] = 0x7FFF'FFFF'FFFF'FFFF; table[0+2][0+2] = 0; vector<P> q = {{0,0}}; while(not q.empty()) { static const P dp[] = { {-2, -1}, {-2, +1}, {-1, -2}, {-1, +2}, {+1, -2}, {+1, +2}, {+2, -1}, {+2, +1}, }; const P p = q.back(); q.pop_back(); const i64 c0 = table[p.y+2][p.x+2]; for(int i = 0; i < 8; i++) { const P np{ p.x+dp[i].x, p.y+dp[i].y }; if(np.x >= TABLE_SIZE+2 || np.y >= TABLE_SIZE+2 || np.x < -2 || np.y < -2) continue; i64& c1 = table[np.y+2][np.x+2]; if(c0+1 < c1) { c1 = c0+1; q.push_back(np); } } } }; i64 cost(P a, P b) { P c { abs(a.x-b.x), abs(a.y-b.y) }; i64 res = 0; if(c.x > c.y) { const i64 i = min( min(c.y, c.x-c.y), max(0L, max((c.x-LU_SIZE+2)/2, (c.y-LU_SIZE+1)/1)) ); c.x -= 2*i; c.y -= i; res += i; /*while(c.y > 0 && c.x > c.y && (c.x >= LU_SIZE || c.y >= LU_SIZE)) { c.x -= 2; c.y -= 1; res += 1; }*/ } else { const i64 i = min( min(c.x, c.y-c.x), max(0L, max((c.x-LU_SIZE+1)/1, (c.y-LU_SIZE+2)/2)) ); c.x -= i; c.y -= 2*i; res += i; /*while(c.x > 0 && c.y > c.x && (c.x >= LU_SIZE || c.y >= LU_SIZE)) { c.x -= 1; c.y -= 2; res += 1; }*/ } if(c.x >= LU_SIZE && c.y >= LU_SIZE) { const i64 i = min( max(0L, max((c.x-LU_SIZE+3)/3, (c.y-LU_SIZE+3)/3)), min(c.x/3, c.y/3) ); c.x -= 3*i; c.y -= 3*i; res += 2*i; /*while(c.x > 0 && c.y > 0 && (c.x >= LU_SIZE || c.y >= LU_SIZE)) { c.x -= 3; c.y -= 3; res += 2; }*/ } if(c.x >= LU_SIZE) { const i64 i = (c.x - LU_SIZE) / 4 + 1; c.x -= 4*i; res += 2*i; } else if(c.y >= LU_SIZE) { const i64 i = (c.y - LU_SIZE) / 4 + 1; c.y -= 4*i; res += 2*i; } res += LU[c.y][c.x]; return res; } i64 testTable() { //testTableHelper(); for(int y = 0; y < TABLE_SIZE; y++) { for(int x = 0; x < TABLE_SIZE; x++) { const i64 myCost = cost({0, 0}, {x, y}); const i64 rightCost = table[y+2][x+2]; if(myCost != rightCost) { printf("Error in {%d, %d}\n", x, y); printf("Has %ld, should have %ld\n", myCost, rightCost); } //printf("%3ld", rightCost); } //printf("\n"); } } i64 hungarianAlgorithm(const i64* costs, i32 n) { static i64 t[16*16]; for(i32 i = 0; i < n*n; i++) t[i] = costs[i]; // rows pass for(i32 y = 0; y < n; y++) { i64 minVal = t[y*n]; for(i32 x = 1; x < n; x++) minVal = min(minVal, t[x + y*n]); for(i32 x = 0; x < n; x++) t[x + y*n] -= minVal; } // cols pass for(i32 x = 0; x < n; x++) { i64 minVal = t[x]; for(i32 y = 1; y < n; y++) minVal = min(minVal, t[x + y*n]); for(i32 y = 0; y < n; y++) t[x + y*n] -= minVal; } // count zeros in each row/col static i32 zeros[32]; for(i32 y = 0; y < n; y++) { zeros[y] = 0; for(i32 x = 0; x < n; x++) if(t[x + y*n] == 0) zeros[y]++; } for(i32 x = 0; x < n; x++) { zeros[n+x] = 0; for(i32 y = 0; y < n; y++) if(t[x + y*n] == 0) zeros[n+x]++; } while(true) { //i32 zeros2[32]; //for(i32 i = 0; i < 2*n; i++) // zeros2[i] = zeros[i]; bitset<32> crossed = 0; /*{ for(i32 y = 0; y < n; y++) { for(i32 x = 0; x < n; x++) { if(t[x + n*y] == 0 && !crossed[n+x] && !crossed[y]) { if(zeros[n+x] > zeros[y]) crossed[n+x] = true; else crossed[y] = true; } } } }*/ // find min number of zero crossings //while(crossed.count() < n) { // assign rows that have one zero bitset<16*16> assigned = 0; bitset<32> crossed2 = 0; for(i32 y = 0; y < n; y++) { i32 countZeros = 0; for(i32 x = 0; x < n; x++) if(t[x + n*y] == 0 && !crossed2[n+x]) countZeros++; if(countZeros == 1) for(i32 x = 0; x < n; x++) { if(t[x + n*y] == 0 && !crossed2[n+x]) { crossed2[n+x] = true; crossed2[y] = true; assigned[x + n*y] = true; break; } } } // assign cols that have one zero for(i32 x = 0; x < n; x++) { i32 countZeros = 0; for(i32 y = 0; y < n; y++) if(t[x + n*y] == 0 && !crossed2[n+x] && !crossed2[y]) countZeros++; if(countZeros == 1) for(i32 y = 0; y < n; y++) { if(t[x + n*y] == 0 && !crossed2[n+x] && !crossed2[y]) { crossed2[n+x] = true; crossed2[y] = true; assigned[x + n*y] = true; break; } } } if(assigned.none()) { [&]{ for(int y = 0; y < n; y++) for(int x = 0; x < n; x++) { if(t[x + y*n] == 0) { crossed2[n+x] = true; crossed2[y] = true; assigned[x + n*y] = true; } } }(); } // Mark one having no assignments bitset<32> marked = 0; bitset<32> justMarkedRows = 0; bitset<32> justMarkedCols = 0; for(i32 y = 0; y < n; y++) { if(!crossed2[y]) { justMarkedRows[y] = true; marked[y] = true; break; } } do { // Mark columns having zeros in newly marked rows justMarkedCols = 0; for(i32 x = 0; x < n; x++) { for(i32 y = 0; y < n; y++) { if(justMarkedRows[y] && t[x + n*y] == 0 && !crossed2[y]) { justMarkedCols[x] = !marked[n+x] && true; break; } } } // Mark rows having assignments in newly marked columns justMarkedRows = 0; for(i32 y = 0; y < n; y++) { for(i32 x = 0; x < n; x++) { if(justMarkedCols[x] && assigned[x + n*y]) { justMarkedRows[y] = !marked[y] && true; break; } } } marked |= justMarkedRows; marked |= justMarkedCols << n; } while(justMarkedRows.any() || justMarkedCols.any()); // cross unmarked rows and marked cols for(i32 i = 0; i < n; i++) crossed[i] = !marked[i]; for(i32 i = 0; i < n; i++) crossed[n+i] = marked[n+i]; } if(crossed.count() == n) { i64 res = 0; for(i32 i = 0; i < n; i++) { i64 minZeros = 0x7FFF'FFFF'FFFF'FFFF; i64 minZerosInd = -1; for(i32 j = 0; j < 2*n; j++) if(zeros[j] > 0 && zeros[j] < minZeros) { minZeros = zeros[j]; minZerosInd = j; } { i32 j = minZerosInd; zeros[j] = 0; if(j < n) { // row i32 x; for(x = 0; x < n; x++) { if(zeros[x+n] && t[x + n*j] == 0) { zeros[x+n] = 0; res += costs[x + n*j]; break; } } for(i32 y = 0; y < n; y++) if(y != j && t[x + n*y] == 0) zeros[y]--; for(x++; x < n; x++) if(zeros[x+n] && t[x + n*j] == 0) zeros[x+n]--; } else { // col j -= n; i32 y; for(y = 0; y < n; y++) { if(zeros[y] && t[j + n*y] == 0) { zeros[y] = 0; res += costs[j + n*y]; break; } } for(i32 x = 0; x < n; x++) if(x != j && t[x + n*y] == 0) zeros[x+n]--; for(y++; y < n; y++) if(zeros[y] && t[j + n*y] == 0) zeros[y]--; } } } return res; } else { // crossed.count() < n i64 valMin = 0x7FFF'FFFF'FFFF'FFFF; for(i32 y = 0; y < n; y++) for(i32 x = 0; x < n; x++) { if(!crossed[y] && !crossed[x+n] && t[x+y*n] < valMin) { valMin = t[x+y*n]; } } for(i32 y = 0; y < n; y++) for(i32 x = 0; x < n; x++) { if(!crossed[y] && !crossed[x+n]) { t[x+y*n] -= valMin; if(t[x+y*n] == 0) { zeros[y]++; zeros[x+n]++; } } else if(crossed[y] && crossed[x+n]) { if(t[x+y*n] == 0) { zeros[y]--; zeros[x+n]--; } t[x+y*n] += valMin; } } } } } int main() { static P hh[16]; static P tt[16]; static i64 mm[16*16]; //testTable(); i64 n; cin >> n; i64 iCase = 1; while(n) { for(i64 i = 0; i < n; i++) cin >> hh[i].x >> hh[i].y; for(i64 i = 0; i < n; i++) cin >> tt[i].x >> tt[i].y; i64 end = 0; for(i64 i = 0; i < n; i++) for(i64 j = 0; j < n; j++) { mm[end] = cost(hh[i], tt[j]); //printf("%ld %ld: %ld\n", i, j, mm[end]); end++; } const i64 res = hungarianAlgorithm(mm, n); cout << iCase << ". " << res << endl; iCase++; cin >> n; } }
29.610169
86
0.318096
[ "vector" ]
3e3d3c264abf73d73812536835c095caa97b5dc0
22,296
cpp
C++
cmdnotify.cpp
bgirard/znc-cmd-notify
1151582c39e5e8833c68a7ddb53944f913dd2b70
[ "MIT" ]
8
2015-02-11T21:42:08.000Z
2021-04-23T11:33:46.000Z
cmdnotify.cpp
bgirard/znc-cmd-notify
1151582c39e5e8833c68a7ddb53944f913dd2b70
[ "MIT" ]
null
null
null
cmdnotify.cpp
bgirard/znc-cmd-notify
1151582c39e5e8833c68a7ddb53944f913dd2b70
[ "MIT" ]
3
2015-02-22T09:21:07.000Z
2016-05-10T03:21:54.000Z
/** * ZNC Cmd Notify * * Fowards a notify to a command of your choice * * Forked credits: * Copyright (c) 2011 John Reese * Licensed under the MIT license */ #include <map> #include <string> #include "znc/znc.h" #include "znc/Chan.h" #include "znc/User.h" #include "znc/IRCNetwork.h" #include "znc/Modules.h" #include "time.h" using std::map; using std::string; #if (!defined(VERSION_MAJOR) || !defined(VERSION_MINOR) || (VERSION_MAJOR == 0 && VERSION_MINOR < 207)) #error This module needs ZNC 0.207 or newer. #endif // Debug output #define NOTIFO_DEBUG 0 #if NOTIFO_DEBUG #define PutDebug(s) PutModule(s) #else #define PutDebug(s) //s #endif class CNotifoMod : public CModule { protected: // Application name CString app; // Too lazy to add CString("\r\n\") everywhere CString crlf; // User agent to use CString user_agent; // Time last notification was sent for a given context map <CString, unsigned int> last_notification_time; // Time of last message by user to a given context map <CString, unsigned int> last_reply_time; // Time of last activity by user for a given context map <CString, unsigned int> last_active_time; // Time of last activity by user in any context unsigned int idle_time; // User object CUser *user; // Network object CIRCNetwork *network; // Configuration options MCString options; MCString defaults; public: MODCONSTRUCTOR(CNotifoMod) { app = "ZNC"; crlf = "\r\n"; idle_time = time(NULL); user_agent = "ZNC To Notifo"; // Current user user = GetUser(); network = GetNetwork(); // Notifo user account and secret defaults["username"] = ""; defaults["secret"] = ""; // Condition strings defaults["channel_conditions"] = "all"; defaults["query_conditions"] = "all"; // Notification conditions defaults["away_only"] = "no"; defaults["client_count_less_than"] = "1"; defaults["highlight"] = "benwa"; defaults["idle"] = "0"; defaults["last_active"] = "0"; defaults["last_notification"] = "0"; defaults["nick_blacklist"] = ""; defaults["replied"] = "no"; // Notification settings defaults["message_length"] = "1024"; defaults["message_uri"] = ""; // Shell command settings defaults["cmd"] = "/etc/znc_notify.sh"; } virtual ~CNotifoMod() {} protected: /** * Shorthand for encoding a string for a URL. * * @param str String to be encoded * @return Encoded string */ CString urlencode(const CString& str) { return str.Escape_n(CString::EASCII, CString::EURL); } /** * Performs string expansion on a set of keywords. * Given an initial string and a dictionary of string replacments, * iterate over the dictionary, expanding keywords one-by-one. * * @param content String contents * @param replace Dictionary of string replacements * @return Result of string replacements */ CString expand(const CString& content, MCString& replace) { CString result = content.c_str(); for(MCString::iterator i = replace.begin(); i != replace.end(); i++) { result.Replace(i->first, i->second); } return result; } /** * Send a message to the currently-configured Notifo account. * Requires (and assumes) that the user has already configured their * username and API secret using the 'set' command. * * @param message Message to be sent to the user * @param title Message title to use * @param context Channel or nick context */ bool send_message(const CString& message, const CString& title="New Message", const CString& context="*notifo", const CNick& nick=CString("*notifo")) { // Set the last notification time last_notification_time[context] = time(NULL); // Shorten message if needed unsigned int message_length = options["message_length"].ToUInt(); CString short_message = message; if (message_length > 0) { short_message = message.Ellipsize(message_length); } // Generate an ISO8601 date string time_t rawtime; struct tm * timeinfo; time(&rawtime); timeinfo = localtime(&rawtime); char iso8601 [20]; strftime(iso8601, 20, "%Y-%m-%d %H:%M:%S", timeinfo); CString cmd = message; int pid; pid = fork(); if(pid < 0) /* process creation failed */ { return false; } else if(pid == 0) /* child executes this */ { execl("/bin/bash", "-c", options["cmd"].c_str(), cmd.c_str(), NULL); /* tells the child to stop executing this code */ PutIRC("PRIVMSG " + nick.GetNick() + " : Send fail."); exit(0); /* and start executing pidgin..or w/e you want*/ } else /* parent executes this */ { } return true; } /** * Evaluate a boolean expression using condition values. * All tokens must be separated by spaces, using "and" and "or" for * boolean operators, "(" and ")" to enclose sub-expressions, and * condition option names to evaluate each condition. * * @param expression Boolean expression string * @param context Notification context * @param nick Sender nick * @param message Message contents * @return Result of boolean evaluation */ bool eval(const CString& expression, const CString& context=CString(""), const CNick& nick=CNick(""), const CString& message=" ") { CString padded = expression.Replace_n("(", " ( "); padded.Replace(")", " ) "); VCString tokens; padded.Split(" ", tokens, false); PutDebug("Evaluating message: <" + nick.GetNick() + "> " + message); bool result = eval_tokens(tokens.begin(), tokens.end(), context, nick, message); return result; } #define expr(x, y) else if (token == x) { \ bool result = y; \ dbg += CString(x) + "/" + CString(result ? "true" : "false") + " "; \ value = oper ? value && result : value || result; \ } /** * Evaluate a tokenized boolean expression, or sub-expression. * * @param pos Token vector iterator current position * @param end Token vector iterator end position * @param context Notification context * @param nick Sender nick * @param message Message contents * @return Result of boolean expression */ bool eval_tokens(VCString::iterator pos, VCString::iterator end, const CString& context, const CNick& nick, const CString& message) { bool oper = true; bool value = true; CString dbg = ""; for(; pos != end; pos++) { CString token = pos->AsLower(); if (token == "(") { // recursively evaluate sub-expressions bool inner = eval_tokens(++pos, end, context, nick, message); dbg += "( inner/" + CString(inner ? "true" : "false") + " ) "; value = oper ? value && inner : value || inner; // search ahead to the matching parenthesis token unsigned int parens = 1; while(pos != end) { if (*pos == "(") { parens++; } else if (*pos == ")") { parens--; } if (parens == 0) { break; } pos++; } } else if (token == ")") { pos++; PutDebug(dbg); return value; } else if (token == "and") { dbg += "and "; oper = true; } else if (token == "or") { dbg += "or "; oper = false; } expr("true", true) expr("false", false) expr("away_only", away_only()) expr("client_count_less_than", client_count_less_than()) expr("highlight", highlight(message)) expr("idle", idle()) expr("last_active", last_active(context)) expr("last_notification", last_notification(context)) expr("nick_blacklist", nick_blacklist(nick)) expr("replied", replied(context)) else { PutModule("Error: Unexpected token \"" + token + "\""); } } PutDebug(dbg); return value; } #undef expr protected: /** * Check if the away status condition is met. * * @return True if away_only is not "yes" or away status is set */ bool away_only() { CString value = options["away_only"].AsLower(); return value != "yes" || network->IsIRCAway(); } /** * Check how many clients are connected to ZNC. * * @return Number of connected clients */ unsigned int client_count() { return network->GetClients().size(); } /** * Check if the client_count condition is met. * * @return True if client_count is less than client_count_less_than or if client_count_less_than is zero */ bool client_count_less_than() { unsigned int value = options["client_count_less_than"].ToUInt(); return value == 0 || client_count() < value; } /** * Determine if the given message matches any highlight rules. * * @param message Message contents * @return True if message matches a highlight */ bool highlight(const CString& message) { CString msg = " " + message.AsLower() + " "; VCString values; options["highlight"].Split(" ", values, false); for (VCString::iterator i = values.begin(); i != values.end(); i++) { CString value = i->AsLower(); char prefix = value[0]; bool notify = true; if (prefix == '-') { notify = false; value.LeftChomp(1); } else if (prefix == '_') { value = " " + value.LeftChomp_n(1) + " "; } value = "*" + value + "*"; if (msg.WildCmp(value)) { return notify; } } CNick nick = network->GetIRCNick(); if (message.find(nick.GetNick()) != string::npos) { return true; } return false; } /** * Check if the idle condition is met. * * @return True if idle is zero or elapsed time is greater than idle */ bool idle() { unsigned int value = options["idle"].ToUInt(); unsigned int now = time(NULL); return value == 0 || idle_time + value < now; } /** * Check if the last_active condition is met. * * @param context Channel or nick context * @return True if last_active is zero or elapsed time is greater than last_active */ bool last_active(const CString& context) { unsigned int value = options["last_active"].ToUInt(); unsigned int now = time(NULL); return value == 0 || last_active_time.count(context) < 1 || last_active_time[context] + value < now; } /** * Check if the last_notification condition is met. * * @param context Channel or nick context * @return True if last_notification is zero or elapsed time is greater than last_nofication */ bool last_notification(const CString& context) { unsigned int value = options["last_notification"].ToUInt(); unsigned int now = time(NULL); return value == 0 || last_notification_time.count(context) < 1 || last_notification_time[context] + value < now; } /** * Check if the nick_blacklist condition is met. * * @param nick Nick that sent the message * @return True if nick is not in the blacklist */ bool nick_blacklist(const CNick& nick) { VCString blacklist; options["nick_blacklist"].Split(" ", blacklist, false); CString name = nick.GetNick().AsLower(); for (VCString::iterator i = blacklist.begin(); i != blacklist.end(); i++) { if (name.WildCmp(i->AsLower())) { return false; } } return true; } /** * Check if the replied condition is met. * * @param context Channel or nick context * @return True if last_reply_time > last_notification_time or if replied is not "yes" */ bool replied(const CString& context) { CString value = options["replied"].AsLower(); return value != "yes" || last_notification_time[context] == 0 || last_notification_time[context] < last_reply_time[context]; } /** * Determine when to notify the user of a channel message. * * @param nick Nick that sent the message * @param channel Channel the message was sent to * @param message Message contents * @return Notification should be sent */ bool notify_channel(const CNick& nick, const CChan& channel, const CString& message) { CString context = channel.GetName(); CString expression = options["channel_conditions"].AsLower(); if (expression != "all") { return eval(expression, context, nick, message); } return away_only() && client_count_less_than() && highlight(message) && idle() && last_active(context) && last_notification(context) && nick_blacklist(nick) && replied(context) && true; } /** * Determine when to notify the user of a private message. * * @param nick Nick that sent the message * @return Notification should be sent */ bool notify_pm(const CNick& nick, const CString& message) { CString context = nick.GetNick(); CString expression = options["query_conditions"].AsLower(); if (expression != "all") { return eval(expression, context, nick, message); } return away_only() && client_count_less_than() && idle() && last_active(context) && last_notification(context) && nick_blacklist(nick) && replied(context) && true; } protected: /** * Handle the plugin being loaded. Retrieve plugin config values. * * @param args Plugin arguments * @param message Message to show the user after loading */ bool OnLoad(const CString& args, CString& message) { for (MCString::iterator i = defaults.begin(); i != defaults.end(); i++) { CString value = GetNV(i->first); if (value != "") { options[i->first] = value; } else { options[i->first] = defaults[i->first]; } } return true; } /** * Handle channel messages. * * @param nick Nick that sent the message * @param channel Channel the message was sent to * @param message Message contents */ EModRet OnChanMsg(CNick& nick, CChan& channel, CString& message) { if (notify_channel(nick, channel, message)) { CString title = "Highlight"; CString msg = channel.GetName(); msg += ": <" + nick.GetNick(); msg += "> " + message; send_message(msg, title, channel.GetName()); } return CONTINUE; } /** * Handle channel actions. * * @param nick Nick that sent the action * @param channel Channel the message was sent to * @param message Message contents */ EModRet OnChanAction(CNick& nick, CChan& channel, CString& message) { if (notify_channel(nick, channel, message)) { CString title = "Highlight"; CString msg = channel.GetName(); msg += ": " + nick.GetNick(); msg += " " + message; send_message(msg, title, channel.GetName()); } return CONTINUE; } /** * Handle a private message. * * @param nick Nick that sent the message * @param message Message contents */ EModRet OnPrivMsg(CNick& nick, CString& message) { if (notify_pm(nick, message)) { CString title = "Private Message"; CString msg = "From " + nick.GetNick(); msg += ": " + message; bool sent = send_message(msg, title, nick.GetNick()); if (sent) { PutIRC("PRIVMSG " + nick.GetNick() + " : [znc] User not connected. Notification message sent."); } else { PutIRC("PRIVMSG " + nick.GetNick() + " : [znc] User not connected. Notification message failed to send."); } } return CONTINUE; } /** * Handle a private action. * * @param nick Nick that sent the action * @param message Message contents */ EModRet OnPrivAction(CNick& nick, CString& message) { return OnPrivMsg(nick, message); } /** * Handle a message sent by the user. * * @param target Target channel or nick * @param message Message contents */ EModRet OnUserMsg(CString& target, CString& message) { last_reply_time[target] = last_active_time[target] = idle_time = time(NULL); return CONTINUE; } /** * Handle an action sent by the user. * * @param target Target channel or nick * @param message Message contents */ EModRet OnUserAction(CString& target, CString& message) { last_reply_time[target] = last_active_time[target] = idle_time = time(NULL); return CONTINUE; } /** * Handle the user joining a channel. * * @param channel Channel name * @param key Channel key */ EModRet OnUserJoin(CString& channel, CString& key) { idle_time = time(NULL); return CONTINUE; } /** * Handle the user parting a channel. * * @param channel Channel name * @param message Part message */ EModRet OnUserPart(CString& channel, CString& message) { idle_time = time(NULL); return CONTINUE; } /** * Handle the user setting the channel topic. * * @param channel Channel name * @param topic Topic message */ EModRet OnUserTopic(CString& channel, CString& topic) { idle_time = time(NULL); return CONTINUE; } /** * Handle the user requesting the channel topic. * * @param channel Channel name */ EModRet OnUserTopicRequest(CString& channel) { idle_time = time(NULL); return CONTINUE; } /** * Handle direct commands to the *notifo virtual user. * * @param command Command string */ void OnModCommand(const CString& command) { VCString tokens; int token_count = command.Split(" ", tokens, false); if (token_count < 1) { return; } CString action = tokens[0].AsLower(); // SET command if (action == "set") { if (token_count < 3) { PutModule("Usage: set <option> <value>"); return; } CString option = tokens[1].AsLower(); CString value = command.Token(2, true, " "); MCString::iterator pos = options.find(option); if (pos == options.end()) { PutModule("Error: invalid option name"); } else { if (option == "channel_conditions" || option == "query_conditions") { if (value != "all") { eval(value); } } options[option] = value; options[option].Trim(); SetNV(option, options[option]); } } // APPEND command else if (action == "append") { if (token_count < 3) { PutModule("Usage: append <option> <value>"); return; } CString option = tokens[1].AsLower(); CString value = command.Token(2, true, " "); MCString::iterator pos = options.find(option); if (pos == options.end()) { PutModule("Error: invalid option name"); } else { options[option] += " " + value; options[option].Trim(); SetNV(option, options[option]); } } // PREPEND command else if (action == "prepend") { if (token_count < 3) { PutModule("Usage: prepend <option> <value>"); return; } CString option = tokens[1].AsLower(); CString value = command.Token(2, true, " "); MCString::iterator pos = options.find(option); if (pos == options.end()) { PutModule("Error: invalid option name"); } else { options[option] = value + " " + options[option]; options[option].Trim(); SetNV(option, options[option]); } } // UNSET command else if (action == "unset") { if (token_count != 2) { PutModule("Usage: unset <option>"); return; } CString option = tokens[1].AsLower(); MCString::iterator pos = options.find(option); if (pos == options.end()) { PutModule("Error: invalid option name"); } else { options[option] = defaults[option]; DelNV(option); } } // GET command else if (action == "get") { if (token_count > 2) { PutModule("Usage: get [<option>]"); return; } if (token_count < 2) { CTable table; table.AddColumn("Option"); table.AddColumn("Value"); for (MCString::iterator i = options.begin(); i != options.end(); i++) { table.AddRow(); table.SetCell("Option", i->first); table.SetCell("Value", i->second); } PutModule(table); return; } CString option = tokens[1].AsLower(); MCString::iterator pos = options.find(option); if (pos == options.end()) { PutModule("Error: invalid option name"); } else { PutModule(option + CString(": \"") + options[option] + CString("\"")); } } // STATUS command else if (action == "status") { CTable table; table.AddColumn("Condition"); table.AddColumn("Status"); table.AddRow(); table.SetCell("Condition", "away"); table.SetCell("Status", network->IsIRCAway() ? "yes" : "no"); table.AddRow(); table.SetCell("Condition", "client_count"); table.SetCell("Status", CString(client_count())); unsigned int now = time(NULL); unsigned int ago = now - idle_time; table.AddRow(); table.SetCell("Condition", "idle"); table.SetCell("Status", CString(ago) + " seconds"); if (token_count > 1) { CString context = tokens[1]; table.AddRow(); table.SetCell("Condition", "last_active"); if (last_active_time.count(context) < 1) { table.SetCell("Status", "n/a"); } else { ago = now - last_active_time[context]; table.SetCell("Status", CString(ago) + " seconds"); } table.AddRow(); table.SetCell("Condition", "last_notification"); if (last_notification_time.count(context) < 1) { table.SetCell("Status", "n/a"); } else { ago = now - last_notification_time[context]; table.SetCell("Status", CString(ago) + " seconds"); } table.AddRow(); table.SetCell("Condition", "replied"); table.SetCell("Status", replied(context) ? "yes" : "no"); } PutModule(table); } // SEND command else if (action == "send") { CString message = command.Token(1, true, " ", true); send_message(message); } // HELP command else if (action == "help") { PutModule("View the detailed documentation at https://github.com/bgirard/znc-cmd-notify/blob/master/README.md"); } // EVAL command else if (action == "eval") { CString value = command.Token(1, true, " "); PutModule(eval(value) ? "true" : "false"); } else { PutModule("Error: invalid command, try `help`"); } } }; MODULEDEFS(CNotifoMod, "Send highlights and personal messages to a Notifo account")
23.273486
151
0.613428
[ "object", "vector" ]
3e3d954bb4cacc9859b0e02baa518a0cf1737f95
583
hpp
C++
include/lives.hpp
ishansheth/ArkanoidGame
81a6e48ef8ebb32dd19bbb18aeb0d95e7a1cd4d5
[ "MIT" ]
null
null
null
include/lives.hpp
ishansheth/ArkanoidGame
81a6e48ef8ebb32dd19bbb18aeb0d95e7a1cd4d5
[ "MIT" ]
null
null
null
include/lives.hpp
ishansheth/ArkanoidGame
81a6e48ef8ebb32dd19bbb18aeb0d95e7a1cd4d5
[ "MIT" ]
null
null
null
#ifndef SRC_LIVES_HPP_ #define SRC_LIVES_HPP_ #include "circle.hpp" #include "entity.hpp" #include <vector> /** * The class is responsible to show the circular dots which represent the number of live player has in the game */ class lives : public Entity, public Circle { sf::CircleShape shape; public: static constexpr float defRadius{5.f}; lives(float mX,float mY,bool updateStatus); ~lives(); virtual void draw(sf::RenderWindow& mTarget) override; virtual void update() override; virtual bool checkEntityDied() override; }; #endif /* SRC_LIVES_HPP_ */
20.821429
111
0.728988
[ "shape", "vector" ]
3e3e1f14a8e4a2f9c38ad477e16e7a82686bcc08
3,187
cpp
C++
LevelEditor/Edit/ESound_Environment.cpp
MlssingTexture/xray-sdk
648de11d78fcc8088e802572da6187ee9b198f9f
[ "CC0-1.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
LevelEditor/Edit/ESound_Environment.cpp
MlssingTexture/xray-sdk
648de11d78fcc8088e802572da6187ee9b198f9f
[ "CC0-1.0" ]
null
null
null
LevelEditor/Edit/ESound_Environment.cpp
MlssingTexture/xray-sdk
648de11d78fcc8088e802572da6187ee9b198f9f
[ "CC0-1.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
//--------------------------------------------------------------------------- #include "stdafx.h" #pragma hdrstop #include "ESound_Environment.h" #include "EShape.h" #include "ui_levelmain.h" //---------------------------------------------------- #define SOUND_SEL0_COLOR 0x00A0A0A0 #define SOUND_SEL1_COLOR 0x00FFFFFF #define SOUND_NORM_COLOR 0x000000FF #define SOUND_LOCK_COLOR 0x00FF0000 //---------------------------------------------------- #define SOUND_ENV_VERSION 0x0012 //---------------------------------------------------- #define SOUND_CHUNK_VERSION 0x1001 #define SOUND_CHUNK_ENV_SHAPE 0x1002 #define SOUND_CHUNK_ENV_REFS 0x1003 //---------------------------------------------------- ESoundEnvironment::ESoundEnvironment(LPVOID data, LPCSTR name) :CEditShape(data,name) { Construct(data); } void ESoundEnvironment::Construct(LPVOID data) { ClassID = OBJCLASS_SOUND_ENV; add_box (Fidentity); SetDrawColor (0x205050FF, 0xFF202020); m_EnvInner = ""; m_EnvOuter = ""; } ESoundEnvironment::~ESoundEnvironment() { } //---------------------------------------------------- void ESoundEnvironment::OnUpdateTransform() { inherited::OnUpdateTransform(); ExecCommand (COMMAND_REFRESH_SOUND_ENV_GEOMETRY); } //---------------------------------------------------- bool ESoundEnvironment::Load(IReader& F) { u32 version = 0; R_ASSERT(F.r_chunk(SOUND_CHUNK_VERSION,&version)); if(version!=SOUND_ENV_VERSION){ ELog.DlgMsg( mtError, "ESoundSource: Unsupported version."); return false; } inherited::Load (F); R_ASSERT(F.find_chunk(SOUND_CHUNK_ENV_REFS)); F.r_stringZ (m_EnvInner); F.r_stringZ (m_EnvOuter); return true; } void ESoundEnvironment::Save(IWriter& F) { inherited::Save (F); F.open_chunk (SOUND_CHUNK_VERSION); F.w_u16 (SOUND_ENV_VERSION); F.close_chunk (); F.open_chunk (SOUND_CHUNK_ENV_REFS); F.w_stringZ (m_EnvInner); F.w_stringZ (m_EnvOuter); F.close_chunk (); } //---------------------------------------------------- void ESoundEnvironment::OnChangeEnvs (PropValue* prop) { ExecCommand (COMMAND_REFRESH_SOUND_ENV_GEOMETRY); } //---------------------------------------------------- void ESoundEnvironment::FillProp(LPCSTR pref, PropItemVec& values) { inherited::FillProp (pref, values); PropValue* P; P=PHelper().CreateChoose (values, PrepareKey(pref,"Environment Inner"), &m_EnvInner, smSoundEnv); P->OnChangeEvent.bind (this,&ESoundEnvironment::OnChangeEnvs); P=PHelper().CreateChoose (values, PrepareKey(pref,"Environment Outer"), &m_EnvOuter, smSoundEnv); P->OnChangeEvent.bind (this,&ESoundEnvironment::OnChangeEnvs); } //---------------------------------------------------- bool ESoundEnvironment::GetSummaryInfo(SSceneSummary* inf) { inherited::GetSummaryInfo (inf); return true; } void ESoundEnvironment::get_box(Fmatrix& m) { CShapeData::shape_def shape = get_shape(0); R_ASSERT(shape.type==CShapeData::cfBox); m.mul (_Transform(),shape.data.box); } void ESoundEnvironment::OnSceneUpdate() { inherited::OnSceneUpdate(); ExecCommand( COMMAND_REFRESH_SOUND_ENV_GEOMETRY ); }
26.558333
101
0.603389
[ "shape" ]
3e4063f53ad860edb6e96c96b900eb5c57783049
1,585
cpp
C++
src/uscxml/plugins/datamodel/ecmascript/v8/dom/V8XPathResultCustom.cpp
sradomski/uscxml
b8ba0e7c31f397a66f9d509ff20a85b33619475a
[ "W3C", "BSD-2-Clause" ]
null
null
null
src/uscxml/plugins/datamodel/ecmascript/v8/dom/V8XPathResultCustom.cpp
sradomski/uscxml
b8ba0e7c31f397a66f9d509ff20a85b33619475a
[ "W3C", "BSD-2-Clause" ]
null
null
null
src/uscxml/plugins/datamodel/ecmascript/v8/dom/V8XPathResultCustom.cpp
sradomski/uscxml
b8ba0e7c31f397a66f9d509ff20a85b33619475a
[ "W3C", "BSD-2-Clause" ]
null
null
null
/** * @file * @author 2012-2013 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de) * @copyright Simplified BSD * * @cond * This program is free software: you can redistribute it and/or modify * it under the terms of the FreeBSD license as published by the FreeBSD * project. * * 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. * * You should have received a copy of the FreeBSD license along with this * program. If not, see <http://www.opensource.org/licenses/bsd-license>. * @endcond */ #include "V8XPathResult.h" #include "V8Node.h" namespace Arabica { namespace DOM { v8::Handle<v8::Value> V8XPathResult::singleNodeValueCustomAttrGetter(v8::Local<v8::String> property, const v8::AccessorInfo& info) { v8::Local<v8::Object> self = info.Holder(); V8XPathResultPrivate* privData = V8DOM::toClassPtr<V8XPathResultPrivate >(self->GetInternalField(0)); Arabica::DOM::Node<std::string>* retVal = new Arabica::DOM::Node<std::string>(privData->nativeObj->asNodeSet()[0]); v8::Handle<v8::Function> retCtor = V8Node::getTmpl()->GetFunction(); v8::Persistent<v8::Object> retObj = v8::Persistent<v8::Object>::New(retCtor->NewInstance()); struct V8Node::V8NodePrivate* retPrivData = new V8Node::V8NodePrivate(); retPrivData->dom = privData->dom; retPrivData->nativeObj = retVal; retObj->SetInternalField(0, V8DOM::toExternal(retPrivData)); retObj.MakeWeak(0, V8Node::jsDestructor); return retObj; } } }
34.456522
132
0.728707
[ "object" ]
3e40cfddf027a1a02c9318cafef6eaf4e29a2cd4
6,670
cc
C++
homework-3/src/assn3.cc
lherman-cs/cs4050
8976f99d2b96449abab2fcad14960dd694c7e071
[ "MIT" ]
null
null
null
homework-3/src/assn3.cc
lherman-cs/cs4050
8976f99d2b96449abab2fcad14960dd694c7e071
[ "MIT" ]
null
null
null
homework-3/src/assn3.cc
lherman-cs/cs4050
8976f99d2b96449abab2fcad14960dd694c7e071
[ "MIT" ]
null
null
null
// // Programming Assignment #1 // // Victor Zordan // // // /***************************************************************************/ /** * Name : Lukas Herman * Homework # : 1 * * Conventions : * - "_": means previous value. Ex: x_last_ -> previous value of x_last */ /* Include needed files */ #include <GL/gl.h> #include <GL/glu.h> #include <GL/glut.h> // The GL Utility Toolkit (Glut) Header #include <assert.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <algorithm> #include <cmath> #include <fstream> #include <iostream> #include <limits> #include <numeric> #include <stack> #include <unordered_map> #include <vector> #include "color.hpp" #include "model.hpp" #include "utils.hpp" #define WIDTH 800 #define HEIGHT 800 #define BUMP_MAP_FILE "bump_map.pgm" #define SMOOTH 1 #define BUMPY 2 int x_last, y_last; Model *model; double bm[HEIGHT][WIDTH] = {0}; static const Coordinate eye = {0.0, 0.0, 2.0}; static const Coordinate light = {0.0, 0.0, 2.0}; static const Color background = Color(1.0); static const Color ambient = get_ambient(); // My functions void init_display(const char *model_path); void display(void); void render(int mode); void set_bump_map(double bm[][WIDTH]); // Your functions void init_window(void); void write_pixel(int x, int y, const Color &color); void mouse(int button, int state, int x, int y); void keyboard(unsigned char key, int x, int y); /***************************************************************************/ int main(int argc, char *argv[]) { /* This main function sets up the main loop of the program and continues the loop until the end of the data is reached. Then the window can be closed using the escape key. */ if (argc != 2) { printf("Usage: ./assn2 [model_path]\n"); return 1; } glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(WIDTH, HEIGHT); glutCreateWindow("Computer Graphics"); glutDisplayFunc(display); glutIdleFunc(display); glutMouseFunc(mouse); glutKeyboardFunc(keyboard); init_window(); // create_window init_display(argv[1]); glutMainLoop(); // Initialize The Main Loop } // My functions start here void init_display(const char *model_path) { model = new Model(model_path); set_bump_map(bm); render(0); glutSwapBuffers(); } void render(int mode) { int row, col; double n_row, n_col; // Normalized row and col bool intersected; Coordinate normal, screen_pixel, direction, intersected_point, to_source, to_viewer, shadow_ray_eye, shadow_ray_direction; Color illumination; Triangle closest; for (row = 0; row < HEIGHT; row++) { for (col = 0; col < WIDTH; col++) { n_row = (double)row / (HEIGHT - 1) - 0.5; n_col = (double)col / (WIDTH - 1) - 0.5; screen_pixel = Coordinate(n_col, n_row, 1.5); direction = (screen_pixel - eye).normalize(); intersected_point = Coordinate(); closest = Triangle(); // Determine the closest intersected triangle switch (mode & 1) { case 0: // Flat shading default: intersected = model->find_closest_intersection( eye, direction, &closest, &intersected_point, nullptr); normal = closest.normal; break; case 1: // Smooth shading intersected = model->find_closest_intersection( eye, direction, &closest, &intersected_point, &normal); break; } if (mode >> 1) normal = normal * bm[row][col]; // Calculate Phong Shading if (intersected) { Color illumination = ambient; to_source = (light - intersected_point).normalize(); to_viewer = (eye - intersected_point).normalize(); shadow_ray_eye = intersected_point; shadow_ray_direction = (light - shadow_ray_eye).normalize(); intersected = model->is_shadowed(shadow_ray_eye, shadow_ray_direction, closest); if (!intersected) illumination = illumination + get_diffuse(to_source, normal) + get_specular(to_source, normal, to_viewer); write_pixel(col, row, illumination); } else write_pixel(col, row, background); } } } void set_bump_map(double bm[][WIDTH]) { std::ifstream fin(BUMP_MAP_FILE); std::string type; int width, height, max_bit; fin >> type >> width >> height >> max_bit; if (!(type == "P2" || type == "P5")) std::cerr << "The image format is not in PGM\n"; for (int row = 0; row < height; row++) { for (int col = 0; col < width; col++) { fin >> bm[row][col]; bm[row][col] /= max_bit; } } fin.close(); } void display(void) {} /***************************************************************************/ void init_window() /* Clear the image area, and set up the coordinate system */ { /* Clear the window */ glClearColor(0.0, 0.0, 0.0, 0.0); glShadeModel(GL_SMOOTH); glOrtho(0, WIDTH, 0, HEIGHT, -1.0, 1.0); } /***************************************************************************/ void write_pixel(int x, int y, const Color &color) /* Turn on the pixel found at x,y */ { glColor3f(color.red, color.blue, color.green); glBegin(GL_POINTS); glVertex3i(x, y, 0); glEnd(); } /***************************************************************************/ void mouse(int button, int state, int x, int y) { /* This function I finessed a bit, the value of the printed x,y should match the screen, also it remembers where the old value was to avoid multiple readings from the same mouse click. This can cause problems when trying to start a line or curve where the last one ended */ static int oldx = 0; static int oldy = 0; int mag; y *= -1; // align y with mouse y += 500; // ignore mag = (oldx - x) * (oldx - x) + (oldy - y) * (oldy - y); if (mag > 20) { printf(" x,y is (%d,%d)\n", x, y); } oldx = x; oldy = y; x_last = x; y_last = y; } /***************************************************************************/ void keyboard(unsigned char key, int x, int y) // Create Keyboard Function { static int mode = 0; switch (key) { case 27: // When Escape Is Pressed... exit(0); // Exit The Program break; case '1': // stub for new screen printf("New screen\n"); break; case 'x': mode = (mode & 2) | ((mode & 1) ^ 1); render(mode); glutSwapBuffers(); break; case 'b': mode = ((mode & 2) ^ 2) | (mode & 1); render(mode); glutSwapBuffers(); break; } }
26.573705
78
0.585007
[ "render", "vector", "model" ]
3e414deef5ffe8802f87de07b59ea04f7bf412f0
27,806
cpp
C++
src/ontology.cpp
severin-lemaignan/liboro
058168bbabd7d79fbf38e242695ba15a6bea5deb
[ "ISC" ]
1
2019-04-24T01:18:16.000Z
2019-04-24T01:18:16.000Z
src/ontology.cpp
severin-lemaignan/liboro
058168bbabd7d79fbf38e242695ba15a6bea5deb
[ "ISC" ]
null
null
null
src/ontology.cpp
severin-lemaignan/liboro
058168bbabd7d79fbf38e242695ba15a6bea5deb
[ "ISC" ]
1
2019-01-31T17:54:59.000Z
2019-01-31T17:54:59.000Z
/* * Copyright (c) 2008-2010 LAAS-CNRS Séverin Lemaignan slemaign@laas.fr * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <algorithm> #include "oro.h" #include "oro_event.h" #include "oro_exceptions.h" #ifdef DEBUG #define TRACE(arg) (std::cerr << "[LIBORO DEBUG] " << arg << std::endl) #else #define TRACE(arg) sizeof(std::cerr << arg << std::endl) #endif using namespace std; using namespace boost; namespace oro { Ontology* Ontology::_instance = NULL; map<string, Ontology::EventObserver> Ontology::_eventObservers; // Protected constructor Ontology::Ontology(IConnector& connector) : _connector(connector) { cerr << "liboro v." << ORO_VERSION; //Initializes the random generator for later generation of unique id for concepts. srand(time(NULL)); _bufferize = false; //By default, always wait for acks. _waitForAck = true; _buf_op_counter = 0; if (!checkOntologyServer()) { cerr << "\nCannot reach the ontology server! Check it is started and that the middleware link is up.\n"; throw OntologyServerException("Cannot reach the ontology server. Abandon."); } _connector.setEventCallback(Ontology::evtCallback); //TODO : destructor required if resources need to be released. } //Singleton creation Ontology* Ontology::createWithConnector(IConnector& connector){ if (_instance == NULL) _instance = new Ontology(connector); cerr << " - ontology initialized." << endl; return _instance; } //Singleton access Ontology* Ontology::getInstance(){ if (_instance != NULL) return _instance; else throw UninitializedOntologyException("the ontology is not properly initialized. Created with Ontology::createWithConnector(IConnector&) before any access attempt."); } bool Ontology::checkOntologyServer(){ ServerResponse res = _connector.execute("stats"); if (res.status != ServerResponse::ok) return false; try { string version = (get<map<string, string> >(res.result))["version"]; cerr << " - oro-server v." << version; } catch (bad_get e) { cerr << "Internal error: oro-server answered malformed results at initialization!"; return false; } return true; } void Ontology::evtCallback(const std::string& event_id, const server_return_types& raw_event_content){ set<Concept> event_content; try { set<string> raw_content = get<set<string> >(raw_event_content); copy( raw_content.begin(), raw_content.end(), inserter(event_content, event_content.begin())); } catch (bad_get e) { try { string raw_content = get<string>(raw_event_content); if (raw_content != "") { cerr << "A set of string or an empty string is expected in the event content! I discard this event" << endl; return; } } catch (bad_get e) { cerr << "A set of string or an empty string is expected in the event content! I discard this event" << endl; return; } } //Create a new event object OroEvent e(event_id, event_content); //Call the liboro event subscriber callback; std::map<std::string, EventObserver>::iterator it; it = _eventObservers.find(event_id); if (it != _eventObservers.end()) { EventObserver& eo = it->second; (*eo.first)(e); //If the event is a "one shot", remove it from the event list if (eo.second) _eventObservers.erase(event_id); } else cerr << "[EE] Got a callback on an event I don't know!" << endl; } void Ontology::bufferize(){ _bufferize = true; _buf_op_counter++; } void Ontology::flush(){ if (!_bufferize) return; if (!(_buf_op_counter--)) return; //more that one on-going bufferization operation? decrement the counter and return. //cout << "End of bufferization" << endl; _bufferize = false; /**** ADD ****/ set<Statement> stmtToAdd; //copy(_buffer["add"].begin(), _buffer["add"].end(), stmtToAdd.begin()); for(BufStatements::iterator i = _buffer["add"].begin() ; i != _buffer["add"].end() ; ++i) { stmtToAdd.insert(i->second); } if (stmtToAdd.size() > 0) add(stmtToAdd); _buffer["add"].clear(); /**** REMOVE ****/ set<Statement> stmtToRemove; //copy(_buffer["remove"].begin(), _buffer["remove"].end(), stmtToRemove.begin()); for(BufStatements::iterator i = _buffer["remove"].begin() ; i != _buffer["remove"].end() ; ++i) { stmtToRemove.insert(i->second); } if (stmtToRemove.size() > 0) remove(stmtToRemove); //the order we call add and remove doesn't matter if the buffer is carefully filled through Ontology::addToBuffer. Else, if the same statement is first removed and then added, the flush operation will only retain the "remove"! _buffer["remove"].clear(); /**** UPDATE ****/ set<Statement> stmtToUpdate; //copy(_buffer["update"].begin(), _buffer["update"].end(), stmtToUpdate.begin()); for(BufStatements::iterator i = _buffer["update"].begin() ; i != _buffer["update"].end() ; ++i) { stmtToUpdate.insert(i->second); } if (stmtToUpdate.size() > 0) update(stmtToUpdate); _buffer["update"].clear(); } void Ontology::addToBuffer(const string action, const Statement& stmt) { // If the connector is disconnected, don't bufferize anything anymore // and clear the buffer. if (!_connector.isConnected()) { cerr << "[WW] Server disconnected, discarding buffered facts" << endl; _buffer["add"].clear(); _buffer["remove"].clear(); _buffer["update"].clear(); return; } //TODO replace vectors by sets or lists. It's stupid to use vectors. if (action == "add") { //here we remove all the previous requests to "remove" this very statement, since the "add" cancel them. BufStatements::iterator i = _buffer["remove"].find(stmt.to_string()); if( i != _buffer["remove"].end()) { _buffer["remove"].erase(i); } else _buffer["add"].insert(pair<string, Statement>(stmt.to_string(), stmt)); } else if (action == "remove") { //here we remove all the previous requests to "add" this very statement, since the "remove" cancel them. BufStatements::iterator i = _buffer["add"].find(stmt.to_string()); if( i != _buffer["add"].end()) { _buffer["add"].erase(i); } else _buffer["remove"].insert(pair<string, Statement>(stmt.to_string(), stmt)); } else if (action == "update") { _buffer["update"].insert(pair<string, Statement>(stmt.to_string(), stmt)); } } void Ontology::add(const Statement& statement){ set<Statement> tmp; tmp.insert(statement); add(tmp); } void Ontology::add(const set<Statement>& statements){ set<string> stringified_stmts; set<Statement>::const_iterator iterator = statements.begin(); while( iterator != statements.end() ) { if (_bufferize) addToBuffer("add", *iterator); else stringified_stmts.insert(iterator->to_string()); ++iterator; } if (!_bufferize) { ServerResponse res = _connector.execute("add", stringified_stmts, _waitForAck); if (res.status == ServerResponse::failed) throw OntologyServerException("Server threw a " + res.exception_msg + " while adding statements. Server message was " + res.error_msg); } } void Ontology::remove(const Statement& statement){ set<Statement> tmp; tmp.insert(statement); remove(tmp); } void Ontology::remove(const set<Statement>& statements){ set<string> stringified_stmts; set<Statement>::const_iterator iterator = statements.begin(); while( iterator != statements.end() ) { if (_bufferize) addToBuffer("remove", (Statement)*iterator); stringified_stmts.insert(((Statement)*iterator).to_string()); ++iterator; } if (!_bufferize) { ServerResponse res = _connector.execute("remove", stringified_stmts, _waitForAck); if (res.status == ServerResponse::failed) throw OntologyServerException("Server" + res.exception_msg + " while removing statements. Server message was " + res.error_msg); } } void Ontology::update(const Statement& statement){ set<Statement> tmp; tmp.insert(statement); update(tmp); } void Ontology::update(const set<Statement>& statements){ set<string> stringified_stmts; set<Statement>::const_iterator iterator = statements.begin(); while( iterator != statements.end() ) { if (_bufferize) addToBuffer("update", (Statement)*iterator); stringified_stmts.insert(((Statement)*iterator).to_string()); ++iterator; } if (!_bufferize) { ServerResponse res = _connector.execute("update", stringified_stmts, _waitForAck); if (res.status == ServerResponse::failed) throw OntologyServerException("Server" + res.exception_msg + " while updating statements. Server message was " + res.error_msg); } } void Ontology::addForAgent(const string& agent, const Statement& statement){ set<Statement> tmp; tmp.insert(statement); addForAgent(agent, tmp); } void Ontology::addForAgent(const string& agent, const set<Statement>& statements){ vector<server_param_types> parameters; set<string> stringified_stmts; set<Statement>::const_iterator iterator = statements.begin(); TRACE("Got 'addForAgent' call with parameters:"); while( iterator != statements.end() ) { TRACE("- " << iterator->to_string()); stringified_stmts.insert(iterator->to_string()); ++iterator; } parameters.push_back(agent); parameters.push_back(stringified_stmts); ServerResponse res = _connector.execute("addForAgent", parameters, _waitForAck); if (res.status == ServerResponse::failed) throw OntologyServerException("Server threw a " + res.exception_msg + " while adding statements for agent " + agent + ". Server message was " + res.error_msg); } void Ontology::removeForAgent(const string& agent, const Statement& statement){ set<Statement> tmp; tmp.insert(statement); removeForAgent(agent, tmp); } void Ontology::removeForAgent(const string& agent, const set<Statement>& statements){ vector<server_param_types> parameters; set<string> stringified_stmts; set<Statement>::const_iterator iterator = statements.begin(); TRACE("Got 'removeForAgent' call with parameters:"); while( iterator != statements.end() ) { TRACE("- " << iterator->to_string()); stringified_stmts.insert(iterator->to_string()); ++iterator; } parameters.push_back(agent); parameters.push_back(stringified_stmts); ServerResponse res = _connector.execute("removeForAgent", parameters, _waitForAck); if (res.status == ServerResponse::failed) throw OntologyServerException("Server threw a " + res.exception_msg + " while removing statements for agent " + agent + ". Server message was " + res.error_msg); } void Ontology::updateForAgent(const string& agent, const Statement& statement){ set<Statement> tmp; tmp.insert(statement); updateForAgent(agent, tmp); } void Ontology::updateForAgent(const string& agent, const set<Statement>& statements){ vector<server_param_types> parameters; set<string> stringified_stmts; set<Statement>::const_iterator iterator = statements.begin(); TRACE("Got 'updateForAgent' call with parameters:"); while( iterator != statements.end() ) { TRACE("- " << iterator->to_string()); stringified_stmts.insert(iterator->to_string()); ++iterator; } parameters.push_back(agent); parameters.push_back(stringified_stmts); ServerResponse res = _connector.execute("updateForAgent", parameters, _waitForAck); if (res.status == ServerResponse::failed) throw OntologyServerException("Server threw a " + res.exception_msg + " while updating statements for agent " + agent + ". Server message was " + res.error_msg); } void Ontology::clear(const set<string>& statements){ ServerResponse res = _connector.execute("clear", statements, _waitForAck); if (res.status == ServerResponse::failed) throw OntologyServerException("Server" + res.exception_msg + " while clearing statements from the ontology. Server message was " + res.error_msg); } void Ontology::clearForAgent(const string& agent, const set<string>& statements){ vector<server_param_types> parameters; TRACE("Got 'clearForAgent' call"); parameters.push_back(agent); parameters.push_back(statements); ServerResponse res = _connector.execute("clearForAgent", parameters, _waitForAck); if (res.status == ServerResponse::failed) throw OntologyServerException("Server threw a " + res.exception_msg + " while clearing statements in " + agent + "'s model. Server message was " + res.error_msg); } bool Ontology::checkConsistency(){ TRACE("Got 'checkConsistency' call"); ServerResponse res = _connector.execute("checkConsistency"); if (res.status == ServerResponse::failed) throw OntologyServerException(("Server" + res.exception_msg + " while checking consistency. Server message was " + res.error_msg).c_str()); if(get<bool>(res.result) == true) return true; return false; } void Ontology::save(const string& path){ ServerResponse res = _connector.execute("save", path); if (res.status == ServerResponse::failed) throw OntologyServerException("Server" + res.exception_msg + " while saving the ontology. Server message was " + res.error_msg); } void Ontology::reload(){ ServerResponse res = _connector.execute("reload"); if (res.status == ServerResponse::failed) throw OntologyServerException("Server" + res.exception_msg + " while reloading the ontology. Server message was " + res.error_msg); } map<string, string> Ontology::stats(){ map<string, string> result; ServerResponse res = _connector.execute("stats"); if (res.status == ServerResponse::failed) throw OntologyServerException(("Server " + res.exception_msg + " while fetching stats. Server message was " + res.error_msg).c_str()); try { result = get<map<string, string> >(res.result); } catch (bad_get e) { throw OntologyServerException("INTERNAL ERROR! Server returned wrong type of data while fetching stats. Please contact the maintener (openrobots@laas.fr)"); } return result; } void Ontology::find(const std::string& resource, const std::set<std::string>& partial_statements, const std::set<std::string>& restrictions, std::set<Concept>& result){ set<string> rawResult; vector<server_param_types> args; args.push_back(resource); args.push_back(partial_statements); args.push_back(restrictions); ServerResponse res = _connector.execute("find", args); if (res.status != ServerResponse::ok) { throw OntologyServerException("\"filtred find\" operation was not successful: server threw a " + res.exception_msg + " (" + res.error_msg +")"); } rawResult = get<set<string> >(res.result); copy(rawResult.begin(), rawResult.end(), inserter(result, result.begin())); } void Ontology::find(const std::string& resource, const std::set<std::string>& partial_statements, std::set<Concept>& result){ set<string> rawResult; vector<server_param_types> args; args.push_back(resource); args.push_back(partial_statements); ServerResponse res = _connector.execute("find", args); if (res.status != ServerResponse::ok) { throw OntologyServerException("\"Find\" operation was not successful: server threw a " + res.exception_msg + " (" + res.error_msg +")"); } try { rawResult = get<set<string> >(res.result); copy(rawResult.begin(), rawResult.end(), inserter(result, result.begin())); } catch (bad_get e) { //nothing was returned. That's fine. } } void Ontology::find(const std::string& resource, const std::string& partial_statement, std::set<Concept>& result){ set<string> tmp; tmp.insert(partial_statement); find(resource, tmp, result); } //TODO: Some code factorization around would be welcome... void Ontology::findForAgent(const string& agent, const std::string& resource, const std::set<std::string>& partial_statements, const std::set<std::string>& restrictions, std::set<Concept>& result){ TRACE("Got 'findForAgent' call"); set<string> rawResult; vector<server_param_types> args; args.push_back(agent); args.push_back(resource); args.push_back(partial_statements); args.push_back(restrictions); ServerResponse res = _connector.execute("findForAgent", args); if (res.status != ServerResponse::ok) { throw OntologyServerException("\"filtred findForAgent\" operation was not successful: server threw a " + res.exception_msg + " (" + res.error_msg +")"); } rawResult = get<set<string> >(res.result); copy(rawResult.begin(), rawResult.end(), inserter(result, result.begin())); } void Ontology::findForAgent(const string& agent, const std::string& resource, const std::set<std::string>& partial_statements, std::set<Concept>& result){ TRACE("Got 'findForAgent' call"); set<string> rawResult; vector<server_param_types> args; args.push_back(agent); args.push_back(resource); args.push_back(partial_statements); ServerResponse res = _connector.execute("findForAgent", args); if (res.status != ServerResponse::ok) { throw OntologyServerException("\"FindForAgent\" operation was not successful: server threw a " + res.exception_msg + " (" + res.error_msg +")"); } rawResult = get<set<string> >(res.result); copy(rawResult.begin(), rawResult.end(), inserter(result, result.begin())); } void Ontology::findForAgent(const string& agent, const std::string& resource, const std::string& partial_statement, std::set<Concept>& result){ TRACE("Got 'findForAgent' call"); set<string> tmp; tmp.insert(partial_statement); findForAgent(agent, resource, tmp, result); } void Ontology::guess(const std::string& resource, const double threshold, const std::vector<std::string>& partial_statements, std::set<std::string>& result){ throw OntologyException("Not yet implemented!"); } void Ontology::query(const string& var_name, const string& query, set<string>& result){ vector<server_param_types> args; args.push_back(var_name); args.push_back(query); ServerResponse res = _connector.execute("query", args); if (res.status != ServerResponse::ok) { if (res.exception_msg.find(SERVER_QUERYPARSE_EXCEPTION) != string::npos) throw InvalidQueryException(query + "\nYour SPARQL query is invalid: " + res.error_msg); throw OntologyServerException("Query was not successful: server threw a " + res.exception_msg + " (" + res.error_msg +")."); } if (set<string>* result_p = get<set<string> >(&res.result)) result = *result_p; } void Ontology::getDirectClasses(const string& resource, set<Concept>& result){ map<string, string> rawResult; ServerResponse res = _connector.execute("getDirectClassesOf", resource); if (res.status != ServerResponse::ok) { if (res.exception_msg.find(SERVER_NOTFOUND_EXCEPTION) != string::npos) throw ResourceNotFoundOntologyException(resource + " does not exist in the current ontology."); else throw OntologyServerException("Couldn't retrieve infos on " + resource + ": server threw a " + res.exception_msg + " (" + res.error_msg +")."); } if (res.status != ServerResponse::ok) { throw OntologyServerException("\"Find\" operation was not successful: server threw a " + res.exception_msg + " (" + res.error_msg +")"); } try { rawResult = get<map<string, string> >(res.result); for(map<string,string>::const_iterator iter = rawResult.begin(); iter != rawResult.end(); ++iter) result.insert(iter->first); } catch (bad_get e) { //nothing was returned. That's fine. } } void Ontology::getInfos(const string& resource, set<string>& result){ ServerResponse res = _connector.execute("getInfos", resource); if (res.status != ServerResponse::ok) { if (res.exception_msg.find(SERVER_NOTFOUND_EXCEPTION) != string::npos) throw ResourceNotFoundOntologyException(resource + " does not exist in the current ontology."); else throw OntologyServerException("Couldn't retrieve infos on " + resource + ": server threw a " + res.exception_msg + " (" + res.error_msg +")."); } result = get<set<string> >(res.result); } void Ontology::getInfosForAgent(const string& agent, const string& resource, set<string>& result){ vector<server_param_types> args; args.push_back(agent); args.push_back(resource); ServerResponse res = _connector.execute("getInfosForAgent", args); if (res.status != ServerResponse::ok) { if (res.exception_msg.find(SERVER_NOTFOUND_EXCEPTION) != string::npos) throw ResourceNotFoundOntologyException(resource + " does not exist in the current ontology."); else throw OntologyServerException("Couldn't retrieve infos on " + resource + ": server threw a " + res.exception_msg + " (" + res.error_msg +")."); } result = get<set<string> >(res.result); } void Ontology::getResourceDetails(const string& resource, string& result){ ServerResponse res = _connector.execute("getResourceDetails", resource); if (res.status != ServerResponse::ok) { if (res.exception_msg.find(SERVER_NOTFOUND_EXCEPTION) != string::npos) throw ResourceNotFoundOntologyException(resource + " does not exist in the current ontology."); else throw OntologyServerException("Couldn't retrieve details on " + resource + ": server threw a " + res.exception_msg + " (" + res.error_msg +")."); } result = res.raw_result; } map<string, string> Ontology::lookup(const string& id) { map<string, string> result; ServerResponse res = _connector.execute("lookup", id); if (res.status != ServerResponse::ok) { throw OntologyServerException("lookup was not successful: server threw a " + res.exception_msg + " (" + res.error_msg +")."); } try { result = get<map<string, string> >(res.result); } catch (bad_get e) { // no result. That's fine. } return result; } string Ontology::getLabel(const string& id) { string label; ServerResponse res = _connector.execute("getLabel", id); if (res.status != ServerResponse::ok) { throw OntologyServerException("getLabel was not successful: server threw a " + res.exception_msg + " (" + res.error_msg +")."); } try { label = get<string>(res.result); } catch (bad_get e) { throw OntologyServerException("getLabel was not successful: unexpected error while deserializing the label."); } return label; } string Ontology::registerEvent( OroEventObserver& callback, EventType eventType, EventTriggeringType triggerType, const std::set<std::string>& pattern, const std::string& variable_to_bind){ return registerEventForAgent(callback, "", eventType, triggerType, pattern, variable_to_bind); } string Ontology::registerEventForAgent( OroEventObserver& callback, const string& agent, EventType eventType, EventTriggeringType triggerType, const std::set<std::string>& pattern, const std::string& variable_to_bind){ vector<server_param_types> args; bool oneShot = false; string event_id; string eventTypeStr; string triggerTypeStr; switch (eventType){ //Painful, but no obvious way to workaround that... case FACT_CHECKING: eventTypeStr = NAME_OF(FACT_CHECKING); break; case NEW_INSTANCE: eventTypeStr = NAME_OF(NEW_INSTANCE); break; case NEW_CLASS_INSTANCE: eventTypeStr = NAME_OF(NEW_CLASS_INSTANCE); break; } switch (triggerType){ //Painful, but no obvious way to workaround that... case ON_TRUE: triggerTypeStr = NAME_OF(ON_TRUE); break; case ON_TRUE_ONE_SHOT: triggerTypeStr = NAME_OF(ON_TRUE_ONE_SHOT); oneShot = true; break; case ON_FALSE: triggerTypeStr = NAME_OF(ON_FALSE); break; case ON_FALSE_ONE_SHOT: triggerTypeStr = NAME_OF(ON_FALSE_ONE_SHOT); oneShot = true; break; case ON_TOGGLE: triggerTypeStr = NAME_OF(ON_TOGGLE); break; } if (agent != "") args.push_back(agent); args.push_back(eventTypeStr); args.push_back(triggerTypeStr); if (variable_to_bind != "") args.push_back(variable_to_bind); args.push_back(pattern); ServerResponse res; if (agent != "") res = _connector.execute("registerEventForAgent", args); else res = _connector.execute("registerEvent", args); if (res.status != ServerResponse::ok) { throw OntologyServerException("Couldn't register event: server threw a " + res.exception_msg + " (" + res.error_msg +")."); } try { event_id = get<string>(res.result); } catch (bad_get e) { cerr << "[EE] Serious error while registering an event! Please report it to openrobots@laas.fr. " << e.what() << endl; } //Store the newly registered event in the list of event observers std::map<std::string, EventObserver>::iterator it; it = _eventObservers.find(event_id); if (it != _eventObservers.end()) cerr << "[II] Event id already known. Re-registering an previous event. Fine." << endl; else { EventObserver e(&callback, oneShot); _eventObservers[event_id] = e; cerr << "[II] New event registered with id " << event_id << endl; } return event_id; } void Ontology::clearEvents(){ TRACE("Got 'clearEvents' call"); ServerResponse res = _connector.execute("clearEvents"); if (res.status == ServerResponse::failed) throw OntologyServerException(("Server" + res.exception_msg + " while checking consistency. Server message was " + res.error_msg).c_str()); } string Ontology::newId(int length) { string result; for(int i=0; i<length; i++) { result += (char)(rand() % 26 + 97); //ASCII codes of letters starts at 98 for "a" } return result; } }
33.541616
281
0.657808
[ "object", "vector", "model" ]
3e43232fa484ff2dfeebb703a031787756f3b4e1
3,657
cpp
C++
practicas/lab_9_greedyAlgorithms/WateringGrass/wateringGrass.cpp
JackMerma/Adagrupob
240b4155a68cf0672299d93f8dc0b61abba2e5e4
[ "BSD-3-Clause" ]
null
null
null
practicas/lab_9_greedyAlgorithms/WateringGrass/wateringGrass.cpp
JackMerma/Adagrupob
240b4155a68cf0672299d93f8dc0b61abba2e5e4
[ "BSD-3-Clause" ]
null
null
null
practicas/lab_9_greedyAlgorithms/WateringGrass/wateringGrass.cpp
JackMerma/Adagrupob
240b4155a68cf0672299d93f8dc0b61abba2e5e4
[ "BSD-3-Clause" ]
null
null
null
/** * @author : Jackson Fernando Merma Portocarrero (jmermap@unsa.edu.pe) * @filename : wateringGrass */ #include <bits/stdc++.h> using namespace std; #define ll long long #define ld long double #define endl "\n" #define PI 3.1415926535897932384626 /** * Explanation: * Para resolverlo, primero se agregan solo a los circulos que puedan * rellenar al menos el ancho del rectangulo; luego, se deben calcular por cada circulo, * el limite derecho e izquierdo que forman cuando intersectan con * el rectangulo, es decir, el circulo forma una franja de interseccion * con el rectangulo, de ello, solo es necesario determinar el limite de * ese sub-rectangulo que ocupara dicho circulo; luego este se inserta * al arreglo y se ordena de menor a mayor por los limites izquierdos * * Luego, para maximizar la respuesta, se maneja un limite estatico o * general, que determina hasta que parte ya se relleno el rectangulo, * si este en algun punto no se puede rellenas (no cambia el limite * estatico), entonces se imprime -1, pero si llega al final, se trendra * la respuesta maximizada. */ void solve(int n, long int l, int w){ /** * Metodo solve: Metodo para desarrollar cada caso * Atributos: * n -> cantidad de sprinklers * l -> longitud del espacio (largo del rectangulo) * w -> angho del espacio (ancho del rectangulo) */ // almacena a limite (izquiedo - derecho) => (first - second) vector<pair<double, double>> sprinklersValues;//arreglo principal for(int i=0;i<n;i++){ long int x; int r; cin>>x>>r; if(r>=w/2.0){//si el circulo llega a cubrir al menos el ancho del espacio //los limites estan dados mediante el uso de la formula del circulo // r^2 = (w/2)^2 + (k)^2 => r^2 = (w^2)/4 + (k)^2 // luego ... r^2 - (w^2)/4 = (k)^2 // finalmente ... k = (r^2 - (w^2)/4)^0.5 // entonces, k, sera esa distancia (largo) que se forma // cuando intersecta el circulo y el rectangulo double k = sqrt(r*r-w*w/4.0);// +/- de rectangulos formados por // los limites que forman el circulo y // rectangulo x*=1.0; sprinklersValues.push_back(make_pair(x-k,x+k));//agregando ambos limites } } //se ordena en secuencia lineal del limite izquierdo (como esta en el caso de muestra - grafico) sort(sprinklersValues.begin(), sprinklersValues.end()); double limit = 0;//limite actual int ans = 0, ini = 0;//respuesta e inicio while(limit < l){//solo los necesarios ans ++;//se aumenta la respuesta double limit_aux = limit; //primero se maximizan los limites de los rectangulos (limites dentro de otros limites) for(int i = ini; i < sprinklersValues.size() && sprinklersValues[i].first <= limit_aux; i++){ if(limit < sprinklersValues[i].second)//si esta dentro del limite principal limit = sprinklersValues[i].second; } if(limit_aux < l && limit_aux == limit){ //no se cumplio el objetivo y hay espacios no rellenados cout<<-1<<endl; return; } } cout<<ans<<endl; } int main(){ /* Metodo principal */ ios_base::sync_with_stdio(0); cin.tie(0); int n, w; long int l; while(cin>>n>>l>>w){//hasta que se pueda insertar n, l, w solve(n,l,w);//cada caso } return 0; }
34.17757
101
0.59475
[ "vector" ]