blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
4c2cb5bb260e2f0a69cb107e8a0bf52f9dc7f568
be284ec2c25db7663da06ff9157f9634a437c3de
/unittest/stdafx.h
fa430a548020d6d9e1dbe34d684255cf484cd8a4
[ "BSD-3-Clause" ]
permissive
hi-eeprom/charls
4dd28a8525c0ee3ede9d20c6a0606db63432718b
5f1f2086f445fedc2fed797277b8e0e16281a62f
refs/heads/master
2020-03-25T16:58:03.772735
2018-08-05T22:24:54
2018-08-05T22:24:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
798
h
stdafx.h
// // (C) CharLS Team 2017, all rights reserved. See the accompanying "License.txt" for licensed use. // #pragma once #pragma warning(push) #pragma warning(disable : 26432) #pragma warning(disable : 26433) #pragma warning(disable : 26439) #pragma warning(disable : 26440) #pragma warning(disable : 26443) #pragma warning(disable : 26461) #pragma warning(disable : 26466) #pragma warning(disable : 26495) #pragma warning(disable : 26496) #include <CppUnitTest.h> #pragma warning(pop) #include <memory> #include <cstdint> #include <vector> #ifdef _MSC_VER #define WARNING_SUPPRESS(x) __pragma(warning(push)) __pragma(warning(disable : x)) // NOLINT(misc-macro-parentheses) #define WARNING_UNSUPPRESS() __pragma(warning(pop)) #else #define WARNING_SUPPRESS(x) #define WARNING_UNSUPPRESS() #endif
62689f60e4e1fb0ef61ca67b9c54a0823acae3aa
e279602fd9195847e5a3e66059a733fe2aab131d
/TestBasalAreaLight.cpp
5ce282f287b138d18c9b329c3c6de10847d4614c
[]
no_license
LMurphy186232/Core_Model_Tester
c79790cca322f119f9faec0c5b3d02730ec42676
b27464daf579d86bc4f38287c7e6f813e65ced6c
refs/heads/master
2023-08-25T01:34:00.495799
2023-08-16T16:41:52
2023-08-16T16:41:52
39,648,065
1
0
null
2023-08-03T12:59:21
2015-07-24T17:39:38
C++
UTF-8
C++
false
false
72,930
cpp
TestBasalAreaLight.cpp
//--------------------------------------------------------------------------- // TestBasalAreaLight.cpp //--------------------------------------------------------------------------- #include "TestBasalAreaLight.h" #include <gtest/gtest.h> #include "Grid.h" #include "SimManager.h" #include "BehaviorBase.h" #include "TreePopulation.h" #include "BasalAreaLight.h" #include <math.h> #include <fstream> //////////////////////////////////////////////////////////////////////////// // TestErrorProcessing() //////////////////////////////////////////////////////////////////////////// TEST(BasalAreaLight, TestErrorProcessing) { clSimManager * p_oSimManager = new clSimManager( 7, 1, "" ); try { p_oSimManager->ReadFile( WriteBasalAreaLightXMLErrorFile1() ); FAIL() << "TestBasalAreaLight error processing didn't catch error for WriteBasalAreaLightXMLErrorFile1."; } catch ( modelErr& err ) { if ( err.sFunction.compare("clBasalAreaLight::DoShellSetup" ) != 0 ) { FAIL() << "TestBasalAreaLight error processing caught wrong error for WriteBasalAreaLightXMLErrorFile1."; } ; } try { p_oSimManager->ReadFile( WriteBasalAreaLightXMLErrorFile2() ); FAIL() << "TestBasalAreaLight error processing didn't catch error for WriteBasalAreaLightXMLErrorFile2."; } catch ( modelErr& err ) { if ( err.sFunction.compare("clBasalAreaLight::DoShellSetup" ) != 0 ) { FAIL() << "TestBasalAreaLight error processing caught wrong error for WriteBasalAreaLightXMLErrorFile2."; } ; } try { p_oSimManager->ReadFile( WriteBasalAreaLightXMLErrorFile3() ); FAIL() << "TestBasalAreaLight error processing didn't catch error for WriteBasalAreaLightXMLErrorFile3."; } catch ( modelErr& err ) { if ( err.sFunction.compare("clBasalAreaLight::DoShellSetup" ) != 0 ) { FAIL() << "TestBasalAreaLight error processing caught wrong error for WriteBasalAreaLightXMLErrorFile3."; } ; } try { p_oSimManager->ReadFile( WriteBasalAreaLightXMLErrorFile4() ); FAIL() << "TestBasalAreaLight error processing didn't catch error for WriteBasalAreaLightXMLErrorFile4."; } catch ( modelErr& err ) { if ( err.sFunction.compare("clBasalAreaLight::DoShellSetup" ) != 0 ) { FAIL() << "TestBasalAreaLight error processing caught wrong error for WriteBasalAreaLightXMLErrorFile4."; } ; } try { p_oSimManager->ReadFile( WriteBasalAreaLightXMLErrorFile5() ); FAIL() << "TestBasalAreaLight error processing didn't catch error for WriteBasalAreaLightXMLErrorFile5."; } catch ( modelErr& err ) { if ( err.sFunction.compare("clBasalAreaLight::DoShellSetup" ) != 0 ) { FAIL() << "TestBasalAreaLight error processing caught wrong error for WriteBasalAreaLightXMLErrorFile5."; } ; } delete p_oSimManager; } ///////////////////////////////////////////////////////////////////////////// // NormalProcessingRun1() // Tests normal processing - run 1. This checks the calculation of mean GLI // and verifies that new light level calculations are triggered correctly. // WriteBasalAreaLightXMLFile1() does setup. ///////////////////////////////////////////////////////////////////////////// TEST(BasalAreaLight, NormalProcessingRun1) { clSimManager * p_oSimManager = new clSimManager( 7, 1, "" ); try { clTreePopulation *p_oPop; clBehaviorBase *p_oTemp; clBasalAreaLight *p_oLightBeh; clGrid *p_oLightGrid; clTree *p_oTree1, *p_oTree2, *p_oTree3, *p_oTree4, *p_oTree5, *p_oTree6, *p_oTree7, *p_oTree8, *p_oTree9, *p_oTree10, *p_oTree11, *p_oTree12, *p_oTree13, *p_oTree14, *p_oTree15, *p_oTree16, *p_oTree17, *p_oTree18, *p_oTree19, *p_oTree20, *p_oTree21, *p_oTree22, *p_oTree23, *p_oTree24, *p_oTree25, *p_oTree26, *p_oTree27, *p_oTree28, *p_oTree29, *p_oTree30, *p_oTree31, *p_oTree32; float fActualLight, //Light level calculated by SORTIE fExpectedLight, //Light level we're expecting fExpConBA, //Conifer basal area we're expecting fExpAngBA, //Angiosperm basal area we're expecting fActualConBA, //Conifer basal area calculated by SORTIE fActualAngBA, //Angiosperm basal area calculated by SORTIE fDiam, fX, fY, //For creating trees //For stashing light levels between timesteps fLight1, fLight2, fLight3, fLight4, fLight5, fLight6, fLight7; int iLightCode, iConBACode, iAngBACode, iX, iY, iNumXCells, iSpecies, iNumYCells; //Feed our file to the sim manager p_oSimManager->ReadFile(WriteBasalAreaLightXMLFile1()); p_oPop = (clTreePopulation*) p_oSimManager->GetPopulationObject("treepopulation"); //Add trees to three grid cells //Grid Cell 0,1: 1 conifer fX = 4; fY = 12; iSpecies = 2; fDiam = 50; p_oTree1 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); //Grid cell 0,2: 1 angiosperm. fX = 4; fY = 20; iSpecies = 1; fDiam = 45; p_oTree2 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); //Grid cell 0,3: 3 conifers, plus more too small fX = 4; fY = 28; iSpecies = 0; fDiam = 45; p_oTree3 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 2; fDiam = 24; p_oTree4 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 2; fDiam = 70; p_oTree5 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 0; fDiam = 8; p_oTree6 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 2; fDiam = 9; p_oTree7 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); //Grid cell 0,4: 5 angiosperms, plus more too small. fX = 4; fY = 36; iSpecies = 3; fDiam = 45; p_oTree8 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 1; fDiam = 24; p_oTree9 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 1; fDiam = 70; p_oTree10 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 3; fDiam = 18; p_oTree11 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 1; fDiam = 31; p_oTree12 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 3; fDiam = 6; p_oTree13 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 1; fDiam = 4; p_oTree14 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); //Grid cell 0,5: 6 trees, mixed conifer and angiosperm, plus more too small, //and snags fX = 4; fY = 44; iSpecies = 3; fDiam = 45; p_oTree15 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 1; fDiam = 24; p_oTree16 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 1; fDiam = 70; p_oTree17 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 3; fDiam = 18; p_oTree18 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 1; fDiam = 31; p_oTree19 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 3; fDiam = 6; p_oTree20 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 1; fDiam = 4; p_oTree21 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 0; fDiam = 45; p_oTree22 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 2; fDiam = 24; p_oTree23 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 1; fDiam = 70; p_oTree24 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 0; fDiam = 8; p_oTree25 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 2; fDiam = 9; p_oTree26 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 0; fDiam = 100; p_oTree27 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::snag, fDiam ); //Grid cell 0,6: Several trees, all too small. fX = 4; fY = 52; iSpecies = 3; fDiam = 3; p_oTree28 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 0; fDiam = 6; p_oTree29 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 2; fDiam = 3; p_oTree30 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); iSpecies = 1; fDiam = 9; p_oTree31 = p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); //Check the mean GLI calculations directly for several values p_oTemp = p_oSimManager->GetBehaviorObject("basalarealightshell"); p_oLightBeh = dynamic_cast<clBasalAreaLight*>(p_oTemp); fExpectedLight = 12.4; fActualConBA = 0; fActualAngBA = 0; fActualLight = p_oLightBeh->GetMeanGLI(fActualConBA, fActualAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 12.22827861; fActualConBA = 0.196349541; fActualAngBA = 0; fActualLight = p_oLightBeh->GetMeanGLI(fActualConBA, fActualAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 12.3998466; fActualConBA = 0; fActualAngBA = 0.159043128; fActualLight = p_oLightBeh->GetMeanGLI(fActualConBA, fActualAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 11.25757809; fActualConBA = 0.589127162; fActualAngBA = 0; fActualLight = p_oLightBeh->GetMeanGLI(fActualConBA, fActualAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 12.35778669; fActualConBA = 0; fActualAngBA = 0.690050826; fActualLight = p_oLightBeh->GetMeanGLI(fActualConBA, fActualAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 11.99536365; fActualConBA = 0.204282062; fActualAngBA = 1.074895926; fActualLight = p_oLightBeh->GetMeanGLI(fActualConBA, fActualAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); //Run one timestep p_oSimManager->RunSim(1); p_oLightGrid = p_oSimManager->GetGridObject("Basal Area Light"); iLightCode = p_oLightGrid->GetFloatDataCode("Light"); EXPECT_LT(-1, iLightCode); iConBACode = p_oLightGrid->GetFloatDataCode("Con BA"); EXPECT_LT(-1, iConBACode); iAngBACode = p_oLightGrid->GetFloatDataCode("Ang BA"); EXPECT_LT(-1, iAngBACode); //Check to make sure the basal area totals are correct //Grid 0, 0 fExpConBA = 0; fExpAngBA = 0; p_oLightGrid->GetValueOfCell(0, 0, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 0, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 1 fExpConBA = 0.196349541; fExpAngBA = 0; p_oLightGrid->GetValueOfCell(0, 1, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 1, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 2 fExpConBA = 0; fExpAngBA = 0.159043128; p_oLightGrid->GetValueOfCell(0, 2, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 2, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 3 fExpConBA = 0.589127162; fExpAngBA = 0; p_oLightGrid->GetValueOfCell(0, 3, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 3, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 4 fExpConBA = 0; fExpAngBA = 0.690050826; p_oLightGrid->GetValueOfCell(0, 4, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 4, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 5 fExpConBA = 0.204282062; fExpAngBA = 1.074895926; p_oLightGrid->GetValueOfCell(0, 5, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 5, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 6 fExpConBA = 0; fExpAngBA = 0; p_oLightGrid->GetValueOfCell(0, 6, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 6, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Make sure that all cells got a light level iNumXCells = p_oLightGrid->GetNumberXCells(); iNumYCells = p_oLightGrid->GetNumberYCells(); for (iX = 0; iX < iNumXCells; iX++) { for (iY = 0; iY < iNumYCells; iY++) { p_oLightGrid->GetValueOfCell(iX, iY, iLightCode, &fActualLight); EXPECT_GT(fActualLight, 0); } } //Save the light values for the seven grid cells to check for density changes p_oLightGrid->GetValueOfCell(0, 0, iLightCode, &fLight1); p_oLightGrid->GetValueOfCell(0, 1, iLightCode, &fLight2); p_oLightGrid->GetValueOfCell(0, 2, iLightCode, &fLight3); p_oLightGrid->GetValueOfCell(0, 3, iLightCode, &fLight4); p_oLightGrid->GetValueOfCell(0, 4, iLightCode, &fLight5); p_oLightGrid->GetValueOfCell(0, 5, iLightCode, &fLight6); p_oLightGrid->GetValueOfCell(0, 6, iLightCode, &fLight7); //Make sure that the species two trees got light values matching their //grids, and nobody else //Grid 0,1 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree1->GetSpecies(), p_oTree1->GetType()), -1); //Grid 0,2 trees p_oTree2->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree2->GetSpecies(), p_oTree2->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight3); //Grid 0,3 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree3->GetSpecies(), p_oTree3->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree4->GetSpecies(), p_oTree4->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree5->GetSpecies(), p_oTree5->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree6->GetSpecies(), p_oTree6->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree7->GetSpecies(), p_oTree7->GetType()), -1); //Grid 0,4 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree8->GetSpecies(), p_oTree8->GetType()), -1); p_oTree9->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree9->GetSpecies(), p_oTree9->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight5); p_oTree10->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree10->GetSpecies(), p_oTree10->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight5); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree11->GetSpecies(), p_oTree11->GetType()), -1); p_oTree12->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree12->GetSpecies(), p_oTree12->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight5); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree13->GetSpecies(), p_oTree13->GetType()), -1); p_oTree14->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree14->GetSpecies(), p_oTree14->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight5); //Grid 0,5 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree15->GetSpecies(), p_oTree15->GetType()), -1); p_oTree16->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree16->GetSpecies(), p_oTree16->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); p_oTree17->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree17->GetSpecies(), p_oTree17->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree18->GetSpecies(), p_oTree18->GetType()), -1); p_oTree19->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree19->GetSpecies(), p_oTree19->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree20->GetSpecies(), p_oTree20->GetType()), -1); p_oTree21->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree21->GetSpecies(), p_oTree21->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree22->GetSpecies(), p_oTree22->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree23->GetSpecies(), p_oTree23->GetType()), -1); p_oTree24->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree24->GetSpecies(), p_oTree24->GetType()), &fActualLight); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree25->GetSpecies(), p_oTree25->GetType()), -1); EXPECT_EQ(fActualLight, fLight6); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree26->GetSpecies(), p_oTree26->GetType()), -1); //Snag - has light but doesn't match p_oTree27->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree27->GetSpecies(), p_oTree27->GetType()), &fActualLight); ASSERT_TRUE(fActualLight != fLight6); //Grid 0,6 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree28->GetSpecies(), p_oTree28->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree29->GetSpecies(), p_oTree29->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree30->GetSpecies(), p_oTree30->GetType()), -1); p_oTree31->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree31->GetSpecies(), p_oTree31->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight7); //Change the number of trees to trigger basal area changes //Grid cell 0, 0 - Add one tree of DBH 25 (total BA 0.049) p_oTree32 = p_oPop->CreateTree( 4, 4, 1, clTreePopulation::adult, 25 ); //Grid cell 0, 1 - Do nothing //Grid cell 0, 2 - Add two trees of DBH 25, one each conifer and //angiosperm (total BA 0.098) fX = 4; fY = 20; fDiam = 25; iSpecies = 1; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); iSpecies = 2; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); //Grid cell 0, 3 - Subtract the tree with DBH 45 (total BA 0.15) p_oPop->KillTree(p_oTree3, natural); //Grid cell 0, 4 - Add three trees too small fX = 4; fY = 36; iSpecies = 3; fDiam = 6; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::sapling, fDiam ); //Grid cell 0, 5 - Subtract 2 trees too small p_oPop->KillTree(p_oTree25, natural); p_oPop->KillTree(p_oTree26, natural); //Grid cell 0, 6 - Do nothing //Run another timestep p_oSimManager->RunSim(1); //Check to make sure that the basal areas are correct //Grid 0, 0 fExpConBA = 0; fExpAngBA = 0; p_oLightGrid->GetValueOfCell(0, 0, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 0, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 1 fExpConBA = 0.196349541; fExpAngBA = 0; p_oLightGrid->GetValueOfCell(0, 1, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 1, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 2 fExpConBA = 0.049087385; fExpAngBA = 0.208130513; p_oLightGrid->GetValueOfCell(0, 2, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 2, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 3 fExpConBA = 0.43008403; fExpAngBA = 0; p_oLightGrid->GetValueOfCell(0, 3, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 3, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 4 fExpConBA = 0; fExpAngBA = 0.690050826; p_oLightGrid->GetValueOfCell(0, 4, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 4, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 5 fExpConBA = 0.204282062; fExpAngBA = 1.074895926; p_oLightGrid->GetValueOfCell(0, 5, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 5, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 0, 6 fExpConBA = 0; fExpAngBA = 0; p_oLightGrid->GetValueOfCell(0, 6, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(0, 6, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Make sure that the light levels for the third and fourth cells //change and the rest stay the same p_oLightGrid->GetValueOfCell(0, 0, iLightCode, &fActualLight); EXPECT_LT(fabs(fActualLight - fLight1), 0.00001); p_oLightGrid->GetValueOfCell(0, 1, iLightCode, &fActualLight); EXPECT_LT(fabs(fActualLight - fLight2), 0.00001); p_oLightGrid->GetValueOfCell(0, 2, iLightCode, &fActualLight); EXPECT_GT(fabs(fActualLight - fLight3), 0.1); p_oLightGrid->GetValueOfCell(0, 3, iLightCode, &fActualLight); EXPECT_GT(fabs(fActualLight - fLight4), 0.1); p_oLightGrid->GetValueOfCell(0, 4, iLightCode, &fActualLight); EXPECT_LT(fabs(fActualLight - fLight5), 0.00001); p_oLightGrid->GetValueOfCell(0, 5, iLightCode, &fActualLight); EXPECT_LT(fabs(fActualLight - fLight6), 0.00001); p_oLightGrid->GetValueOfCell(0, 6, iLightCode, &fActualLight); EXPECT_LT(fabs(fActualLight - fLight7), 0.00001); //Check tree values p_oLightGrid->GetValueOfCell(0, 0, iLightCode, &fLight1); p_oLightGrid->GetValueOfCell(0, 1, iLightCode, &fLight2); p_oLightGrid->GetValueOfCell(0, 2, iLightCode, &fLight3); p_oLightGrid->GetValueOfCell(0, 3, iLightCode, &fLight4); p_oLightGrid->GetValueOfCell(0, 4, iLightCode, &fLight5); p_oLightGrid->GetValueOfCell(0, 5, iLightCode, &fLight6); p_oLightGrid->GetValueOfCell(0, 6, iLightCode, &fLight7); //Make sure that the species two trees got light values matching their //grids, and nobody else //Grid 0,0 trees p_oTree32->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree32->GetSpecies(), p_oTree32->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight1); //Grid 0,1 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree1->GetSpecies(), p_oTree1->GetType()), -1); //Grid 0,2 trees p_oTree2->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree2->GetSpecies(), p_oTree2->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight3); //Grid 0,3 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree4->GetSpecies(), p_oTree4->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree5->GetSpecies(), p_oTree5->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree6->GetSpecies(), p_oTree6->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree7->GetSpecies(), p_oTree7->GetType()), -1); //Grid 0,4 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree8->GetSpecies(), p_oTree8->GetType()), -1); p_oTree9->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree9->GetSpecies(), p_oTree9->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight5); p_oTree10->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree10->GetSpecies(), p_oTree10->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight5); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree11->GetSpecies(), p_oTree11->GetType()), -1); p_oTree12->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree12->GetSpecies(), p_oTree12->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight5); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree13->GetSpecies(), p_oTree13->GetType()), -1); p_oTree14->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree14->GetSpecies(), p_oTree14->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight5); //Grid 0,5 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree15->GetSpecies(), p_oTree15->GetType()), -1); p_oTree16->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree16->GetSpecies(), p_oTree16->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); p_oTree17->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree17->GetSpecies(), p_oTree17->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree18->GetSpecies(), p_oTree18->GetType()), -1); p_oTree19->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree19->GetSpecies(), p_oTree19->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree20->GetSpecies(), p_oTree20->GetType()), -1); p_oTree21->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree21->GetSpecies(), p_oTree21->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree22->GetSpecies(), p_oTree22->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree23->GetSpecies(), p_oTree23->GetType()), -1); p_oTree24->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree24->GetSpecies(), p_oTree24->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight6); //Snag - has light but doesn't match p_oTree27->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree27->GetSpecies(), p_oTree27->GetType()), &fActualLight); ASSERT_TRUE(fActualLight != fLight6); //Grid 0,6 trees EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree28->GetSpecies(), p_oTree28->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree29->GetSpecies(), p_oTree29->GetType()), -1); EXPECT_EQ(p_oPop->GetFloatDataCode("Light", p_oTree30->GetSpecies(), p_oTree30->GetType()), -1); p_oTree31->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree31->GetSpecies(), p_oTree31->GetType()), &fActualLight); EXPECT_EQ(fActualLight, fLight7); delete p_oSimManager; } catch (modelErr &e) { delete p_oSimManager; FAIL() << "Testing failed in function: " << e.sFunction << " with message: " << e.sMoreInfo; } } ///////////////////////////////////////////////////////////////////////////// // NormalProcessingRun2() // Tests normal processing - run 2. This ensures that the calculation of mean // GLI is bounded between 0 and 100. WriteBasalAreaLightXMLFile2() does setup. ///////////////////////////////////////////////////////////////////////////// TEST(BasalAreaLight, NormalProcessingRun2) { clSimManager * p_oSimManager = new clSimManager( 7, 1, "" ); try { clBehaviorBase *p_oTemp; clBasalAreaLight *p_oLightBeh; float fActualLight, fExpectedLight, fConBA, fAngBA; //Feed our file to the sim manager p_oSimManager->ReadFile(WriteBasalAreaLightXMLFile2()); //Check the mean GLI calculations directly for 4 values p_oTemp = p_oSimManager->GetBehaviorObject("basalarealightshell"); p_oLightBeh = dynamic_cast<clBasalAreaLight*>(p_oTemp); fExpectedLight = 12.4; fConBA = 0; fAngBA = 0; fActualLight = p_oLightBeh->GetMeanGLI(fConBA, fAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 4.677703256; fConBA = 1; fAngBA = 6; fActualLight = p_oLightBeh->GetMeanGLI(fConBA, fAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 100; fConBA = 5; fAngBA = 0; fActualLight = p_oLightBeh->GetMeanGLI(fConBA, fAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 0; fConBA = 6; fAngBA = 0; fActualLight = p_oLightBeh->GetMeanGLI(fConBA, fAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); fExpectedLight = 0; fConBA = 100; fAngBA = 0; fActualLight = p_oLightBeh->GetMeanGLI(fConBA, fAngBA); EXPECT_LT(fabs(fExpectedLight - fActualLight), 0.0001); delete p_oSimManager; } catch (modelErr &e) { delete p_oSimManager; FAIL() << "Testing failed in function: " << e.sFunction << " with message: " << e.sMoreInfo; } } ///////////////////////////////////////////////////////////////////////////// // NormalProcessingRun3() // Tests normal processing - run 3. This checks to make sure grid cell sizes // are honored and allows checking of the light level distribution. // WriteBasalAreaLightXMLFile3() does setup. This produces an output file called "Density // Light Distribution.txt". ///////////////////////////////////////////////////////////////////////////// TEST(BasalAreaLight, NormalProcessingRun3) { clSimManager * p_oSimManager = new clSimManager( 7, 1, "" ); try { using namespace std; //clTreePopulation *p_oPop; //clTreeSearch *p_oAllTrees; //clTree *p_oTree; clGrid *p_oLightGrid; //int p_iCount[101]; //float fLight; int iLightCode; //iX, iY //Feed our file to the sim manager p_oSimManager->ReadFile(WriteBasalAreaLightXMLFile3()); //Verify the grid cell size p_oLightGrid = p_oSimManager->GetGridObject("Basal Area Light"); iLightCode = p_oLightGrid->GetFloatDataCode("Light"); EXPECT_LT(-1, iLightCode); EXPECT_EQ(10, p_oLightGrid->GetLengthXCells()); EXPECT_EQ(10, p_oLightGrid->GetLengthYCells()); //Put 3 trees in each grid cell /* p_oPop = (clTreePopulation*) p_oSimManager->GetPopulationObject("treepopulation"); for (iX = 0; iX < p_oLightGrid->GetNumberXCells(); iX++) { for (iY = 0; iY < p_oLightGrid->GetNumberYCells(); iY++) { p_oPop->CreateTree( (iX * 10) + 5, (iY * 10) + 5, 0, clTreePopulation::adult, 45 ); p_oPop->CreateTree( (iX * 10) + 5, (iY * 10) + 5, 1, clTreePopulation::adult, 24 ); p_oPop->CreateTree( (iX * 10) + 5, (iY * 10) + 5, 2, clTreePopulation::adult, 70 ); } } //Run one timestep p_oSimManager->RunSim(1); //Count up the light levels and put them in buckets for (iX = 0; iX < 101; iX++) p_iCount[iX] = 0; for (iX = 0; iX < p_oLightGrid->GetNumberXCells(); iX++) { for (iY = 0; iY < p_oLightGrid->GetNumberYCells(); iY++) { p_oLightGrid->GetValueOfCell(iX, iY, iLightCode, &fLight); p_iCount[(int)fLight]++; } } //Write out the results std::fstream oOut; oOut.open( "Basal Area Light Distribution.txt", ios::out | ios::trunc ); oOut << "Basal Area Light Distribution\n"; oOut << "Number of grid values falling into each GLI bucket (BA = 0.59):\n"; oOut << "0"; for (iX = 1; iX < 101; iX++) oOut << "\t" << iX; oOut << "\n" << p_iCount[0]; for (iX = 1; iX < 101; iX++) oOut << "\t" << p_iCount[iX]; oOut << "\n"; //Count up the tree values and write that distribution as well for (iX = 0; iX < 101; iX++) p_iCount[iX] = 0; p_oAllTrees = p_oPop->Find("all"); p_oTree = p_oAllTrees->NextTree(); while (p_oTree) { p_oTree->GetValue(p_oPop->GetFloatDataCode("Light", p_oTree->GetSpecies(), p_oTree->GetType()), &fLight); p_iCount[(int)fLight]++; p_oTree = p_oAllTrees->NextTree(); } oOut << "Number of tree values falling into each GLI bucket (BA = 0.59):\n"; oOut << "0"; for (iX = 1; iX < 101; iX++) oOut << "\t" << iX; oOut << "\n" << p_iCount[0]; for (iX = 1; iX < 101; iX++) oOut << "\t" << p_iCount[iX]; oOut << "\n"; oOut.close(); */ delete p_oSimManager; } catch (modelErr &e) { delete p_oSimManager; FAIL() << "Testing failed in function: " << e.sFunction << " with message: " << e.sMoreInfo; } } ///////////////////////////////////////////////////////////////////////////// // NormalProcessingRun4() // Tests normal processing - run 4. This double-checks grid map reading. // WriteBasalAreaLightXMLFile4() does setup. ///////////////////////////////////////////////////////////////////////////// TEST(BasalAreaLight, NormalProcessingRun4) { clSimManager * p_oSimManager = new clSimManager( 7, 1, "" ); try { clGrid *p_oLightGrid; float fActualLight, fExpectedLight = 95, fExpConBA = 0.03, fExpAngBA = 0, fActualConBA, fActualAngBA; int iLightCode, iConBACode, iAngBACode, iX, iY, iNumXCells, iNumYCells; //Feed our file to the sim manager p_oSimManager->ReadFile(WriteBasalAreaLightXMLFile4()); //Run one timestep p_oSimManager->RunSim(1); p_oLightGrid = p_oSimManager->GetGridObject("Basal Area Light"); iLightCode = p_oLightGrid->GetFloatDataCode("Light"); EXPECT_LT(-1, iLightCode); iConBACode = p_oLightGrid->GetFloatDataCode("Con BA"); EXPECT_LT(-1, iConBACode); iAngBACode = p_oLightGrid->GetFloatDataCode("Ang BA"); EXPECT_LT(-1, iAngBACode); //Make sure that all cells got a light level iNumXCells = p_oLightGrid->GetNumberXCells(); iNumYCells = p_oLightGrid->GetNumberYCells(); for (iX = 0; iX < iNumXCells; iX++) { for (iY = 0; iY < iNumYCells; iY++) { p_oLightGrid->GetValueOfCell(iX, iY, iLightCode, &fActualLight); p_oLightGrid->GetValueOfCell(iX, iY, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(iX, iY, iAngBACode, &fActualAngBA); EXPECT_EQ(fExpectedLight, fActualLight); EXPECT_EQ(fExpConBA, fActualConBA); EXPECT_EQ(fExpAngBA, fActualAngBA); } } delete p_oSimManager; } catch (modelErr &e) { delete p_oSimManager; FAIL() << "Testing failed in function: " << e.sFunction << " with message: " << e.sMoreInfo; } } ///////////////////////////////////////////////////////////////////////////// // NormalProcessingRun5() // Tests normal processing - run 5. This double-checks radius. // WriteBasalAreaLightXMLFile5() does setup. ///////////////////////////////////////////////////////////////////////////// TEST(BasalAreaLight, NormalProcessingRun5) { clSimManager * p_oSimManager = new clSimManager( 7, 1, "" ); try { clTreePopulation *p_oPop; clGrid *p_oLightGrid; float fExpConBA, //Conifer basal area we're expecting fExpAngBA, //Angiosperm basal area we're expecting fActualConBA, //Conifer basal area calculated by SORTIE fActualAngBA, //Angiosperm basal area calculated by SORTIE fDiam, fX, fY; //For creating trees //For stashing light levels between timesteps int iLightCode, iConBACode, iAngBACode, iSpecies; //Feed our file to the sim manager p_oSimManager->ReadFile(WriteBasalAreaLightXMLFile5()); p_oPop = (clTreePopulation*) p_oSimManager->GetPopulationObject("treepopulation"); //Add trees fX = 29.38; fY = 34.87; iSpecies = 0; fDiam = 74.50; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 23.44; fY = 35.27; iSpecies = 2; fDiam = 95.05; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 30.70; fY = 28.31; iSpecies = 1; fDiam = 78.92; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 25.69; fY = 27.20; iSpecies = 3; fDiam = 69.95; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 25.34; fY = 38.52; iSpecies = 0; fDiam = 74.06; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 30.11; fY = 38.41; iSpecies = 3; fDiam = 93.52; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 24.55; fY = 25.90; iSpecies = 1; fDiam = 67.81; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 20.73; fY = 36.66; iSpecies = 2; fDiam = 40.47; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 19.64; fY = 31.49; iSpecies = 3; fDiam = 92.60; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 24.82; fY = 25.12; iSpecies = 0; fDiam = 35.49; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 35.63; fY = 33.87; iSpecies = 1; fDiam = 71.42; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 27.03; fY = 24.10; iSpecies = 3; fDiam = 63.52; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 36.08; fY = 31.00; iSpecies = 3; fDiam = 59.44; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 20.41; fY = 27.57; iSpecies = 2; fDiam = 51.39; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 20.83; fY = 25.51; iSpecies = 2; fDiam = 95.57; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 38.26; fY = 32.18; iSpecies = 0; fDiam = 34.70; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 38.56; fY = 35.23; iSpecies = 3; fDiam = 60.03; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 35.73; fY = 24.74; iSpecies = 2; fDiam = 62.12; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 38.55; fY = 29.70; iSpecies = 0; fDiam = 31.72; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 38.71; fY = 29.89; iSpecies = 2; fDiam = 78.87; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 37.34; fY = 38.96; iSpecies = 3; fDiam = 83.99; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 36.84; fY = 23.88; iSpecies = 0; fDiam = 52.87; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 35.42; fY = 22.05; iSpecies = 1; fDiam = 31.12; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 38.84; fY = 24.81; iSpecies = 0; fDiam = 41.15; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 23.09; fY = 18.10; iSpecies = 1; fDiam = 49.68; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 29.13; fY = 17.01; iSpecies = 3; fDiam = 18.39; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 25.42; fY = 15.83; iSpecies = 2; fDiam = 96.25; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 27.92; fY = 15.67; iSpecies = 0; fDiam = 40.37; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 25.23; fY = 15.28; iSpecies = 1; fDiam = 24.07; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 34.72; fY = 16.18; iSpecies = 1; fDiam = 44.42; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 36.12; fY = 16.65; iSpecies = 2; fDiam = 99.04; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); fX = 39.98; fY = 15.98; iSpecies = 1; fDiam = 45.91; p_oPop->CreateTree( fX, fY, iSpecies, clTreePopulation::adult, fDiam ); //Run one timestep p_oSimManager->RunSim(1); p_oLightGrid = p_oSimManager->GetGridObject("Basal Area Light"); iLightCode = p_oLightGrid->GetFloatDataCode("Light"); EXPECT_LT(-1, iLightCode); iConBACode = p_oLightGrid->GetFloatDataCode("Con BA"); EXPECT_LT(-1, iConBACode); iAngBACode = p_oLightGrid->GetFloatDataCode("Ang BA"); EXPECT_LT(-1, iAngBACode); //Check to make sure the basal area totals are correct //Grid 5, 5 fExpConBA = 1.459611208; fExpAngBA = 1.551503445; p_oLightGrid->GetValueOfCell(5, 5, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(5, 5, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 5, 6 fExpConBA = 1.803823734; fExpAngBA = 3.31248918; p_oLightGrid->GetValueOfCell(5, 6, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(5, 6, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); //Grid 6, 5 fExpConBA = 1.852594769; fExpAngBA = 2.305672952; p_oLightGrid->GetValueOfCell(6, 5, iConBACode, &fActualConBA); p_oLightGrid->GetValueOfCell(6, 5, iAngBACode, &fActualAngBA); EXPECT_LT(fabs(fExpConBA - fActualConBA), 0.001); EXPECT_LT(fabs(fExpAngBA - fActualAngBA), 0.001); delete p_oSimManager; } catch (modelErr &e) { delete p_oSimManager; FAIL() << "Testing failed in function: " << e.sFunction << " with message: " << e.sMoreInfo; } } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLFile1() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLFile1() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>96</plot_lenX>" << "<plot_lenY>96</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_2\" type=\"Sapling\" />" << "<version>1</version>" << "<listPosition>1</listPosition>" << "</behavior>" << "<behavior>" << "<behaviorName>ConstantGLI</behaviorName>" << "<version>1</version>" << "<listPosition>2</listPosition>" << "<applyTo species=\"Species_1\" type=\"Snag\"/>" << "</behavior>" << "</behaviorList>" << "<ConstantGLI2>" << "<li_constGLI>100</li_constGLI>" << "</ConstantGLI2>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>2.1</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>4</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLFile2() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLFile2() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>96</plot_lenX>" << "<plot_lenY>96</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_2\" type=\"Sapling\" />" << "<version>1</version>" << "<listPosition>1</listPosition>" << "</behavior>" << "</behaviorList>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1</li_baConiferLightB>" << "<li_baConiferLightC>-5.17921</li_baConiferLightC>" << "<li_baAngiospermLightB>0.9</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>10</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLFile3() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLFile3() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>1000</plot_lenX>" << "<plot_lenY>1000</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<grid gridName=\"Basal Area Light\">" << "<ma_floatCodes>" << "<ma_floatCode label=\"Light\">0</ma_floatCode>" << "<ma_floatCode label=\"Con BA\">1</ma_floatCode>" << "<ma_floatCode label=\"Ang BA\">2</ma_floatCode>" << "</ma_floatCodes>" << "<ma_lengthXCells>10</ma_lengthXCells>" << "<ma_lengthYCells>10</ma_lengthYCells>" << "</grid>"; oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<version>1</version>" << "<listPosition>1</listPosition>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_1\" type=\"Adult\" />" << "<applyTo species=\"Species_3\" type=\"Adult\" />" << "<applyTo species=\"Species_4\" type=\"Adult\" />" << "</behavior>" << "</behaviorList>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>2.1</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>10</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLFile4() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLFile4() { using namespace std; const char *cFileString = "TestFile1.xml"; float fLight = 95, fConBA = 0.03; int iX, iY, iNumXCells = 10, iNumYCells = 10; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>100</plot_lenX>" << "<plot_lenY>100</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<grid gridName=\"Basal Area Light\">" << "<ma_floatCodes>" << "<ma_floatCode label=\"Light\">0</ma_floatCode>" << "<ma_floatCode label=\"Con BA\">1</ma_floatCode>" << "<ma_floatCode label=\"Ang BA\">2</ma_floatCode>" << "</ma_floatCodes>" << "<ma_lengthXCells>10</ma_lengthXCells>" << "<ma_lengthYCells>10</ma_lengthYCells>"; for (iX = 0; iX < iNumXCells; iX++) { for (iY = 0; iY < iNumYCells; iY++) { oOut << "<ma_v x=\"" << iX << "\" y=\"" << iY << "\">" << "<fl c=\"0\">" << fLight << "</fl>" << "<fl c=\"1\">" << fConBA << "</fl>" << "</ma_v>"; } } oOut << "</grid>" << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<listPosition>1</listPosition>" << "<version>1</version>" << "</behavior>" << "</behaviorList>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>2.1</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>10</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLFile5() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLFile5() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>100</plot_lenX>" << "<plot_lenY>100</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_2\" type=\"Sapling\" />" << "<version>1</version>" << "<listPosition>1</listPosition>" << "</behavior>" << "<behavior>" << "<behaviorName>ConstantGLI</behaviorName>" << "<version>1</version>" << "<applyTo species=\"Species_1\" type=\"Snag\"/>" << "<listPosition>2</listPosition>" << "</behavior>" << "</behaviorList>" << "<grid gridName=\"Basal Area Light\">" << "<ma_floatCodes>" << "<ma_floatCode label=\"Light\">0</ma_floatCode>" << "<ma_floatCode label=\"Con BA\">1</ma_floatCode>" << "<ma_floatCode label=\"Ang BA\">2</ma_floatCode>" << "</ma_floatCodes>" << "<ma_lengthXCells>5</ma_lengthXCells>" << "<ma_lengthYCells>5</ma_lengthYCells>" << "</grid>" << "<ConstantGLI2>" << "<li_constGLI>100</li_constGLI>" << "</ConstantGLI2>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>2.1</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>8.46</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLErrorFile1() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLErrorFile1() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>96</plot_lenX>" << "<plot_lenY>96</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_2\" type=\"Sapling\" />" << "<version>1</version>" << "<listPosition>1</listPosition>" << "</behavior>" << "</behaviorList>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>0</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>10</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLErrorFile2() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLErrorFile2() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>96</plot_lenX>" << "<plot_lenY>96</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_2\" type=\"Sapling\" />" << "<version>1</version>" << "<listPosition>1</listPosition>" << "</behavior>" << "</behaviorList>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>2.1</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>0</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>10</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLErrorFile3() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLErrorFile3() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>96</plot_lenX>" << "<plot_lenY>96</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_2\" type=\"Sapling\" />" << "<version>1</version>" << "<listPosition>1</listPosition>" << "</behavior>" << "</behaviorList>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>2.1</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>-0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>10</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLErrorFile4() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLErrorFile4() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>96</plot_lenX>" << "<plot_lenY>96</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_2\" type=\"Sapling\" />" << "<version>1</version>" << "<listPosition>1</listPosition>" << "</behavior>" << "</behaviorList>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>2.1</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>-10</li_baLightMinDBH>" << "<li_baLightSearchRadius>10</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightXMLErrorFile5() ///////////////////////////////////////////////////////////////////////////// const char* WriteBasalAreaLightXMLErrorFile5() { using namespace std; const char *cFileString = "TestFile1.xml"; //Open file to write to std::fstream oOut; oOut.open( cFileString, ios::out | ios::trunc ); oOut << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\" ?>" << "<paramFile fileCode=\"06010101\">" << "<plot>" << "<timesteps>3</timesteps>" << "<yearsPerTimestep>1</yearsPerTimestep>" << "<randomSeed>1</randomSeed>" << "<plot_lenX>100</plot_lenX>" << "<plot_lenY>100</plot_lenY>" << "<plot_latitude>55.37</plot_latitude>" << "<plot_precip_mm_yr>1150.645781</plot_precip_mm_yr>" << "<plot_temp_C>12.88171785</plot_temp_C>" << "</plot>"; WriteBasalAreaLightCommonStuff(oOut); oOut << "<behaviorList>" << "<behavior>" << "<behaviorName>BasalAreaLight</behaviorName>" << "<applyTo species=\"Species_2\" type=\"Adult\" />" << "<applyTo species=\"Species_2\" type=\"Sapling\" />" << "<listPosition>1</listPosition>" << "<version>1</version>" << "</behavior>" << "<behavior>" << "<behaviorName>ConstantGLI</behaviorName>" << "<version>1</version>" << "<listPosition>2</listPosition>" << "<applyTo species=\"Species_1\" type=\"Snag\"/>" << "</behavior>" << "</behaviorList>" << "<ConstantGLI2>" << "<li_constGLI>100</li_constGLI>" << "</ConstantGLI2>" << "<BasalAreaLight1>" << "<li_baLightA>12.4</li_baLightA>" << "<li_baConiferLightB>1.8</li_baConiferLightB>" << "<li_baConiferLightC>2.1</li_baConiferLightC>" << "<li_baAngiospermLightB>3.83</li_baAngiospermLightB>" << "<li_baAngiospermLightC>3.04</li_baAngiospermLightC>" << "<li_baLightSigma>0.82</li_baLightSigma>" << "<li_baLightChangeThreshold>0.05</li_baLightChangeThreshold>" << "<li_baLightMinDBH>10</li_baLightMinDBH>" << "<li_baLightSearchRadius>-10</li_baLightSearchRadius>" << "<li_baTreeType>" << "<li_bttVal species=\"Species_1\">1</li_bttVal>" << "<li_bttVal species=\"Species_2\">0</li_bttVal>" << "<li_bttVal species=\"Species_3\">1</li_bttVal>" << "<li_bttVal species=\"Species_4\">0</li_bttVal>" << "</li_baTreeType>" << "</BasalAreaLight1>" << "</paramFile>"; oOut.close(); return cFileString; } ///////////////////////////////////////////////////////////////////////////// // WriteBasalAreaLightCommonStuff() ///////////////////////////////////////////////////////////////////////////// void WriteBasalAreaLightCommonStuff( std::fstream &oOut ) { using namespace std; oOut << "<trees>" << "<tr_speciesList>" << "<tr_species speciesName=\"Species_1\"/>" << "<tr_species speciesName=\"Species_2\"/>" << "<tr_species speciesName=\"Species_3\"/>" << "<tr_species speciesName=\"Species_4\"/>" << "</tr_speciesList>" << "<tr_seedDiam10Cm>0.1</tr_seedDiam10Cm>" << "<tr_minAdultDBH>" << "<tr_madVal species=\"Species_1\">10.0</tr_madVal>" << "<tr_madVal species=\"Species_2\">10.0</tr_madVal>" << "<tr_madVal species=\"Species_3\">10.0</tr_madVal>" << "<tr_madVal species=\"Species_4\">10.0</tr_madVal>" << "</tr_minAdultDBH>" << "<tr_maxSeedlingHeight>" << "<tr_mshVal species=\"Species_1\">1.35</tr_mshVal>" << "<tr_mshVal species=\"Species_2\">1.35</tr_mshVal>" << "<tr_mshVal species=\"Species_3\">1.35</tr_mshVal>" << "<tr_mshVal species=\"Species_4\">1.35</tr_mshVal>" << "</tr_maxSeedlingHeight>" << "</trees>" << "<allometry>" << "<tr_slopeOfAsymHeight>" << "<tr_soahVal species=\"Species_1\">0.0299</tr_soahVal>" << "<tr_soahVal species=\"Species_2\">0.0299</tr_soahVal>" << "<tr_soahVal species=\"Species_3\">0.0299</tr_soahVal>" << "<tr_soahVal species=\"Species_4\">0.0299</tr_soahVal>" << "</tr_slopeOfAsymHeight>" << "<tr_canopyHeight>" << "<tr_chVal species=\"Species_1\">39.48</tr_chVal>" << "<tr_chVal species=\"Species_2\">39.48</tr_chVal>" << "<tr_chVal species=\"Species_3\">39.48</tr_chVal>" << "<tr_chVal species=\"Species_4\">39.48</tr_chVal>" << "</tr_canopyHeight>" << "<tr_stdAsympCrownRad>" << "<tr_sacrVal species=\"Species_1\">0.0549</tr_sacrVal>" << "<tr_sacrVal species=\"Species_2\">0.0549</tr_sacrVal>" << "<tr_sacrVal species=\"Species_3\">0.0549</tr_sacrVal>" << "<tr_sacrVal species=\"Species_4\">0.0549</tr_sacrVal>" << "</tr_stdAsympCrownRad>" << "<tr_stdCrownRadExp>" << "<tr_screVal species=\"Species_1\">1.0</tr_screVal>" << "<tr_screVal species=\"Species_2\">1.0</tr_screVal>" << "<tr_screVal species=\"Species_3\">1.0</tr_screVal>" << "<tr_screVal species=\"Species_4\">1.0</tr_screVal>" << "</tr_stdCrownRadExp>" << "<tr_stdMaxCrownRad>" << "<tr_smcrVal species=\"Species_1\">10</tr_smcrVal>" << "<tr_smcrVal species=\"Species_2\">10</tr_smcrVal>" << "<tr_smcrVal species=\"Species_3\">10</tr_smcrVal>" << "<tr_smcrVal species=\"Species_4\">10</tr_smcrVal>" << "</tr_stdMaxCrownRad>" << "<tr_conversionDiam10ToDBH>" << "<tr_cdtdVal species=\"Species_1\">0.8008</tr_cdtdVal>" << "<tr_cdtdVal species=\"Species_2\">0.8008</tr_cdtdVal>" << "<tr_cdtdVal species=\"Species_3\">0.8008</tr_cdtdVal>" << "<tr_cdtdVal species=\"Species_4\">0.8008</tr_cdtdVal>" << "</tr_conversionDiam10ToDBH>" << "<tr_interceptDiam10ToDBH>" << "<tr_idtdVal species=\"Species_1\">0</tr_idtdVal>" << "<tr_idtdVal species=\"Species_2\">0</tr_idtdVal>" << "<tr_idtdVal species=\"Species_3\">0</tr_idtdVal>" << "<tr_idtdVal species=\"Species_4\">0</tr_idtdVal>" << "</tr_interceptDiam10ToDBH>" << "<tr_stdAsympCrownHt>" << "<tr_sachVal species=\"Species_1\">0.389</tr_sachVal>" << "<tr_sachVal species=\"Species_2\">0.389</tr_sachVal>" << "<tr_sachVal species=\"Species_3\">0.389</tr_sachVal>" << "<tr_sachVal species=\"Species_4\">0.389</tr_sachVal>" << "</tr_stdAsympCrownHt>" << "<tr_stdCrownHtExp>" << "<tr_scheVal species=\"Species_1\">1.0</tr_scheVal>" << "<tr_scheVal species=\"Species_2\">1.0</tr_scheVal>" << "<tr_scheVal species=\"Species_3\">1.0</tr_scheVal>" << "<tr_scheVal species=\"Species_4\">1.0</tr_scheVal>" << "</tr_stdCrownHtExp>" << "<tr_slopeOfHeight-Diam10>" << "<tr_sohdVal species=\"Species_1\">0.03418</tr_sohdVal>" << "<tr_sohdVal species=\"Species_2\">0.03418</tr_sohdVal>" << "<tr_sohdVal species=\"Species_3\">0.03418</tr_sohdVal>" << "<tr_sohdVal species=\"Species_4\">0.03418</tr_sohdVal>" << "</tr_slopeOfHeight-Diam10>" << "<tr_whatSeedlingHeightDiam>" << "<tr_wsehdVal species=\"Species_1\">0</tr_wsehdVal>" << "<tr_wsehdVal species=\"Species_2\">0</tr_wsehdVal>" << "<tr_wsehdVal species=\"Species_3\">0</tr_wsehdVal>" << "<tr_wsehdVal species=\"Species_4\">0</tr_wsehdVal>" << "</tr_whatSeedlingHeightDiam>" << "<tr_whatSaplingHeightDiam>" << "<tr_wsahdVal species=\"Species_1\">0</tr_wsahdVal>" << "<tr_wsahdVal species=\"Species_2\">0</tr_wsahdVal>" << "<tr_wsahdVal species=\"Species_3\">0</tr_wsahdVal>" << "<tr_wsahdVal species=\"Species_4\">0</tr_wsahdVal>" << "</tr_whatSaplingHeightDiam>" << "<tr_whatAdultHeightDiam>" << "<tr_wahdVal species=\"Species_1\">0</tr_wahdVal>" << "<tr_wahdVal species=\"Species_2\">0</tr_wahdVal>" << "<tr_wahdVal species=\"Species_3\">0</tr_wahdVal>" << "<tr_wahdVal species=\"Species_4\">0</tr_wahdVal>" << "</tr_whatAdultHeightDiam>" << "<tr_whatAdultCrownRadDiam>" << "<tr_wacrdVal species=\"Species_1\">0</tr_wacrdVal>" << "<tr_wacrdVal species=\"Species_2\">0</tr_wacrdVal>" << "<tr_wacrdVal species=\"Species_3\">0</tr_wacrdVal>" << "<tr_wacrdVal species=\"Species_4\">0</tr_wacrdVal>" << "</tr_whatAdultCrownRadDiam>" << "<tr_whatAdultCrownHeightHeight>" << "<tr_wachhVal species=\"Species_1\">0</tr_wachhVal>" << "<tr_wachhVal species=\"Species_2\">0</tr_wachhVal>" << "<tr_wachhVal species=\"Species_3\">0</tr_wachhVal>" << "<tr_wachhVal species=\"Species_4\">0</tr_wachhVal>" << "</tr_whatAdultCrownHeightHeight>" << "<tr_whatSaplingCrownRadDiam>" << "<tr_wscrdVal species=\"Species_1\">0</tr_wscrdVal>" << "<tr_wscrdVal species=\"Species_2\">0</tr_wscrdVal>" << "<tr_wscrdVal species=\"Species_3\">0</tr_wscrdVal>" << "<tr_wscrdVal species=\"Species_4\">0</tr_wscrdVal>" << "</tr_whatSaplingCrownRadDiam>" << "<tr_whatSaplingCrownHeightHeight>" << "<tr_wschhVal species=\"Species_1\">0</tr_wschhVal>" << "<tr_wschhVal species=\"Species_2\">0</tr_wschhVal>" << "<tr_wschhVal species=\"Species_3\">0</tr_wschhVal>" << "<tr_wschhVal species=\"Species_4\">0</tr_wschhVal>" << "</tr_whatSaplingCrownHeightHeight>" << "</allometry>"; }
55fbadb3d3cbff521d87bbbcceefb72f497ccf73
90cc6a5afed181a9611bd831d5a0487685e67080
/rendering/Geometric_Primitives.h
5009e75c9b279647e2dfcb6ee7f45f027d9015a8
[]
no_license
RezzaRect/SandBox
1de493845757781c04edac79e9c045c3a5474325
6a5ced8159dd4606b9b6ac7caea714e425bd1a95
refs/heads/master
2020-05-21T15:03:49.868580
2017-04-14T22:55:30
2017-04-14T22:55:30
65,657,080
0
0
null
null
null
null
UTF-8
C++
false
false
668
h
Geometric_Primitives.h
#ifndef GEOMETRIC_PRIMITIVES_H_INCLUDED #define GEOMETRIC_PRIMITIVES_H_INCLUDED //#include "obj_loader.h" #include "Mesh.h" //setup err create..? int rgbToGrayscale(int r, int g, int b); Mesh setupSphere(float radius, float latitudeBands, float longitudeBands); Mesh setupCube(float cubeSize); Mesh setupLowDensityPlane(float planeSize); Mesh setupHighDensityPlane(int mapSize, float density, bool bump); Mesh setupFullScreenQuad(float quadSize); //Mesh Terrain(const std::string& fileName, float hScale, unsigned char** data, int w, int h, int bpp); Mesh Terrain(float hScale, unsigned char** data, int w, int h, int bpp); #endif // GEOMETRIC_PRIMITIVES_H_INCLUDED
0602b14a77ec0e7f8d82e6cfb63a369cf8c3cac6
7b1dba72bac15ec61738584e0877d63a57134b81
/analysiscode_v2.1/include/LoadDVCS.h
b5de9a87c2726fcc69b4b4b3bc6137707458a45b
[]
no_license
kuantumlad/eg1dvcs_Analysis_v2
6983cfac008000e069cb4aae57e2bfe11af07360
02aa08c59cbdeb8f03207c7d8f4c0bfca31b5c91
refs/heads/master
2020-12-30T15:09:20.931235
2017-08-16T16:25:19
2017-08-16T16:25:19
91,117,287
0
0
null
null
null
null
UTF-8
C++
false
false
1,608
h
LoadDVCS.h
#ifndef LoadDVCS_h #define LoadDVCS_h #include "TROOT.h" #include "TChain.h" #include "TString.h" #include "TFile.h" #include "EventDVCS.h" #include "TBranch.h" #include <iostream> class LoadDVCS{ public: TChain *gChain; EventDVCS dvcs; TBranch *b_RunNumber; TBranch *b_PeriodID; TBranch *b_TargetType; TBranch *b_pol_sign; TBranch *b_beampol; TBranch *b_helicity; TBranch *b_TarPol; TBranch *b_Q2; TBranch *b_Xbj; TBranch *b_W; TBranch *b_t_Pr; TBranch *b_t_Ph; TBranch *b_Phi_Pr; TBranch *b_Phi_Ph; TBranch *b_AngleXg; TBranch *b_Anglehg_hp; TBranch *b_Xbal; TBranch *b_Ybal; TBranch *b_Zbal; TBranch *b_Ebal; TBranch *b_el_p; TBranch *b_el_theta; TBranch *b_el_phi; TBranch *b_pr_p; TBranch *b_pr_theta; TBranch *b_pr_phi; TBranch *b_nphotEC; TBranch *b_ph_ec_p; TBranch *b_ph_ec_theta; TBranch *b_ph_ec_phi; TBranch *b_nphotIC; TBranch *b_ph_ic_p; TBranch *b_ph_ic_theta; TBranch *b_ph_ic_phi; TBranch *b_ph_det; TBranch *b_nphot; TBranch *b_ph_p; TBranch *b_ph_theta; TBranch *b_ph_phi; TBranch *b_ph_hitID; TBranch *b_mm2_epg; TBranch *b_mm2_ep; TBranch *b_mm2_eg; public: LoadDVCS(); ~LoadDVCS(); public: void Init(); void MakeChain( const char*, Int_t ); void MakeChain( TChain* ); void AddBranch( TTree* ); void FillNewBranch( Int_t ); EventDVCS GetEvent(){ return dvcs; } Int_t NumEntries(){ return gChain->GetEntries(); } void GetEntry( Int_t ientry ){ gChain->GetEntry(ientry); } Int_t RunNum(TString); public: Int_t runnum; Int_t runnumber; }; #endif
cc7850c531f0cda8fcbcbdfc9a689a08b75e5afc
157c466d9577b48400bd00bf4f3c4d7a48f71e20
/Source/ProjectR/UpdateService/Auth/RequestPermissionsState.cpp
ebaf9570a3ac3bff744bb3aaae0b89d5cdcc5c19
[]
no_license
SeungyulOh/OverlordSource
55015d357297393c7315c798f6813a9daba28b15
2e2339183bf847663d8f1722ed0f932fed6c7516
refs/heads/master
2020-04-19T16:00:25.346619
2019-01-30T06:41:12
2019-01-30T06:41:12
168,291,223
8
1
null
null
null
null
UTF-8
C++
false
false
2,623
cpp
RequestPermissionsState.cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ProjectR.h" #include "RequestPermissionsState.h" #include "RAuth.h" #include "AuthStateMachine.h" void URequestPermissionsState::OnEnter() { #if !API_NZIN StateMachine->ChangeState(EAuthStateEnum::VE_GameServerLogin); return; #endif //all code API_NZIN auto OnCheckPermissionsCompleteDelegate = FOnCheckPermissionsCompleteDelegate::CreateUObject(this, &URequestPermissionsState::OnCheckPermissionsComplete); auto OnRequestPermissionsCompleteDelegate = FOnRequestPermissionsCompleteDelegate::CreateUObject(this, &URequestPermissionsState::OnCheckPermissionsComplete); //RAuth->GetPublisherAPI()->AddOnCheckPermissionsCompleteDelegate_Handle(OnCheckPermissionsCompleteDelegate); //RAuth->GetPublisherAPI()->AddOnRequestPermissionsCompleteDelegate_Handle(OnRequestPermissionsCompleteDelegate); OnCheckPermissionsCompleteHandle = OnCheckPermissionsCompleteDelegate.GetHandle(); OnRequestPermissionsCompleteHandle = OnRequestPermissionsCompleteDelegate.GetHandle(); RAuth->GetPublisherAPI()->CheckPermissions(); } void URequestPermissionsState::OnLeave() { RAuth->GetPublisherAPI()->ClearOnCheckPermissionsCompleteDelegate_Handle(OnCheckPermissionsCompleteHandle); RAuth->GetPublisherAPI()->ClearOnRequestPermissionsCompleteDelegate_Handle(OnRequestPermissionsCompleteHandle); } void URequestPermissionsState::OnCheckPermissionsComplete(bool bSuccess, bool bGranted) { UE_LOG(LogRAuth, Log, TEXT("ENTER OnCheckPermissionsComplete(%d, %d)"), (int32)bSuccess, (int32)bGranted); if (!bSuccess) { UE_LOG(LogRAuth, Log, TEXT("OnCheckPermissionsComplete failure")); // FIXME: proceding anyway StateMachine->ChangeState(EAuthStateEnum::VE_GameServerLogin); return; } if (bGranted) { // Procede StateMachine->ChangeState(EAuthStateEnum::VE_GameServerLogin); } else { // TODO: Show Permissions Notice UI RAuth->GetPublisherAPI()->RequestPermissions(); } } void URequestPermissionsState::OnRequestPermissionsComplete(bool bSuccess, bool bGranted) { UE_LOG(LogRAuth, Log, TEXT("ENTER OnRequestPermissionsComplete(%d, %d)"), (int32)bSuccess, (int32)bGranted); if (!bSuccess) { UE_LOG(LogRAuth, Log, TEXT("OnRequestPermissionsComplete failure")); // FIXME: proceding anyway StateMachine->ChangeState(EAuthStateEnum::VE_GameServerLogin); return; } if (bGranted) { // Procede StateMachine->ChangeState(EAuthStateEnum::VE_GameServerLogin); } else { // TODO: complaint to user // FIXME: proceding anyway StateMachine->ChangeState(EAuthStateEnum::VE_GameServerLogin); } }
de30af5bcfd50b626170a85b2219743c170ff8da
ac41d2ccb549dc09ed34e5c0f4da403509abb5c3
/src/DOFIndexed.hpp
240ae82586ac4985fa093ac07c9915e6fd37ac26
[ "MIT" ]
permissive
spraetor/amdis2
c65b530dabd087d922d616bfaf9d53f4c8d5e3c4
53c45c81a65752a8fafbb54f9ae6724a86639dcd
refs/heads/master
2020-12-24T15:51:03.069002
2016-03-06T14:42:53
2016-03-06T14:42:53
39,136,073
2
0
null
null
null
null
UTF-8
C++
false
false
5,045
hpp
DOFIndexed.hpp
/** \file DOFIndexed.h */ #pragma once #include <cassert> #include <vector> #include "AMDiS_fwd.hpp" #include "AMDiS_base.hpp" namespace AMDiS { /** \ingroup DOFAdministration * \brief * Interface for objects that stores information indexed by DOF indices * (like DOFVector or DOFMatrix). This interface is template type independent, * so a DOFAdmin can handle a single list of DOFIndexedBase objects. */ class DOFIndexedBase { public: DOFIndexedBase() : coarsenOperation(COARSE_INTERPOL), refineOperation(REFINE_INTERPOL) {} virtual ~DOFIndexedBase() {} /// Returns the actual size. Must be overriden by sub classes virtual int getSize() const = 0; /// Resizes the object to size. Must be overriden by sub classes virtual void resize(int size) = 0; /// Check that object's size is equal to \p size or 0. If object's size is 0 change it to \p size. virtual void checked_change_dim(int size) { assert(getSize() == 0 || getSize() == size); if (getSize() == 0) resize(size); } /// Used by DOFAdmin::compress. Must be overriden by sub classes virtual void compressDOFIndexed(int first, int last, std::vector<DegreeOfFreedom>& newDOF) = 0; /// Performs needed action when a DOF index is freed. Can be overriden in /// sub classes. The default behavior is to do nothing. virtual void freeDOFContent(DegreeOfFreedom) {} /// Interpolation after refinement. Can be overriden in subclasses. /// The default behavior is to do nothing. virtual void refineInterpol(RCNeighbourList&, int) {} /// Restriction after coarsening. Can be overriden in subclasses. /// The default behavior is to do nothing. virtual void coarseRestrict(RCNeighbourList&, int) {} /// Returns the finite element space of this DOFIndexed object. Must be /// overriden in sub classes. virtual const FiniteElemSpace* getFeSpace() const = 0; /// Sets \ref coarsenOperation to op void setCoarsenOperation(RefineCoarsenOperation op) { coarsenOperation = op; } /// Returns \ref coarsenOperation RefineCoarsenOperation getCoarsenOperation() const { return coarsenOperation; } /// Sets \ref refineOperation to op void setRefineOperation(RefineCoarsenOperation op) { refineOperation = op; } /// Returns \ref refineOperation RefineCoarsenOperation getRefineOperation() const { return refineOperation; } protected: /// Specifies what operation should be performed after coarsening RefineCoarsenOperation coarsenOperation; RefineCoarsenOperation refineOperation; }; /** \ingroup DOFAdministration * \brief * Templated interface for DOFIndexed objects. */ template <class T> class DOFIndexed : public DOFIndexedBase { public: // typedefs typedef T value_type; typedef DegreeOfFreedom size_type; typedef value_type& reference; typedef value_type const& const_reference; typedef value_type* pointer; typedef value_type const* const_pointer; typedef typename std::vector<value_type>::iterator iterator; typedef typename std::vector<value_type>::const_iterator const_iterator; public: virtual ~DOFIndexed() {} /// Returns iterator to the begin of container virtual iterator begin() = 0; /// Returns iterator to the end of container virtual iterator end() = 0; /// Returns iterator to the begin of container virtual const_iterator begin() const = 0; /// Returns iterator to the end of container virtual const_iterator end() const = 0; /// Returns container element at index i virtual reference operator[](size_type i) = 0; /// Returns container element at index i virtual const_reference operator[](size_type i) const = 0; }; template<> class DOFIndexed<bool> : public DOFIndexedBase { public: // typedefs typedef bool value_type; typedef DegreeOfFreedom size_type; typedef std::vector<bool>::reference reference; typedef std::vector<bool>::const_reference const_reference; typedef std::vector<bool>::pointer pointer; typedef std::vector<bool>::const_pointer const_pointer; typedef std::vector<bool>::iterator iterator; typedef std::vector<bool>::const_iterator const_iterator; public: virtual ~DOFIndexed() {} /// Returns iterator to the begin of container virtual iterator begin() = 0; /// Returns iterator to the end of container virtual iterator end() = 0; /// Returns iterator to the begin of container virtual const_iterator begin() const = 0; /// Returns iterator to the end of container virtual const_iterator end() const = 0; /// Returns container element at index i virtual reference operator[](size_type i) = 0; /// Returns container element at index i virtual const_reference operator[](size_type i) const = 0; }; } // end namespace AMDiS
d6d0e8b45103a560329c5e7f5c61e978349adcc4
b581675ebe3633ea7d6e63ac7898335dc4dcd28c
/chef/MAXORD.cpp
f6c2bb215b07d409df57a800803b002c11cbcb6a
[]
no_license
udit043/little_bit_competitive
c219c1d77a48c87ac4b8384c5c09fdacbd1fe8c2
b54279e75c54337bd4d89f9a44489bf8ad00635b
refs/heads/master
2021-07-12T18:43:29.056528
2021-05-29T12:17:30
2021-05-29T12:17:30
86,187,789
0
0
null
null
null
null
UTF-8
C++
false
false
431
cpp
MAXORD.cpp
#include <bits/stdc++.h> using namespace std; #define mx 100007 #define ll unsigned long long #define sd(x) scanf("%d",&x) #define pd(x) printf("%d \n", x) #define sll(x) scanf("%lld",&x) #define pll(x) printf("%lld \n", x) int main() { int n, i, k, o=0, a=0; sd(n); for(i=0; i<n; i++) { sd(k); o = (o|k); a = max(a, k); } cout << a << " " << o << "\n"; return 0; } /* 4 1 3 5 4 5 7 */
56f2505e9dcbcf219b340cbe36f29df7c7a00f15
681e5578721dabbc517262463cdb48f3630b7c29
/src/plugins/Analysis/DCdEdxStudy_tree/DEventProcessor_DCdEdxStudy_tree.h
32b54a9e818c1c5859e5c723151c0a4fb7e93727
[]
no_license
JeffersonLab/sim-recon
d7a76e03887cfee255e1309ade73edb5a4f3bd87
de076695f16956fe649366b53959c7582285001f
refs/heads/master
2020-04-12T09:00:00.639534
2018-07-30T20:26:51
2018-07-30T20:26:51
39,176,669
15
20
null
2018-07-30T20:26:52
2015-07-16T04:35:19
C++
UTF-8
C++
false
false
1,254
h
DEventProcessor_DCdEdxStudy_tree.h
#ifndef _DEventProcessor_DCdEdxStudy_tree_ #define _DEventProcessor_DCdEdxStudy_tree_ #include <JANA/JEventProcessor.h> using namespace jana; #include <TFile.h> #include <TTree.h> #include <DVector3.h> #include <particleType.h> #include <DANA/DApplication.h> #include <TRACKING/DMCThrown.h> #include <TRACKING/DTrackTimeBased.h> #include <PID/DParticleID.h> #include <DCdEdxInformation.h> class DEventProcessor_DCdEdxStudy_tree:public JEventProcessor{ public: DEventProcessor_DCdEdxStudy_tree(){}; ~DEventProcessor_DCdEdxStudy_tree(){}; const char* className(void){return "DEventProcessor_DCdEdxStudy_tree";} private: jerror_t init(void); ///< Called once at program start. jerror_t brun(JEventLoop *eventLoop, int32_t runnumber); ///< Called everytime a new run number is detected. jerror_t evnt(JEventLoop *eventLoop, uint64_t eventnumber); ///< Called every event. jerror_t erun(void); ///< Called everytime run number changes, provided brun has been called. jerror_t fini(void); ///< Called after last event of last event source has been processed. DCdEdxInformation *dDCdEdxInformation; TTree* dPluginTree_DCdEdxInformation; DParticleID *dPIDAlgorithm; }; #endif // _DEventProcessor_DCdEdxStudy_tree_
265092857678bb73a4fa6d04926a8b7818e31088
4d28185e7a78a569f9a449f39f183cac3024f711
/source/Plugins/Process/NetBSD/NativeRegisterContextNetBSD.cpp
3a9caaad74c86ea5103deb840c884a6bfecc2542
[ "NCSA", "Apache-2.0", "LLVM-exception" ]
permissive
apple/swift-lldb
2789bf44f648609a1674ee520ac20b64c95de072
d74be846ef3e62de946df343e8c234bde93a8912
refs/heads/stable
2023-04-06T00:28:15.882479
2019-10-25T22:46:59
2019-10-25T22:46:59
44,838,862
780
291
Apache-2.0
2020-01-10T19:28:43
2015-10-23T21:13:18
C++
UTF-8
C++
false
false
1,345
cpp
NativeRegisterContextNetBSD.cpp
//===-- NativeRegisterContextNetBSD.cpp -------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "NativeRegisterContextNetBSD.h" #include "lldb/Host/common/NativeProcessProtocol.h" using namespace lldb_private; using namespace lldb_private::process_netbsd; // clang-format off #include <sys/types.h> #include <sys/ptrace.h> // clang-format on NativeRegisterContextNetBSD::NativeRegisterContextNetBSD( NativeThreadProtocol &native_thread, RegisterInfoInterface *reg_info_interface_p) : NativeRegisterContextRegisterInfo(native_thread, reg_info_interface_p) {} Status NativeRegisterContextNetBSD::DoRegisterSet(int ptrace_req, void *buf) { return NativeProcessNetBSD::PtraceWrapper(ptrace_req, GetProcessPid(), buf, m_thread.GetID()); } NativeProcessNetBSD &NativeRegisterContextNetBSD::GetProcess() { return static_cast<NativeProcessNetBSD &>(m_thread.GetProcess()); } ::pid_t NativeRegisterContextNetBSD::GetProcessPid() { return GetProcess().GetID(); }
f6cf291c03fb2f31b9eba5f3f050d27341dc0453
967c06d5e91c62ebf12625f424680ca1550f2225
/Qt_DataStructure/Tree/BinarySearchTree/binarysearchtree.cpp
33e659a8c931ba9ddf4e3780777332b0eaeac0ef
[]
no_license
tycao/opencvgit
45e26ea942fc08237aaed6f859da6789b11529af
4da3942b3f1188bcdee0bdf4d0767700c15af83f
refs/heads/master
2021-01-01T18:24:14.774618
2018-01-28T07:53:51
2018-01-28T07:53:51
98,324,366
0
0
null
null
null
null
GB18030
C++
false
false
296
cpp
binarysearchtree.cpp
#include "binarysearchtree.h" // 默认构造函数 BinaryNode::BinaryNode(int theElement, BinaryNode* lt, BinaryNode* rt) : element(theElement), leftChild(lt), rightChild(rt) { } // 获得结点里存储的数据的 接口函数 int BinaryNode::GetElement() { return this->element; }
9305a20ba53c0b1e8c830d7f6b5401f1febc1664
01adde025fec5c63c0edd9bfa662bdb39fca15e8
/software/satsim/energy-harvester/include/EnergyHarvester.hpp
bad1ed277d2f7e1052cf66075694b47d91f473ff
[ "Apache-2.0" ]
permissive
sausthapit/oec-asplos20-artifact
023fd1a598e9f9e455c03ef28b57bc9aeb501a4c
8966e88b04e7261f26ad0689ffcfe2d12efec711
refs/heads/master
2022-12-30T22:32:47.950265
2019-12-04T21:26:04
2019-12-04T21:26:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,223
hpp
EnergyHarvester.hpp
// EnergyHarvester.hpp // Energy harvester class header file // // Copyright 2019 Bradley Denby // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy of // the License at <http://www.apache.org/licenses/LICENSE-2.0>. // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #ifndef SATSIM_ENERGY_HARVESTER_HPP #define SATSIM_ENERGY_HARVESTER_HPP // Standard library #include <string> // string // satsim #include <ILog.hpp> // Logger interface #include <ISim.hpp> // Simulator interface #include <Logger.hpp> // Logger namespace satsim { class EnergyHarvester: public ILog, public ISim { public: EnergyHarvester( const double& initialVoltage_V, const double& initialCurrent_A, Logger* logger=NULL ); EnergyHarvester(const EnergyHarvester& energyHarvester) = default; EnergyHarvester(EnergyHarvester&& energyHarvester) = default; virtual ~EnergyHarvester() = default; virtual EnergyHarvester& operator=(const EnergyHarvester& energyHarvester) = default; virtual EnergyHarvester& operator=(EnergyHarvester&& energyHarvester) = default; virtual EnergyHarvester* clone() const; size_t getWorkerId() const; void setWorkerId(const size_t& id); double getVoltage() const; double getCurrent() const; void setVoltage(const double& volts); void setCurrent(const double& amperes); virtual void logEvent(const std::string& name, const double& time); virtual void logMeasurement( const std::string& name, const double& time, const double& measurement ); virtual void update(const double& seconds); private: double instantaneousVoltage_V; // voltage at present time in Volts double instantaneousCurrent_A; // current at present time in Amperes size_t workerId; Logger* logger; // singleton, should not be deleted }; } #endif
495316ffa394bbbc043abbdb0074efa9685c9c23
89fc4899c426329cf4d41f024bf5deb4353017e5
/src/controller/scan/ScanController.cpp
334ac978e3d2efcd7ca9606f8de7358000f62f0d
[ "MIT" ]
permissive
seanngpack/swag-scanner-cpp
770bbcbbcb8f1073963bab98ca8ac74b3648452c
afc905cbba40de424488d2b60bb0b506e5fee5f2
refs/heads/master
2021-05-18T18:01:48.558462
2020-10-27T06:02:44
2020-10-27T06:02:44
251,347,462
10
2
MIT
2020-10-27T06:02:45
2020-03-30T15:29:12
C++
UTF-8
C++
false
false
1,485
cpp
ScanController.cpp
#include "ScanController.h" #include "ScanModel.h" #include "Arduino.h" #include "SR305.h" #include "Visualizer.h" #include "ScanFileHandler.h" #include "Logger.h" #include <utility> #include <filesystem> namespace fs = std::filesystem; controller::ScanController::ScanController(std::shared_ptr<camera::ICamera> camera, std::shared_ptr<arduino::Arduino> arduino, std::shared_ptr<model::ScanModel> model) : camera(std::move(camera)), arduino(std::move(arduino)), model(std::move(model)) {} void controller::ScanController::run() { scan(); } void controller::ScanController::set_deg(int deg) { deg = deg; } void controller::ScanController::set_num_rot(int num_rot) { num_rot = num_rot; } void controller::ScanController::scan() { model->update_info_json(deg, num_rot); camera->scan(); const camera::intrinsics intrin = camera->get_intrinsics(); logger::info("started scanning..."); for (int i = 0; i < num_rot; i++) { std::string name = std::to_string(i * deg) + ".pcd"; camera->scan(); std::vector<uint16_t> depth_frame_raw = camera->get_depth_frame(); std::shared_ptr<pcl::PointCloud<pcl::PointXYZ>> cloud_raw = camera->create_point_cloud(depth_frame_raw, intrin); model->add_cloud(cloud_raw, name); model->save_cloud(name, CloudType::Type::RAW); arduino->rotate_by(deg); } }
6d3fffd70daf430b8c84497a85ff5309732a9df5
a9010b46e7d70b958a85cfa2fb01fedc1c7ecb1f
/Lesson_4/task_3/task_3.cpp
59a47233315905eb43273bc9bd58b160b6a7e60d
[]
no_license
OliynykArtem/NG_2021_Oliynyk-artem
b84f905a3ecdaf8e6cc946a324f2bcd9b4e129fc
d183ae0bb665e2d9644604cf976e54130749c603
refs/heads/main
2023-08-23T16:52:49.546612
2021-09-25T17:13:46
2021-09-25T17:13:46
383,277,073
0
0
null
null
null
null
UTF-8
C++
false
false
517
cpp
task_3.cpp
#include <iostream> using namespace std; int main() { char inj_arr[1000]; // Message cout << "Welcome!" << endl; cout << "Please enter any line: "; cin.getline(inj_arr, 1000); cout << endl; // Converting letters from lower to upper case for (int i = 0; inj_arr[i] != 0; i++) { if ((inj_arr[i] >= 'a' && inj_arr[i] <= 'z')) { cout << (char)(inj_arr[i] - 32); } else { cout << inj_arr[i]; } } // Message cout << endl << endl << "Thanks for using our program :)" << endl << endl; }
c580734b6808e99c0776d75c025f589790c7b998
71e0bd173aca1e37c4cd4e4809d660ee252328a1
/usagewindows.cpp
09884b4a6e26dd5d3855b2e102e238fd3bf58245
[]
no_license
Xinyu-Wu-0000/Subway-System-QT
d85cb1169b60e8c11229506fe352060c795a7e0e
ea1de2abd69763deb9f372656a56cdde87e51a7d
refs/heads/master
2023-01-06T17:22:04.674273
2020-10-30T18:39:28
2020-10-30T18:39:28
294,948,229
0
0
null
null
null
null
UTF-8
C++
false
false
271
cpp
usagewindows.cpp
#include "usagewindows.h" #include "ui_usagewindows.h" UsageWindows::UsageWindows(QWidget *parent) : QMainWindow(parent), ui(new Ui::UsageWindows) { ui->setupUi(this); } UsageWindows::~UsageWindows() { delete ui; }
ef999ff626d6c9339d19bbab43da56893555b428
0e22e189d1d487ab3e8346746aa8e3a94526a5d5
/TrainProvider/src/Providers/DeparturesProvider.hpp
5c8b3a26cd13b4b2dcc3070f0859864c8572bafc
[ "Apache-2.0" ]
permissive
valiro21/FastTrainService
6eb0415a4c470a3e2805063a8d2c63a408727d4b
8b13b6f31a3b2bf22d179f97b1db97160dbb8fbb
refs/heads/master
2021-01-20T11:45:31.092710
2017-01-27T21:26:35
2017-01-27T21:26:35
78,062,383
0
0
null
null
null
null
UTF-8
C++
false
false
539
hpp
DeparturesProvider.hpp
// // Created by vrosca on 1/21/17. // #ifndef FASTTRAINSERVICE_DEPARTURESPROVIDER_HPP #define FASTTRAINSERVICE_DEPARTURESPROVIDER_HPP #include "SingleQueryProvider.hpp" #include <Calendar.hpp> /** Returns trains that will depart after a given time at the given station */ class DeparturesProvider : public SingleQueryProvider { public: json provide (neo4j_result_stream_t * result_stream); DeparturesProvider (std::string station, std::string country, Calendar calendar); }; #endif //FASTTRAINSERVICE_DEPARTURESPROVIDER_HPP
9bbba6539fddcd3126ec60781bec7cb9de9702b4
cc46132e7a9a35d42bff5665315a3a11a98177c4
/src/include/pyutils.hpp
78ad88fcc04c6f5efff506fc35aa2b8f87b6b7f9
[]
no_license
shion-h/PartitionAroundMedoids
3b9f3bce25f8da787439b9adaf72ea152376b143
f2eb9f010268a196a9de9bbca5dfd3ebdc850395
refs/heads/master
2023-01-12T16:08:56.819441
2020-11-15T01:59:23
2020-11-15T01:59:23
107,092,889
0
0
null
null
null
null
UTF-8
C++
false
false
3,314
hpp
pyutils.hpp
// // pyutils.hpp // // Copyright (c) 2017 Shion Hosoda // // This software is released under the MIT License. // http://opensource.org/licenses/mit-license.php // #include <boost/python.hpp> #include <iostream> #include <vector> #include <random> #include <cmath> namespace py = boost::python; std::vector<std::vector<double> > convertListToVector2D(py::list list){//{{{ std::vector<std::vector<double> > vector(len(list)); for(int i=0; i<vector.size(); i++)vector[i].assign(len(list[0]),0); for(int i=0; i<len(list); i++){ for(int j=0; j<len(list[0]); j++){ py::list listBuf = py::extract<py::list>(list[i]); vector[i][j] = py::extract<double>(listBuf[j]); } } return vector; }//}}} py::list convertVectorToList2D(std::vector<std::vector<unsigned int> > vector){//{{{ py::list list; for(int i=0; i<vector.size(); i++){ py::list oneDlist; for(int j=0; j<vector[i].size(); j++){ oneDlist.append(vector[i][j]); } list.append(oneDlist); } return list; }//}}} py::list convertVectorToList1D(std::vector<unsigned int> vector){//{{{ py::list list; for(int i=0; i<vector.size(); i++){ list.append(vector[i]); } return list; }//}}} double calculateJSD(const std::vector<double> vector1, const std::vector<double> vector2){//{{{ double JSD = 0.0; double factor1, factor2; for(int i=0; i<vector1.size(); i++){ if(vector1[i] == 0.0){ factor1 = 0.0000000001; }else{ factor1 = vector1[i]; } if(vector2[i] == 0.0){ factor2 = 0.0000000001; }else{ factor2 = vector2[i]; } JSD += 0.5 * (factor1*log(factor1/factor2) + factor2*log(factor2/factor1)); } return JSD; }//}}} double calculateEuclidDistance(std::vector<double> vector1, std::vector<double> vector2){//{{{ double euclidDistance = 0.0; for(int i=0; i<vector1.size(); i++){ double diff = vector1[i]-vector2[i]; euclidDistance += diff * diff; } return euclidDistance; }//}}} std::vector<unsigned int> choiceRandomItems(const int size, int randMin, int randMax){//{{{ if(randMin > randMax) std::swap(randMin, randMax); const int maxMinDiff = randMax - randMin + 1; if(maxMinDiff < size) throw std::runtime_error("augument error"); std::vector<unsigned int> tmp; std::random_device rnd; std::mt19937 mt(rnd()); std::uniform_int_distribution<int> distribution(randMin, randMax); const double makeSize = size*1.2; std::cout<<"tmp size:"<<tmp.size()<<' '<<size<<std::endl; while(tmp.size() < size){ while(tmp.size() < makeSize){ tmp.push_back(distribution(mt)); // std::cout<<distribution(mt)<<std::endl; } std::cout<<"tmp"; for(int i=0; i<tmp.size(); i++){ std::cout<<tmp[i]<<' '; } std::cout<<std::endl; std::sort(tmp.begin(), tmp.end()); auto uniqueEnd = std::unique(tmp.begin(), tmp.end()); if(size < std::distance(tmp.begin(), uniqueEnd)){ uniqueEnd = std::next(tmp.begin(), size); } tmp.erase(uniqueEnd, tmp.end()); } std::shuffle(tmp.begin(), tmp.end(), mt); return tmp; }//}}}
8b5e860e84da8d1b35d20f1cfb52f2a727c1576d
e50b5f066628ef65fd7f79078b4b1088f9d11e87
/llvm/include/llvm/DebugInfo/PDB/DIA/DIAEnumSourceFiles.h
5db8fd93e9b8512c2a019f3ede9c0b6cfe01facc
[ "NCSA" ]
permissive
uzleo/coast
1471e03b2a1ffc9883392bf80711e6159917dca1
04bd688ac9a18d2327c59ea0c90f72e9b49df0f4
refs/heads/master
2020-05-16T11:46:24.870750
2019-04-23T13:57:53
2019-04-23T13:57:53
183,025,687
0
0
null
2019-04-23T13:52:28
2019-04-23T13:52:27
null
UTF-8
C++
false
false
1,133
h
DIAEnumSourceFiles.h
//==- DIAEnumSourceFiles.h - DIA Source File Enumerator impl -----*- C++ -*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLVM_DEBUGINFO_PDB_DIA_DIAENUMSOURCEFILES_H #define LLVM_DEBUGINFO_PDB_DIA_DIAENUMSOURCEFILES_H #include "DIASupport.h" #include "llvm/DebugInfo/PDB/IPDBEnumChildren.h" namespace llvm { namespace pdb { class DIASession; class DIAEnumSourceFiles : public IPDBEnumChildren<IPDBSourceFile> { public: explicit DIAEnumSourceFiles(const DIASession &PDBSession, CComPtr<IDiaEnumSourceFiles> DiaEnumerator); uint32_t getChildCount() const override; ChildTypePtr getChildAtIndex(uint32_t Index) const override; ChildTypePtr getNext() override; void reset() override; DIAEnumSourceFiles *clone() const override; private: const DIASession &Session; CComPtr<IDiaEnumSourceFiles> Enumerator; }; } } #endif
2f32fdaaaf26d327e8f03938a265ffb630f614cb
6343becde6901e0fcf3a791e719b9d2a08966be8
/src/layout.cpp
55d9e8f30061e077f0bb902863d32fe45d4c092c
[ "MIT" ]
permissive
xiu810/rive-cpp
1bfd591eed9c80ec27a984d8b805ddb88754ee17
bfb16907447239687ef6dee918eda9b87beffb6e
refs/heads/master
2023-07-16T12:03:22.676575
2021-08-21T11:13:32
2021-08-31T23:14:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
626
cpp
layout.cpp
#include "rive/layout.hpp" using namespace rive; const Alignment Alignment::topLeft = Alignment(-1.0f, -1.0f); const Alignment Alignment::topCenter = Alignment(0.0f, -1.0f); const Alignment Alignment::topRight = Alignment(1.0f, -1.0f); const Alignment Alignment::centerLeft = Alignment(-1.0f, 0.0f); const Alignment Alignment::center = Alignment(0.0f, 0.0f); const Alignment Alignment::centerRight = Alignment(1.0f, 0.0f); const Alignment Alignment::bottomLeft = Alignment(-1.0f, 1.0f); const Alignment Alignment::bottomCenter = Alignment(0.0f, 1.0f); const Alignment Alignment::bottomRight = Alignment(1.0f, 1.0f);
7ece2e250be50b5848ee1f5bc6986fea57d3c8a7
4d23097a7b370c35160edfca642e2d37f532b518
/Algorithms/MapGenerator/FSEGTAMapGeneratorParams.cpp
cb94b5d2a75e6b6750167b1a75094cfb2737ec73
[ "MIT" ]
permissive
demensdeum/FlameSteelEngineGameToolkitAlgorithms
2e68b54bc8366490d8640b6cf4c5349c1e5e820a
d042b70a89946510e97ef767f3ee9a731808cd18
refs/heads/master
2020-04-05T17:41:43.570630
2018-11-07T12:12:54
2018-11-07T12:12:54
133,219,970
0
0
null
null
null
null
UTF-8
C++
false
false
632
cpp
FSEGTAMapGeneratorParams.cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: DMMapGeneratorParams.cpp * Author: demensdeum * * Created on April 25, 2017, 10:34 AM */ #include "FSEGTAMapGeneratorParams.h" #include <memory> #include <FlameSteelCore/Objects.h> FSEGTAMapGeneratorParams::FSEGTAMapGeneratorParams() { freeTileIndex = 0; solidTileIndex = 0; maxIterations = 0; maxLineLength = 0; minCursorSize = 0; maxCursorSize = 0; minFreeSpace = 0; maxFreeSpace = 0; }
64d7f362a01045ee7878acdeb9922f3516a7e2ea
409be0b4888249482bba2687ac89d036c515a7b8
/lib/ve/profusion/lib/libviewplus/src/MyUnixUtils.hpp
99a726a3e8c17f0c252ae4e06ab944cdc17aa2f6
[]
no_license
lqhk/ve-cmu
c0758ac72268b06baa2b3cc1c3af5db7de945bbe
32a7dc0c95deb73223ea6f3012daeb2ea449331d
refs/heads/master
2021-01-19T16:25:08.303969
2012-12-02T07:04:39
2012-12-02T07:04:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,186
hpp
MyUnixUtils.hpp
// ====================================================================== // MyUnixUtils.hpp // // Revision History: // Rev.01 2008/08/05 The First edition // Rev.02 2010/05/07 Change license to the modified BSD license // // This file is licensed under the modified BSD license. // // Copyright (C) 2008-2010 Dairoku Sekiguchi // 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 ViewPLUS Inc. nor the names of // its contributors may be used to endorse or promote products // derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ====================================================================== /*! \file MyUnixUtils.hpp \author Dairoku Sekiguchi \version 1.0 \date 2008 \license modified BSD license \brief Unix Utilites Collection of useful unix utilites */ #ifndef __MY_UNIX_UTILS_H #define __MY_UNIX_UTILS_H // Includes ------------------------------------------------------------ #include <limits.h> #include <time.h> #include <sys/time.h> // ---------------------------------------------------------------------- // typedefs // ---------------------------------------------------------------------- typedef unsigned int timeout_t; // ---------------------------------------------------------------------- // macros // ---------------------------------------------------------------------- #define TIMEOUT_T_MAX UINT_MAX #define MY_MILLI_SECOND_UNIT 1000 #define MY_MICRO_SECOND_UNIT 1000000 #define MY_NANO_SECOND_UNIT 1000000000 // ---------------------------------------------------------------------- // MyUnixUtils classe // ---------------------------------------------------------------------- class MyUnixUtils { public: static void Sleep(timeout_t inMilliseconds) { struct timespec reqTime; reqTime.tv_sec = inMilliseconds / 1000; inMilliseconds -= (reqTime.tv_sec * 1000); reqTime.tv_nsec = inMilliseconds * 1000000; nanosleep(&reqTime, NULL); //usleep(inMilliseconds * 1000); // microseconds to miliseconds } static int GetUnixTimeout(struct timespec *outTime, timeout_t inMilliseconds) { int error; error = GetUnixTime(outTime); if (error != 0) return error; CalcUnixTimeout(outTime, inMilliseconds); return 0; } static int GetUnixTime(struct timespec *outTime) { #ifdef _USE_CLOCK_GETTIME_ return clock_gettime(CLOCK_REALTIME, outTime); #else int error; struct timeval timeVal; struct timezone timeZone; error = gettimeofday(&timeVal, &timeZone); if (error != 0) return error; outTime->tv_sec = timeVal.tv_sec; outTime->tv_nsec = timeVal.tv_usec * MY_MILLI_SECOND_UNIT; return error; #endif } static unsigned int GetTickCount() { unsigned int tick; #ifdef _USE_CLOCK_GETTIME_ struct timespec t; clock_gettime(CLOCK_REALTIME, &t); tick = t.tv_sec * MY_MILLI_SECOND_UNIT; tick += (t.tv_nsec / MY_MICRO_SECOND_UNIT); return tick; #else int error; struct timeval timeVal; struct timezone timeZone; error = gettimeofday(&timeVal, &timeZone); if (error != 0) return 0; tick = timeVal.tv_sec * MY_MILLI_SECOND_UNIT; tick += (timeVal.tv_usec / MY_MILLI_SECOND_UNIT); return tick; #endif } static void CalcUnixTimeout(struct timespec *ioTime, timeout_t inMilliseconds) { timeout_t t; t = inMilliseconds / MY_MILLI_SECOND_UNIT; if (TIMEOUT_T_MAX - ioTime->tv_sec < t) { ioTime->tv_sec = TIMEOUT_T_MAX; ioTime->tv_nsec = TIMEOUT_T_MAX; return; } ioTime->tv_sec += t; inMilliseconds = inMilliseconds - t * MY_MILLI_SECOND_UNIT; ioTime->tv_nsec += inMilliseconds * MY_MICRO_SECOND_UNIT; if (ioTime->tv_nsec >= MY_NANO_SECOND_UNIT) { (ioTime->tv_nsec) -= MY_NANO_SECOND_UNIT; if (TIMEOUT_T_MAX - ioTime->tv_sec == 0) { ioTime->tv_nsec = MY_NANO_SECOND_UNIT; return; } (ioTime->tv_sec)++; } } }; #endif // #ifdef __MY_UNIX_UTILS_H
3b1a0ab6cc90661fb40a20f7b406f30e20518ac9
293902682d7ee13be81ada6c28ef6b840983ac33
/CoralCommon/CoralCommon/Cipher.h
19c67e67455533e6031e3f860ccd66d5eae5529b
[]
no_license
cms-externals/coral
d17cba45fff7f34d7a1ba13ab3bb371e0696c1af
a879b41c994fa956ff0ae78e3410bb409582ad20
refs/heads/cms/CORAL_2_3_21py3
2022-02-26T18:51:25.258362
2022-02-23T13:19:11
2022-02-23T13:19:11
91,173,895
0
4
null
2022-02-14T13:20:11
2017-05-13T12:47:54
C++
UTF-8
C++
false
false
594
h
Cipher.h
#ifndef CORALCOMMON_CIPHER_H #define CORALCOMMON_CIPHER_H #include <string> namespace coral { class Cipher { public: static std::string encode (const std::string &text, const std::string &key); static std::string decode (const std::string &text, const std::string &key); static std::string u64enc(const std::string &text); static std::string u64dec(const std::string &text); static char u64encMap(char c); static char u64decMap(char c); private: static void u64dec(char i[4], char o[3]); static void u64enc(char i[3], char o[4]); }; } #endif
e3182766a06c76b8a061981b34009a04c7f2b906
b77dd6dcb1f84fc249e0050013e6d74f2b3f039d
/include/shapes/ransac_Boctree.h
2b18756b4e6ae667927e1dcce95bda96a1a5cb06
[]
no_license
3DTK/3DTK
fad4333832d5ee3c4fa43a0e3c2ab719bd7ec278
bfc46d1b30b35a955ebde78c229ac40ee10e296c
refs/heads/master
2023-08-10T01:58:20.472841
2023-07-28T11:54:42
2023-07-28T11:54:42
120,477,018
64
28
null
null
null
null
UTF-8
C++
false
false
9,309
h
ransac_Boctree.h
/** * @file * @brief Efficient representation of an octree for ransac * @author Jan Elsberg. Automation Group, Jacobs University Bremen gGmbH, Germany. */ #ifndef RANSAC_OCTREE_H #define RANSAC_OCTREE_H #include <stdio.h> #include <vector> #include <deque> #include <set> #include <list> #include <iostream> #include <fstream> #include <string> #include "shapes/geom_math.h" #include "slam6d/globals.icc" #include "slam6d/Boctree.h" #include "shape.h" /** * @brief Octree * * A cubic bounding box is calculated * from the given 3D points. Then it * is recusivly subdivided into smaller * subboxes */ template <class T> class RansacOctTree : public BOctTree<T> { public: template <class P> RansacOctTree(P* const* pts, int n, T _voxelSize, PointType _pointtype = PointType() ) : BOctTree<T>(pts, n, _voxelSize, _pointtype) {} // RansacOctTree(vector<const T *> &pts, T voxelSize, PointType _pointtype = PointType() ) : BOctTree<T>(pts, voxelSize, _pointtype) {} RansacOctTree(std::string filename) : BOctTree<T> (filename) {} void DrawPoints(vector<T *> &p, unsigned char nrp) { DrawPoints(p, *BOctTree<T>::root, nrp); } unsigned long PointsOnShape(CollisionShape<T> &shape) { return PointsOnShape(*BOctTree<T>::root, BOctTree<T>::center, BOctTree<T>::size, shape); } void PointsOnShape(CollisionShape<T> &shape, vector<T *> &points) { PointsOnShape(*BOctTree<T>::root, BOctTree<T>::center, BOctTree<T>::size, shape, points); // exit(0); } void PointsOnShapeAndDelete(CollisionShape<T> &shape, vector<T *> &points) { PointsOnShapeAndDelete(*BOctTree<T>::root, BOctTree<T>::center, BOctTree<T>::size, shape, points); // exit(0); } protected: void showbits(char a) { int i , k , mask; for( i =7 ; i >= 0 ; i--) { mask = 1 << i; k = a & mask; if( k == 0) cout<<"0 "; else cout<<"1 "; } } long PointsOnShape(bitoct &node, T *center, T size, CollisionShape<T> &shape ) { if (! shape.isInCube(center[0], center[1], center[2], size)) { return 0; } T ccenter[3]; bitunion<T> *children; bitoct::getChildren(node, children); /* printf("parent %p children: %p \n", &node, children); cout << " "; showbits(node.valid); cout << endl; cout << " "; showbits(node.leaf); cout << endl; */ long result = 0; // int r = 0; for (unsigned char i = 0; i < 8; i++) { if ( ( 1 << i ) & node.valid ) { // if ith node exists // printf("i: %u r: %d parent %p child[r]: %p \n", i, r, &node, children); // r++; BOctTree<T>::childcenter(center, ccenter, size, i); // childrens center if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center // check if leaf contains shape if ( shape.isInCube(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) { pointrep *points = children->getPointreps(); unsigned int length = points[0].length; T *point = &(points[1].v); // first point for(unsigned int iterator = 0; iterator < length; iterator++ ) { if ( shape.containsPoint(point) ) result++; point+= BOctTree<T>::POINTDIM; } } } else { // recurse result += PointsOnShape( children->node, ccenter, size/2.0, shape); } ++children; // next child //r++; } } return result; } void PointsOnShape(bitoct &node, T *center, T size, CollisionShape<T> &shape, vector<T*> &vpoints) { if (! shape.isInCube(center[0], center[1], center[2], size)) { return; } T ccenter[3]; bitunion<T> *children; bitoct::getChildren(node, children); for (unsigned char i = 0; i < 8; i++) { if ( ( 1 << i ) & node.valid ) { // if ith node exists BOctTree<T>::childcenter(center, ccenter, size, i); // childrens center if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center // check if leaf contains shape if ( shape.isInCube(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) { pointrep *points = children->getPointreps(); unsigned int length = points[0].length; T *point = &(points[1].v); // first point for(unsigned int iterator = 0; iterator < length; iterator++ ) { // cerr << point[0] << " " << point[1] << " " << point[2] << endl; if ( shape.containsPoint(point) ) { T * p = new T[BOctTree<T>::POINTDIM]; for (unsigned int iterator = 0; iterator < BOctTree<T>::POINTDIM; iterator++) { p[iterator] = point[iterator]; } vpoints.push_back(p); } point+= BOctTree<T>::POINTDIM; } } } else { // recurse PointsOnShape( children->node, ccenter, size/2.0, shape, vpoints); } ++children; // next child } } } void PointsOnShapeAndDelete(bitoct &node, T *center, T size, CollisionShape<T> &shape, vector<T*> &vpoints) { if (! shape.isInCube(center[0], center[1], center[2], size)) { return; } T ccenter[3]; bitunion<T> *children; bitoct::getChildren(node, children); for (unsigned char i = 0; i < 8; i++) { if ( ( 1 << i ) & node.valid ) { // if ith node exists BOctTree<T>::childcenter(center, ccenter, size, i); // childrens center if ( ( 1 << i ) & node.leaf ) { // if ith node is leaf get center // check if leaf contains shape if ( shape.isInCube(ccenter[0], ccenter[1], ccenter[2], size/2.0) ) { pointrep *points = children->getPointreps(); unsigned int length = points[0].length; T *point = &(points[1].v); // first point for(unsigned int iterator = 0; iterator < length; iterator++ ) { // cerr << point[0] << " " << point[1] << " " << point[2] << endl; if ( shape.containsPoint(point) ) { T * p = new T[BOctTree<T>::POINTDIM]; for (unsigned int iterator = 0; iterator < BOctTree<T>::POINTDIM; iterator++) { p[iterator] = point[iterator]; } vpoints.push_back(p); } point+= BOctTree<T>::POINTDIM; } points[0].length = 0; } } else { // recurse PointsOnShapeAndDelete( children->node, ccenter, size/2.0, shape, vpoints); } ++children; // next child } } } void DrawPoints(vector<T *> &p, bitoct &node, unsigned char nrp) { bitunion<T> *children; bitoct::getChildren(node, children); unsigned char n_children = POPCOUNT(node.valid); unsigned char r = randUC(n_children); if (r == n_children) r--; /* cout << (unsigned int)r << " nc " << (unsigned int)n_children << endl; showbits(node.valid); cout << endl; showbits(node.leaf); cout << endl; */ bool leaf = false; unsigned char child_index = 0; /* if (r == 2) { for (unsigned char i = 0; i < 8; i++) { cout << "i " << (unsigned int)i << endl; if ( ( 1 << i ) & node.valid ) { // if ith node exists cout << "valid " << endl; if (child_index == r) { cout << "ci == r" << endl; if ( ( 1 << i ) & node.leaf ) { // if ith node exists cout << "leaf" << endl; leaf = true; } cout << "no leaf" << endl; break; } child_index++; } } } else {*/ for (unsigned char i = 0; i < 8; i++) { if ( ( 1 << i ) & node.valid ) { // if ith node exists if (child_index == r) { if ( ( 1 << i ) & node.leaf ) { // if ith node exists leaf = true; } break; } child_index++; } } // } // cout << (unsigned int)r << " nc " << (unsigned int)n_children << " " << (unsigned int)child_index << endl; if (child_index != r) return; // bitmask valid might be all zero if (leaf) { /* cout << "STOPPED" << endl; return;*/ pointrep *points = children[r].getPointreps(); unsigned int length = points[0].length; if (length < nrp) return; if (length == nrp) { for (char c = 0; c < nrp; c++) { p.push_back(&(points[BOctTree<T>::POINTDIM*c+1].v)); } return; } // randomly get nrp points, we will not check if this succeeds in getting nrp distinct points for (char c = 0; c < nrp; c++) { int tmp = rand(points[0].length); p.push_back(&(points[BOctTree<T>::POINTDIM*tmp+1].v)); } } else { /* printf("r: %d parent %p children %p child[r]: %p \n", r, &node, children, &(children[r].node)); showbits(node.valid); cout << endl; showbits(node.leaf); cout << endl; cout << "RECURSED" << endl;*/ DrawPoints(p, children[r].node, nrp); } } }; #endif
5e0865571fefb998a1a2e5a0ce92028b19a3ec4f
ea2c4866d73d0d74b8607cd8e64e16d3b254f95b
/src/Protocol.cxx
32b7e7999ee9e1bb545e1f3db039393e62823d75
[]
no_license
puneetk/Punisher
1f2bc1486454af87bdaeb8f4dff2af624de3592e
f636dca33ae7347f4dc05f5ad1a6480d2fa3dd03
refs/heads/master
2021-01-16T20:43:45.367643
2012-02-11T00:53:57
2012-02-11T00:53:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
720
cxx
Protocol.cxx
/* * Punisher * by Michael Spiegle * 10.15.09 * * Protocol.cxx */ #include "Protocol.hxx" #include <string.h> namespace Punisher { Protocol::Protocol() { request = NULL; validator = NULL; memset(&start_time, 0, sizeof(struct timeval)); memset(&end_time, 0, sizeof(struct timeval)); } Protocol::Protocol(const Request* request) { this->request = request; } Protocol::~Protocol() { if (NULL != validator) { delete(validator); validator = NULL; } } const Request* Protocol::GetRequest() const { return request; } Validator* Protocol::GetValidator() const { return validator; } void Protocol::SetValidator(Validator* validator) { if (NULL != validator) { this->validator = validator; } } }
65d0b4e9e507c75dd0b888a862b68490e79c413a
6366ca977ce7652cf50e561f2c63a49fd5b9e4f1
/CPlusPlusCode/InterQiew/ItqInherit.cxx
4a53f740843c0e87713496fe57e8a7fc6ccbd415
[]
no_license
PhailedPhysicst/InterviewPrep
5969725fb450c2079a1816e6027d954e07ab99ca
3fd92ec3e7bcc74b66964967d394d5f5e58ebef9
refs/heads/master
2020-04-25T05:05:19.050288
2015-06-14T22:25:48
2015-06-14T22:25:48
37,376,230
0
0
null
null
null
null
UTF-8
C++
false
false
389
cxx
ItqInherit.cxx
#include <iostream> class A { public: A(int n = 0) : m_i(n) { std::cout << m_i; ++m_i; } protected: int m_i; }; class B : public A { public: B(int n = 5) : m_a(new A[2]), m_x(++m_i) { std::cout << m_i; } ~B() { delete [] m_a; } private: A m_x; A *m_a; }; int main() { B b; std::cout << std::endl; return 0; }
f8963cf555446848469ebb99fa4823becab76c46
d2190cbb5ea5463410eb84ec8b4c6a660e4b3d0e
/old_hydra/hydra/tags/apr07a/hyp/hhypXKine.cc
2910bd6be2299e87d2973e41afda45bf4e301273
[]
no_license
wesmail/hydra
6c681572ff6db2c60c9e36ec864a3c0e83e6aa6a
ab934d4c7eff335cc2d25f212034121f050aadf1
refs/heads/master
2021-07-05T17:04:53.402387
2020-08-12T08:54:11
2020-08-12T08:54:11
149,625,232
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
9,593
cc
hhypXKine.cc
//*-- AUTHOR : B. Spruck //*-- Modified : 10/nov/2006 by B. Spruck //_HADES_CLASS_DESCRIPTION //////////////////////////////////////////////////////////////////////// // // HHypXKine // // This is // i) an ALGORITHM which updates the momenta using the HypKine Object // ii) a SELECTOR which removes background using the kine refit // //////////////////////////////////////////////////////////////////////// #include "hhypXKine.h" using namespace std; ClassImp(HHypXKine) HHypXKine::HHypXKine(char *name_i, Option_t par[]) :HHypBaseAlgorithm(name_i,par) { fitter=new HLagrangeSolmitzFit(); kinetest=0; } HHypXKine::~HHypXKine() { delete fitter; } Double_t HHypXKine::getMomErr(Int_t sec,Double_t P,Int_t pid) {// Everything is calculated in MeV here! Double_t dP, M; M=HPidPhysicsConstants::mass(pid);// get mass in MeV { Double_t c1, c2; if(sec>=0 && sec<6){ Double_t momResC1[6]={0.0289,0.0160,0.0993,0.0122,0.0106,0.0284}; Double_t momResC2[6]={0.0221,0.0221,0.0221,0.0221,0.0221,0.0221}; c1=momResC1[sec]*1e-3; c2=momResC2[sec]; }else{ Error("getMomErr","Sector<0 || Sector>5"); c1=0; c2=0; } /* switch(sec){ case 0: c1=3.197e-5; c2=0.0561; break; case 1: c1=3.317e-5; c2=0.02067; break; case 2: c1=7.572e-5; c2=0.1254; break; case 3: c1=2.383e-5; c2=0.02371; break; case 4: c1=1.602e-5; c2=0.02777; break; case 5: c1=3.556e-5; c2=0.06099; break; default: Error("getMomErr","Sector<0 || Sector>5"); c1=0; c2=0; break; }*/ // Formula is (dP/P)²=(c1*p)²+(c2/beta)² Double_t P2=P*P; dP=TMath::Sqrt(c1*c1*P2*P2 + c2*c2*(P2+M*M)); } if(kinetest) kinetest->Fill(P,dP,M,sec); return(dP); } #define KINEDEBUG 0 Bool_t HHypXKine::execute() { Int_t npart; npart=mylist->getNpart(); if (npart != 4) return kFALSE; //needs 4 particles ... at least in this code version TVector3 momentum_ini[4];// npart TVector3 momentum_fitted[4];// npart Int_t pidofPart[4];// npart HPidParticle *pPidPart[4];// npart Double_t cov_ini[4][9];// npart Double_t cov_fitted[4][9];// npart Float_t FakErrMom=1.255;//*0.35; Float_t FakErrTheta=1.11;//*0.4; Float_t FakErrPhi=1.11;//*0.4; // The momenta will be modified... if i am the first this // is /in principle/ not needed but who knows, am I? mylist->initcopyMomentum(); #if KINEDEBUG cout << "=============== new Event ===========" << endl; #endif mylist->CombIteratorReset(); while (mylist->CombIterator()) { #if KINEDEBUG cout << "------- new Comb ------" << endl; #endif // clear particles... fitter->clearParticleSet(); // Getting the particles for(Int_t i=0; i<npart; i++){ Double_t momErr, theErr, phiErr; HBaseTrack *b; #if KINEDEBUG cout << "Track: " << i << endl; #endif pidofPart[i]=mylist->getPid(i); momentum_ini[i]=mylist->getMomentum(i); pPidPart[i]=mylist->getPidParticle(i); // pPidPart[i]->getCovarianceMatrix(); momErr=FakErrMom*getMomErr(pPidPart[i]->sector(),momentum_ini[i].Mag(),pidofPart[i]); b=(HBaseTrack *)(pPidPart[i]->getTrackData()->getBaseTrack(pPidPart[i]->getMomAlg())); theErr=FakErrTheta*b->getErrTheta(); phiErr=FakErrPhi*b->getErrPhi(); for(Int_t j=0; j<9; j++) cov_ini[i][j]=0; cov_ini[i][0] = momErr*momErr *1e-6;// MeV in GeV cov_ini[i][4] = theErr*theErr; cov_ini[i][8] = phiErr*phiErr; // MeV in GeV for Momentum! Double_t theta, phi; theta=momentum_ini[i].Theta(); if( theta<0.0) theta+=2.0*TMath::Pi(); if( theta>=2.0*TMath::Pi()) theta-=2.0*TMath::Pi(); phi=momentum_ini[i].Phi(); if( phi<0.0) phi+=2.0*TMath::Pi(); if( phi>=2.0*TMath::Pi()) phi-=2.0*TMath::Pi(); #if KINEDEBUG cout << "PID: " <<pidofPart[i] << " Mom: "<<momentum_ini[i].Mag()*1e-3 << " Theta: "<< theta <<" Phi: "<<phi <<endl; cout << "MomErr: " <<sqrt(cov_ini[i][0]) <<" ThetaErr: " <<sqrt(cov_ini[i][4]) <<" PhiErr: " <<sqrt(cov_ini[i][8]) <<endl; #endif fitter->addChargedParticle(pidofPart[i], momentum_ini[i].Mag()*1e-3, theta, phi, cov_ini[i]); // cout << ":: " << i <<": "<<pidofPart[i] <<" , "<< momentum_ini[i].Mag()*1e-3 << " , "<< theta <<" , " << phi<< endl; } if (mylist->getIterStatus() != kTRUE) { cerr << algoName << " IterStatus is FALSE. Big Problem! " << endl; mylist->removeComb(); continue; } Float_t mpid; Int_t miss_pid; if (!mylist->getUserValue(FILLER_MISSING_PID, mpid)) mpid = -999; miss_pid=(Int_t)mpid; if( miss_pid==-999){ cout << "// Missing particle not supported: "<< miss_pid <<endl; mylist->removeComb(); continue; }else if(miss_pid==0){ #if KINEDEBUG cout << "// Missing particle: "<< miss_pid <<endl; #endif }// else ? if(miss_pid==0){// no neutral (missing) particle fitter->clearNeutralParticle(); #if KINEDEBUG cout <<"Missing nothing" << endl; #endif }else{ fitter->setNeutralParticle(miss_pid); #if KINEDEBUG cout <<"Missing " << miss_pid << endl; #endif } if (mylist->getIterStatus() != kTRUE) { cerr << algoName << " IterStatus is FALSE. Might be missing FILLER_MISSING_PID UserValue! " << endl; mylist->removeComb(); continue; } // Now try to fit if(!fitter->fit()){ cout << algoName << " Fitter Parameters not correct. " << endl; mylist->removeComb(); continue; } // check result if(!fitter->isConvergence()){ #if KINEDEBUG cout << algoName << " Fitter not converged! " << endl; #endif mylist->removeComb(); continue; } // more exact result... // Double_t getRetCode (); // Int_t getIT (); // Float_t get_dE (); // Bool_t get_dMom (Float_t* dM); Double_t chi2=fitter->getChi2(); // Float_t getProb (); Double_t channel_code= fitter->getChannelCode(); #if KINEDEBUG cout << "Chi2: "<<chi2<<" ChannelCode: "<<channel_code<<endl; #endif // Now get the fitted tracks for(Int_t i=0; i<npart; i++){ //Double_t momErr, theErr, phiErr; Double_t p, theta, phi; fitter->getFittedChargedParticle ( i, &p, &theta, &phi, cov_fitted[i]); p*=1e+3;// GeV in MeV momentum_fitted[i].SetXYZ(p*sin(theta)*cos(phi),p*sin(theta)*sin(phi),p*cos(theta)); mylist->setMomentum(i, momentum_fitted[i]); //momErr=TMath::Sqrt(cov_fitted[i][0]*1e+6);// GeV in MeV //theErr=TMath::Sqrt(cov_fitted[i][4]); //phiErr=TMath::Sqrt(cov_fitted[i][8]); } // Bool_t getFittedNeutralParticle ( Float_t* p, Float_t* theta, Float_t* phi, Double_t* cov); if (mylist->getIterStatus() == kFALSE) { cout << "!!!!!error HHypXKine execute mylist->getIterStatus() == kFALSE!!!!!! " << endl; exit(2); } mylist->resetProbAlg( TMath::Prob(chi2,1)); //store more data here.... mylist->setUserValue(KINEFIT_CHI24, chi2); Float_t pulls_p[4];// npart Float_t pulls_the[4];// npart Float_t pulls_phi[4];// npart for(Int_t i=0; i<npart; i++){ // Real Pull is: Double_t nom; Double_t mi, mf; Double_t ki, kf; Double_t dki, dkf; mi=momentum_ini[i].Mag(); ki=1.0/mi; mf=momentum_fitted[i].Mag(); kf=1.0/mf; dki=cov_ini[i][0]*1e+6/(mi*mi*mi*mi); dkf=cov_fitted[i][0]*1e+6/(mf*mf*mf*mf); nom=dki-dkf; if(nom>0){ pulls_p[i]=(ki-kf)/TMath::Sqrt(nom); }else{ pulls_p[i]=-99.0;// NAN would not be visible in histogramm } nom=cov_ini[i][4]-cov_fitted[i][4]; if(nom>0){ Double_t dt; dt=momentum_ini[i].Theta()-momentum_fitted[i].Theta(); pulls_the[i]=dt/TMath::Sqrt(nom); }else{ pulls_the[i]=-99.0;// NAN would not be visible in histogramm } nom=cov_ini[i][8]-cov_fitted[i][8]; if(nom>0){ Double_t dp; dp=momentum_ini[i].Phi()-momentum_fitted[i].Phi(); if(dp>TMath::Pi()) dp-=2.0*TMath::Pi(); if(dp<=-TMath::Pi()) dp+=2.0*TMath::Pi(); pulls_phi[i]=dp/TMath::Sqrt(nom); }else{ pulls_phi[i]=-99.0;// NAN would not be visible in histogramm } } mylist->setUserValue(KINEFIT_CHANNEL_LO, (((Int_t)channel_code)%1000000));// lo mylist->setUserValue(KINEFIT_CHANNEL_HI, ((Int_t)(channel_code*1e-6)));// hi if (histofile) { Float_t tmp[30]; Int_t ii; ii=0; tmp[ii++]=chi2; tmp[ii++]=((Int_t)channel_code)%1000000;// lo tmp[ii++]=(Int_t)(channel_code*1e-6);// hi tmp[ii++]=miss_pid; for(Int_t i=0; i<4; i++){ tmp[ii++]=pidofPart[i]; tmp[ii++]=pulls_p[i]; tmp[ii++]=pulls_the[i]; tmp[ii++]=pulls_phi[i]; } qa->Fill(tmp); } } //END Iterator if (exitIdx > -1) return kTRUE; return kFALSE; } Bool_t HHypXKine::init() { // in GeV! fitter->setBeamTargetParametra(14, -0.005011, 0.006559, 2.994717, 14); use_err_fixed=false; // use_err_fixed = (GetOpt("ERR_FIXED") != NULL); // if(use_err_fixed) Info("init","using fixed kine ERRORS"); // need to get name from channel TString output(channel->Get(exitList)); if (histofile){ qa = new TNtuple(output + TString("_kine_debug"), "Kine Debug ntuple", "chi24:channel_code_lo:channel_code_hi:miss_pid" ":pid1:pull_p1:pull_the1:pull_phi1" ":pid2:pull_p2:pull_the2:pull_phi2" ":pid3:pull_p3:pull_the3:pull_phi3" ":pid4:pull_p4:pull_the4:pull_phi4" ); } kinetest = new TNtuple(output + TString("_kine_errors"), "Kine DebugErrors ntuple","p:dp:m:sec"); return kTRUE; } Bool_t HHypXKine::reinit() { //Here, we set/reset the Momentum Error //Resolution could be run-dependent! return kTRUE; } Bool_t HHypXKine::finalize() { if (histofile) qa->Write(); if (kinetest) kinetest->Write(); return kTRUE; }
65b3f126318faa1a4038deebca04e407bb72c34e
44ff9f9239894c93b1d430f9b50dcba48213538a
/Rec.ino
1ec20086965617f071ccf399bb2be4cc84d59f09
[]
no_license
baller4/ECE_387_Midterm_IB
433e97e5216ba4b0fecfe7e27cb175cc4d619568
d34c0f85f63856bc438e5c6a2b5e44e855aff998
refs/heads/master
2021-01-22T18:43:14.665067
2017-03-16T02:19:57
2017-03-16T02:19:57
85,108,504
0
0
null
null
null
null
UTF-8
C++
false
false
2,949
ino
Rec.ino
#include <VirtualWire.h> //for RF communication #include <SPI.h> //for Digital Potentiometer //Iniitializes message which will store data recieved from trasmitter byte message[VW_MAX_MESSAGE_LEN]; //messageLength is to assist in recieving data byte messageLength = VW_MAX_MESSAGE_LEN; const int ledPin = 4; //an LED is used to confirm that a signal has been recieved const int recPin = 7; //data line from RF reciever const int potPin = 10; //CS port on the digital Potentiometer const int speakerPin = 8; //Integer volume represents the steps (out of 256) of the digital potentiometer int volume = 10; void setup() { Serial.begin(9600); //RF Reciever setup, from virtualwire library vw_set_ptt_inverted(true); vw_setup(2000); vw_set_rx_pin(recPin); vw_rx_start(); pinMode(ledPin, OUTPUT); pinMode(potPin, OUTPUT); SPI.begin(); //begin transmitting data to the digital potentiometer } void loop() { tone(speakerPin, 1000); //begin outputing a tone from the speaker if (vw_get_message(message, &messageLength)) //the function "vw_get_message()" verifies a message has been recieved // and stores the message in a variable (from virtualwire library) { for (int i = 0; i < messageLength; i++)//printing data recieved from RF transission { Serial.print(message[i]); //print the message Serial.print(" "); if(message[i] == 2) { volume = volume + 10; volume = correctVolume(volume); //see correctVolume below digitalPotWrite(1, volume); //see digitalPotWrite below blink(); } if(message[i] == 3) { volume = volume - 10; volume = correctVolume(volume); digitalPotWrite(1, volume); blink(); blink(); } } Serial.println("Found"); //"Found" prints if a message was recieved } Serial.println("Loop\n"); //"Loop" prints after a cycle of void loop() is completed delay(500); } //blink(): a blink method void blink() { digitalWrite(ledPin, HIGH); delay(500); digitalWrite(ledPin, LOW); delay(500); } /* digitalPotWrite: sets the CS pin of the digital potentiometer high to send in data * the first value sent is a two bit address that specifies which channel of the DP to talk with, * and the following value is the "position" of the wiper that variates the resistence between * ports A and B of the specified channel * Borrowed from: https://www.arduino.cc/en/Tutorial/DigitalPotControl */ void digitalPotWrite(int address, int value) { digitalWrite(potPin, LOW); SPI.transfer(address); SPI.transfer(value); digitalWrite(potPin, HIGH); } /*the correctVolume method makes sure the volume is not adjusted beyond the bounds * of the digital potentiometer (0 - 256) */ int correctVolume(int vol) { int volume = vol; while(volume >= 255) { volume--; } while(volume <= 1) { volume++; } return volume; }
4fbe1ee157a6ac7d2477f901232adf597c7bf9dd
dc267510c2beff37b8cb64657ef43f5984de2c73
/bohyoh/chap12/floating.cpp
e92baa16941f87df2b93b6d68e9c6ad0da4e957a
[]
no_license
sunglen/cpp
375949dce14cc4f8ba457a72b5a8eedd2288d936
79d22872642fe4b3576fb8e789e94571d714154f
refs/heads/master
2021-08-29T16:38:20.036076
2017-12-14T10:07:52
2017-12-14T10:07:52
114,233,646
0
0
null
null
null
null
UTF-8
C++
false
false
698
cpp
floating.cpp
サソ// 豬ョ蜍募ー乗焚轤ケ謨ー縺ョ譖ク蠑 #include <iostream> using namespace std; int main() { int precision; // 邊セ蠎ヲ double x; // 陦ィ遉コ縺吶k蛟、 cout << "螳滓焚蛟、シ"; cin >> x; cout << "邊セ蠎ヲシ"; cin >> precision; cout.precision(precision); // 邊セ蠎ヲ縺ッ譛蠕後∪縺ァ譛牙柑 cout.setf(ios_base::scientific, ios_base::floatfield); cout << "遘大ュヲ蠖「蠑擾シ" << x << '\n'; cout.setf(ios_base::fixed, ios_base::floatfield); cout << "蝗コ螳壼ス「蠑擾シ" << x << '\n'; cout.setf(0, ios_base::floatfield); cout << "騾壼クク陦ィ遉コシ" << x << '\n'; }
cef6c635c0cbada878da44043f9c74258f155ef1
6e809cd807ae46cb0037fc73d35861c4c804a559
/src/bounce/renderer/render.cpp
32e1a3f4542b92dafcf813e88bd9f022158157db
[ "MIT" ]
permissive
cbosoft/bounce
78b46c3c121f8400149fe232b4b4200803e1a78c
f63e5ad1aabe201debf7a9a73525e93973c34932
refs/heads/master
2023-05-06T07:27:29.301254
2021-05-23T21:31:32
2021-05-23T21:31:32
352,585,085
0
0
null
null
null
null
UTF-8
C++
false
false
3,637
cpp
render.cpp
#include <bounce/renderer/renderer.hpp> #include <bounce/physics/engine/engine.hpp> #include <bounce/game/game.hpp> #include <bounce/scene/scene.hpp> /** @return Current GLFW window. Used when dealing with input. */ GLFWwindow *Renderer::get_window() { return this->window; } /** * Check if the a render pass is required at all based on the time since the previous render. This calculates and * enforces frame rate. * * @return Whether the render should go ahead. */ bool Renderer::should_render() { this->error_check("once-per-frame error check"); auto now = _RDR_CLOCK_T::now(); auto time_since = std::chrono::duration_cast<std::chrono::milliseconds>(now - this->time_last_render); int us = int(time_since.count()); if (us < this->_min_mspf) { return false; } this->_actual_fps = (this->_actual_fps + (1000/us))/2; this->time_last_render = now; return true; } /** * Main call which renders the scene. * * First checks if the render is needed by checking Renderer::should_render. Then, the current active scene is updated * (by calling the Scene::update method). After, the scenes which need to be rendered are gathered and passed to * Renderer::render_scene. * * Scenes which need rendering may not just be the active scene. Scenes can be "insubstantial" which essentially means * it has no background and is intended to be rendered on the backdrop of a previous scene. This is useful for drawing a * menu atop some gameplay (for example, in a pause menu or conversation). * * Once the scenes are rendered, any screen effects are applied. Then, finally, the freame is rendered to screen. * * \sa Scene::is_insubstantial * \sa Renderer::render_scene */ void Renderer::render() { if (!this->should_render()) { return; } // Call update action on transforms in active scene. this->game->get_active_scene()->update(); this->set_target_to_texture(this->txt); glClear(GL_COLOR_BUFFER_BIT); glBindVertexArray(this->varr); glBindBuffer(GL_ARRAY_BUFFER, this->vbuf); int w, h; glfwGetWindowSize(this->window, &w, &h); this->set_window_size(w, h); for (const Scene *scene :this->game->get_scenes_to_be_rendered()) { this->render_scene(scene); } // draw quad to screen this->set_target_to_screen(); glClear(GL_COLOR_BUFFER_BIT); GLuint shader_id = this->get_screen_effect(); glUseProgram(shader_id); glBindTexture(GL_TEXTURE_2D, this->txt); glBindVertexArray(this->qarr); glBindBuffer(GL_ARRAY_BUFFER, this->qbuf); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void *)(0)); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4*sizeof(float), (void *)(2*sizeof(float))); glEnableVertexAttribArray(1); glDrawArrays(GL_TRIANGLES, 0, 6); glfwSwapBuffers(this->window); glfwPollEvents(); } /** * Render scene. This gets a list of Renderable(s) in the scene and draws them. The Renderable(s) are drawn in order of * their z value. The Renderable actually handles its own drawing - Renderable::draw. * * \sa Renderable::get_z * \sa Renderable::set_z * * @param scene */ void Renderer::render_scene(const Scene *scene) { if (scene) { this->update_common_shader_variables(scene->get_active_camera()); // draw zsorted renderables std::list<const Renderable *> rbls; scene->get_renderables(rbls); rbls.sort(Renderable::z_sort); for (auto *rbl : rbls) { if (rbl && rbl->get_visible()) rbl->draw(); } } }
82514b77c30cf2b62ce3168b43c03f1f9d8322c2
f7f09782d15ee7bdd14e637bd717dfb8327bc57c
/2016Train/Peo4/F.cpp
e7e8199ac2387aa5af4638f9c00a33e6aa26d1db
[]
no_license
whywhyzhang/ACM-ICPC-Code
14f3f6b0532c18da9694d7f70914a97e0983913f
d15bd475774ff104ebfe9504f8ea0acffdb5ddb0
refs/heads/master
2022-12-09T06:27:14.893967
2017-03-09T14:31:49
2017-03-09T14:31:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,518
cpp
F.cpp
// ━━━━━━神兽出没━━━━━━ // ┏┓ ┏┓ // ┏┛┻━━━━━━━┛┻┓ // ┃ ┃ // ┃ ━ ┃ // ████━████ ┃ // ┃ ┃ // ┃ ┻ ┃ // ┃ ┃ // ┗━┓ ┏━┛ // ┃ ┃ // ┃ ┃ // ┃ ┗━━━┓ // ┃ ┣┓ // ┃ ┏┛ // ┗┓┓┏━━━━━┳┓┏┛ // ┃┫┫ ┃┫┫ // ┗┻┛ ┗┻┛ // // ━━━━━━感觉萌萌哒━━━━━━ // Author : WhyWhy // Created Time : 2016年03月12日 星期六 17时12分01秒 // File Name : F.cpp #include <stdio.h> #include <string.h> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <math.h> #include <stdlib.h> #include <time.h> using namespace std; const int MaxN=60005; int N; int num1[MaxN],num2[MaxN],num3[MaxN]; int bcou,blen,blenl; long long rem[MaxN][4]; inline void merge(int a[],int b[],int to,int x,int y) { int ans[4]; ans[0]=min(a[0]+b[0]+x+y,a[0]+b[2] } inline void change(int L,int R,int p) { } inline void change(int p) { change((p-1)*blen+1,p*blen,p); } void init() { blen=sqrt(N+0.0)+1; bcou=(N-1)/blen+1; blenl=N-(bcou-1)*blen; for(int i=1;i<=bcou;++i) change(i); } void update(int type,int p,int v) { if(type==1) num1[p]=v; if(type==2) num2[p]=v; if(type==3) num3[p]=v; change((p-1)/blen+1); } long long getans(int L,int R) { int b1=(L-1)/blen+1; int b2=(R-1)/blen+1; if(b1==b2) change(L,R,0); else { change(L,b1*blen,0); change((b2-1)*blen+1,R,N+1); merge(rem[0],rem[b1+1],0,num1[b1*len],num2[b1*len]); for(int i=b1+2;i<b2;++i) merge(rem[i],rem[0],0,num1[(i-1)*len],num2[(i-1)*len]); merge(rem[N+1],rem[0],0,num1[(b2-1)*len],num2[(b2-1)*len]); } return rem[0][3]; } int main() { //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); int M,a,b,c,d,e; char s[10]; while(~scanf("%d %d",&N,&M)) { for(int i=1;i<N;++i) scanf("%d",num1+i); for(int i=1;i<N;++i) scanf("%d",num2+i); for(int i=1;i<=N;++i) scanf("%d",num3+i); init(); while(M--) { scanf("%s",s); if(s[0]=='C') { scanf("%d %d %d %d %d",&a,&b,&c,&d,&e); if(a==c) update(a,b,e); else update(3,b,e); } else { scanf("%d %d",&a,&b); printf("%lld\n",getans(a,b)); } } } return 0; }
1272e809145f3d2255a3860c4f2749f805777d4c
69253c4d41655d673adbb19e80ffee5b12448689
/test/PropertyTest.cpp
3c1b0d231eb94a984995a7afb7c241d54f75b40d
[ "BSD-3-Clause" ]
permissive
cybergarage/uecho
d61a64a36f535ea966cdce5743975ffe1688e6b6
9475aadb1d440d3e61a60d6f22e8210a1aa54262
refs/heads/master
2023-09-01T06:48:12.927416
2023-05-07T05:38:46
2023-05-07T05:38:46
38,615,424
9
9
BSD-3-Clause
2022-02-22T09:23:41
2015-07-06T11:45:03
C
UTF-8
C++
false
false
9,482
cpp
PropertyTest.cpp
/****************************************************************** * * uEcho for C * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <boost/test/unit_test.hpp> #include <string> #include <vector> #include <uecho/_property.h> BOOST_AUTO_TEST_CASE(PropertyBasicFunctions) { uEchoProperty* prop = uecho_property_new(); BOOST_CHECK(prop); for (int n = uEchoPropertyCodeMin; n < uEchoPropertyCodeMax; n++) { uecho_property_setcode(prop, n); BOOST_CHECK_EQUAL(uecho_property_getcode(prop), n); } BOOST_CHECK(uecho_property_delete(prop)); } BOOST_AUTO_TEST_CASE(PropertySetData) { uEchoProperty* prop = uecho_property_new(); BOOST_CHECK_EQUAL(uecho_property_getdatasize(prop), 0); BOOST_CHECK_EQUAL(uecho_property_getdata(prop), (byte*)NULL); uecho_property_cleardata(prop); BOOST_CHECK_EQUAL(uecho_property_getdatasize(prop), 0); BOOST_CHECK_EQUAL(uecho_property_getdata(prop), (byte*)NULL); uecho_property_setdata(prop, NULL, 0); BOOST_CHECK_EQUAL(uecho_property_getdatasize(prop), 0); BOOST_CHECK_EQUAL(uecho_property_getdata(prop), (byte*)NULL); std::vector<std::string> test_data_vec; test_data_vec.push_back("a"); test_data_vec.push_back("abcd"); test_data_vec.push_back("abcd0123456789"); for (int i = 0; i < test_data_vec.size(); i++) { const char* test_data = test_data_vec[i].c_str(); size_t test_data_len = strlen(test_data); uecho_property_setdata(prop, (const byte*)test_data, test_data_len); BOOST_CHECK_EQUAL(uecho_property_getdatasize(prop), test_data_len); BOOST_CHECK(uecho_property_isdataequal(prop, (const byte*)test_data, test_data_len)); byte* prop_data = uecho_property_getdata(prop); BOOST_CHECK(prop_data); for (int n = 0; n < test_data_len; n++) { BOOST_CHECK_EQUAL(test_data[n], prop_data[n]); } } uecho_property_cleardata(prop); BOOST_CHECK_EQUAL(uecho_property_getdatasize(prop), 0); BOOST_CHECK_EQUAL(uecho_property_getdata(prop), (byte*)NULL); BOOST_CHECK(uecho_property_delete(prop)); } BOOST_AUTO_TEST_CASE(PropertyPermission) { uEchoProperty* prop = uecho_property_new(); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), true); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), true); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrNone); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrRead); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), true); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), true); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrReadRequired); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), true); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), true); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), true); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrWrite); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), true); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), true); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrWriteRequired); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), true); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), true); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), true); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrReadWrite); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), true); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), true); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrAnno); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), true); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrAnnoRequired); BOOST_CHECK_EQUAL(uecho_property_isreadable(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadrequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswritable(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriterequired(prop), false); BOOST_CHECK_EQUAL(uecho_property_isreadonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_iswriteonly(prop), false); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), true); BOOST_CHECK_EQUAL(uecho_property_isannouncerequired(prop), true); BOOST_CHECK(uecho_property_delete(prop)); } BOOST_AUTO_TEST_CASE(PropertyAnnouncement) { uEchoProperty* prop = uecho_property_new(); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); uecho_property_setattribute(prop, uEchoPropertyAttrAnno); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), true); uecho_property_setattribute(prop, uEchoPropertyAttrNone); BOOST_CHECK_EQUAL(uecho_property_isannounceable(prop), false); BOOST_CHECK(uecho_property_delete(prop)); } BOOST_AUTO_TEST_CASE(PropertyByte2Integer) { uEchoProperty* prop = uecho_property_new(); int val; for (int n = 0; n <= 0xFF; n++) { BOOST_CHECK(uecho_property_setintegerdata(prop, n, 1)); BOOST_CHECK(uecho_property_getintegerdata(prop, &val)); BOOST_CHECK_EQUAL(n, val); } for (int n = 0; n <= 0xFFFF; n += (0xFFFF / 0xFF)) { BOOST_CHECK(uecho_property_setintegerdata(prop, n, 2)); BOOST_CHECK(uecho_property_getintegerdata(prop, &val)); BOOST_CHECK_EQUAL(n, val); } for (int n = 0; n <= 0xFFFFFF; n += (0xFFFFFF / 0xFF)) { BOOST_CHECK(uecho_property_setintegerdata(prop, n, 3)); BOOST_CHECK(uecho_property_getintegerdata(prop, &val)); BOOST_CHECK_EQUAL(n, val); } for (int n = 0; n < 0xFFFFFFFF; n += (0xFFFFFFFF / 0xFF)) { BOOST_CHECK(uecho_property_setintegerdata(prop, n, 4)); BOOST_CHECK(uecho_property_getintegerdata(prop, &val)); BOOST_CHECK_EQUAL(n, val); } BOOST_CHECK(uecho_property_delete(prop)); } BOOST_AUTO_TEST_CASE(PropertyAddData) { uEchoProperty* prop = uecho_property_new(); BOOST_CHECK_EQUAL(uecho_property_getdatasize(prop), 0); const size_t property_add_data_count = 10; for (size_t n = 0; n < property_add_data_count; n++) { byte new_byte = n; BOOST_CHECK(uecho_property_addbytedata(prop, new_byte)); BOOST_CHECK_EQUAL(uecho_property_getdatasize(prop), (n + 1)); byte* bytes = uecho_property_getdata(prop); BOOST_CHECK(bytes); BOOST_CHECK_EQUAL(bytes[n], new_byte); } BOOST_CHECK_EQUAL(uecho_property_getdatasize(prop), property_add_data_count); BOOST_CHECK(uecho_property_delete(prop)); }
2218b9257f99b9f4421870957a3a374aa9c517b7
d20cf7de868dfb2c53578a70d0dda21306167d72
/data/raw/train/student_62/2324/2322/ShotPea.h
32f93cbd405b07f8c4b7fe557dd81b0ff8ad6352
[]
no_license
bulacu-magda/Alemia
905a84ca79157fb657eb424e337b0303fd3323bd
0fd019c4517064d300399feb94dbcb0f467e8d48
refs/heads/main
2023-03-01T17:41:08.788500
2021-02-05T08:00:35
2021-02-05T08:00:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
355
h
ShotPea.h
#pragma once #include "Shot.h" class ShotPea : public Shot { protected: ShotPea(wchar_t cSign, COORD Center) :Shot(cSign, Center) {} public: ShotPea(COORD Center) :Shot(PEASHOT, Center) {} ~ShotPea(){} //Efect virtual void Move(Panel&) override; //Behavior virtual bool Draw(Panel& panel) override; virtual bool Erase(Panel& panel) override; };
849969a68c6d63311b52e083f2fd21a8b4303b76
cf89a89d2bd5970e3504784d458734bd90e5627c
/04/ex01/RadScorpion.cpp
53ead93704ffb6fbada1a22f2a55144320ef2033
[]
no_license
CUAGAIN-95/CPP_Module
9e69da847989fc9ef0ab563003fde26f50fe5e2f
b06cbbac23a4ad51f140050610803786f363e124
refs/heads/master
2023-06-03T17:36:09.152336
2021-06-18T14:43:23
2021-06-18T14:43:23
370,113,215
0
0
null
null
null
null
UTF-8
C++
false
false
2,122
cpp
RadScorpion.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* RadScorpion.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yeonhlee <yeonhlee@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/14 22:14:26 by yeonhlee #+# #+# */ /* Updated: 2021/06/15 12:22:46 by yeonhlee ### ########.fr */ /* */ /* ************************************************************************** */ #include "RadScorpion.hpp" /* ** ------------------------------- CONSTRUCTOR -------------------------------- */ RadScorpion::RadScorpion() : Enemy(80, "Rad Scorpion") { std::cout << "* click click click *" << std::endl; } RadScorpion::RadScorpion( const RadScorpion & src ) : Enemy(src) { } /* ** -------------------------------- DESTRUCTOR -------------------------------- */ RadScorpion::~RadScorpion() { std::cout << "* SPROTCH *" << std::endl; } /* ** --------------------------------- OVERLOAD --------------------------------- */ RadScorpion & RadScorpion::operator=( RadScorpion const & rhs ) { if ( this != &rhs ) this->Enemy::operator=(rhs); return *this; } // std::ostream & operator<<( std::ostream & o, RadScorpion const & i ) // { // //o << "Value = " << i.getValue(); // return o; // } /* ** --------------------------------- METHODS ---------------------------------- */ // MEMBER FUNCTION void RadScorpion::takeDamage(int _damage) { if (_damage < 0) return ; this->hp -= _damage; if (hp < 0) this->hp = 0; } /* ** --------------------------------- ACCESSOR --------------------------------- */ /* ************************************************************************** */
a2ab56f839fcc6536e9e7ae652664908855a951c
91a882547e393d4c4946a6c2c99186b5f72122dd
/Source/XPSP1/NT/admin/wmi/wbem/sdk/activex/controls/msgdlg/wbemerror.cpp
8ac014fd02f727fa6c34322ce2063f146e45b793
[]
no_license
IAmAnubhavSaini/cryptoAlgorithm-nt5src
94f9b46f101b983954ac6e453d0cf8d02aa76fc7
d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2
refs/heads/master
2023-09-02T10:14:14.795579
2021-11-20T13:47:06
2021-11-20T13:47:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,433
cpp
wbemerror.cpp
//============================================================================= // // WbemError.cpp // // Copyright (c) 1997-2001 Microsoft Corporation, All Rights Reserved // // Helper routine for core's error features. // // History: // // a-khint 5-mar-98 Created. // a-khint 14-sep-98 hooked into core's error routines. // //============================================================================= #include "precomp.h" #include "WbemError.h" #include "resource.h" #include <wbemcli.h> //------------------------------------------------- #define TEMP_BUF 512 void ErrorStringEx(HRESULT hr, WCHAR *errMsg, UINT errSize, UINT *sevIcon) { WCHAR szError[TEMP_BUF]; WCHAR szFacility[TEMP_BUF]; WCHAR szFormat[100]; IWbemStatusCodeText * pStatus = NULL; // initialize buffers. errMsg[0] = 0; szFacility[0] = 0; szError[0] = 0; HRESULT hr1 = CoInitialize(NULL); SCODE sc = CoCreateInstance(CLSID_WbemStatusCodeText, 0, CLSCTX_INPROC_SERVER, IID_IWbemStatusCodeText, (LPVOID *) &pStatus); // loaded OK? if(sc == S_OK) { BSTR bstr = 0; sc = pStatus->GetErrorCodeText(hr, 0, 0, &bstr); if(sc == S_OK) { _tcsncpy(szError, bstr, TEMP_BUF-1); SysFreeString(bstr); bstr = 0; } sc = pStatus->GetFacilityCodeText(hr, 0, 0, &bstr); if(sc == S_OK) { _tcsncpy(szFacility, bstr, TEMP_BUF-1); SysFreeString(bstr); bstr = 0; } // RELEASE pStatus->Release(); pStatus = NULL; } else { ::MessageBox(NULL, _T("WMI error features not available. Upgrade WMI to a newer build."), _T("Internal Error"), MB_ICONSTOP|MB_OK); } // if not msgs returned.... if(wcslen(szFacility) == 0 || wcslen(szError) == 0) { // format the error nbr as a reasonable default. LoadString(GetModuleHandle(_T("WBEMUtils.dll")), IDS_ERROR_UNKN_ERROR_FMT, szFormat, 99); _stprintf(errMsg, szFormat, hr); } else { // format a readable msg. LoadString(GetModuleHandle(_T("WBEMUtils.dll")), IDS_ERROR_FMT, szFormat, 99); _stprintf(errMsg, szFormat, szFacility, szError); } // want an icon recommendation with that? if(sevIcon) { switch(SCODE_SEVERITY(hr)) { case 0: // - Success *sevIcon = MB_ICONINFORMATION; break; case 1: //- Failed *sevIcon = MB_ICONEXCLAMATION; break; } //endswitch severity } //endif sevIcon if(hr1 == S_OK) CoUninitialize(); }
420ca8efd039b0be0021c31f00ea640386d6018d
3e85351787b37cf51d0bfe2bc8ac5aabe5755e0a
/src/eGPIO/eGPIO.cpp
0569f718bf3f32e84c8f6bba008862c7744ab8a9
[]
no_license
mroctavious/CentzonThinClient
46c239d55c0cb9a9980975b6fb12d530c02fa510
8337c7ffd1753ba7285f1de052e2b048076c4245
refs/heads/master
2022-04-16T22:49:32.288460
2020-04-15T21:36:15
2020-04-15T21:36:15
256,041,639
2
0
null
null
null
null
UTF-8
C++
false
false
879
cpp
eGPIO.cpp
#include "eGPIO.h" #include <string> #include <iostream> eGPIO::eGPIO( string pin, string direction ):GPIOClass( pin ){ //Create the file for the specified gpio pin this->export_gpio(); if( direction.compare("r") == 0 ) { //std::cout << "Reading" << std::endl; this->setdir_gpio("in"); } else if ( direction.compare("w") == 0 ) { //std::cout << "Writing" << std::endl; this->setdir_gpio("out"); this->setval_gpio("0"); } else{ std::cout << "Error in parameter 2. Only ''w'' or ''r'' available.\nReading only...\n"; } }; eGPIO::~eGPIO(){ this->reset(); } void eGPIO::on(){ this->setval_gpio("1"); return; } void eGPIO::off(){ this->setval_gpio("0"); return; } void eGPIO::reset(){ this->setval_gpio("0"); this->unexport_gpio(); return; } bool eGPIO::read(){ this->getval_gpio(this->inputstate); return this->inputstate == "1" ? true:false; }
e9941caea0eb94c95151186fdd279f23324d3a07
ad6304b713fab3ca8ff018aad2df0d057e194300
/URI/PARADIGMAS/1029 - Fibonacci, Quantas Chamadas.cpp
9654ed8d32f5c974d60c497a06c4138cca3f85fb
[]
no_license
nicowxd/Competitive-Programming
d3f63b6eac4ccd508d194c8e6244f3d18bdca518
de92532f753f6eeebe5dff18da8b10f3186bf107
refs/heads/master
2022-01-11T20:07:34.149034
2019-06-06T23:40:15
2019-06-06T23:40:15
115,149,544
1
0
null
null
null
null
UTF-8
C++
false
false
615
cpp
1029 - Fibonacci, Quantas Chamadas.cpp
// Autor: CarlosJunior<carloserratojr@gmail.com> // Nome: Fibonacci, Quantas Chamadas? // Nível: 2 // Categoria: PARADIGMAS // URL: https://www.urionlinejudge.com.br/judge/pt/problems/view/1029 #include <bits/stdc++.h> using namespace std; int memo[50], cnt; int fib(int x) { cnt++; if (x == 0) return 0; if (x == 1) return 1; memo[x] = (fib(x-1) + fib(x-2)); return memo[x]; } int main() { int n, x; scanf("%d", &n); while(n--) { scanf("%d", &x); cnt = 0; int ans = fib(x); printf("fib(%d) = %d calls = %d\n", x, cnt-1, memo[x]); } return 0; }
689028e7ab0f8e0d275f7d1c2ca30f54f0f0ed9d
f3da51bde59afd55b24462156c2338b2a687a64e
/src/Inventory.h
0841c42bdf9e7d3f0749c37b3dd0578508e52b1d
[ "MIT" ]
permissive
ScaredStorm/SpaceGame
c8dcfe134207a4a1156dbf36dabf4fbdf62a5d13
136df0e173b07ebc3f6a0b7c2370edeb7c120af8
refs/heads/master
2021-01-19T10:02:49.877528
2017-04-10T14:23:24
2017-04-10T14:23:24
87,812,989
0
0
null
null
null
null
UTF-8
C++
false
false
496
h
Inventory.h
#pragma once #ifdef _WIN32 #include <SDL.h> #include <SDL_image.h> #else #include <SDL2/SDL.h> #include <SDL2_image/SDL_image.h> #endif #include <stdio.h> #include <vector> #include "TextureManager.h" #include "DisplayContainer.h" #include "Camera.h" class Inventory { public: Inventory(); ~Inventory(); void setItem(int id); void update(); void render(SDL_Renderer *renderer, TextureManager &manager, Camera &cam); private: std::vector<DisplayContainer*> _items; };
8db5ce77492293323fb385244c64ffd53fec89d4
18e49bc109a47cd2e6ec430ed222ee95ead3c081
/Chapter006/006-008/006-008.cpp
61c51cff31884f31ea675504076f7a5f457aa600
[]
no_license
mobuhiko/C-PrimerPlus
144b9ec638cc22c26732dcbc396ae24bda4194fa
1d5d145a04b57f8b51bd5b4d33d43aa5b66def73
refs/heads/master
2022-11-29T15:30:34.856765
2020-08-07T08:03:56
2020-08-07T08:03:56
265,569,579
0
0
null
null
null
null
UTF-8
C++
false
false
841
cpp
006-008.cpp
#include <iostream> #include <cctype> #include <string> #include <fstream> #include <cstdlib> using namespace std; int main() { ifstream inFile; inFile.open("Sample006-008.txt"); // check whether reading the file successfully if(!inFile.is_open()) { cout << "Fail to open\n"; exit(EXIT_FAILURE); } int counter = 0; char ch; // begin to read the content in the file // <hello, world! > = 10 alphabets + 2 punctuations (+ 2 space) inFile >> ch; while(inFile.good()) { counter++; inFile >> ch; } // message if reading the EOF if(inFile.eof()) { cout << "EOF reached\n"; } // close the file inFile.close(); // <There are 12 characters> cout << "There are " << counter << " characters\n"; return 0; }
d9e74e5bf3791bccd3f9989c676c53527c351cc8
67abbc3f0dd24c7f4e5efb90e161ebc27a0b4dde
/Arduino/BLE_MPU6050_MPU9150.ino
07b844c871464c6472a6703d6c24d461dd4cd4b8
[]
no_license
Kapil19-dev/Energy-Expenditure-1
482616eb10ad8740ceac409b198c637344e74b81
bd38b2de4850aa8fb70e874150728d982f2d96fa
refs/heads/master
2022-11-10T23:50:45.629494
2020-06-25T16:49:24
2020-06-25T16:49:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,918
ino
BLE_MPU6050_MPU9150.ino
#include <BLEDevice.h> #include <BLEServer.h> #include <BLEUtils.h> #include <BLE2902.h> #include <Wire.h> #include <iostream> #include <string> // Register names according to the datasheet #define MPU9150_ACCEL_XOUT_H 0x3B // R #define MPU9150_ACCEL_XOUT_L 0x3C // R #define MPU9150_ACCEL_YOUT_H 0x3D // R #define MPU9150_ACCEL_YOUT_L 0x3E // R #define MPU9150_ACCEL_ZOUT_H 0x3F // R #define MPU9150_ACCEL_ZOUT_L 0x40 // R #define MPU9150_PWR_MGMT_1 0x6B // R/W //MPU9150 Compass #define MPU9150_CMPS_XOUT_L 0x4A // R #define MPU9150_CMPS_XOUT_H 0x4B // R #define MPU9150_CMPS_YOUT_L 0x4C // R #define MPU9150_CMPS_YOUT_H 0x4D // R #define MPU9150_CMPS_ZOUT_L 0x4E // R #define MPU9150_CMPS_ZOUT_H 0x4F // R // BLE uuids #define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID #define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" #define DHTDATA_CHAR_UUID "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" // MPU addresses const int MPU = 0x68; // MPU-6050 I2C address int MPU9150_I2C_ADDRESS = 0x69; // MPU-9150 I2C address // Variables to store MPU-9150 acc data int mpu9150_accX; int mpu9150_accY; int mpu9150_accZ; // Variables to store MPU-6050 acc data float mpu6050_accX; float mpu6050_accY; float mpu6050_accZ; bool deviceConnected = false; char mpuDataString[30]; // String to send over BLE BLECharacteristic *pCharacteristic; class MyServerCallbacks: public BLEServerCallbacks { void onConnect(BLEServer* pServer) { deviceConnected = true; }; void onDisconnect(BLEServer* pServer) { deviceConnected = false; } }; class MyCallbacks: public BLECharacteristicCallbacks { void onWrite(BLECharacteristic *pCharacteristic) { std::string rxValue = pCharacteristic->getValue(); Serial.println(rxValue[0]); if (rxValue.length() > 0) { Serial.println("*********"); Serial.print("Received Value: "); for (int i = 0; i < rxValue.length(); i++) { Serial.print(rxValue[i]); } Serial.println(); Serial.println("*********"); } } }; void setup() { // Initialize the Serial Bus for printing data. Serial.begin(115200); // Initialize the 'Wire' class for the I2C-bus. Wire.begin(); Wire.beginTransmission(MPU); // Start communication with MPU6050 // MPU=0x68 Wire.write(0x6B); // Talk to the register 6B Wire.write(0x00); // Make reset - place a 0 into the 6B register Wire.endTransmission(true); //end the transmission delay(20); // Clear the 'sleep' bit to start the sensor. MPU9150_writeSensor(MPU9150_PWR_MGMT_1, 0); MPU9150_setupCompass(); // Create the BLE Device BLEDevice::init("ESP32 Acc"); // Give it a name // Configures the device as a BLE server BLEServer *pServer = BLEDevice::createServer(); pServer->setCallbacks(new MyServerCallbacks()); // Creates the UART service BLEService *pService = pServer->createService(SERVICE_UUID); // Creates a characteristic BLE to send data pCharacteristic = pService->createCharacteristic( DHTDATA_CHAR_UUID, BLECharacteristic::PROPERTY_NOTIFY ); pCharacteristic->addDescriptor(new BLE2902()); // Creates a characteristic BLE to receive data BLECharacteristic *pCharacteristic = pService->createCharacteristic( CHARACTERISTIC_UUID_RX, BLECharacteristic::PROPERTY_WRITE ); pCharacteristic->setCallbacks(new MyCallbacks()); // Starts the service pService->start(); // Starts the discovery of the device pServer->getAdvertising()->start(); Serial.println("Waiting for a client to connect..."); } void loop() { if (deviceConnected) { // Store MPU-9150 acc values mpu9150_accX = MPU9150_readSensor(MPU9150_ACCEL_XOUT_L,MPU9150_ACCEL_XOUT_H); mpu9150_accY = MPU9150_readSensor(MPU9150_ACCEL_YOUT_L,MPU9150_ACCEL_YOUT_H); mpu9150_accZ = MPU9150_readSensor(MPU9150_ACCEL_ZOUT_L,MPU9150_ACCEL_ZOUT_H); // Read MPU-6050 acc data Wire.beginTransmission(MPU); Wire.write(0x3B); // Start with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); Wire.requestFrom(MPU, 6, true); // Read 6 registers total, each axis value is stored in 2 registers //For a range of +-2g, 4g, 8g or 16g, we need to divide the raw values by 16384, 8192, 4096 or 2048 according to the datasheet mpu6050_accX = (Wire.read() << 8 | Wire.read()) / 4096.0; // X-axis value mpu6050_accY = (Wire.read() << 8 | Wire.read()) / 4096.0; // Y-axis value mpu6050_accZ = (Wire.read() << 8 | Wire.read()) / 4096.0; // Z-axis value // Print MPU-9150 values Serial.print(mpu9150_accX); Serial.print(" "); Serial.print(mpu9150_accY); Serial.print(" "); Serial.print(mpu9150_accZ); Serial.println(); // Print MPU-6050 values Serial.print(mpu6050_accX); Serial.print(","); Serial.print(mpu6050_accY); Serial.print(","); Serial.println(mpu6050_accZ); Serial.println(); sprintf(mpuDataString,"%d,%d,%d,%.2f,%.2f,%.2f",mpu9150_accX,mpu9150_accY,mpu9150_accZ,mpu6050_accX,mpu6050_accY,mpu6050_accZ); pCharacteristic->setValue(mpuDataString); pCharacteristic->notify(); // Sends the value to the connected device Serial.print("*** Sent: "); Serial.print(mpuDataString); Serial.println(" ***"); } delay(1000); } void MPU9150_setupCompass(){ MPU9150_I2C_ADDRESS = 0x0C; //change Address to Compass MPU9150_writeSensor(0x0A, 0x00); //PowerDownMode MPU9150_writeSensor(0x0A, 0x0F); //SelfTest MPU9150_writeSensor(0x0A, 0x00); //PowerDownMode MPU9150_I2C_ADDRESS = 0x69; //change Address to MPU MPU9150_writeSensor(0x24, 0x40); //Wait for Data at Slave0 MPU9150_writeSensor(0x25, 0x8C); //Set i2c address at slave0 at 0x0C MPU9150_writeSensor(0x26, 0x02); //Set where reading at slave 0 starts MPU9150_writeSensor(0x27, 0x88); //set offset at start reading and enable MPU9150_writeSensor(0x28, 0x0C); //set i2c address at slv1 at 0x0C MPU9150_writeSensor(0x29, 0x0A); //Set where reading at slave 1 starts MPU9150_writeSensor(0x2A, 0x81); //Enable at set length to 1 MPU9150_writeSensor(0x64, 0x01); //overvride register MPU9150_writeSensor(0x67, 0x03); //set delay rate MPU9150_writeSensor(0x01, 0x80); MPU9150_writeSensor(0x34, 0x04); //set i2c slv4 delay MPU9150_writeSensor(0x64, 0x00); //override register MPU9150_writeSensor(0x6A, 0x00); //clear usr setting MPU9150_writeSensor(0x64, 0x01); //override register MPU9150_writeSensor(0x6A, 0x20); //enable master i2c mode MPU9150_writeSensor(0x34, 0x13); //disable slv4 } //////////////////////////////////////////////////////////// ///////// I2C functions to get easier all values /////////// //////////////////////////////////////////////////////////// int MPU9150_readSensor(int addrL, int addrH){ Wire.beginTransmission(MPU9150_I2C_ADDRESS); Wire.write(addrL); Wire.endTransmission(false); Wire.requestFrom(MPU9150_I2C_ADDRESS, 1, true); byte L = Wire.read(); Wire.beginTransmission(MPU9150_I2C_ADDRESS); Wire.write(addrH); Wire.endTransmission(false); Wire.requestFrom(MPU9150_I2C_ADDRESS, 1, true); byte H = Wire.read(); //For a range of +-2g, 4g, 8g or 16g, we need to divide the raw values by 16384, 8192, 4096 or 2048 according to the datasheet return (int16_t)(((H<<8)+L)/4096); } int MPU9150_writeSensor(int addr,int data){ Wire.beginTransmission(MPU9150_I2C_ADDRESS); Wire.write(addr); Wire.write(data); Wire.endTransmission(true); return 1; }
73bf91a0ad6ce5da5ab95aaba783c34ae709804c
311da5b17c18be34422ae55a12c4d6e8ec3a0767
/src/grid/grid_2D_cyln.cpp
f5d8dbf2878679a81d8d98752cfbd60492acc7d9
[]
no_license
Knights-Templars/pubsed
f3d17df709f5e0d4c556a59fd80d38c4370b0979
f124d000b0d8eedae86a6cee4253a1eb4c202665
refs/heads/main
2023-05-09T19:26:17.747010
2020-07-20T22:29:53
2020-07-20T22:29:53
445,101,129
1
0
null
2022-01-06T08:47:19
2022-01-06T08:47:19
null
UTF-8
C++
false
false
19,910
cpp
grid_2D_cyln.cpp
#include <cstdlib> #include <fstream> #include <iostream> #include <iomanip> #include <math.h> #include <cassert> #include <limits> #include "hdf5.h" #include "hdf5_hl.h" #include "grid_2D_cyln.h" #include "physical_constants.h" #ifdef MPI_PARALLEL #include "mpi.h" #endif namespace pc = physical_constants; using std::string; using std::cout; using std::cerr; using std::endl; //------------------------------------------------------------ // initialize the zone geometry from model file //------------------------------------------------------------ void grid_2D_cyln::read_model_file(ParameterReader* params) { // verbocity #ifdef MPI_PARALLEL int my_rank; MPI_Comm_rank( MPI_COMM_WORLD, &my_rank ); const int verbose = (my_rank == 0); #else const int verbose = 1; #endif // open up the model file, complaining if it fails to open string model_file = params->getScalar<string>("model_file"); // open hdf5 file hid_t file_id = H5Fopen (model_file.c_str(), H5F_ACC_RDONLY, H5P_DEFAULT); herr_t status; // get time double tt[1]; status = H5LTread_dataset_double(file_id,"/time",tt); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find time" << endl; t_now = tt[0]; // get grid size and dimensions hsize_t dims[3]; status = H5LTget_dataset_info(file_id,"/comp",dims, NULL, NULL); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find comp" << endl; nx_ = dims[0]; nz_ = dims[1]; n_elems = dims[2]; n_zones = nx_*nz_; x_out_.resize(nx_); z_out_.resize(nz_); z.resize(n_zones); dx_.resize(nx_); dz_.resize(nz_); vol_.resize(n_zones); int *etmp = new int[n_elems]; status = H5LTread_dataset_int(file_id,"/Z",etmp); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find Z" << endl; for (int k=0;k<n_elems;k++) elems_Z.push_back(etmp[k]); status = H5LTread_dataset_int(file_id,"/A",etmp); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find A" << endl; for (int k=0;k<n_elems;k++) elems_A.push_back(etmp[k]); delete [] etmp; // read x & z grids -- read everything in that exists and piece it together double* xtmp; double* ztmp; double xmin; double zmin; double dr[2]; double rmin[2]; // Check which grid inputs exist herr_t status_x = H5LTfind_dataset(file_id,"x_out"); herr_t status_z = H5LTfind_dataset(file_id,"z_out"); status_dr_ = H5LTfind_dataset(file_id,"dr"); status_rmin_ = H5LTfind_dataset(file_id,"rmin"); status_xz_ = (status_x && status_z); // Read in data if exists if (status_dr_) { status = H5LTread_dataset_double(file_id,"/dr",dr); } if (status_rmin_) { status = H5LTread_dataset_double(file_id,"/rmin",rmin); xmin = rmin[0]; zmin = rmin[1]; } else { if (status_dr_) { xmin = 0; zmin = -dr[1]*nz_/2.0; } } if (status_x && status_z) { xtmp = new double[nx_]; status = H5LTread_dataset_double(file_id,"/x_out",xtmp); ztmp = new double[nz_]; status = H5LTread_dataset_double(file_id,"/z_out",ztmp); } // Initialize x_out_ and z_out_ if possible if (status_xz_ && status_rmin_) { x_out_.init(xtmp, nx_, xmin); z_out_.init(ztmp, nz_, zmin); delete [] xtmp; delete [] ztmp; } else if (status_xz_ && (!status_rmin_)) { std::cerr << "Error: Missing rmin in grid. Exiting." << std::endl; delete [] xtmp; delete [] ztmp; exit(99); } else if (status_dr_ && status_rmin_) { double xmax = xmin + dr[0] * nx_; double zmax = zmin + dr[1] * nz_; x_out_.init(xmin, xmax, dr[0]); z_out_.init(zmin, zmax, dr[1]); } else if (status_dr_ && (!status_rmin_)) { xmin = 0.; zmin = -dr[1]*nz_/2.0; double xmax = xmin + dr[0] * nx_; double zmax = zmin + dr[1] * nz_; x_out_.init(xmin, xmax, dr[0]); z_out_.init(zmin, zmax, dr[1]); } else { if (verbose) std::cerr << "# Grid Err; can't find one of the following inputs to define the grid: 1) dr or 2) x_out, z_out" << endl; exit(10); } for (int i=0; i < nx_; i++) dx_[i] = x_out_.delta(i); for (int i=0; i < nz_; i++) dz_[i] = z_out_.delta(i); // read zone properties double *tmp = new double[n_zones]; // read density status = H5LTread_dataset_double(file_id,"/rho",tmp); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find rho" << endl; for (int i=0; i < n_zones; i++) z[i].rho = tmp[i]; // read temperature status = H5LTread_dataset_double(file_id,"/temp",tmp); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find temp" << endl; for (int i=0; i < n_zones; i++) z[i].T_gas = tmp[i]; // read vx status = H5LTread_dataset_double(file_id,"/vx",tmp); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find vx" << endl; for (int i=0; i < n_zones; i++) z[i].v[0] = tmp[i]; // read vz status = H5LTread_dataset_double(file_id,"/vz",tmp); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find vz" << endl; for (int i=0; i < n_zones; i++) z[i].v[2] = tmp[i]; // read erad status = H5LTread_dataset_double(file_id,"/erad",tmp); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find erad" << endl; for (int i=0; i < n_zones; i++) z[i].e_rad = tmp[i]; // read grey opacity if the user defines a zone-specific grey opacity int use_zone_specific_grey_opacity = params->getScalar<int>("opacity_zone_specific_grey_opacity"); if(use_zone_specific_grey_opacity != 0){ status = H5LTread_dataset_double(file_id,"/grey_opacity",tmp); if (status < 0) if (verbose) std::cerr << "# Grid Err; can't find grey_opacity" << endl; for (int i=0; i < n_zones; i++) z[i].zone_specific_grey_opacity = tmp[i]; } // set bulk grey opacity (note: this parameter is set in the param file, not in the hdf5 file) // and set total grey opacity double bulk_grey_opacity = params->getScalar<double>("opacity_grey_opacity"); for (int i=0; i < n_zones; i++){ z[i].bulk_grey_opacity = bulk_grey_opacity; z[i].total_grey_opacity = z[i].bulk_grey_opacity + z[i].zone_specific_grey_opacity; } delete [] tmp; // get mass fractions double *ctmp = new double[n_zones*n_elems]; status = H5LTread_dataset_double(file_id,"/comp",ctmp); int cnt = 0; for (int i=0; i < n_zones; i++) { z[i].X_gas.resize(n_elems); for (int k=0; k < n_elems; k++) { z[i].X_gas[k] = ctmp[cnt]; cnt++; } } delete [] ctmp; // close HDF5 input file H5Fclose (file_id); // allocate indexs index_x_.resize(n_zones); index_z_.resize(n_zones); //--------------------------------------------------- // Calculate volume, indices, model properties //--------------------------------------------------- double totmass = 0, totke = 0, totrad = 0; double *elem_mass = new double[n_elems]; for (int k = 0;k < n_elems; k++) elem_mass[k] = 0; cnt = 0; for (int i=0;i<nx_;++i) for (int j=0;j<nz_;++j) { double r0 = x_out_.left(i); double r1 = x_out_.right(i); vol_[cnt] = pc::pi*(r1*r1 - r0*r0)*dz_[j]; index_x_[cnt] = i; index_z_[cnt] = j; double vrsq = z[cnt].v[0]*z[cnt].v[0] + z[cnt].v[2]*z[cnt].v[2]; // compute integral quantities totmass += vol_[cnt]*z[cnt].rho; totke += 0.5*vol_[cnt]*z[cnt].rho*vrsq; totrad += vol_[cnt]*z[cnt].e_rad; for (int k = 0;k < n_elems; k++) elem_mass[k] += vol_[cnt]*z[cnt].rho*z[cnt].X_gas[k]; cnt++; } //--------------------------------------------------- // Printout model properties //--------------------------------------------------- if (verbose) { std::cout << "# gridtype: 2D cylindrical\n"; std::cout << "# n_zones = " << n_zones << "\n"; std::cout << "# (nx,nz) = (" << nx_ << ", " << nz_ << ")\n"; // std::cout << "# (dx,dz) = (" << dx_ << ", " << dz_ << ")\n"; printf("# mass = %.4e (%.4e Msun)\n",totmass,totmass/pc::m_sun); for (int k=0;k<n_elems;k++) { cout << "# " << elems_Z[k] << "." << elems_A[k] << "\t"; cout << elem_mass[k] << " (" << elem_mass[k]/pc::m_sun << " Msun)\n"; } printf("# kinetic energy = %.4e\n",totke); printf("# radiation energy = %.4e\n",totrad); cout << "##############################\n#" << endl; } delete [] elem_mass; } //************************************************************ // Write out the file //************************************************************ void grid_2D_cyln::write_plotfile(int iw, double tt, int write_mass_fractions) { // get file name char zonefile[1000]; sprintf(zonefile,"plt_%05d.h5",iw); // open hdf5 file hid_t file_id = H5Fcreate( zonefile, H5F_ACC_TRUNC, H5P_DEFAULT, H5P_DEFAULT); // If fixed dr's exist, output them. Some tests want it if (status_dr_) { hsize_t dims_dr[1]={2}; float dr[2]; dr[0] = x_out_.delval(); dr[1] = z_out_.delval(); H5LTmake_dataset(file_id,"dr",1,dims_dr,H5T_NATIVE_FLOAT,dr); } // print out x array hsize_t dims_x[1]={(hsize_t)nx_}; float *xarr = new float[nx_]; for (int i=0;i<nx_;i++) xarr[i] = x_out_.left(i); H5LTmake_dataset(file_id,"r",1,dims_x,H5T_NATIVE_FLOAT,xarr); delete [] xarr; // print out z array hsize_t dims_z[1]={(hsize_t)nz_}; float *zarr = new float[nz_]; for (int i=0;i<nz_;i++) zarr[i] = z_out_.left(i); H5LTmake_dataset(file_id,"z",1,dims_z,H5T_NATIVE_FLOAT,zarr); delete [] zarr; hsize_t dims_min[1]={1}; float x0 = x_out_.minval(); H5LTmake_dataset(file_id,"x_min",1,dims_min,H5T_NATIVE_FLOAT,&x0); float z0 = z_out_.minval(); H5LTmake_dataset(file_id,"z_min",1,dims_min,H5T_NATIVE_FLOAT,&z0); hsize_t dims_g[2]={(hsize_t) nx_,(hsize_t) nz_}; write_hdf5_plotfile_zones(file_id, dims_g, 2, tt); write_integrated_quantities(iw,tt); // close HDF5 input file H5Fclose (file_id); } //************************************************************ // expand the grid //************************************************************ void grid_2D_cyln::expand(double e) { x_out_.scale(e); z_out_.scale(e); for (int i=0; i < nx_; i++) dx_[i] = dx_[i]*e; for (int k=0; k < nz_; k++) dz_[k] = dz_[k]*e; for (int i=0; i < n_zones; i++) vol_[i] = vol_[i]*e*e*e; } //************************************************************ // Overly simple search to find zone //************************************************************ int grid_2D_cyln::get_zone(const double *x) const { // double p = sqrt(x[0]*x[0] + x[1]*x[1]); // int ix = floor(p/dx_); // int iz = floor((x[2] + zcen_)/dz_); // // check if off boundaries // if (ix >= nx_) return -2; // if (iz < 0) return -2; // if (iz >= nz_) return -2; // return ix*nz_ + iz; double p = sqrt(x[0]*x[0] + x[1]*x[1]); if (p < x_out_.minval()) return -2; if (p > x_out_[nx_-1]) return -2; if (x[2] < z_out_.minval()) return -2; if (x[2] > z_out_[nz_-1]) return -2; int i = x_out_.locate_within_bounds(p); int k = z_out_.locate_within_bounds(x[2]); int ind = i*nz_ + k; return ind; } //************************************************************ // Find distance to next zone along path //************************************************************ int grid_2D_cyln::get_next_zone (const double *x, const double *D, int i, double r_core, double *l) const { // impact parameter of particle position double p = sqrt(x[0]*x[0] + x[1]*x[1]); // z position and direction vector double z = x[2]; double Dz = D[2]; int ix = index_x_[i]; int iz = index_z_[i]; double lp,lz; int d_ip = 0; int d_iz = 0; //std::cout << "p: " << ix*dx_ << " " << p << " " << (ix+1)*dx_ << "\n"; //std::cout << "z: " << iz*dz_ - zcen_ << " " << z << " " << (iz+1)*dz_ - zcen_ << "\n"; //std::cout << "i: " << i << " " << " ix: " << index_x_[i] << " iz:" << index_z_[i] << " "; //std::cout << "ii: " << get_zone(x) << "\n"; // tiny offset so we don't land exactly on boundaries double tiny = 1e-10; // distance to z interface if (Dz > 0) { // up interface double zt = z_out_.right(iz) + dz_[iz]*tiny; lz = (zt - z)/Dz; //std::cout << "iz_up = "<< iz << "; Dz = " << Dz << "; zt = " << zt << "; z = " << z << "; lz = " << lz << "\n"; d_iz = 1; } else { // down interface double zt = z_out_.left(iz) - dz_[iz]*tiny; lz = (zt - z)/Dz; if (Dz == 0) lz = std::numeric_limits<double>::infinity(); //std::cout << "Dz_dn = " << Dz << ";zt = " << zt << "; z = " << z << "; lz = " << lz << "\n"; d_iz = -1; } // distance to p interfaces (annulus) double pt,c,lp_out,lp_in,det; double a = D[0]*D[0] + D[1]*D[1]; double b = 2*(x[0]*D[0] + x[1]*D[1]); if (a == 0) lp = std::numeric_limits<double>::infinity(); else { // outer interface pt = x_out_.right(ix) + dx_[ix]*tiny; c = p*p - pt*pt; det = b*b - 4*a*c; if (det < 0) lp_out = std::numeric_limits<double>::infinity(); else lp_out = (-1.0*b + sqrt(det))/(2*a); if (lp_out < 0) lp_out = std::numeric_limits<double>::infinity(); // inner interface pt = x_out_.left(ix) - dx_[ix]*tiny; c = p*p - pt*pt; det = b*b - 4*a*c; if (det < 0) lp_in = std::numeric_limits<double>::infinity(); else lp_in = (-1.0*b - sqrt(det))/(2*a); if (lp_in < 0) lp_in = std::numeric_limits<double>::infinity(); if (ix == 0) lp_in = std::numeric_limits<double>::infinity(); if (lp_in < lp_out) { lp = lp_in; d_ip = -1; } else { lp = lp_out; d_ip = 1; } } int new_iz = index_z_[i]; int new_ip = index_x_[i]; // find smallest interface if (lz < lp) { *l = lz; new_iz += d_iz; //std::cout << "step z " << new_iz << " " << d_iz << " " << lz << "\n"; } else { *l = lp; new_ip += d_ip; //std::cout << "step p " << new_ip << " " << d_ip << " " << lp << "\n"; } if (isnan(*l)) { // std::cout << "step p " << new_ip << " " << d_ip << " " << lp << "\n"; // std::cout << "step z " << new_iz << " " << d_iz << " " << lz << "\n"; } // escaped if ((new_iz < 0)||(new_iz >= nz_)||(new_ip >= nx_)) return -2; return new_ip*nz_ + new_iz; ; /* double rsq = (x[0]*x[0] + x[1]*x[1] + x[2]*x[2]); double xdotD = (D[0]*x[0] + D[1]*x[1] + D[2]*x[2]); // distance to outer shell edge double r_o = r_out[i]; double l_out = -1*xdotD + sqrt(xdotD*xdotD + r_o*r_o - rsq); double r_i = 0; int ind_in = i-1; if (i != 0) r_i = r_out[i-1]; if (r_core >= r_i) { r_i = r_core; ind_in = -1; } double l_in; if ((i == 0)&&(r_core == 0)) l_in = -1; else { double rad = xdotD*xdotD + r_i*r_i - rsq; if (rad < 0) l_in = -1; else l_in = -1*xdotD - sqrt(rad); } // find shortest positive distance int ind; //double tiny = 1 + 1e-10; if ((l_out < l_in)||(l_in < 0)) { ind = i + 1; if (ind == n_zones) ind = -2; *l = l_out; //tiny; } else { ind = ind_in; *l = l_in; //tiny; } return ind; */ } //************************************************************ // return volume of zone (precomputed) //************************************************************ double grid_2D_cyln::zone_volume(const int i) const { return vol_[i]; } //************************************************************ // sample a random position within the annulus weighted by volume //************************************************************ void grid_2D_cyln::sample_in_zone(int i, std::vector<double> ran, double r[3]) { int ix = index_x_[i]; int iz = index_z_[i]; double phi = 2*pc::pi*ran[1]; double p_in = x_out_.left(ix); double p_out = x_out_.right(ix); double p_samp = sqrt( p_in*p_in + ran[0]*( p_out*p_out-p_in*p_in ) ); r[0] = p_samp*cos(phi); r[1] = p_samp*sin(phi); r[2] = z_out_.left(iz) + ran[2]*dz_[iz]; } //************************************************************ // get the velocity vector //************************************************************ void grid_2D_cyln::get_velocity(int i, double x[3], double D[3], double v[3], double *dvds) { if (use_homologous_velocities_ == 1) { v[0] = x[0]/t_now; v[1] = x[1]/t_now; v[2] = x[2]/t_now; *dvds = 1.0/t_now; } else { double p = sqrt(x[0]*x[0] + x[1]*x[1]); v[0] = z[i].v[0]*x[0]/p; v[1] = z[i].v[0]*x[1]/p; v[2] = z[i].v[2]; if (p == 0) { v[0] = 0; v[1] = 0; } *dvds = 0; } } void grid_2D_cyln::writeCheckpointGrid(std::string fname) { if (my_rank == 0) { /* Write out geometry-independent quantities */ writeCheckpointGeneralGrid(fname); hsize_t single_val = 1; createDataset(fname, "grid", "status_dr", 1, &single_val, H5T_NATIVE_INT); createDataset(fname, "grid", "status_rmin", 1, &single_val, H5T_NATIVE_INT); createDataset(fname, "grid", "status_xz", 1, &single_val, H5T_NATIVE_INT); createDataset(fname, "grid", "nx", 1, &single_val, H5T_NATIVE_INT); createDataset(fname, "grid", "nz", 1, &single_val, H5T_NATIVE_INT); writeSimple(fname, "grid", "status_dr", &status_dr_, H5T_NATIVE_INT); writeSimple(fname, "grid", "status_rmin", &status_rmin_, H5T_NATIVE_INT); writeSimple(fname, "grid", "status_xz", &status_xz_, H5T_NATIVE_INT); writeSimple(fname, "grid", "nx", &nx_, H5T_NATIVE_INT); writeSimple(fname, "grid", "nz", &nz_, H5T_NATIVE_INT); x_out_.writeCheckpoint(fname, "grid", "x_out"); z_out_.writeCheckpoint(fname, "grid", "z_out"); writeVector(fname, "grid", "dx", dx_, H5T_NATIVE_DOUBLE); writeVector(fname, "grid", "dz", dz_, H5T_NATIVE_DOUBLE); writeVector(fname, "grid", "index_x", index_x_, H5T_NATIVE_INT); writeVector(fname, "grid", "index_z", index_z_, H5T_NATIVE_INT); writeVector(fname, "grid", "vol", vol_, H5T_NATIVE_DOUBLE); } MPI_Barrier(MPI_COMM_WORLD); } void grid_2D_cyln::readCheckpointGrid(std::string fname, bool test) { for (int rank = 0; rank < nproc; rank++) { if (my_rank == rank) { readCheckpointGeneralGrid(fname, test); readSimple(fname, "grid", "status_dr", &status_dr_, H5T_NATIVE_INT); readSimple(fname, "grid", "status_rmin", &status_rmin_, H5T_NATIVE_INT); readSimple(fname, "grid", "status_xz", &status_xz_, H5T_NATIVE_INT); readSimple(fname, "grid", "nx", &nx_new_, H5T_NATIVE_INT); readSimple(fname, "grid", "nx", &nx_new_, H5T_NATIVE_INT); readSimple(fname, "grid", "nz", &nz_new_, H5T_NATIVE_INT); x_out_new_.readCheckpoint(fname, "grid", "x_out"); z_out_new_.readCheckpoint(fname, "grid", "z_out"); readVector(fname, "grid", "dx", dx_new_, H5T_NATIVE_DOUBLE); readVector(fname, "grid", "dz", dz_new_, H5T_NATIVE_DOUBLE); readVector(fname, "grid", "index_x", index_x_new_, H5T_NATIVE_INT); readVector(fname, "grid", "index_z", index_z_new_, H5T_NATIVE_INT); readVector(fname, "grid", "vol", vol_new_, H5T_NATIVE_DOUBLE); if (not test) { nx_ = nx_new_; nz_ = nz_new_; x_out_ = x_out_new_; z_out_ = z_out_new_; index_x_ = index_x_new_; index_z_ = index_z_new_; vol_ = vol_new_; dx_ = dx_new_; dz_ = dz_new_; } } MPI_Barrier(MPI_COMM_WORLD); } } void grid_2D_cyln::restartGrid(ParameterReader* params) { #ifdef MPI_PARALLEL int my_rank; MPI_Comm_rank( MPI_COMM_WORLD, &my_rank ); const int verbose = (my_rank == 0); #else const int verbose = 1; #endif string restart_file = params->getScalar<string>("run_restart_file"); // geometry of model if(params->getScalar<string>("grid_type") != "grid_2D_cyln") { if (verbose) cerr << "Err: grid_type param disagrees with the model file" << endl; exit(4); } if (verbose) { cout << "# model file = " << restart_file << "\n"; cout << "# Model is a 2D_sphere\n"; } readCheckpointGrid(restart_file); readCheckpointZones(restart_file); }
2ece25c479175433b28bbfe4b768ac7840413f9a
858f2c4950912eb2f46e1d16a1a9be136a453f75
/homework2/prt/src/proplist.cpp
b37d4ccd402519638b44218909013806099f0c59
[]
no_license
Crocs512/GAMES202-HW
0ba7f77a902176e3439c5e4e8cb34823c6798c77
6008695ed1015ac0580a4afab8257e527c1b1cbf
refs/heads/master
2023-06-11T05:22:29.146228
2021-07-05T15:19:17
2021-07-05T15:19:17
373,748,933
10
2
null
null
null
null
UTF-8
C++
false
false
2,527
cpp
proplist.cpp
/* This file is part of Nori, a simple educational ray tracer Copyright (c) 2015 by Wenzel Jakob Nori is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. Nori 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 <nori/proplist.h> NORI_NAMESPACE_BEGIN #define DEFINE_PROPERTY_ACCESSOR(Type, TypeName, XmlName) \ void PropertyList::set##TypeName(const std::string &name, const Type &value) { \ if (m_properties.find(name) != m_properties.end()) \ cerr << "Property \"" << name << "\" was specified multiple times!" << endl; \ auto &prop = m_properties[name]; \ prop.value.XmlName##_value = value; \ prop.type = Property::XmlName##_type; \ } \ \ Type PropertyList::get##TypeName(const std::string &name) const { \ auto it = m_properties.find(name); \ if (it == m_properties.end()) \ throw NoriException("Property '%s' is missing!", name); \ if (it->second.type != Property::XmlName##_type) \ throw NoriException("Property '%s' has the wrong type! " \ "(expected <" #XmlName ">)!", name); \ return it->second.value.XmlName##_value; \ } \ \ Type PropertyList::get##TypeName(const std::string &name, const Type &defVal) const { \ auto it = m_properties.find(name); \ if (it == m_properties.end()) \ return defVal; \ if (it->second.type != Property::XmlName##_type) \ throw NoriException("Property '%s' has the wrong type! " \ "(expected <" #XmlName ">)!", name); \ return it->second.value.XmlName##_value; \ } DEFINE_PROPERTY_ACCESSOR(bool, Boolean, boolean) DEFINE_PROPERTY_ACCESSOR(int, Integer, integer) DEFINE_PROPERTY_ACCESSOR(float, Float, float) DEFINE_PROPERTY_ACCESSOR(Color3f, Color, color) DEFINE_PROPERTY_ACCESSOR(Point3f, Point, point) DEFINE_PROPERTY_ACCESSOR(Vector3f, Vector, vector) DEFINE_PROPERTY_ACCESSOR(std::string, String, string) DEFINE_PROPERTY_ACCESSOR(Transform, Transform, transform) NORI_NAMESPACE_END
5b28b8758aed8646f4c549fbdc1e4d41f8f4c5fe
d671b95eb67aadb84bcfdaf84520ba6dc47c68d9
/ESP8266_WifiConection/lib/Net_Manager/Net_manager.cpp
872966b9d30c08a00a216e965e19a301ce15d473
[]
no_license
MarioBritoMay/Esp8266_Codes
98f110e042b211c5e73f66acc1f0161a996e089f
5f89c518c9fb38dcf0977d8da5f373a403a5d4b7
refs/heads/master
2023-01-03T11:03:34.825518
2020-09-29T00:38:25
2020-09-29T00:38:25
299,453,861
0
0
null
null
null
null
UTF-8
C++
false
false
2,451
cpp
Net_manager.cpp
#include "Net_manager.h" #include <htmlPage.h> #define SERVER_PORT 80 ESP8266WebServer server(SERVER_PORT); String message = ""; void configurePage() { server.send(200, "text/html", htmlPage + message + htmlPageEnd); } Net_manager::Net_manager() { ssidAP = "ESP_red"; wifi_Status = 0; } void Net_manager::begin() { previousMillis = millis(); Serial.begin(9600); } void Net_manager::loop() { currentMillis = millis(); if (currentMillis - previousMillis > 3000) { if (WiFi.status() != WL_CONNECTED) { previousMillis = millis(); wifi_Status = false; Serial.print("."); // ledmanager.blinkG(250); WiFi.mode(WIFI_STA); //para que no inicie el SoftAP en el modo normal WiFi.begin(net_manager.getSsid(), net_manager.getPassword()); } } if (WiFi.status() == WL_CONNECTED && wifi_Status == false) { Serial.println(""); Serial.println("WiFi connected"); wifi_Status = true; Serial.print("IP_address: "); Serial.println(WiFi.localIP()); // ledmanager.greenOf(); } } String Net_manager::getSsid() { ssid = eepromdatastored.read(1); return ssid; } String Net_manager::getPassword() { password = eepromdatastored.read(51); return password; } void Net_manager::accessPointConnection() { serverOn(); Serial.print("Setting soft-AP ... "); boolean result = WiFi.softAP(ssidAP);//mando nombre de la red creada, se le puede añadir la contraseña if(result) { // ledmanager.greenOn(); } IPAddress myIP = WiFi.softAPIP(); Serial.print("IP:"); Serial.println(myIP); while(true) { server.handleClient(); } } void Net_manager::serverOn() { server.on("/", configurePage); server.on("/configuration", std::bind(&Net_manager::saveWiFiCredentials, this)); server.begin(); Serial.println("HTTP server started"); } void Net_manager::saveWiFiCredentials() { eepromdatastored.saveSSID(net_manager.ssidValue()); eepromdatastored.savePassword(net_manager.PassValue()); eepromdatastored.printSsidPass(); message = "Saved configuration..."; configurePage(); delay (500); ESP.restart();//reset } String Net_manager::ssidValue() { String ssid= server.arg("ssid"); return ssid; } String Net_manager::PassValue() { String pass= server.arg("pass"); return pass; } Net_manager net_manager;
06efe8f2794554e3e8c7936d442ec1c13864d5d7
7d7efaf156c201ee742b51b0d7b6122abd3236d2
/math_util.h
f8d5afbb1eff61c75ecc57fafe271672a7aba1d7
[]
no_license
jrobble/kalman-filter
efbc711e10f70670e6228203c07e6b2153b9ff93
ef698b665f68af0b73cdb040db3eb5222b8d8b83
refs/heads/master
2021-01-19T17:13:31.442565
2009-05-14T09:59:08
2009-05-14T09:59:08
32,262,597
0
1
null
null
null
null
UTF-8
C++
false
false
4,431
h
math_util.h
#ifndef MATH_UTIL_H #define MATH_UTIL_H // limits library not fully implemented in Open Watcom, so use Visual C++ 2008 compiler #include <limits> #include <iostream> // Visual C++ 2008 compiler has no pow(int,int) implementation int pow(int a, int p) { return (int)(pow((double)a,p)); } // element-by-element matrix square root void sqrt(double* a, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = sqrt(a[i]); } } // matrix maximum void max(double* a, int size, double* ret) { double max = -std::numeric_limits<double>::infinity(); double maxindex = -1; for(int i = 0; i < size; i++) { if(a[i] > max) { max = a[i]; maxindex = i; } } ret[0] = max; ret[1] = maxindex; } // matrix minimum void min(double* a, int size, double* ret) { // double min = mxGetInf(); // corrupts obj data double min = std::numeric_limits<double>::infinity(); double minindex = -1; for(int i = 0; i < size; i++) { if(a[i] < min) { min = a[i]; minindex = i; } } ret[0] = min; ret[1] = minindex; } // element-by-element absolute matrix values void abs(double* a, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = abs(a[i]); } } // element-by-element matrix multiplication void mult(double a1, double* a2, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = a1 * a2[i]; } } // element-by-element matrix multiplication void mult(double* a1, double* a2, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = a1[i] * a2[i]; } } // element-by-element matrix substraction void subtract(double a1, double* a2, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = a1 - a2[i]; } } // element-by-element matrix substraction void subtract(double* a1, double* a2, int size, double* ret) { for(int i = 0; i < size; i++) { ret[i] = a1[i] - a2[i]; } } // calc Euclidean distance double distance(double x1, double x2, double y1, double y2) { return sqrt( pow(x2-x1,2) + pow(y2-y1,2) ); } // calc maximum double max(double first, double second) { if(first >= second) { return first; } else { return second; } } // calc minimum double min(double first, double second) { if(first <= second) { return first; } else { return second; } } // calc product double prod(double array[], int size) { double prod = 0; if(size > 0) { prod = 1; for(int i = 0; i < size; i++) { prod *= array[i]; } } // DEBUG /* mexPrintf("prod size: %d\n",size); // DEBUG for(int i = 0; i < size; i++) { mexPrintf("array[%d]: %f\n",i,array[i]); // DEBUG } mexPrintf("prod: %f\n",prod); // DEBUG */ return prod; } // calculate mean squared error double calc_fitnessMSE(double absErr) { double fitnessMSE = 100000 * (1 / (1 + pow(absErr,2))); return fitnessMSE; } // round number int round(double num) { return (int) floor(num+.5); } // calculate sum double sum(double* array, int size) { double sum = 0; for(int i = 0; i < size; i++) { sum += array[i]; } return sum; } // calculate mean // note that there is no way to get the size of a dynamic array, so pass it in double mean(double* array, int size) { return sum(array,size) / size; } // calculate median double median(double* array, int size) { // quickSort(array, size); // actually, already sorted /* mexPrintf("pre-sorted:\n"); // DEBUG for(int i = 0; i < size; i++) { mexPrintf("%f, ", array[i]); // DEBUG } mexPrintf("\n"); // DEBUG mexPrintf("post-sorted:\n"); // DEBUG for(int i = 0; i < size; i++) { mexPrintf("%f, ", array[i]); // DEBUG } mexPrintf("\n"); // DEBUG */ double median = -1; if (size % 2 == 1) { // odd median = array[(int)size/2]; } else { // even median = (array[(int)size/2] + array[((int)(size/2))-1]) / 2; } return median; } #endif /* MATH_UTIL_H */
0cf5303260183a39fa1b27b8077665be354d8a83
6e8a49958b525f10f213d26374a8bebce2d46cd0
/SpaceInvaders/SpaceInvaders/Player.hpp
e45b275a82985381f13c8f2c64312c2627c1d046
[]
no_license
Mnaukal/SpaceInvaders
f28651d45c2761d6d39deed3d78e18ec6254ca62
0b29cdcf073f61d5a198bd6bf4dbc8a52d9102f9
refs/heads/master
2020-04-13T02:10:10.829697
2019-02-18T14:21:53
2019-02-18T14:21:53
162,895,473
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
hpp
Player.hpp
/* Player.hpp - code for user controlled player */ #ifndef player_hpp_ #define player_hpp_ #include "Game.hpp" #include "Rocket.hpp" #include "InvadersConstants.hpp" #include "GameObjectManager.hpp" class Player : public GameObject { private: sf::Sprite sprite; int width, height; float shootTime; public: float Speed; float energy = 1.f; int Score = 0; unsigned lives; Player(const sf::Texture & texture); void HitPlayer(); // subtract life // Inherited via GameObject virtual void Draw(sf::RenderWindow & window) override; virtual void Update(sf::Time deltaTime) override; virtual sf::Rect<float> BoundingBox() override; }; class HitEffect : public GameObject, public Animated { private: sf::RectangleShape shape; public: HitEffect(); // Inherited via GameObject virtual void Draw(sf::RenderWindow & window) override; virtual void Update(sf::Time deltaTime); virtual sf::Rect<float> BoundingBox() { return sf::Rect<float>(); }; // Inherited via Animated virtual void DoAnimation(float progress) override; }; #endif
763d971404b26a349d42e3c46b2d3027bffb7dce
37608e72c40794f39719b87aa4962e2c6fe798ad
/curb_project/src/trtmodel.cpp
1873c5b7659575836a828edbe5b7b03fc1e5e046
[]
no_license
maomaoding/TensorRT_convert
4addf0c08b3d75206521d3b9b72770be688e37d5
6a76cdef7a8a36938045792fef86fde5cc8e334a
refs/heads/master
2022-04-13T17:42:06.274614
2020-04-09T07:12:41
2020-04-09T07:12:41
254,284,526
0
0
null
null
null
null
UTF-8
C++
false
false
4,277
cpp
trtmodel.cpp
#include "trtmodel.h" nvinfer1::DimsCHW TRTmodel::getTensorDims(const char* TensorName) { assert(engine != nullptr); return static_cast<nvinfer1::DimsCHW&&>(engine->getBindingDimensions(engine->getBindingIndex(TensorName))); } void TRTmodel::caffeToTRTModel() { // create the builder nvinfer1::IBuilder* builder = nvinfer1::createInferBuilder(gLogger); // parse the caffe model to populate the network, then set the outputs nvinfer1::INetworkDefinition* network = builder->createNetwork(); nvcaffeparser1::ICaffeParser* parser = nvcaffeparser1::createCaffeParser(); parser->setPluginFactory(&pluginFactory); bool fp16 = builder->platformHasFastFp16(); const nvcaffeparser1::IBlobNameToTensor* blobNameToTensor = parser->parse(deployFile.c_str(), modelFile.c_str(), *network, fp16 ? nvinfer1::DataType::kHALF : nvinfer1::DataType::kFLOAT); // specify which tensors are outputs const std::vector<std::string>& outputs = { OUTPUT_BLOB_NAME }; for(auto& s:outputs) network->markOutput(*blobNameToTensor->find(s.c_str())); // Build the engine builder->setMaxBatchSize(maxBatchSize); builder->setMaxWorkspaceSize(1 << 20); builder->setFp16Mode(fp16); engine = builder->buildCudaEngine(*network); assert(engine); // we don't need the network any more, and we can destroy the parser network->destroy(); parser->destroy(); // serialize the engine, then close everything down nvinfer1::IHostMemory *trtModelStream{ nullptr }; trtModelStream = engine->serialize(); engine->destroy(); builder->destroy(); nvcaffeparser1::shutdownProtobufLibrary(); cout<<"RT init done!"<<endl; ofstream out(tensorrt_cache.c_str(),ios::out|ios::binary); out.write((const char*)(trtModelStream->data()),trtModelStream->size()); out.close(); pluginFactory.destroyPlugin(); assert(trtModelStream != nullptr); trtModelStream->destroy(); } void TRTmodel::doInference(float* input, float* output, int batchSize) { // std::shared_ptr<char> engine_buffer; // int engine_buffer_size; // TRTmodel::ReadModel(engine_buffer, engine_buffer_size); // runtime = nvinfer1::createInferRuntime(gLogger); // assert(runtime != nullptr); // engine = runtime->deserializeCudaEngine(engine_buffer.get(), // engine_buffer_size, // &pluginFactory); assert(engine != nullptr); // context = engine->createExecutionContext(); assert(context != nullptr); // const nvinfer1::ICudaEngine& engine = context->getEngine(); // assert(engine.getNbBindings() == 2); void* buffers[2]; int inputIndex = engine->getBindingIndex(INPUT_BLOB_NAME), outputIndex = engine->getBindingIndex(OUTPUT_BLOB_NAME); nvinfer1::DimsCHW dim_in = getTensorDims(INPUT_BLOB_NAME); nvinfer1::DimsCHW dim_out = getTensorDims(OUTPUT_BLOB_NAME); cudaMalloc(&buffers[inputIndex], batchSize * dim_in.h() * dim_in.w() * dim_in.c() * sizeof(float)); cudaMalloc(&buffers[outputIndex], batchSize * dim_out.h() * dim_out.w() * dim_out.c() * sizeof(float)); cudaStream_t stream; cudaStreamCreate(&stream); cudaMemcpyAsync(buffers[inputIndex], input, batchSize * dim_in.h() * dim_in.w() * dim_in.c() * sizeof(float), cudaMemcpyHostToDevice, stream); boost::timer t; context->enqueue(batchSize, buffers, stream, nullptr); cout<<"enqueue time:"<<t.elapsed()<<endl; cudaMemcpyAsync(output, buffers[outputIndex], batchSize * dim_out.h() * dim_out.w() * dim_out.c() * sizeof(float), cudaMemcpyDeviceToHost, stream); cudaStreamSynchronize(stream); cudaStreamDestroy(stream); cudaFree(buffers[inputIndex]); cudaFree(buffers[outputIndex]); } void TRTmodel::ReadModel(std::shared_ptr<char>& engine_buffer, int& engine_buffer_size){ std::ifstream in(tensorrt_cache.c_str(),std::ios::in | std::ios::binary); if (!in.is_open()){ engine_buffer_size = 0; engine_buffer = nullptr; } in.seekg(0,std::ios::end); engine_buffer_size = in.tellg(); in.seekg(0,std::ios::beg); engine_buffer.reset(new char[engine_buffer_size]); in.read(engine_buffer.get(),engine_buffer_size); in.close(); }
31ed581d6f2d593d31e356a1d2eee128d80808ba
042a27949aad6d7570186c11b236736238258f7b
/GameProject/Engine/Components/Component.cpp
831205dd53bbf4b43166cf200c6524d77b795853
[]
no_license
TheoBerlin/GameProject
793a9aeaf24ce2a70c31fd4e55aa0c229c20c3d2
f135675592c7f1f6e3f2ecec546bada531ad7265
refs/heads/master
2021-07-05T06:49:32.464376
2020-08-23T14:39:10
2020-08-23T14:39:10
166,996,599
4
2
null
2019-03-20T13:52:44
2019-01-22T13:12:28
C++
UTF-8
C++
false
false
807
cpp
Component.cpp
#include "Component.h" #include <Engine/Entity/Entity.h> #include "Utils/Logger.h" Component::Component(Entity* parentEntity, const std::string & tagName) { this->tagName = tagName; this->setHost(parentEntity); } Component::~Component() { } std::string Component::getName() { return this->tagName; } Entity * Component::getHost() { return this->host; } void Component::setHost(Entity* entity) { if (entity == nullptr) { this->host = nullptr; return; } // Detach component from old host if (this->host != nullptr) { this->host->detachComponent(this->tagName); this->host = nullptr; } // Set new host if (entity->addComponent(this)) { this->host = entity; } else { LOG_WARNING("Component already exists on entity %s", this->tagName.c_str()); } } void Component::init() { }
48152fe435e0f35bd489783cad71345d97bf4388
402d3f05d5c2716d17928ec66077f5eb584ee294
/GLFWIntro/GLFWIntro/MyEngine/Camera/MyEulerCamera.h
b6dd1ae4d52fd517d3ad06fceebcc226fe6dde1c
[]
no_license
animeshbaranawal/LearningOpenGL
dfd6b96641c287bb7fb887dc0e0984f0120e6802
84f882413e37505061dd80718fce8f9a2e984189
refs/heads/master
2021-06-23T18:54:35.271845
2019-02-25T17:13:53
2019-02-25T17:13:53
135,611,878
1
0
null
null
null
null
UTF-8
C++
false
false
928
h
MyEulerCamera.h
#ifndef MYEULERCAMERA_H #define MYEULERCAMERA_H #include "MyCamera.h" class MyEulerCamera : public MyCamera { public: /** * @brief We define MyCamera as a singleton class * API to return an instance of MyCamera class * @return MyCamera* - instance of MyCamera class */ static MyCamera* getInstance(); /** * @brief method to get view matrix of camera * @return const glm::mat4 - view matrix of camera */ virtual const glm::mat4 getViewMatrix(); virtual void processMouseEvent(GLFWwindow* window, double xpos, double ypos); virtual void processScrollEvent(GLFWwindow* window, double xOffset, double yOffset); protected: MyEulerCamera(); virtual ~MyEulerCamera(); virtual void processEvent(); private: float yaw; //!< yaw of the camera float pitch; //!< pitch of the camera float fov; //!< field of view of the camera bool firstTime; //!< the first time mouse event is processed by camera }; #endif
98c73cb09940e4ef96f41c711564d8b25dd19ad0
535e550c253b99f563962427f1dc840f26662f8f
/cartest.ino
ccc19d99448061f238546f042b57317b740da37e
[]
no_license
azimah-133/COMP501-Research-Report
4b582d970fbec9d288ac6e184ecd6266cfe030f9
b6031b787b5fa4dbd57660d2b9f155c7b9e12e7d
refs/heads/main
2023-01-21T09:35:43.870821
2020-11-16T07:44:59
2020-11-16T07:44:59
313,223,016
0
0
null
null
null
null
UTF-8
C++
false
false
2,142
ino
cartest.ino
//the right motor will be controlled by the motor A pins on the motor driver const int AIN1 = 13; //control pin 1 on the motor driver for the right motor const int AIN2 = 12; //control pin 2 on the motor driver for the right motor const int PWMA = 11; //speed control pin on the motor driver for the right motor //the left motor will be controlled by the motor B pins on the motor driver const int PWMB = 10; //speed control pin on the motor driver for the left motor const int BIN2 = 9; //control pin 2 on the motor driver for the left motor const int BIN1 = 8; //control pin 1 on the motor driver for the left motor int switchPin = 7; //switch to turn the robot on and off int movement = 100; void setup() { // put your setup code here, to run once: pinMode(switchPin, INPUT_PULLUP); //set this as a pullup to sense whether the switch is flipped //set the motor contro pins as outputs pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT); pinMode(PWMA, OUTPUT); pinMode(BIN1, OUTPUT); pinMode(BIN2, OUTPUT); pinMode(PWMB, OUTPUT); } void loop() { digitalWrite(AIN1, HIGH); //set pin 1 to high digitalWrite(AIN2, LOW); //set pin 2 to low analogWrite(PWMA, abs(movement)); delay(100); analogWrite(PWMB, abs(movement)); delay(100); digitalWrite(AIN1, LOW); //set pin 1 to low digitalWrite(AIN2, HIGH); analogWrite(PWMA, abs(-movement)); delay(100); analogWrite(PWMB, abs(-movement)); delay(100); digitalWrite(AIN1, LOW); digitalWrite(AIN2, LOW); digitalWrite(BIN1, HIGH); //set pin 1 to high digitalWrite(BIN2, LOW); //set pin 2 to low analogWrite(PWMA, abs(movement)); delay(100); analogWrite(PWMB, abs(movement)); delay(100); digitalWrite(BIN1, LOW); //set pin 1 to low digitalWrite(BIN2, HIGH); analogWrite(PWMA, abs(-movement)); delay(100); analogWrite(PWMB, abs(-movement)); delay(100); digitalWrite(BIN1, LOW); digitalWrite(BIN2, LOW); }
558d35a51354f23f042b2367f02ccd2d849fba95
5e11a1fc9f0f25650bab60bd19428fc96ac4869b
/20170731/morning/templateStack.cc
22dbd88b844d91124bd5aa3247452cc8ac40e2f9
[]
no_license
colinhp/WangdaoCPP
eb0e98b9b53ac87dca97cea26675218704f7a485
d787fefcf87508d629927e7573f90eb71118ac12
refs/heads/master
2021-12-15T11:21:04.701947
2017-08-18T01:39:43
2017-08-18T01:39:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,884
cc
templateStack.cc
#include <iostream> #include <string> using std::cin; using std::cout; using std::endl; using std::string; template <typename T,int kSize = 10> class Stack { public: Stack() :_top(-1) ,_arr(new T[kSize]()) {} ~Stack(); bool empty() const; bool full() const; void push(const T &value); void pop(); T top(); private: int _top; T *_arr; }; template <typename T,int kSize> Stack<T,kSize>::~Stack() { delete [] _arr; } template <typename T,int kSize> bool Stack<T,kSize>::empty() const { return _top == -1; } template <typename T,int kSize> bool Stack<T,kSize>::full() const { return _top == kSize - 1; } template <typename T,int kSize> void Stack<T,kSize>::push(const T &value) { if(!full()) { _arr[++_top] = value; }else { cout<<"stack is full!"<<endl; } } template <typename T,int kSize> void Stack<T,kSize>::pop() { if(!empty()) { --_top; }else { cout<<"stack is empty"<<endl; } } template <typename T,int kSize> T Stack<T,kSize>::top() { return _arr[_top]; } int test0(void) { Stack<int> istack; cout<<"此时栈是否为空?"<<istack.empty()<<endl; istack.push(1); cout<<"此时栈是否为空?"<<istack.empty()<<endl; for(int idx = 2;idx != 12; ++idx) { istack.push(idx); } cout<<"此时栈是否已满?"<<istack.full()<<endl; while(!istack.empty()) { cout<<istack.top()<<" "; istack.pop(); } cout<<"此时栈是否为空?"<<istack.empty()<<endl; return 0; } int main(void) { Stack<string> istack; cout<<"此时栈是否为空?"<<istack.empty()<<endl; istack.push("AAAAAA"); cout<<"此时栈是否为空?"<<istack.empty()<<endl; for(int idx = 1;idx != 11; ++idx) { string elem(6,'A' + idx); istack.push(elem); } cout<<"此时栈是否已满?"<<istack.full()<<endl; while(!istack.empty()) { cout<<istack.top()<<" "; istack.pop(); } cout<<"此时栈是否为空?"<<istack.empty()<<endl; }
28cd30b0e082f864ce5ccdb83902d5fd00e06b57
5d504ef315f93a742efb249ff1c8698527e8e779
/test/02_scope_guard.cpp
249462717c721b3c340b74891aa4a8fa032145e1
[ "MIT" ]
permissive
nakat-t/scope-cpp11
0612e6b6a8254b17d7ec0b7b6db2908f0cf56958
ae6cc87cfe9c16c9bc1e03647728f84cf4d67c69
refs/heads/master
2020-11-24T05:38:08.660641
2019-12-29T14:17:41
2019-12-29T14:17:41
227,988,490
1
1
null
null
null
null
UTF-8
C++
false
false
2,748
cpp
02_scope_guard.cpp
// MIT License // // Copyright (c) 2019 nakat-t <armaiti.wizard@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. #include "scope/scope.hpp" #include <type_traits> #include <catch2/catch.hpp> #include "helper.hpp" using namespace helper; TEST_CASE("scope_guard (scope_guard && rhs)") { { auto g = scope::make_scope_exit(func); auto g2{std::move(g)}; value_of_func = 0; } REQUIRE(value_of_func == 1); } TEST_CASE("scope_guard (scope_guard && rhs): noexpect if is_nothrow_move_constructible_v<EF>") { REQUIRE(std::is_nothrow_move_constructible<scope::scope_exit<void_func_t>>::value); } TEST_CASE("scope_guard (scope_guard && rhs): noexpect if is_nothrow_copy_constructible_v<EF>") { struct EF { EF() noexcept {} EF(const EF&) noexcept {} EF(EF&&) { throw TestException(); } void operator()() noexcept {} }; REQUIRE(std::is_nothrow_move_constructible<scope::scope_exit<EF>>::value); } TEST_CASE("scope_guard (scope_guard && rhs): Any exception thrown during the initialization of exit_function") { struct EF { EF() noexcept {} EF(const EF&) { throw TestException(); } void operator()() noexcept {} }; try { scope::scope_exit<EF> g(EF{}); scope::scope_exit<EF> g2{std::move(g)}; // throw exception REQUIRE(false); // not reached } catch(TestException&) { // Test OK } catch(...) { REQUIRE(false); } } TEST_CASE("release(): Equivalent to execute_on_destruction = false.") { { auto g = scope::make_scope_exit(func); g.release(); value_of_func = 0; } REQUIRE(value_of_func == 0); }
cba2a61e093a9292eaf05ca347abd331f84a58d4
c6149792e471e0badca575c95532a70e7ab3df26
/DemoDirectX/GameObjects/Enemy/Enemy3/Enemy3.cpp
3dd3bf1cc341c0de51a36d8f4cf28df56e9f8133
[]
no_license
duyuit/Aladdin2
b9067432970ce7ee1c134a5b65212b85d8146dbb
c8461bfca48b6de786faea6ebed10d587384e3a4
refs/heads/master
2021-10-28T15:03:06.536526
2019-04-24T06:51:59
2019-04-24T06:51:59
109,827,304
0
0
null
2017-12-19T10:20:16
2017-11-07T11:35:12
C++
UTF-8
C++
false
false
10,614
cpp
Enemy3.cpp
#include "Enemy3.h" vector<RECT> Enemy3::LoadRECT(Enemy3State::StateName state) { vector<RECT> listSourceRect; RECT rect; switch (state) { case Enemy3State::Die: rect.left = 342; rect.top = 23; rect.right = rect.left + 29; rect.bottom = rect.top + 30; listSourceRect.push_back(rect); rect.left = 383; rect.top = 22; rect.right = rect.left + 31; rect.bottom = rect.top + 31; listSourceRect.push_back(rect); rect.left = 423; rect.top = 9; rect.right = rect.left + 44; rect.bottom = rect.top + 44; listSourceRect.push_back(rect); rect.left = 383; rect.top = 22; rect.right = rect.left + 31; rect.bottom = rect.top + 31; listSourceRect.push_back(rect); rect.left = 342; rect.top = 23; rect.right = rect.left + 29; rect.bottom = rect.top + 30; listSourceRect.push_back(rect); break; case Enemy3State::None: break; case Enemy3State::Running: rect.left = 7; rect.top = 784; rect.right = rect.left + 36; rect.bottom = rect.top + 51; listSourceRect.push_back(rect); rect.left = 52; rect.top = 786; rect.right = rect.left + 34; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); rect.left = 93; rect.top = 789; rect.right = rect.left + 36; rect.bottom = rect.top + 46; listSourceRect.push_back(rect); rect.left = 133; rect.top = 781; rect.right = rect.left + 38; rect.bottom = rect.top + 54; listSourceRect.push_back(rect); rect.left = 178; rect.top = 776; rect.right = rect.left + 43; rect.bottom = rect.top + 59; listSourceRect.push_back(rect); rect.left = 233; rect.top = 781; rect.right = rect.left + 38; rect.bottom = rect.top + 54; listSourceRect.push_back(rect); rect.left = 281; rect.top = 788; rect.right = rect.left + 36; rect.bottom = rect.top + 47; listSourceRect.push_back(rect); rect.left = 323; rect.top = 785; rect.right = rect.left + 33; rect.bottom = rect.top + 50; listSourceRect.push_back(rect); break; case Enemy3State::Fighting: rect.left = 2; rect.top = 842; rect.right = rect.left + 55; rect.bottom = rect.top + 57; listSourceRect.push_back(rect); rect.left = 68; rect.top = 844; rect.right = rect.left + 36; rect.bottom = rect.top + 55; listSourceRect.push_back(rect); rect.left = 115; rect.top = 850; rect.right = rect.left + 60; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); rect.left = 182; rect.top = 856; rect.right = rect.left + 45; rect.bottom = rect.top + 43; listSourceRect.push_back(rect); rect.left = 236; rect.top = 848; rect.right = rect.left + 32; rect.bottom = rect.top + 51; listSourceRect.push_back(rect); rect.left = 9; rect.top = 663; rect.right = rect.left + 43; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); rect.left = 9; rect.top = 663; rect.right = rect.left + 43; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); rect.left = 9; rect.top = 663; rect.right = rect.left + 43; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); rect.left = 9; rect.top = 663; rect.right = rect.left + 43; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); break; case Enemy3State::Attacked: rect.left = 4; rect.top = 919; rect.right = rect.left + 54; rect.bottom = rect.top + 51; listSourceRect.push_back(rect); rect.left = 63; rect.top = 920; rect.right = rect.left + 55; rect.bottom = rect.top + 50; listSourceRect.push_back(rect); rect.left = 124; rect.top = 921; rect.right = rect.left + 55; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); rect.left = 185; rect.top = 921; rect.right = rect.left + 55; rect.bottom = rect.top + 49; listSourceRect.push_back(rect); rect.left = 246; rect.top = 923; rect.right = rect.left + 65; rect.bottom = rect.top + 47; listSourceRect.push_back(rect); rect.left = 322; rect.top = 906; rect.right = rect.left + 68; rect.bottom = rect.top + 64; listSourceRect.push_back(rect); rect.left = 399; rect.top = 910; rect.right = rect.left + 68; rect.bottom = rect.top + 60; listSourceRect.push_back(rect); rect.left = 399; rect.top = 910; rect.right = rect.left + 68; rect.bottom = rect.top + 60; listSourceRect.push_back(rect); rect.left = 399; rect.top = 910; rect.right = rect.left + 68; rect.bottom = rect.top + 60; listSourceRect.push_back(rect); rect.left = 399; rect.top = 910; rect.right = rect.left + 68; rect.bottom = rect.top + 60; listSourceRect.push_back(rect); break; default: break; } return listSourceRect; } Enemy3::Enemy3(Player *player, vector<D3DXVECTOR2> list) { mPlayer = player; mListPosition = list; mAnimationRunning = new Animation("Resources/guard.png", 8, LoadRECT(Enemy3State::Running), (float)1 / 1, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(120, 193, 152), Entity::Enemy); mAnimationFighting = new Animation("Resources/guard.png", 9, LoadRECT(Enemy3State::Fighting), (float)1 / 0.2, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(120, 193, 152), Entity::Enemy); mAnimationAttacked = new Animation("Resources/guard.png", 10, LoadRECT(Enemy3State::Attacked), (float)1 / 0.25, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(120, 193, 152), Entity::Enemy); mAnimationDied = new Animation("Resources/flare.png", 5, LoadRECT(Enemy3State::Die), (float)1 / 0.5, D3DXVECTOR2(0.5, 1), D3DCOLOR_XRGB(186, 254, 202), Entity::flare); mAnimationDied->SetScale(D3DXVECTOR2(1.5, 1.5)); RECT rect; rect.left = 9; rect.top = 663; rect.right = rect.left + 43; rect.bottom = rect.top + 49; mSprite = new Sprite("Resources/guard.png", rect, 0, 0, D3DCOLOR_XRGB(120, 193, 152), D3DXVECTOR2(0.5, 1), GameGlobal::mEnemytexture); mCurrentAnimation = nullptr; mCurrentState = Enemy3State::None; Tag = EntityTypes::Enemy; this->mData = new Enemy3Data(); this->mData->enemy = this; mKnife = new Apple(Entity::KnifeEnemy3); mKnife->SetState(AppleState::NONE); } Enemy3::~Enemy3() { /*mAnimationRunning->~Animation(); mAnimationAttacked->~Animation(); mAnimationFighting->~Animation(); mAnimationDied->~Animation();*/ mSprite->~Sprite(); } void Enemy3::Update() { CheckAction(); mKnife->Update(1); mKnife->mReverse = !Reverse; if (Heal == 0) { positionted.push_back(CurrentPosIndex); SetState(new Enemy3Die(this->mData)); } if (mCurrentState != Enemy3State::Attacked && mCurrentState != Enemy3State::Die) { if (CheckFire) { SetState(new Enemy3Fighting(this->mData)); if (mKnife->GetCurrentState() == AppleState::NONE) { mKnife->SetPosition(GetPosition().x, GetPosition().y - 50); mKnife->SetState(AppleState::Flying); } } if (CheckRunning) SetState(new Enemy3Running(this->mData)); if (!CheckFire && !CheckRunning) { mCurrentState = Enemy3State::None; } } if (mCurrentState != Enemy3State::None && mCurrentAnimation != nullptr) { mCurrentAnimation->Update(1); if (this->mData->state) { this->mData->state->Update(); } } if (GetPosition().x < mPlayer->GetPosition().x) Reverse = true; else Reverse = false; } void Enemy3::Draw(D3DXVECTOR2 transform) { if (mCurrentAnimation != nullptr && mCurrentState != Enemy3State::None) { mCurrentAnimation->SetPosition(this->GetPosition()); mCurrentAnimation->GetSprite()->FlipVertical(Reverse); mCurrentAnimation->GetSprite()->SetTranslation(transform); mCurrentAnimation->Draw(); } else { mSprite->FlipVertical(Reverse); mSprite->SetTranslation(transform); mSprite->SetPosition(GetPosition()); mSprite->Draw(); } mKnife->Draw(D3DXVECTOR3(), RECT(), D3DXVECTOR2(1, 1), transform); } void Enemy3::SetState(Enemy3State *newState) { delete this->mData->state; this->mData->state = newState; this->changeAnimation(newState->GetState()); mCurrentState = newState->GetState(); } RECT Enemy3::GetBound() { RECT rect; if (mCurrentAnimation == nullptr) { rect.left = this->posX - mSprite->GetWidth() / 2; rect.right = rect.left + mSprite->GetWidth(); rect.top = this->posY - mSprite->GetHeight(); //Chú ý đoạn này rect.bottom = this->posY;// + mCurrentAnimation->GetSprite()->GetHeight() / 2; return rect; } rect.left = this->posX - mCurrentAnimation->GetSprite()->GetWidth() / 2; rect.right = rect.left + mCurrentAnimation->GetSprite()->GetWidth(); rect.top = this->posY - mCurrentAnimation->GetSprite()->GetHeight(); //Chú ý đoạn này rect.bottom = this->posY;// + mCurrentAnimation->GetSprite()->GetHeight() / 2; float cWidth = this->posX; float cHeight = this->posY - mCurrentAnimation->GetSprite()->GetHeight() / 2; SetCenter(D3DXVECTOR2(cWidth, cHeight)); return rect; } void Enemy3::changeAnimation(Enemy3State::StateName state) { switch (state) { case Enemy3State::None: mCurrentAnimation = nullptr; break; case Enemy3State::Running: mCurrentAnimation = mAnimationRunning; break; case Enemy3State::Fighting: mCurrentAnimation = mAnimationFighting; break; case Enemy3State::Attacked: mCurrentAnimation = mAnimationAttacked; break; case Enemy3State::Die: mCurrentAnimation = mAnimationDied; break; default: break; } this->width = mCurrentAnimation->GetSprite()->GetWidth(); this->height = mCurrentAnimation->GetSprite()->GetHeight(); } void Enemy3::OnCollision(Entity *impactor, Entity::CollisionReturn data, Entity::SideCollisions side) { if (this->mPlayer->getState() == PlayerState::Fighting || impactor->Tag == Entity::AppleThrow ) { SetState(new Enemy3Attacked(this->mData)); } if (mCurrentState == Enemy3State::Fighting && mCurrentAnimation->GetCurrentFrame() == 4 && mPlayer->mCurrentState != PlayerState::Fired) { mPlayer->SetState(new PlayerFiredState(mPlayer->mPlayerData)); } if (this->mData->state) this->mData->state->OnCollision(impactor, side, data); } void Enemy3::CheckAction() { for (int i = 0; i < mListPosition.size(); i++) { bool flag = false; for (int j = 0; j<positionted.size(); j++) if (i == positionted.at(j)) { flag = true; break; } if (flag) continue; if (abs(mPlayer->GetPosition().y - mListPosition.at(i).y) >= 60) continue; int deltay = abs(mPlayer->GetPosition().y - mListPosition.at(i).y); int deltax = abs(mPlayer->GetPosition().x - mListPosition.at(i).x); if (deltax <= 300 && deltay <= 100) { if (i == CurrentPosIndex) continue; SetPosition(mListPosition.at(i)); CurrentPosIndex = i; break; } } int deltax = abs(GetPosition().x - mPlayer->GetPosition().x); if (deltax > 200) { CheckRunning = false; CheckFire = false; return; } if (deltax <= 200 && deltax >= 100) { CheckRunning = true; CheckFire = false; } if (deltax <= 150) { CheckRunning = false; CheckFire = true; } } Animation* Enemy3::GetCurrentAnimation() { return mCurrentAnimation; } void Enemy3::Reset() { positionted.clear(); CurrentPosIndex = -1; }
aa7b2d0e1227fcb06beb0ebc1f51ade707b586f2
181f5cd8fa14eae47ec1cb665331ed57ef8384f3
/Linklist/utils.cpp
3878f8db240402bbd53e4df82b9f2c5a48710d54
[]
no_license
mofeilu/leetcode
6480a0e5fcc810f9ab0514da07101d24a901bf96
d39b0ffd6833fc022e87176fbd22d6962f380da2
refs/heads/master
2020-04-09T06:28:00.470105
2018-12-09T18:52:41
2018-12-09T18:52:41
160,113,742
0
0
null
null
null
null
UTF-8
C++
false
false
3,810
cpp
utils.cpp
#include "utils.hpp" TreeNode* createTree(std::vector<std::vector<int> > const & vals) { TreeNode* root =NULL; if (vals.size() == 0) return root; if (vals[0].size() == 0) return root; if (vals[0][0] == INT_MAX) return root; // this means it's null root = new TreeNode(vals[0][0]); std::vector<TreeNode* > lastLev(1, root); std::vector<TreeNode* > currLev; //std::cout<<root->val<<std::endl; for (int i=1; i<vals.size(); ++i) { currLev.clear(); int count = 0; for (int n=0; n<lastLev.size(); ++n) { if (count >= vals[i].size()) lastLev[n]->left = NULL; else if (vals[i][count] == INT_MAX) lastLev[n]->left = NULL; else { lastLev[n]->left = new TreeNode(vals[i][count]); currLev.push_back(lastLev[n]->left); } count++; if (count >= vals[i].size()) lastLev[n]->right = NULL; else if (vals[i][count] == INT_MAX) lastLev[n]->right = NULL; else { lastLev[n]->right = new TreeNode(vals[i][count]); currLev.push_back(lastLev[n]->right); } count++; } // show current level /*for (int j=0; j<currLev.size(); ++j) if (currLev[j] != NULL) std::cout << currLev[j]->val << ' ';*/ std::cout<<std::endl; lastLev.clear(); lastLev = currLev; } return root; } void printTreeLevelOrder(TreeNode* root) { std::vector<TreeNode* > currLev; currLev.push_back(root); std::vector<TreeNode* > nextLev; while (!currLev.empty()) { nextLev.clear(); // from the end go backward, find the first non NULL pos int endPos = (int)currLev.size()-1; for (; endPos >=0; --endPos) if (currLev[endPos] != NULL) break; for (int i=0; i<=endPos; ++i) { if (currLev[i] != NULL) { std::cout << currLev[i]->val << ' '; nextLev.push_back(currLev[i]->left); nextLev.push_back(currLev[i]->right); } else { std::cout << "n" << ' '; } } std::cout << std::endl; currLev.clear(); currLev = nextLev; } } TreeNode* createTreeLevelOrder(std::vector<int> const & vals) { TreeNode* root = NULL; if (vals.empty()) return root; root = new TreeNode(vals[0]); std::vector<TreeNode* > lastLev(1, root); std::vector<TreeNode* > nextLev; int count = 1; while (count<vals.size()) { nextLev.clear(); for (int i=0; i<lastLev.size(); ++i) { if (count < vals.size()) { if (lastLev[i] != NULL) { lastLev[i]->left = (vals[count] == INT_MAX) ? NULL : new TreeNode(vals[count]); nextLev.push_back(lastLev[i]->left); count++; if (count < vals.size()) { lastLev[i]->right = (vals[count] == INT_MAX) ? NULL : new TreeNode(vals[count]); nextLev.push_back(lastLev[i]->right); count++; } else { lastLev[i]->right = NULL; } } } else { if (lastLev[i] != NULL) { lastLev[i]->left = NULL; lastLev[i]->right = NULL; } } } lastLev.clear(); lastLev = nextLev; } return root; } ListNode* createList(std::vector<int> const & vec) { if (vec.empty()) return NULL; ListNode* head = new ListNode(vec[0]); ListNode* prev = head; for (int i=1; i<vec.size(); ++i) { prev->next = new ListNode(vec[i]); prev = prev->next; } prev->next = NULL; return head; } void printList(ListNode* head) { ListNode* ptr = head; std::cout << "[ "; while (ptr != NULL) { std::cout << ptr->val << ' '; ptr = ptr->next; } std::cout << "]\n"; }
9fe0bc6b57d164f5bd56574cca72da918861a3ff
751fd10f1bbd8924bbc206c2f2a4ad0edebd9d66
/Data structures CSE-2003/Find the element that appears once in sorted array/ele_occ_once.cpp
aa770be81939db74c23ba47b68c6d615cbee1715
[]
no_license
awarirahul365/CSE-2003-Data-Structures-and-Algorithms
0570a8e0f40ad8f491b65c512af36e9afa103ebd
e30cdbcb2eef0eea69d785064907d70797cbca4a
refs/heads/master
2022-09-13T00:57:21.884336
2022-09-06T18:06:30
2022-09-06T18:06:30
248,284,321
1
1
null
2020-10-01T07:14:15
2020-03-18T16:27:00
C++
UTF-8
C++
false
false
1,274
cpp
ele_occ_once.cpp
#include<iostream> #include<vector> using namespace std; int main() { int t; cin>>t; int arr[10000]; vector<int>vect; vector<int>out; int n; int con=0; int cur_con=1; int res; for(int i=0;i<t;i++) { cin>>n; for(int j=0;j<n;j++) { int m; cin>>m; vect.push_back(m); } int p=0; while(p<n) { cur_con=1; for(int k=p+1;k<n;k++) { if(vect[p]!=vect[k]) { break; } else if(vect[p]==vect[k]) { cur_con++; } } if(cur_con>con) { con=cur_con; } if(cur_con==1) { res=vect[p]; p=p+cur_con; } else if(cur_con!=1) { p=p+cur_con; } } out.push_back(res); con=0; cur_con=1; res=0; vect.clear(); p=0; } for(int i=0;i<out.size();i++) { cout<<out[i]<<endl; } }
6577be801e489c13d253bb36ace876d70d83ff23
8838c73f6c041e153a1993ba142e1feab038c4bb
/resonance_audio/dsp/spectral_reverb_test.cc
015159fa1c0cdd17842842323fb2cde17309390d
[ "Apache-2.0" ]
permissive
resonance-audio/resonance-audio
429bb71aa141f4632032a55046cc2d9206835c87
4556a46afd4ffae092aa281bfd072eb0279d3a29
refs/heads/master
2023-03-08T20:55:24.586054
2022-09-08T16:03:57
2022-09-08T16:03:57
125,184,446
490
117
Apache-2.0
2022-09-08T16:03:59
2018-03-14T09:03:03
C++
UTF-8
C++
false
false
13,838
cc
spectral_reverb_test.cc
/* Copyright 2018 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. */ #include "dsp/spectral_reverb.h" #include <algorithm> #include <cmath> #include <numeric> #include <vector> #include "third_party/googletest/googletest/include/gtest/gtest.h" #include "base/constants_and_types.h" #include "dsp/biquad_filter.h" #include "dsp/fft_manager.h" #include "dsp/filter_coefficient_generators.h" #include "utils/test_util.h" namespace vraudio { namespace { const size_t kFramesPerBuffer512 = 512; const size_t kFramesPerBuffer2048 = 2048; const size_t kFramesPerBuffer713 = 713; const size_t kNumReverbOverlap = 4; const size_t kReverbFftSize = 4096; const int kSampleFrequency16 = 16000; const int kSampleFrequency24 = 24000; // A set of 9 RT60 values for each of the octave bands with center frequencies // between 31.25Hz and 8kHz. const float kRt60s[kNumReverbOctaveBands] = {0.8f, 0.8f, 0.7f, 0.7f, 0.65f, 0.65f, 0.6f, 0.6f, 0.5f}; void ImpulseResponse(float length_sec, int sample_frequency, size_t frames_per_buffer, SpectralReverb* reverb, std::vector<float>* left_response, std::vector<float>* right_response) { AudioBuffer input(kNumMonoChannels, frames_per_buffer); input.Clear(); input[0][0] = 1.0f; AudioBuffer output(kNumStereoChannels, frames_per_buffer); reverb->Process(input[0], &output[0], &output[1]); // The number of iterations required so that we will have no more than a few // zeros following each of our impulse responses. const float tail_length_samples = kReverbFftSize + length_sec * static_cast<float>(sample_frequency); const size_t num_iterations = 100 + 1 + static_cast<size_t>(std::ceil(tail_length_samples / static_cast<float>(frames_per_buffer))); for (size_t i = 0; i < num_iterations; ++i) { left_response->insert(left_response->end(), output[0].begin(), output[0].end()); right_response->insert(right_response->end(), output[1].begin(), output[1].end()); input.Clear(); reverb->Process(input[0], &output[0], &output[1]); } } void StereoOutputTestHelper(int sample_frequency, size_t frames_per_buffer) { SpectralReverb reverb(sample_frequency, frames_per_buffer); reverb.SetRt60PerOctaveBand(kRt60s); std::vector<float> output_collect_left; std::vector<float> output_collect_right; ImpulseResponse(1.0f /*length [sec]*/, sample_frequency, frames_per_buffer, &reverb, &output_collect_left, &output_collect_right); // First test that there are kReverbFftSize / kNumReverbOverlap zeros at the // beginning of the system impulse responses ONLY if this value is greater // than |frames_per_buffer|, otherwise expect no onset zeros. const size_t kOverlapLength = kReverbFftSize / kNumReverbOverlap; const size_t onset = kOverlapLength > frames_per_buffer ? kOverlapLength : 0; for (size_t i = 0; i < onset; ++i) { EXPECT_NEAR(0.0f, output_collect_left[i], kEpsilonFloat); EXPECT_NEAR(0.0f, output_collect_right[i], kEpsilonFloat); } // Test the sample five samples later is non zero. i.e. the tail has begun. EXPECT_NE(0.0f, output_collect_left[onset + 5]); EXPECT_NE(0.0f, output_collect_right[onset + 5]); } void ZeroRt60TestHelper(int sample_frequency, float rt_60) { SpectralReverb reverb(sample_frequency, kFramesPerBuffer512); reverb.SetRt60PerOctaveBand(kRt60s); std::vector<float> output_collect_left; std::vector<float> output_collect_right; ImpulseResponse(1.0f /*length [sec]*/, sample_frequency, kFramesPerBuffer512, &reverb, &output_collect_left, &output_collect_right); // Test that all the frames of the tail buffer are zeros. for (size_t i = 0; i < kFramesPerBuffer512; ++i) { EXPECT_NEAR(0.0f, output_collect_left[i], kEpsilonFloat); EXPECT_NEAR(0.0f, output_collect_right[i], kEpsilonFloat); } } void TailDecayTestHelper(int sample_frequency, size_t frames_per_buffer) { // Butterworth Lowpass filter with cutoff frequency at 3Hz. BiquadCoefficients low_pass_coefficients( 1.0f, -1.999444639647f, 0.999444793816755f, 1e-5f, 2e-5f, 1e-5f); BiquadFilter low_pass_filter(low_pass_coefficients, frames_per_buffer); const std::vector<float> kUniformRt60s(kNumReverbOctaveBands, kRt60s[0]); SpectralReverb reverb(sample_frequency, frames_per_buffer); reverb.SetRt60PerOctaveBand(kUniformRt60s.data()); std::vector<float> output_collect_left; std::vector<float> output_collect_right; ImpulseResponse(2.0f /*length [sec]*/, sample_frequency, frames_per_buffer, &reverb, &output_collect_left, &output_collect_right); for (size_t i = 0; i < output_collect_left.size(); ++i) { output_collect_left[i] = std::abs(output_collect_left[i]); output_collect_right[i] = std::abs(output_collect_right[i]); } const size_t response_length = output_collect_left.size(); AudioBuffer test_buffer(kNumMonoChannels, response_length); test_buffer[0] = output_collect_left; // Very low frequency content of tail. This should essentially just preserve // the decay. low_pass_filter.Filter(test_buffer[0], &test_buffer[0]); const size_t max_location = static_cast<size_t>( std::max_element(test_buffer[0].begin(), test_buffer[0].end()) - test_buffer[0].begin()); // Stop before the very end of the tail as it goes to zero. const size_t end_point = max_location + kReverbFftSize; const size_t step_size = (end_point - max_location) / 20; // Test for decay. for (size_t i = max_location + step_size; i < end_point; i += step_size) { EXPECT_GT(std::abs(test_buffer[0][i - step_size]), std::abs(test_buffer[0][i])); } } void DecorrelatedTailsTestHelper(int sample_frequency, size_t frames_per_buffer) { // This value has been found empirically in MATLAB. const float kMaxCrossCorrelation = 12.0f; const std::vector<float> kUniformRt60s(kNumReverbOctaveBands, 0.7f); SpectralReverb reverb(sample_frequency, frames_per_buffer); reverb.SetRt60PerOctaveBand(kUniformRt60s.data()); std::vector<float> output_collect_left; std::vector<float> output_collect_right; ImpulseResponse(0.7f /*length [sec]*/, sample_frequency, frames_per_buffer, &reverb, &output_collect_left, &output_collect_right); // Find the absolute maximum elements of each vector. auto min_max_left = std::minmax_element(output_collect_left.begin(), output_collect_left.end()); size_t left_max_index = std::abs(*min_max_left.first) > std::abs(*min_max_left.second) ? (min_max_left.first - output_collect_left.begin()) : (min_max_left.second - output_collect_left.begin()); auto min_max_right = std::minmax_element(output_collect_right.begin(), output_collect_right.end()); size_t right_max_index = std::abs(*min_max_right.first) > std::abs(*min_max_right.second) ? (min_max_right.first - output_collect_right.begin()) : (min_max_right.second - output_collect_right.begin()); // Take a sample of the tails for cross correlation. AudioBuffer pair(kNumStereoChannels, kReverbFftSize); for (size_t i = 0; i < kReverbFftSize; ++i) { pair[0][i] = output_collect_left[i + left_max_index] / output_collect_left[left_max_index]; pair[1][i] = output_collect_right[i + right_max_index] / output_collect_right[right_max_index]; } // The cross correlation is not normalized. Thus we can expect a very small // value. Naturally, if the RT60 inputs are changed the expected value would // thus be different. const float max_xcorr = MaxCrossCorrelation(pair[0], pair[1]); EXPECT_LT(max_xcorr, kMaxCrossCorrelation); } } // namespace // Tests that the stereo output from the Reverbs Process fuction has the // expected properties of predelay and length. TEST(SpectralReverbTest, StereoOutputTest) { StereoOutputTestHelper(kSampleFrequency24, kFramesPerBuffer512); StereoOutputTestHelper(kSampleFrequency24, kFramesPerBuffer2048); StereoOutputTestHelper(kSampleFrequency24, kFramesPerBuffer713); StereoOutputTestHelper(kSampleFrequency16, kFramesPerBuffer512); StereoOutputTestHelper(kSampleFrequency16, kFramesPerBuffer2048); StereoOutputTestHelper(kSampleFrequency16, kFramesPerBuffer713); } // Tests that the stereo output from the Reverb's Process function has the // output of all zeros when the RT60 values are all zero. TEST(SpectralReverbTest, ZeroRt60Test) { const float kZeroRt = 0.0f; const float kBelowMinRt = 0.12f; ZeroRt60TestHelper(kSampleFrequency24, kZeroRt); ZeroRt60TestHelper(kSampleFrequency16, kBelowMinRt); ZeroRt60TestHelper(kSampleFrequency16, kZeroRt); ZeroRt60TestHelper(kSampleFrequency16, kBelowMinRt); } // Tests that the tail is decaying over time. TEST(SpectralReverbTest, TailDecayTest) { TailDecayTestHelper(kSampleFrequency24, kFramesPerBuffer512); TailDecayTestHelper(kSampleFrequency24, kFramesPerBuffer2048); TailDecayTestHelper(kSampleFrequency16, kFramesPerBuffer512); TailDecayTestHelper(kSampleFrequency16, kFramesPerBuffer2048); } // Tests that the stereo tail pairs are highy decorrelated. TEST(SpectralReverbTest, DecorrelatedTailsTest) { DecorrelatedTailsTestHelper(kSampleFrequency24, kFramesPerBuffer512); DecorrelatedTailsTestHelper(kSampleFrequency24, kFramesPerBuffer2048); DecorrelatedTailsTestHelper(kSampleFrequency24, kFramesPerBuffer713); DecorrelatedTailsTestHelper(kSampleFrequency16, kFramesPerBuffer512); DecorrelatedTailsTestHelper(kSampleFrequency16, kFramesPerBuffer2048); DecorrelatedTailsTestHelper(kSampleFrequency16, kFramesPerBuffer713); } // Tests that the gain parameter behaves as expected. TEST(SpecralReverbTest, GainTest) { const float kReverbLength = 0.5f; const float kGain = 100.0f; const float kGainEpsilon = 0.32f; const std::vector<float> kUniformRt60s(kNumReverbOctaveBands, kReverbLength); SpectralReverb reverb(kSampleFrequency24, kFramesPerBuffer512); reverb.SetRt60PerOctaveBand(kUniformRt60s.data()); // Calculate scaled and unscaled impulse responses. std::vector<float> output_left; std::vector<float> output_right; ImpulseResponse(kReverbLength, kSampleFrequency24, kFramesPerBuffer512, &reverb, &output_left, &output_right); std::vector<float> output_left_scaled; reverb.SetGain(kGain); ImpulseResponse(kReverbLength, kSampleFrequency24, kFramesPerBuffer512, &reverb, &output_left_scaled, &output_right); // Determine the max absolute entry in each impulse response. std::transform(output_left.begin(), output_left.end(), output_left.begin(), static_cast<float (*)(float)>(&std::abs)); std::transform(output_left_scaled.begin(), output_left_scaled.end(), output_left_scaled.begin(), static_cast<float (*)(float)>(&std::abs)); const float max_unscaled = *std::max_element(output_left.begin(), output_left.end()); const float max_scaled = *std::max_element(output_left_scaled.begin(), output_left_scaled.end()); EXPECT_GT(max_scaled, max_unscaled); EXPECT_NEAR((max_unscaled / max_scaled) / (1.0f / kGain), 1.0f, kGainEpsilon); } // Tests that when the feedback values are all ~0.0f, no processing is // performed (output is all zero). Also tests that if even one of the rt60s // result in a non zero feedback that the result will be non zero. TEST(SpectralReverbTest, DisabledProcessingTest) { const float kReverbLength = 0.1f; const std::vector<float> kUniformRt60s(kNumReverbOctaveBands, kReverbLength); SpectralReverb reverb(kSampleFrequency24, kFramesPerBuffer512); reverb.SetRt60PerOctaveBand(kUniformRt60s.data()); std::vector<float> output_left; std::vector<float> output_right; ImpulseResponse(kReverbLength, kSampleFrequency24, kFramesPerBuffer512, &reverb, &output_left, &output_right); for (size_t i = 0; i < output_left.size(); ++i) { EXPECT_FLOAT_EQ(output_left[i], 0.0f); EXPECT_FLOAT_EQ(output_right[i], 0.0f); } // Test a non zero case. const float kLongerReverbLength = 0.4f; std::vector<float> rt60s(kNumReverbOctaveBands, 0.0f); rt60s[0] = kLongerReverbLength; output_left.resize(0); output_right.resize(0); reverb.SetRt60PerOctaveBand(rt60s.data()); ImpulseResponse(kReverbLength, kSampleFrequency24, kFramesPerBuffer512, &reverb, &output_left, &output_right); const float sum_left = std::accumulate(output_left.begin(), output_left.end(), 0.0f); EXPECT_NE(sum_left, 0.0f); const float sum_right = std::accumulate(output_right.begin(), output_right.end(), 0.0f); EXPECT_NE(sum_right, 0.0f); // Set gain to zero and test again. output_left.resize(0); output_right.resize(0); reverb.SetGain(0.0f); ImpulseResponse(kReverbLength, kSampleFrequency24, kFramesPerBuffer512, &reverb, &output_left, &output_right); for (size_t i = 0; i < output_left.size(); ++i) { EXPECT_FLOAT_EQ(output_left[i], 0.0f); EXPECT_FLOAT_EQ(output_right[i], 0.0f); } } } // namespace vraudio
5edc4fd05997eb1dbab0d858db6b7ac2d66fca49
7dca8fc2aa415c6aef959126e268085a28781db1
/SSM_practice/practice-day1/solve/2018.cc
a6fb2a6a826357338811ef9b9c21e8118b4a4f5f
[]
no_license
Gnob/algorithm
e94ccaf0975568a76bebeb43f0c94f81a3366dd4
266b4cc966ee3648ece5380fdb0d31fdfcb0e719
refs/heads/master
2021-08-03T02:20:53.773013
2016-07-15T16:46:55
2016-07-15T16:46:55
60,790,768
0
0
null
null
null
null
UTF-8
C++
false
false
435
cc
2018.cc
/* [bdoc #two-pointer] [/bdoc] */ #include <iostream> using namespace std; int main() { int N; cin >> N; int left, right; left = right = 1; int sum = 1; int cnt = 1; while (right < N &&left <= right) { if (sum < N) { right++; sum += right; } else if (N < sum) { sum -= left; left++; } else if (right - left >= 1) { cnt++; right++; sum += right; } else break; } cout << cnt; }
263f3869aed24142cb177539a7a3d1c60a3ba458
00fe5140380a28ec51b1da703589eaca40b3f071
/hawi.cpp
908bb99f0960f8704ff79b42cf8c8b0ecb7a989e
[]
no_license
SecC-SWEG2012Batch-G1/admin-menu
0072cb77257096e7e6d9526659c79019ccbc15c4
7a97de1daf2427f822fb12d69a1634c063843695
refs/heads/main
2023-07-19T21:02:49.374250
2021-09-04T13:05:18
2021-09-04T13:05:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,031
cpp
hawi.cpp
#include<iostream> using namespace std; struct product{ int product_id; string product_id_add; string product_name; int quantity; float price; float discount;//by percent string product_type; }add_pro; void add_product(product added_pro); //void show_add_product(product added_pro); void Admin_menu(){ int option; system("cls"); cout<<"\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"; cout<<"\n\tPress 1 to ADD PRODUCT"; cout<<"\n\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"; cout<<"\n\n\tOption: "; cin>>option; if(option==1){ added_product(add_pro); } system("cls"); cout<<"\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"; cout<<"\n\tPress 2 to DISPLAY PRODUCT"; cout<<"\n\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"; cout<<"\n\n\tOption: "; cin>>option; if(option==2){ show_add_product(add_pro); } } int main(){ int option; Admin_menu(); } void add_product(product added_pro){ product add[100]; char press; int num; cout<<"********************** The programm already have clothes,shoes and bags. ****************************\n"; cout<<"********************* Do you want to add another type of product?"<<endl; cout<<"Press Y to continue or N to go back to menu\n"; cin>>press; if(press='Y'){ cout<<"What is the your Product type: "<<endl; cin>>added_pro.product_type; cout<<"How many products are their in your product type: "<<endl; cin>>num; for(int i=0;i<num;i++){ cout<<"The product in "<<i+1<<endl; cout<<"Enter the ID of the Product : "; cin>>add[i].product_id_add; cout<<"The Name of the Product : "; cin>>add[i].product_name; cout<<"The price of the product : "; cin>>add[i].price; cout<<"THe quantity of your product :"; cin>>add[i].quantity; cout<<"The dicount of the Product : "; cin>>add[i].discount; cout<<endl; } } }
e703a07f6117906c9877983cd023ad2a1e5e73cb
f3a9174535cd7e76d1c1e0f0fa1a3929751fb48d
/SDK/PVR_AK_AnimBlueprint_functions.cpp
20f0498b194100d8e58cf2485287b9d5a3b60c68
[]
no_license
hinnie123/PavlovVRSDK
9fcdf97e7ed2ad6c5cb485af16652a4c83266a2b
503f8d9a6770046cc23f935f2df1f1dede4022a8
refs/heads/master
2020-03-31T05:30:40.125042
2020-01-28T20:16:11
2020-01-28T20:16:11
151,949,019
5
2
null
null
null
null
UTF-8
C++
false
false
3,543
cpp
PVR_AK_AnimBlueprint_functions.cpp
// PavlovVR (Dumped by Hinnie) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function AK_AnimBlueprint.AK_AnimBlueprint_C.EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_713C42934E6311C225B3EF9A60CFBB94 // (BlueprintEvent) void UAK_AnimBlueprint_C::EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_713C42934E6311C225B3EF9A60CFBB94() { static auto fn = UObject::FindObject<UFunction>("Function AK_AnimBlueprint.AK_AnimBlueprint_C.EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_713C42934E6311C225B3EF9A60CFBB94"); UAK_AnimBlueprint_C_EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_713C42934E6311C225B3EF9A60CFBB94_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function AK_AnimBlueprint.AK_AnimBlueprint_C.EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_17B34C454E1B0DA98A81A897B710DE49 // (BlueprintEvent) void UAK_AnimBlueprint_C::EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_17B34C454E1B0DA98A81A897B710DE49() { static auto fn = UObject::FindObject<UFunction>("Function AK_AnimBlueprint.AK_AnimBlueprint_C.EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_17B34C454E1B0DA98A81A897B710DE49"); UAK_AnimBlueprint_C_EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_17B34C454E1B0DA98A81A897B710DE49_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function AK_AnimBlueprint.AK_AnimBlueprint_C.EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_BA429F4B44AC95B5AA3D538F165FBED3 // (BlueprintEvent) void UAK_AnimBlueprint_C::EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_BA429F4B44AC95B5AA3D538F165FBED3() { static auto fn = UObject::FindObject<UFunction>("Function AK_AnimBlueprint.AK_AnimBlueprint_C.EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_BA429F4B44AC95B5AA3D538F165FBED3"); UAK_AnimBlueprint_C_EvaluateGraphExposedInputs_ExecuteUbergraph_AK_AnimBlueprint_AnimGraphNode_ModifyBone_BA429F4B44AC95B5AA3D538F165FBED3_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function AK_AnimBlueprint.AK_AnimBlueprint_C.ExecuteUbergraph_AK_AnimBlueprint // (Final) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UAK_AnimBlueprint_C::ExecuteUbergraph_AK_AnimBlueprint(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function AK_AnimBlueprint.AK_AnimBlueprint_C.ExecuteUbergraph_AK_AnimBlueprint"); UAK_AnimBlueprint_C_ExecuteUbergraph_AK_AnimBlueprint_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
9148b7d42fc6fc8f2ebf61dbed56a5c79c1987e6
8ec51293aa31a1a2c8502cd9a6c0bcce55976e3b
/treap/treap.cpp
0d3d4edd483169e5c89792f965ba8764c69debd6
[]
no_license
learn22coding/templates
beefef411b706974f8ca899f3c18a600ffdc106b
475c58776019a777497fbb845f08b0df3e731f5d
refs/heads/master
2023-03-16T12:26:04.967220
2020-08-11T02:29:05
2020-08-11T02:29:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,820
cpp
treap.cpp
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<cstdlib> #include<ctime> #define pre(x) kth(root,rank(root,x)-1) #define next(x) kth(root,rank(root,x+1)) #define update(x) s[x]=s[ch[x][0]]+s[ch[x][1]]+cnt[x] using namespace std; int n,tot,root; int ch[100010][2],rnd[100010],val[100010],s[100010],cnt[100010]; void rotate(int &p,int k) { int x=ch[p][k]; ch[p][k]=ch[x][k^1]; ch[x][k^1]=p; update(p); update(x); p=x; } void insert(int &p,int x) { if(!p) { p=++tot; val[p]=x; cnt[p]=1; rnd[p]=rand(); } else if(val[p]==x) cnt[p]++; else { int d=x>val[p]; insert(ch[p][d],x); if(rnd[ch[p][d]]>rnd[p]) rotate(p,d); } update(p); } void del(int &p,int x) { if(val[p]==x) { if(cnt[p]>1) cnt[p]--; else if(!(ch[p][0]&&ch[p][1])) p=ch[p][0]|ch[p][1]; else { // cnt[p]=0; int d=rnd[ch[p][1]]>rnd[ch[p][0]]; rotate(p,d); del(ch[p][d^1],x); } } else { int d=x>val[p]; del(ch[p][d],x); } update(p); } int rank(int p,int x) { if(x==val[p]||!p) return s[ch[p][0]]+1; if(x<val[p]) return rank(ch[p][0],x); return s[ch[p][0]]+cnt[p]+rank(ch[p][1],x); } int kth(int p,int x) { int sum=s[ch[p][0]]; if(x>=sum+1&&x<=sum+cnt[p]) return val[p]; if(x<=sum) return kth(ch[p][0],x); return kth(ch[p][1],x-sum-cnt[p]); } int main() { #ifndef ONLINE_JUDGE freopen("treap.in","r",stdin); freopen("treap.out","w",stdout); #endif srand(time(0)); scanf("%d",&n); for(int i=1;i<=n;i++) { int a,b; scanf("%d%d",&a,&b); // printf("a:%d ",a); if(a==1) insert(root,b); else if(a==2) del(root,b); else if(a==3) printf("%d\n",rank(root,b)); else if(a==4) printf("%d\n",kth(root,b)); else if(a==5) printf("%d\n",pre(b)); else if(a==6) printf("%d\n",next(b)); // fflush(stdout); } return 0; }
8bcc07bf4c83e42e215422ab41faadd498afcb1c
3fb4a4450fee9427e0c17f7e4db58a07d38d88e6
/BST/BST.h
bd6c143db47c3827e542289b8117e1d4f11a1e0d
[]
no_license
weienjun/GetHub
bae149506285cfdbd3458310915f66eb0b4c29d4
250aaa32fb582023d9dd45e67dd281bc7b2d8230
refs/heads/master
2021-10-08T18:48:39.135895
2018-12-16T06:48:22
2018-12-16T06:48:22
111,115,489
0
1
null
null
null
null
GB18030
C++
false
false
10,502
h
BST.h
#pragma once #include<iostream> #include<vector> #include<algorithm> using namespace std; template<class T,class V> struct BSTNode{ T _key; V _value; size_t _count; //节点作为根节点对应的节点数目 BSTNode<T,V> *_left; BSTNode<T,V> *_right; BSTNode(T key,V value) :_key(key) ,_value(value) ,_count(1) ,_left(NULL) ,_right(NULL) {} }; template<class T,class V> class BSTree { public: typedef struct BSTNode<T,V> BSTNode; BSTree() :_root(NULL) {} BSTree(const BSTree &bst) :_root(NULL) { _root = _copy(_root,bst._root); //深拷贝 } BSTree &operator=(const BSTree &bst) { if (this != &bst) { BSTree<T,V> tmp(bst); swap(this->_root, tmp._root); //注:此处交换的是root的地址 } return *this; } //后序遍历删除 ~BSTree() { Delete(_root); _root = NULL; } int Size() { if (_root) { return _root->_count; } } int Size(BSTNode *node) { if (node) { return node->_count; } return 0; } void Delete(BSTNode* root) { if (root) { Delete(root->_left); Delete(root->_right); delete root; root = NULL; } } //树拷贝 BSTNode* _copy(BSTNode *root, const BSTNode *bst) { if (bst == NULL) return NULL; root = new BSTNode(bst->_key,bst->_value); root->_count = bst->_count; if (bst->_left != NULL) { (root)->_left = _copy(root, bst->_left); } if (bst->_right) { (root)->_right = _copy(root, bst->_right); } return root; } /* void insert(T key,V value) { BSTNode *newNode = new BSTNode(key,value); if (_root == NULL) { _root = newNode; } BSTNode *InNode = _root; BSTNode *cur = _root; while (cur) { InNode = cur; if (cur->_key > key) { cur->_count++; cur = cur->_left; } else if (cur->_key < key) { cur->_count++; cur = cur->_right; } else { //重复key,退出 cur->_value = value; return; } } if (InNode->_key > key) { InNode->_left = newNode; } else { InNode->_right = newNode; } // _root->_count = Size(_root)+1; } */ void insert(T key, V value) { _root = _insert(_root, key, value); } BSTNode* _insert(BSTNode* root,T key, V value) { if (root == NULL) { return new BSTNode(key, value); } if (root->_key > key) { root->_left = _insert(root->_left, key, value); } else if (root->_key < key) { root->_right = _insert(root->_right, key, value); } else { root->_value = value; } root->_count = Size(root->_left) + Size(root->_right) + 1; return root; } void InoPrint() { _InoPrint(_root); //中序遍历 } void _InoPrint(BSTNode *root) { if (root) { _InoPrint(root->_left); cout << "key:" << root->_key << " value:" << root->_value << " " << endl; _InoPrint(root->_right); } } //查找 V Find(T key) { BSTNode *cur = _root; while (cur) { if (cur->_key == key) { return cur->_value; }else if (cur->_key > key) { cur = cur->_left; } else { cur = cur->_right; } } return 0; } //查找向上取整的数 V findNearUp(T key) { BSTNode *tmp = find_near_up(_root, key); if (tmp) { return tmp->_key; } else { return -1; } } BSTNode* find_near_up(BSTNode* root, T key) { if (root == NULL) { return NULL; } if (root->_key == key) { return root; } if (root->_key < key) { //root->key小于key值,则比key大值在右子树。 return find_near_up(root->_right, key); } //右子树未找到 BSTNode *cur = find_near_up(root->_left, key); //root->key 大与key,或右子树未找到,则在左子树找最接近key的值 if (cur != NULL) return cur; //找到相等的值,则返回该节点 else return root; //未找到,则根节点为最接近key的值 } V findNearDown(T key) { BSTNode* tmp = find_near_down(_root, key); if (tmp) { return tmp->_key; } return -1; } BSTNode* find_near_down(BSTNode *root, T key) { if (root == NULL) return NULL; if (root->_key == key) { return root; } if (root->_key > key) { //root->key > key,则最接近小于key的值在左子树 return find_near_down(root->_left, key); } BSTNode *cur = find_near_down(root->_right, key); //root->key < key,最接近key的值在右子树 if (cur) return cur; //找到最接近的值 else return root; //根为最接近的值 } //查找第k大小的值。 //如果左子数的节点个数 > k,则在左子树 //如果左子的个数 < k 则在右子树。 V find_sizeth(int k){ return _find_sizeth(_root, k - 1); } V _find_sizeth(BSTNode* root, int k) { if (root == NULL) { return 0; } int size_left = Size(root->_left); if (size_left == k) return root->_value; if (size_left > k) { return _find_sizeth(root->_left, k); } if (size_left < k) { return _find_sizeth(root->_right, k - size_left - 1); } } //查找key的排名 int rank(T key) { return _rank(_root, key)+1; //此处统计从0算起 } int _rank(BSTNode *root,T key) { if (root == NULL) { return -1; } if (root->_key < key) { //右子树节点的排名=左子树节点个数+1(根节点)+右子树 int size_right = _rank(root->_right, key); if (size_right < 0) { //注:小于0,则说明未找到该数据,直接退出,不再加上之前计算的值。 return size_right; } else { return Size(root->_left) + 1 + size_right; } } else if(root->_key > key){ return _rank(root->_left, key); } else { return Size(root->_left); } } //节点删除 //删除最小节点的问题。 //向左遍历到最左的节点,将其上一个节点指向该节点不为空的节点上。删除该节点 //注方向与原来的方向保持一致,同时更新size值 void deleteMin() { BSTNode *del = NULL; _root = _deleteMin(_root,del); delete del; } //递归查找删除节点,并从树中移除该节点 BSTNode* _deleteMin(BSTNode *root,BSTNode *&del) { if (root->_left == NULL) { del = root; return root->_right; } root->_left = _deleteMin(root->_left,del); root->_count = Size(root->_left) + Size(root->_right) + 1; //重新计算节点个数 return root; } V keyMin() { BSTNode* tmp = _keyMin(_root); if (tmp) { return tmp->_key; } else { return -1; } } BSTNode* _keyMin(BSTNode *root) { if (root == NULL) { return NULL; } if (root->_left == NULL) { return root; } else { return _keyMin(root->_left); } } //输出某范围的数据min~max void minToMax(T min, T max) { _minToMax(_root, min, max); } void _minToMax(BSTNode *root, T min, T max) { if (root == NULL) { return; } if (root->_key > min) { _minToMax(root->_left, min, max); } if (min <= root->_key && max > root->_key) { cout << root->_key << endl; } if (root->_key < max) { _minToMax(root->_right, min, max); } } //删除任意某节点 //删除节点只有左子树/右子树之一,删除节点,并让上一个节点指向不为空的左/右子树,方法同上 //删除左右子树都不为空的节点: //方法1:在删除节点的左子树中找最最大节点作为替换节点,与删除节点进行数据交换,删除交换节点,方法同删除一个子树节点 //方法2:删除节点的右子树最小值替换删除节点,修改替换节点的左右指针域。删除替换节点。 void deleteKey(T key) { //_deleteKey(_root, key); _deleteKey2(_root, key); } //方法2: //寻找删除节点 BSTNode* _deleteKey2(BSTNode* root, T key) { if (root == NULL) { return NULL; } //寻找删除节点 if (root->_key > key) { root->_left = _deleteKey2(root->_left, key); } else if (root->_key < key) { root->_right = _deleteKey2(root->_right, key); } else { //找到删除节点 if (root->_left == NULL) { return root->_right; } else if (root->_right == NULL) { return root->_left; } else { //左右节点都不为空 BSTNode *del = root; del->_right = _deleteMin(del->_right,root); //找出最小节点,并更新删除节点的右,并摘除,注:并未析构最小节点, root->_right = del->_right; root->_left = del->_left; delete del; } } root->_count = Size(root->_left) + Size(root->_right) + 1; //更新节点个数 return root; //返回替换后的节点 } bool _deleteKey(BSTNode *&root, T key) { //注:存在删除根节点的问题,此处使用二级指针。 if (root == NULL) { return false; } if (root->_key > key) { _deleteKey(root->_left, key); } else if (root->_key < key) { _deleteKey(root->_right, key); } else { BSTNode *tmp = root; if (root->_left == NULL) { root = root->_right; delete tmp; tmp = NULL; } else if(root->_right == NULL){ root = root->_left; delete tmp; tmp = NULL; } else { BSTNode* right_min = _keyMin(root->_right); _swap(root, right_min); _deleteKey(root->_right, right_min->_key); } if (root) { root->_count = Size(root->_left) + Size(root->_right) + 1; } return true; } if (root) { root->_count = Size(root->_left) + Size(root->_right) + 1; } } void _swap(BSTNode* left, BSTNode* right) { swap(left->_key, right->_key); swap(left->_value, right->_value); } private: BSTNode *_root; }; void test_BSTree() { BSTree<float,float> bst; bst.insert(1,1); cout << bst.Size() << endl; bst.insert(2, 2); cout << bst.Size() << endl; bst.InoPrint(); BSTree<float,float> bst2(bst); cout << bst2.Size() << endl; bst2.insert(3, 2.1); bst2.InoPrint(); bst.InoPrint(); cout << bst2.Size() << endl; BSTree<float,float> bst3; //bst3 = bst; cout << "bst3" << endl; bst3.insert(3, 4.2); bst3.insert(2, 10); bst3.insert(1.9, 1.8); bst3.insert(4.1, 2.2); bst3.insert(3.2, 3.4); bst3.insert(5, 5); bst3.InoPrint(); cout << "bst" << endl; bst.InoPrint(); cout << bst.Size() << endl; cout << bst3.Size() << endl; cout << "find_near_up" << endl; cout << bst3.findNearUp(3.5) << endl; cout << "find_near_dowan" << endl; cout << bst3.findNearDown(3.8) << endl; cout << "rank" << endl; cout << bst3.rank(3.2) << endl; cout << bst3.rank(2.5) << endl; cout << "find_sizeth" << endl; cout << bst3.find_sizeth(6) << endl; bst3.deleteMin(); bst3.InoPrint(); cout << "keyMin" << endl; cout << bst3.keyMin() << endl; bst3.InoPrint(); cout << "deleteKye" << endl; bst3.deleteKey(4.1); bst3.InoPrint(); cout << "minToMax" << endl; bst3.minToMax(3, 4); return; }
8da11e58f12c7e00b1fa8eae441a897b95507b72
39cdb6ff35231538ef25c565181981ccf237cc30
/programmers_level_2/together_photo.cpp
5d157d3af01ad1296bdd6e64978e9d152bbb4e97
[]
no_license
dittoo8/algorithm_cpp
51b35321f6cf16c8c1c259af746a9f35d5ba8b76
d9cdda322d3658ffc07744e4080c71faeee6370c
refs/heads/master
2023-08-03T14:49:08.808253
2021-02-16T04:13:53
2021-02-16T04:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,568
cpp
together_photo.cpp
#include <iostream> #include <string> #include <vector> #include <algorithm> #include <cmath> using namespace std; // 전역 변수를 정의할 경우 함수 내에 초기화 코드를 꼭 작성해주세요. int solution(int n, vector<string> data) { int answer = 0; vector<char> friends; friends.push_back('A'); friends.push_back('C'); friends.push_back('F'); friends.push_back('J'); friends.push_back('M'); friends.push_back('N'); friends.push_back('R'); friends.push_back('T'); sort(friends.begin(),friends.end()); do{ bool check = true; for(int i=0;i<data.size();i++){ char l = data[i][0]; char r = data[i][2]; char sign = data[i][3]; int dist = data[i][4]-'0'+1; int lIdx, rIdx; for(int j=0;j<8;j++){ if(friends[j]==l) lIdx = j; if(friends[j]==r) rIdx = j; } switch(sign){ case '=': if(abs(lIdx-rIdx)!=dist) check = false; break; case '<': if(abs(lIdx-rIdx)>=dist) check = false; break; case '>': if(abs(lIdx-rIdx)<=dist) check = false; break; } if(!check) break; } if(check) answer++; }while (next_permutation(friends.begin(),friends.end())); return answer; } int main(){ vector<string> v; v.push_back("N~F=0"); v.push_back("R~T>2"); cout << solution(2,v) << endl; return 0; }
6e6131e6bb5bbe059651fd47f42647fa1e52075e
a8eaebbb9f24fc92c19fc71880c1569246427dc0
/_10032.c++
9263af7e7e878ff2bafeec3d8d5ce0fc46404b0d
[]
no_license
KingJoo/swExpertAcademy
aa1e6bca33c7a929eb99b993175315f3fe2b2caa
bc7ffdfc1cbfc6e942394da10dd0d8489a025ed3
refs/heads/master
2023-08-10T21:38:33.559194
2021-09-28T13:42:39
2021-09-28T13:42:39
410,418,480
0
0
null
null
null
null
UTF-8
C++
false
false
171
_10032.c++
#include<cstdio> int T,n,k; int main(){ scanf("%d",&T); for(int t=1;t<=T;t++){ scanf("%d%d",&n,&k); printf("#%d %d\n",t,n%k==0?0:1); } return 0; }
7ac6890142ca360652026ab6542813c031f7596f
0019f0af5518efe2144b6c0e63a89e3bd2bdb597
/antares/src/servers/app/FontStyle.cpp
ca86f40cd6bd1c0ddfa403e1070b5afcd0f98917
[]
no_license
mmanley/Antares
5ededcbdf09ef725e6800c45bafd982b269137b1
d35f39c12a0a62336040efad7540c8c5bce9678a
refs/heads/master
2020-06-02T22:28:26.722064
2010-03-08T21:51:31
2010-03-08T21:51:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,739
cpp
FontStyle.cpp
/* * Copyright 2001-2008, Antares. * Distributed under the terms of the MIT License. * * Authors: * DarkWyrm <bpmagic@columbus.rr.com> * Axel Dörfler, axeld@pinc-software.de */ /** Classes to represent font styles and families */ #include "FontFamily.h" #include "ServerFont.h" #include "FontManager.h" #include <FontPrivate.h> #include <Entry.h> static BLocker sFontLock("font lock"); /*! \brief Constructor \param filepath path to a font file \param face FreeType handle for the font file after it is loaded - it will be kept open until the FontStyle is destroyed */ FontStyle::FontStyle(node_ref& nodeRef, const char* path, FT_Face face) : fFreeTypeFace(face), fName(face->style_name), fPath(path), fNodeRef(nodeRef), fFamily(NULL), fID(0), fBounds(0, 0, 0, 0), fFace(_TranslateStyleToFace(face->style_name)) { fName.Truncate(B_FONT_STYLE_LENGTH); // make sure this style can be found using the Be API fHeight.ascent = (double)face->ascender / face->units_per_EM; fHeight.descent = (double)-face->descender / face->units_per_EM; // FT2's descent numbers are negative. Be's is positive // FT2 doesn't provide a linegap, but according to the docs, we can // calculate it because height = ascending + descending + leading fHeight.leading = (double)(face->height - face->ascender + face->descender) / face->units_per_EM; } FontStyle::~FontStyle() { // make sure the font server is ours if (fFamily != NULL && gFontManager->Lock()) { gFontManager->RemoveStyle(this); gFontManager->Unlock(); } FT_Done_Face(fFreeTypeFace); } uint32 FontStyle::Hash() const { return (ID() << 16) | fFamily->ID(); } bool FontStyle::CompareTo(Hashable& other) const { // our hash values are unique (unless you have more than 65536 font // families installed...) return Hash() == other.Hash(); } bool FontStyle::Lock() { return sFontLock.Lock(); } void FontStyle::Unlock() { sFontLock.Unlock(); } void FontStyle::GetHeight(float size, font_height& height) const { height.ascent = fHeight.ascent * size; height.descent = fHeight.descent * size; height.leading = fHeight.leading * size; } /*! \brief Returns the path to the style's font file \return The style's font file path */ const char* FontStyle::Path() const { return fPath.Path(); } /*! \brief Updates the path of the font style in case the style has been moved around. */ void FontStyle::UpdatePath(const node_ref& parentNodeRef) { entry_ref ref; ref.device = parentNodeRef.device; ref.directory = parentNodeRef.node; ref.set_name(fPath.Leaf()); fPath.SetTo(&ref); } /*! \brief Unlike BFont::Flags() this returns the extra flags field as used in the private part of BFont. */ uint32 FontStyle::Flags() const { uint32 flags = uint32(Direction()) << B_PRIVATE_FONT_DIRECTION_SHIFT; if (IsFixedWidth()) flags |= B_IS_FIXED; if (IsFullAndHalfFixed()) flags |= B_PRIVATE_FONT_IS_FULL_AND_HALF_FIXED; if (TunedCount() > 0) flags |= B_HAS_TUNED_FONT; if (HasKerning()) flags |= B_PRIVATE_FONT_HAS_KERNING; return flags; } /*! \brief Updates the given face to match the one from this style The specified font face often doesn't match the exact face of a style. This method will preserve the attributes of the face that this style does not alter, and will only update the attributes that matter to this style. The font renderer could then emulate the other face attributes taking this style as a base. */ uint16 FontStyle::PreservedFace(uint16 face) const { // TODO: make this better face &= ~(B_REGULAR_FACE | B_BOLD_FACE | B_ITALIC_FACE); face |= Face(); return face; } status_t FontStyle::UpdateFace(FT_Face face) { if (!sFontLock.IsLocked()) { debugger("UpdateFace() called without having locked FontStyle!"); return B_ERROR; } // we only accept the face if it hasn't change its style BString name = face->style_name; name.Truncate(B_FONT_STYLE_LENGTH); if (name != fName) return B_BAD_VALUE; FT_Done_Face(fFreeTypeFace); fFreeTypeFace = face; return B_OK; } void FontStyle::_SetFontFamily(FontFamily* family, uint16 id) { fFamily = family; fID = id; } uint16 FontStyle::_TranslateStyleToFace(const char* name) const { if (name == NULL) return 0; BString string(name); uint16 face = 0; if (string.IFindFirst("bold") >= 0) face |= B_BOLD_FACE; if (string.IFindFirst("italic") >= 0 || string.IFindFirst("oblique") >= 0) face |= B_ITALIC_FACE; if (string.IFindFirst("condensed") >= 0) face |= B_CONDENSED_FACE; if (string.IFindFirst("light") >= 0) face |= B_LIGHT_FACE; if (string.IFindFirst("heavy") >= 0 || string.IFindFirst("black") >= 0) face |= B_HEAVY_FACE; if (face == 0) return B_REGULAR_FACE; return face; }
29eed442d9bdb95290fc22267f2bd532b39a9ae8
fa889d051a1b3c4d861fb06b10aa5b2e21f97123
/kbe/src/server/tools/guiconsole/guiconsoleDlg.cpp
45f821d077b127fdd20cb477055185a39ae4669e
[ "MIT", "LGPL-3.0-only" ]
permissive
BuddhistDeveloper/HeroLegendServer
bcaa837e3bbd6544ce0cf8920fd54a1a324d95c8
8bf77679595a2c49c6f381c961e6c52d31a88245
refs/heads/master
2022-12-08T00:32:45.623725
2018-01-15T02:01:44
2018-01-15T02:01:44
117,069,431
1
1
MIT
2022-11-19T15:58:30
2018-01-11T08:05:32
Python
GB18030
C++
false
false
47,932
cpp
guiconsoleDlg.cpp
// guiconsoleDlg.cpp : implementation file // #include "stdafx.h" #include "guiconsole.h" #include "guiconsoleDlg.h" #include "StartServerWindow.h" #include "network/bundle_broadcast.h" #include "network/message_handler.h" #include "server/components.h" #include "helper/console_helper.h" #include "xml/xml.h" #undef DEFINE_IN_INTERFACE #include "client_lib/client_interface.h" #define DEFINE_IN_INTERFACE #include "client_lib/client_interface.h" #undef DEFINE_IN_INTERFACE #include "baseapp/baseapp_interface.h" #define DEFINE_IN_INTERFACE #include "baseapp/baseapp_interface.h" #undef DEFINE_IN_INTERFACE #include "loginapp/loginapp_interface.h" #define DEFINE_IN_INTERFACE #include "loginapp/loginapp_interface.h" #undef DEFINE_IN_INTERFACE #include "cellapp/cellapp_interface.h" #define DEFINE_IN_INTERFACE #include "cellapp/cellapp_interface.h" #undef DEFINE_IN_INTERFACE #include "baseappmgr/baseappmgr_interface.h" #define DEFINE_IN_INTERFACE #include "baseappmgr/baseappmgr_interface.h" #undef DEFINE_IN_INTERFACE #include "dbmgr/dbmgr_interface.h" #define DEFINE_IN_INTERFACE #include "dbmgr/dbmgr_interface.h" #undef DEFINE_IN_INTERFACE #include "machine/machine_interface.h" #define DEFINE_IN_INTERFACE #include "machine/machine_interface.h" #undef DEFINE_IN_INTERFACE #include "cellappmgr/cellappmgr_interface.h" #define DEFINE_IN_INTERFACE #include "cellappmgr/cellappmgr_interface.h" #undef DEFINE_IN_INTERFACE #include "tools/logger/logger_interface.h" #define DEFINE_IN_INTERFACE #include "tools/logger/logger_interface.h" #undef DEFINE_IN_INTERFACE #include "tools/bots/bots_interface.h" #define DEFINE_IN_INTERFACE #include "tools/bots/bots_interface.h" #undef DEFINE_IN_INTERFACE #include "tools/interfaces/interfaces_interface.h" #define DEFINE_IN_INTERFACE #include "tools/interfaces/interfaces_interface.h" #ifdef _DEBUG #define new DEBUG_NEW #endif namespace KBEngine{ namespace ConsoleInterface{ Network::MessageHandlers messageHandlers; } } BOOL g_sendData = FALSE; class ConsoleExecCommandCBMessageHandlerEx : public KBEngine::ConsoleInterface::ConsoleExecCommandCBMessageHandler { public: virtual void handle(Network::Channel* pChannel, MemoryStream& s) { CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); std::string strarg; s.readBlob(strarg); dlg->onExecScriptCommandCB(pChannel, strarg); }; }; class ConsoleLogMessageHandlerEx : public KBEngine::ConsoleInterface::ConsoleLogMessageHandler { public: virtual void handle(Network::Channel* pChannel, MemoryStream& s) { CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); std::string str; s >> str; dlg->onReceiveRemoteLog(str); }; }; class ConsoleWatcherCBMessageHandlerEx : public KBEngine::ConsoleInterface::ConsoleWatcherCBMessageHandler { public: virtual void handle(Network::Channel* pChannel, MemoryStream& s) { CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); dlg->onReceiveWatcherData(s); }; }; class ConsoleProfileHandlerEx : public KBEngine::ConsoleInterface::ConsoleProfileHandler { public: virtual void handle(Network::Channel* pChannel, MemoryStream& s) { CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); dlg->onReceiveProfileData(s); }; }; class FindServersTask : public thread::TPTask { public: std::vector<COMPONENT_TYPE> findComponentTypes; FindServersTask(): thread::TPTask(), findComponentTypes() { CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); dlg->clearTree(); } FindServersTask(COMPONENT_TYPE findComponentType): thread::TPTask(), findComponentTypes() { CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); dlg->clearTree(); findComponentTypes.push_back(findComponentType); } virtual ~FindServersTask() { } virtual bool process() { //COMPONENT_TYPE findComponentTypes[] = {LOGGER_TYPE, BASEAPP_TYPE, CELLAPP_TYPE, BASEAPPMGR_TYPE, CELLAPPMGR_TYPE, LOGINAPP_TYPE, DBMGR_TYPE, BOTS_TYPE, UNKNOWN_COMPONENT_TYPE}; int ifind = 0; if(g_isDestroyed) return false; CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); while(true) { if(ifind >= (int)findComponentTypes.size() || g_isDestroyed) { //INFO_MSG("Componentbridge::process: not found %s, try again...\n", // COMPONENT_NAME_EX(findComponentType)); return false; } COMPONENT_TYPE findComponentType = findComponentTypes[ifind]; dlg->updateFindTreeStatus(); srand(KBEngine::getSystemTime()); uint16 nport = KBE_PORT_START + (rand() % 1000); Network::BundleBroadcast bhandler(dlg->networkInterface(), nport); if(!bhandler.good()) { KBEngine::sleep(10); nport = KBE_PORT_START + (rand() % 1000); continue; } if(bhandler.pCurrPacket() != NULL) { bhandler.pCurrPacket()->resetPacket(); } bhandler.newMessage(MachineInterface::onFindInterfaceAddr); MachineInterface::onFindInterfaceAddrArgs7::staticAddToBundle(bhandler, getUserUID(), getUsername(), dlg->componentType(), dlg->componentID(), (COMPONENT_TYPE)findComponentType, dlg->networkInterface().intaddr().ip, bhandler.epListen().addr().port); if(!bhandler.broadcast()) { ERROR_MSG("CguiconsoleDlg::OnTimer: broadcast error!\n"); ::AfxMessageBox(L"初始化错误:不能发送服务器探测包。"); return false; } MachineInterface::onBroadcastInterfaceArgs25 args; int32 timeout = 1000000; RESTART_RECV: if(bhandler.receive(&args, 0, timeout)) { bool isContinue = false; do { if(g_isDestroyed) return false; if(isContinue) { try { args.createFromStream(*bhandler.pCurrPacket()); }catch(MemoryStreamException &) { break; } } if(args.componentType == UNKNOWN_COMPONENT_TYPE) { //INFO_MSG("Componentbridge::process: not found %s, try again...\n", // COMPONENT_NAME_EX(findComponentType)); //ifind++; isContinue = true; continue; } INFO_MSG(fmt::format("CguiconsoleDlg::OnTimer: found {}, addr:{}:{}\n", COMPONENT_NAME_EX((COMPONENT_TYPE)args.componentType), inet_ntoa((struct in_addr&)args.intaddr), ntohs(args.intport))); Components::getSingleton().addComponent(args.uid, args.username.c_str(), (KBEngine::COMPONENT_TYPE)args.componentType, args.componentID, args.globalorderid, args.grouporderid, args.gus, args.intaddr, args.intport, args.extaddr, args.extport, args.extaddrEx, args.pid, args.cpu, args.mem, args.usedmem, args.extradata, args.extradata1, args.extradata2, args.extradata3); isContinue = true; }while(bhandler.pCurrPacket()->length() > 0); // 防止接收到的数据不是想要的数据 if(findComponentType == args.componentType) { //ifind++; if(g_isDestroyed) return false; dlg->updateTree(); } else { ERROR_MSG(fmt::format("CguiconsoleDlg::OnTimer: {} not found. receive data is error!\n", COMPONENT_NAME_EX((COMPONENT_TYPE)findComponentType))); } //timeout = 10000; goto RESTART_RECV; } else { ifind++; continue; } } return false; } virtual thread::TPTask::TPTaskState presentMainThread() { if(!g_isDestroyed) { CguiconsoleDlg* dlg = static_cast<CguiconsoleDlg*>(theApp.m_pMainWnd); dlg->updateTree(); } return thread::TPTask::TPTASK_STATE_COMPLETED; } }; // CAboutDlg dialog used for App About class CAboutDlg : public CDialog { public: CAboutDlg(); // Dialog Data enum { IDD = IDD_ABOUTBOX }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support // Implementation protected: DECLARE_MESSAGE_MAP() }; CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialog) END_MESSAGE_MAP() // CguiconsoleDlg dialog CguiconsoleDlg::CguiconsoleDlg(CWnd* pParent /*=NULL*/) : CDialog(CguiconsoleDlg::IDD, pParent), _componentType(CONSOLE_TYPE), _componentID(genUUID64()), _dispatcher(), _networkInterface(&_dispatcher), m_debugWnd(), m_logWnd(), m_statusWnd(), m_profileWnd(), m_watcherWnd(), m_spaceViewWnd(), m_graphsWindow(), m_isInit(false), m_historyCommand(), m_historyCommandIndex(0), m_isUsingHistroy(false), threadPool_() { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } void CguiconsoleDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_TAB1, m_tab); DDX_Control(pDX, IDC_TREE1, m_tree); } BEGIN_MESSAGE_MAP(CguiconsoleDlg, CDialog) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() //}}AFX_MSG_MAP ON_WM_TIMER() ON_WM_SIZING() ON_WM_SIZE() ON_NOTIFY(NM_RCLICK, IDC_TREE1, &CguiconsoleDlg::OnNMRClickTree1) ON_COMMAND(ID_32772, &CguiconsoleDlg::OnMenu_Update) ON_NOTIFY(TCN_SELCHANGE, IDC_TAB1, &CguiconsoleDlg::OnTcnSelchangeTab1) ON_NOTIFY(NM_CLICK, IDC_TREE1, &CguiconsoleDlg::OnNMClickTree1) ON_COMMAND(ID_32771, &CguiconsoleDlg::OnConnectRemoteMachine) ON_COMMAND(ID_HELP_ABOUT, &CguiconsoleDlg::OnHelpAbout) ON_COMMAND(ID_BUTTON32784, &CguiconsoleDlg::OnToolBar_Find) ON_COMMAND(ID_BUTTON32780, &CguiconsoleDlg::OnToolBar_StartServer) ON_COMMAND(ID_BUTTON32783, &CguiconsoleDlg::OnToolBar_StopServer) ON_WM_CLOSE() ON_WM_DESTROY() END_MESSAGE_MAP() // CguiconsoleDlg message handlers BOOL CguiconsoleDlg::OnInitDialog() { CDialog::OnInitDialog(); // Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range. ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != NULL) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // Set the icon for this dialog. The framework does this automatically // when the application's main window is not a dialog SetIcon(m_hIcon, TRUE); // Set big icon SetIcon(m_hIcon, FALSE); // Set small icon if(!m_ToolBar.CreateEx(this, TBSTYLE_FLAT , WS_CHILD | WS_VISIBLE | CBRS_ALIGN_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS, CRect(4,4,0,0)) ||!m_ToolBar.LoadToolBar(IDR_TOOLBAR1)) { return FALSE; } m_ToolBar.ShowWindow(SW_SHOW); RepositionBars(AFX_IDW_CONTROLBAR_FIRST, AFX_IDW_CONTROLBAR_LAST, 0); // TODO: Add extra initialization here _dispatcher.breakProcessing(false); ::SetTimer(m_hWnd, 1, 10, NULL); ::SetTimer(m_hWnd, 2, 100, NULL); ::SetTimer(m_hWnd, 3, 1000 * 20, NULL); m_isInit = true; m_tab.InsertItem(0, _T("Status"), 0); m_statusWnd.Create(IDD_STATUS, GetDlgItem(IDC_TAB1)); m_tab.InsertItem(1, _T("Debug"), 0); m_debugWnd.Create(IDD_DEBUG, GetDlgItem(IDC_TAB1)); m_tab.InsertItem(2, _T("Log"), 0); m_logWnd.Create(IDD_LOG, GetDlgItem(IDC_TAB1)); m_tab.InsertItem(3, _T("Profile"), 0); m_profileWnd.Create(IDD_PROFILE, GetDlgItem(IDC_TAB1)); m_tab.InsertItem(4, _T("Watcher"), 0); m_watcherWnd.Create(IDD_WATCHER, GetDlgItem(IDC_TAB1)); m_tab.InsertItem(5, _T("SpaceView"), 0); m_spaceViewWnd.Create(IDD_SPACEVIEW, GetDlgItem(IDC_TAB1)); m_tab.InsertItem(6, _T("Graphs"), 0); m_graphsWindow.Create(IDD_GRAPHS, GetDlgItem(IDC_TAB1)); DWORD styles = ::GetWindowLong(m_tree.m_hWnd, GWL_STYLE); styles |= TVS_HASLINES | TVS_LINESATROOT | TVS_SHOWSELALWAYS; ::SetWindowLong(m_tree.m_hWnd, GWL_STYLE, styles); loadHistory(); autoWndSize(); updateTree(); KBEngine::ConsoleInterface::messageHandlers.add("Console::onExecScriptCommandCB", new KBEngine::ConsoleInterface::ConsoleExecCommandCBMessageHandlerArgs1, NETWORK_VARIABLE_MESSAGE, new ConsoleExecCommandCBMessageHandlerEx); KBEngine::ConsoleInterface::messageHandlers.add("Console::onReceiveRemoteLog", new KBEngine::ConsoleInterface::ConsoleLogMessageHandlerArgsStream, NETWORK_VARIABLE_MESSAGE, new ConsoleLogMessageHandlerEx); KBEngine::ConsoleInterface::messageHandlers.add("Console::onReceiveWatcherData", new KBEngine::ConsoleInterface::ConsoleWatcherCBHandlerMessageArgsStream, NETWORK_VARIABLE_MESSAGE, new ConsoleWatcherCBMessageHandlerEx); KBEngine::ConsoleInterface::messageHandlers.add("Console::onReceiveProfileData", new KBEngine::ConsoleInterface::ConsoleProfileHandlerArgsStream, NETWORK_VARIABLE_MESSAGE, new ConsoleProfileHandlerEx); KBEngine::Network::Bundle::ObjPool().pMutex(new KBEngine::thread::ThreadMutex()); KBEngine::Network::TCPPacket::ObjPool().pMutex(new KBEngine::thread::ThreadMutex()); KBEngine::Network::UDPPacket::ObjPool().pMutex(new KBEngine::thread::ThreadMutex()); KBEngine::MemoryStream::ObjPool().pMutex(new KBEngine::thread::ThreadMutex()); threadPool_.createThreadPool(1, 1, 16); return TRUE; // return TRUE unless you set the focus to a control } void CguiconsoleDlg::onReceiveRemoteLog(std::string str) { m_logWnd.onReceiveRemoteLog(str); } void CguiconsoleDlg::historyCommandCheck() { if(m_historyCommand.size() > 50) m_historyCommand.pop_front(); if(m_historyCommandIndex < 0) m_historyCommandIndex = m_historyCommand.size() - 1; if(m_historyCommandIndex > (int)m_historyCommand.size() - 1) m_historyCommandIndex = 0; } CString CguiconsoleDlg::getHistoryCommand(bool isNextCommand) { if(m_isUsingHistroy) { if(isNextCommand) m_historyCommandIndex++; else m_historyCommandIndex--; } m_isUsingHistroy = true; historyCommandCheck(); if(m_historyCommand.size() == 0) return L""; return m_historyCommand[m_historyCommandIndex]; } HTREEITEM CguiconsoleDlg::hasCheckApp(COMPONENT_TYPE type) { HTREEITEM rootitem = m_tree.GetRootItem(); if(rootitem == NULL) return NULL; rootitem = m_tree.GetChildItem(rootitem); if(rootitem == NULL) return NULL; do { HTREEITEM childItem = m_tree.GetChildItem(rootitem); while(NULL != childItem) { COMPONENT_TYPE ctype = getTreeItemComponent(childItem); if(ctype == type) { if(m_tree.GetCheck(childItem)) return childItem; } childItem = m_tree.GetNextItem(childItem, TVGN_NEXT); } }while((rootitem = m_tree.GetNextItem(rootitem, TVGN_NEXT)) != NULL); return NULL; } void CguiconsoleDlg::onReceiveProfileData(MemoryStream& s) { KBEngine::int8 type; s >> type; m_profileWnd.onReceiveData(type, s); } void CguiconsoleDlg::commitPythonCommand(CString strCommand) { strCommand.Replace(L"\r", L""); if(strCommand.GetLength() <= 0) return; if(getTreeItemComponent(m_tree.GetSelectedItem()) != CELLAPP_TYPE && getTreeItemComponent(m_tree.GetSelectedItem()) != BASEAPP_TYPE && getTreeItemComponent(m_tree.GetSelectedItem()) != BOTS_TYPE) { ::AfxMessageBox(L"Component can not debug!"); return; } m_isUsingHistroy = false; m_historyCommand.push_back(strCommand); historyCommandCheck(); m_historyCommandIndex = m_historyCommand.size() - 1; CString strCommand1 = strCommand; /* // 对普通的输入加入print 让服务器回显信息 if((strCommand.Find(L"=")) == -1 && (strCommand.Find(L"print(")) == -1 && (strCommand.Find(L"import ")) == -1 && (strCommand.Find(L"class ")) == -1 && (strCommand.Find(L"def ")) == -1 && (strCommand.Find(L"del ")) == -1 && (strCommand.Find(L"if ")) == -1 && (strCommand.Find(L"for ")) == -1 && (strCommand.Find(L"while ")) == -1 ) strCommand = L"print(" + strCommand + L")"; */ std::wstring incmd = strCommand.GetBuffer(0); std::string outcmd; strutil::wchar2utf8(incmd, outcmd); Network::Channel* pChannel = _networkInterface.findChannel(this->getTreeItemAddr(m_tree.GetSelectedItem())); if(pChannel) { Network::Bundle* pBundle = Network::Bundle::createPoolObject(); if(getTreeItemComponent(m_tree.GetSelectedItem()) == BASEAPP_TYPE) (*pBundle).newMessage(BaseappInterface::onExecScriptCommand); else if(getTreeItemComponent(m_tree.GetSelectedItem()) == CELLAPP_TYPE) (*pBundle).newMessage(CellappInterface::onExecScriptCommand); else (*pBundle).newMessage(BotsInterface::onExecScriptCommand); ArraySize size = outcmd.size(); (*pBundle) << size; (*pBundle).append(outcmd.data(), size); pChannel->send(pBundle); CString str1, str2; m_debugWnd.displaybufferWnd()->GetWindowText(str2); wchar_t sign[10] = {L">>>"}; str1.Append(sign); str1.Append(strCommand1); g_sendData = TRUE; str2 += str1; m_debugWnd.displaybufferWnd()->SetWindowTextW(str2); saveHistory(); } } void CguiconsoleDlg::saveHistory() { //创建一个XML的文档对象。 TiXmlDocument *pDocument = new TiXmlDocument(); int i = 0; std::deque<CString>::iterator iter = m_historyCommand.begin(); TiXmlElement *rootElement = new TiXmlElement("root"); pDocument->LinkEndChild(rootElement); for(; iter != m_historyCommand.end(); iter++) { char key[256] = {0}; kbe_snprintf(key, 256, "item%d", i++); TiXmlElement *rootElementChild = new TiXmlElement(key); rootElement->LinkEndChild(rootElementChild); std::wstring strCommand = (*iter); std::string str; strutil::wchar2utf8(strCommand, str); TiXmlText *content = new TiXmlText(str.data()); rootElementChild->LinkEndChild(content); } CString appPath = GetAppPath(); CString fullPath = appPath + L"\\histroycommands.xml"; char fname[4096] = {0}; int len = WideCharToMultiByte(CP_ACP, 0, fullPath, fullPath.GetLength(), NULL, 0, NULL, NULL); WideCharToMultiByte(CP_ACP,0, fullPath, fullPath.GetLength(), fname, len, NULL, NULL); fname[len] = '\0'; pDocument->SaveFile(fname); } void CguiconsoleDlg::loadHistory() { CString appPath = GetAppPath(); CString fullPath = appPath + L"\\histroycommands.xml"; char fname[4096] = {0}; int len = WideCharToMultiByte(CP_ACP, 0, fullPath, fullPath.GetLength(), NULL, 0, NULL, NULL); WideCharToMultiByte(CP_ACP,0, fullPath, fullPath.GetLength(), fname, len, NULL, NULL); fname[len + 1] = '\0'; TiXmlDocument *pDocument = new TiXmlDocument(fname); if(pDocument == NULL || !pDocument->LoadFile(TIXML_ENCODING_UTF8)) return; TiXmlElement *rootElement = pDocument->RootElement(); TiXmlNode* node = rootElement->FirstChild(); if(node) { do { if(node->FirstChild() != NULL) { std::string c = node->FirstChild()->Value(); if(c.size() > 0) { std::wstring strCommand; strutil::utf82wchar(c, strCommand); CString sstrCommand = strCommand.data(); m_historyCommand.push_back(sstrCommand); } } }while((node = node->NextSibling())); } pDocument->Clear(); delete pDocument; } BOOL CguiconsoleDlg::PreTranslateMessage(MSG* pMsg) { if (pMsg->message == WM_KEYDOWN) { if(pMsg-> wParam == 0x0d) { return false; } } return CDialog::PreTranslateMessage(pMsg); } void CguiconsoleDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialog::OnSysCommand(nID, lParam); } } // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void CguiconsoleDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // device context for painting SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // Center icon in client rectangle int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // Draw the icon dc.DrawIcon(x, y, m_hIcon); } else { CDialog::OnPaint(); } } // The system calls this function to obtain the cursor to display while the user drags // the minimized window. HCURSOR CguiconsoleDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CguiconsoleDlg::addThreadTask(thread::TPTask* tptask) { threadPool_.addTask(tptask); } void CguiconsoleDlg::updateFindTreeStatus() { static int count = 0; if(count++ >= 6) { count = 0; } CString s = L"find server"; for(int i=0; i<count; i++) { s += L"."; } this->SetWindowTextW(s.GetBuffer(0)); /* m_tree.DeleteAllItems(); m_statusWnd.m_statusList.DeleteAllItems(); HTREEITEM hItemRoot; TV_INSERTSTRUCT tcitem; tcitem.hParent = TVI_ROOT; tcitem.hInsertAfter = TVI_LAST; tcitem.item.mask = TVIF_TEXT|TVIF_PARAM|TVIF_IMAGE|TVIF_SELECTEDIMAGE; tcitem.item.pszText = L"servergroups"; tcitem.item.lParam = 0; tcitem.item.iImage = 0; tcitem.item.iSelectedImage = 1; hItemRoot = m_tree.InsertItem(&tcitem); tcitem.hParent = hItemRoot; tcitem.hInsertAfter = TVI_LAST; tcitem.item.mask = TVIF_TEXT|TVIF_PARAM|TVIF_IMAGE|TVIF_SELECTEDIMAGE; CString s = L"find server"; for(int i=0; i<count; i++) { s += L"."; } tcitem.item.pszText = s.GetBuffer(0); tcitem.item.lParam = 0; tcitem.item.iImage = 0; tcitem.item.iSelectedImage = 1; m_tree.InsertItem(&tcitem); m_tree.Expand(hItemRoot, TVE_EXPAND); */ } void CguiconsoleDlg::OnTimer(UINT_PTR nIDEvent) { // TODO: Add your message handler code here and/or call default CDialog::OnTimer(nIDEvent); if(g_sendData) { g_sendData = !g_sendData; m_debugWnd.sendbufferWnd()->SetWindowTextW(L""); } switch(nIDEvent) { case 1: threadPool_.onMainThreadTick(); _dispatcher.processOnce(false); _networkInterface.processChannels(&KBEngine::ConsoleInterface::messageHandlers); break; case 2: { threadPool_.addTask(new FindServersTask(LOGGER_TYPE)); threadPool_.addTask(new FindServersTask(BASEAPP_TYPE)); threadPool_.addTask(new FindServersTask(CELLAPP_TYPE)); threadPool_.addTask(new FindServersTask(BASEAPPMGR_TYPE)); threadPool_.addTask(new FindServersTask(CELLAPPMGR_TYPE)); threadPool_.addTask(new FindServersTask(LOGINAPP_TYPE)); threadPool_.addTask(new FindServersTask(DBMGR_TYPE)); threadPool_.addTask(new FindServersTask(BOTS_TYPE)); ::KillTimer(m_hWnd, nIDEvent); } break; case 3: { const Network::NetworkInterface::ChannelMap& channels = _networkInterface.channels(); Network::NetworkInterface::ChannelMap::const_iterator iter = channels.begin(); for(; iter != channels.end(); iter++) { Network::Channel* pChannel = const_cast<KBEngine::Network::Channel*>(iter->second); Network::Bundle* pBundle = Network::Bundle::createPoolObject(); if(pChannel->proxyID() != BOTS_TYPE) { COMMON_NETWORK_MESSAGE((KBEngine::COMPONENT_TYPE)pChannel->proxyID(), (*pBundle), onAppActiveTick); } else { (*pBundle).newMessage(BotsInterface::onAppActiveTick); } (*pBundle) << _componentType; (*pBundle) << _componentID; pChannel->send(pBundle); pChannel->updateLastReceivedTime(); } } break; default: break; }; } void CguiconsoleDlg::onExecScriptCommandCB(Network::Channel* pChannel, std::string& command) { DEBUG_MSG(fmt::format("CguiconsoleDlg::onExecScriptCommandCB: {}\n", command.c_str())); std::wstring wcmd; strutil::utf82wchar(command, wcmd); CString str; CEdit* lpEdit = (CEdit*)m_debugWnd.displaybufferWnd(); lpEdit->GetWindowText(str); if(str.GetLength() > 0) str += L"\r\n"; else str += L""; for(unsigned int i=0; i<wcmd.size(); i++) { wchar_t c = wcmd.c_str()[i]; switch(c) { case 10: str += L"\r\n"; break; case 32: str += c; break; case 34: str += L"\t"; break; default: str += c; } } str += L"\r\n"; lpEdit->SetWindowText(str.GetBuffer(0)); int nline = lpEdit->GetLineCount(); lpEdit->LineScroll(nline - 1); } void CguiconsoleDlg::OnSizing(UINT fwSide, LPRECT pRect) { CDialog::OnSizing(fwSide, pRect); autoWndSize(); // TODO: Add your message handler code here } void CguiconsoleDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); autoWndSize(); } bool CguiconsoleDlg::hasTreeComponent(Components::ComponentInfos& cinfos) { HTREEITEM hItemRoot = m_tree.GetRootItem(); if(hItemRoot == NULL) return false; HTREEITEM item = m_tree.GetChildItem(hItemRoot), hasUIDItem = NULL; do { CString s = m_tree.GetItemText(item); CString s1; s1.Format(L"uid[%u]", cinfos.uid); if(s1 == s) { hasUIDItem = item; break; } }while(item = m_tree.GetNextItem(item, TVGN_NEXT)); if(hasUIDItem == NULL) return false; item = m_tree.GetChildItem(hasUIDItem); char sbuf[1024]; kbe_snprintf(sbuf, 1024, "%s[%s]", COMPONENT_NAME_EX(cinfos.componentType), cinfos.pIntAddr->c_str()); wchar_t* wbuf = KBEngine::strutil::char2wchar(sbuf); CString s1 = wbuf; free(wbuf); do { CString s = m_tree.GetItemText(item); if(s1 == s) { return true; } }while(item = m_tree.GetNextItem(item, TVGN_NEXT)); return false; } void CguiconsoleDlg::updateTree() { if(!m_isInit) return; Components::COMPONENTS& cts0 = Components::getSingleton().getComponents(BASEAPP_TYPE); Components::COMPONENTS& cts1 = Components::getSingleton().getComponents(CELLAPP_TYPE); Components::COMPONENTS& cts2 = Components::getSingleton().getComponents(BASEAPPMGR_TYPE); Components::COMPONENTS& cts3 = Components::getSingleton().getComponents(CELLAPPMGR_TYPE); Components::COMPONENTS& cts4 = Components::getSingleton().getComponents(DBMGR_TYPE); Components::COMPONENTS& cts5 = Components::getSingleton().getComponents(LOGINAPP_TYPE); Components::COMPONENTS& cts6 = Components::getSingleton().getComponents(LOGGER_TYPE); Components::COMPONENTS& cts7 = Components::getSingleton().getComponents(BOTS_TYPE); Components::COMPONENTS cts; if(cts0.size() > 0) cts.insert(cts.begin(), cts0.begin(), cts0.end()); if(cts1.size() > 0) cts.insert(cts.begin(), cts1.begin(), cts1.end()); if(cts2.size() > 0) cts.insert(cts.begin(), cts2.begin(), cts2.end()); if(cts3.size() > 0) cts.insert(cts.begin(), cts3.begin(), cts3.end()); if(cts4.size() > 0) cts.insert(cts.begin(), cts4.begin(), cts4.end()); if(cts5.size() > 0) cts.insert(cts.begin(), cts5.begin(), cts5.end()); if(cts6.size() > 0) cts.insert(cts.begin(), cts6.begin(), cts6.end()); if(cts7.size() > 0) cts.insert(cts.begin(), cts7.begin(), cts7.end()); HTREEITEM hItemRoot; TV_INSERTSTRUCT tcitem; hItemRoot = m_tree.GetRootItem(); if(hItemRoot == NULL) { tcitem.hParent = TVI_ROOT; tcitem.hInsertAfter = TVI_LAST; tcitem.item.mask = TVIF_TEXT|TVIF_PARAM|TVIF_IMAGE|TVIF_SELECTEDIMAGE; tcitem.item.pszText = L"servergroups"; tcitem.item.lParam = 0; tcitem.item.iImage = 0; tcitem.item.iSelectedImage = 1; hItemRoot = m_tree.InsertItem(&tcitem); } Components::COMPONENTS::iterator iter = cts.begin(); for(; iter != cts.end(); iter++) { Components::ComponentInfos& cinfos = (*iter); HTREEITEM item = m_tree.GetChildItem(hItemRoot), hasUIDItem = NULL; if(item) { do { CString s = m_tree.GetItemText(item); CString s1; s1.Format(L"uid[%u]", cinfos.uid); if(s1 == s) { hasUIDItem = item; break; } }while(item = m_tree.GetNextItem(item, TVGN_NEXT)); } if(hasUIDItem == NULL) { CString s; s.Format(L"uid[%u]", cinfos.uid); tcitem.hParent = hItemRoot; tcitem.hInsertAfter = TVI_LAST; tcitem.item.mask = TVIF_TEXT|TVIF_PARAM|TVIF_IMAGE|TVIF_SELECTEDIMAGE; tcitem.item.pszText = s.GetBuffer(0); tcitem.item.lParam = 0; tcitem.item.iImage = 0; tcitem.item.iSelectedImage = 1; hasUIDItem = m_tree.InsertItem(&tcitem); } if(this->hasTreeComponent(cinfos)) { continue; } char sbuf[1024]; kbe_snprintf(sbuf, 1024, "%s[%s]", COMPONENT_NAME_EX(cinfos.componentType), cinfos.pIntAddr->c_str()); wchar_t* wbuf = KBEngine::strutil::char2wchar(sbuf); tcitem.hParent = hasUIDItem; tcitem.hInsertAfter = TVI_LAST; tcitem.item.mask = TVIF_TEXT|TVIF_PARAM|TVIF_IMAGE|TVIF_SELECTEDIMAGE; tcitem.item.pszText = wbuf; tcitem.item.lParam = 0; tcitem.item.iImage = 0; tcitem.item.iSelectedImage = 1; HTREEITEM insertItem = m_tree.InsertItem(&tcitem); m_tree.SetItemData(insertItem, (DWORD)&cinfos.cid); m_tree.Expand(hasUIDItem, TVE_EXPAND); free(wbuf); m_statusWnd.addApp(cinfos); } m_tree.Expand(hItemRoot, TVE_EXPAND); ListSortData *tmpp = new ListSortData; tmpp->listctrl = &m_statusWnd.m_statusList; tmpp->isub = 0; tmpp->seq = 0; m_statusWnd.m_statusList.SortItems(CompareFunc,(LPARAM)tmpp); delete tmpp; } void CguiconsoleDlg::autoWndSize() { if(!m_isInit) return; CRect rect1; m_ToolBar.GetClientRect(&rect1); g_diffHeight = rect1.bottom + 8; this->GetClientRect(&rect1); rect1.left += int(rect1.right * 0.25); rect1.top += g_diffHeight; m_tab.MoveWindow(rect1); CRect rect; m_tab.GetClientRect(&rect); CRect rect2; this->GetClientRect(&rect2); rect2.right = int(rect2.right * 0.25); rect2.top += g_diffHeight; m_tree.MoveWindow(rect2); rect.top += 25; rect.bottom -= 5; rect.left += 5; rect.right -= 5; m_statusWnd.MoveWindow(&rect); m_statusWnd.autoWndSize(); m_logWnd.MoveWindow(&rect); m_logWnd.autoWndSize(); m_debugWnd.MoveWindow(&rect); m_debugWnd.autoWndSize(); m_profileWnd.MoveWindow(&rect); m_profileWnd.autoWndSize(); m_watcherWnd.MoveWindow(&rect); m_watcherWnd.autoWndSize(); m_spaceViewWnd.MoveWindow(&rect); m_spaceViewWnd.autoWndSize(); m_graphsWindow.MoveWindow(&rect); m_graphsWindow.autoWndSize(); autoShowWindow(); } void CguiconsoleDlg::OnNMRClickTree1(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: Add your control notification handler code here *pResult = 0; CMenu menu; menu.LoadMenu(IDR_POPMENU); CMenu* pPopup = menu.GetSubMenu(0); CPoint point; GetCursorPos(&point); //鼠标位置 pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this); } void CguiconsoleDlg::reqQueryWatcher(std::string paths) { COMPONENT_TYPE debugComponentType = getTreeItemComponent(m_tree.GetSelectedItem()); Network::Address addr = getTreeItemAddr(m_tree.GetSelectedItem()); Network::Channel* pChannel = _networkInterface.findChannel(addr); if(pChannel) { Network::Bundle* pBundle = Network::Bundle::createPoolObject(); if(debugComponentType == BOTS_TYPE) { (*pBundle).newMessage(BotsInterface::queryWatcher); } else { COMMON_NETWORK_MESSAGE(debugComponentType, (*pBundle), queryWatcher); } (*pBundle) << paths; pChannel->send(pBundle); } } COMPONENT_TYPE CguiconsoleDlg::getTreeItemComponent(HTREEITEM hItem) { if(hItem == NULL) return UNKNOWN_COMPONENT_TYPE; CString s = m_tree.GetItemText(hItem); int fi_cellappmgr = s.Find(L"cellappmgr", 0); int fi_baseappmgr = s.Find(L"baseappmgr", 0); int fi_cellapp = s.Find(L"cellapp", 0); int fi_baseapp = s.Find(L"baseapp", 0); if(fi_cellappmgr >= 0) fi_cellapp = -1; if(fi_baseappmgr >= 0) fi_baseapp = -1; int fi_loginapp = s.Find(L"loginapp", 0); int fi_dbmgr = s.Find(L"dbmgr", 0); int fi_logger = s.Find(L"logger", 0); int fi_bots = s.Find(L"bots", 0); if(fi_cellapp < 0 && fi_baseapp < 0 && fi_cellappmgr < 0 && fi_baseappmgr < 0 && fi_loginapp < 0 && fi_logger < 0 && fi_dbmgr < 0 && fi_bots < 0) { return UNKNOWN_COMPONENT_TYPE; } if(fi_cellapp >= 0) { return CELLAPP_TYPE; } else if(fi_baseapp >= 0) { return BASEAPP_TYPE; } else if(fi_cellappmgr >= 0) { return CELLAPPMGR_TYPE; } else if(fi_baseappmgr >= 0) { return BASEAPPMGR_TYPE; } else if(fi_loginapp >= 0) { return LOGINAPP_TYPE; } else if(fi_dbmgr >= 0) { return DBMGR_TYPE; } else if(fi_logger >= 0) { return LOGGER_TYPE; } else if(fi_bots >= 0) { return BOTS_TYPE; } return UNKNOWN_COMPONENT_TYPE; } int32 CguiconsoleDlg::getSelTreeItemUID() { HTREEITEM hItem = m_tree.GetSelectedItem(); if(hItem == NULL) return 0; CString s = m_tree.GetItemText(hItem); if(s.Find(L"uid[") >= 0) { s.Replace(L"uid[", L""); s.Replace(L"]", L""); } else { hItem = m_tree.GetParentItem(hItem); if(hItem == NULL) return 0; s = m_tree.GetItemText(hItem); if(s.Find(L"uid[") >= 0) { s.Replace(L"uid[", L""); s.Replace(L"]", L""); } else { s = L""; } } if(s.GetLength() == 0) return 0; char* buf = KBEngine::strutil::wchar2char(s.GetBuffer(0)); int32 uid = atoi(buf); free(buf); return uid; } Network::Address CguiconsoleDlg::getTreeItemAddr(HTREEITEM hItem) { if(hItem == NULL) return Network::Address::NONE; CString s = m_tree.GetItemText(hItem); int fi_cellappmgr = s.Find(L"cellappmgr", 0); int fi_baseappmgr = s.Find(L"baseappmgr", 0); int fi_cellapp = s.Find(L"cellapp", 0); int fi_baseapp = s.Find(L"baseapp", 0); if(fi_cellappmgr >= 0) fi_cellapp = -1; if(fi_baseappmgr >= 0) fi_baseapp = -1; int fi_loginapp = s.Find(L"loginapp", 0); int fi_dbmgr = s.Find(L"dbmgr", 0); int fi_logger = s.Find(L"logger", 0); int fi_bots = s.Find(L"bots", 0); if(fi_cellapp < 0 && fi_baseapp < 0 && fi_cellappmgr < 0 && fi_baseappmgr < 0 && fi_loginapp < 0 && fi_logger < 0 && fi_dbmgr < 0 && fi_bots < 0) { return Network::Address::NONE; } char* buf = KBEngine::strutil::wchar2char(s.GetBuffer(0)); std::string sbuf = buf; free(buf); std::string::size_type i = sbuf.find("["); std::string::size_type j = sbuf.find("]"); sbuf = sbuf.substr(i + 1, j - 1); std::string::size_type k = sbuf.find(":"); std::string sip, sport; sip = sbuf.substr(0, k); sport = sbuf.substr(k + 1, sbuf.find("]")); strutil::kbe_replace(sport, "]", ""); std::map<CString, CString>::iterator mapiter = m_ipMappings.find(CString(sip.c_str())); if (mapiter != m_ipMappings.end()) { buf = KBEngine::strutil::wchar2char(mapiter->second.GetBuffer(0)); sip = buf; free(buf); } Network::EndPoint endpoint; u_int32_t address; Network::Address::string2ip(sip.c_str(), address); KBEngine::Network::Address addr(address, htons(atoi(sport.c_str()))); return addr; } bool CguiconsoleDlg::connectTo() { // TODO: Add your command handler code here HTREEITEM hItem = m_tree.GetSelectedItem(); KBEngine::Network::Address addr = getTreeItemAddr(hItem); if(addr.ip == 0) { ::AfxMessageBox(L"no select!"); return false; } Network::EndPoint* endpoint = Network::EndPoint::createPoolObject(); endpoint->socket(SOCK_STREAM); if (!endpoint->good()) { AfxMessageBox(L"couldn't create a socket\n"); return false; } endpoint->addr(addr); if(endpoint->connect(addr.port, addr.ip) == -1) { CString err; err.Format(L"connect server is error! %d", ::WSAGetLastError()); AfxMessageBox(err); return false; } endpoint->setnonblocking(true); Network::Channel* pChannel = _networkInterface.findChannel(endpoint->addr()); if(pChannel) { _networkInterface.deregisterChannel(pChannel); pChannel->destroy(); Network::Channel::reclaimPoolObject(pChannel); } pChannel = Network::Channel::createPoolObject(); bool ret = pChannel->initialize(_networkInterface, endpoint, Network::Channel::INTERNAL); if(!ret) { ERROR_MSG(fmt::format("CguiconsoleDlg::connectTo: initialize({}) is failed!\n", pChannel->c_str())); pChannel->destroy(); Network::Channel::reclaimPoolObject(pChannel); return 0; } pChannel->proxyID(getTreeItemComponent(m_tree.GetSelectedItem())); if(!_networkInterface.registerChannel(pChannel)) { pChannel->destroy(); Network::Channel::reclaimPoolObject(pChannel); CString err; err.Format(L"CguiconsoleDlg::connectTo: registerChannel(%s) is failed!\n", pChannel->c_str()); AfxMessageBox(err); return false; } return true; } void CguiconsoleDlg::closeCurrTreeSelChannel() { HTREEITEM hItem = m_tree.GetSelectedItem(); KBEngine::Network::Address addr = getTreeItemAddr(hItem); if(addr.ip == 0) { ::AfxMessageBox(L"no select!"); return; } Network::Channel* pChannel = _networkInterface.findChannel(addr); if(pChannel) { _networkInterface.deregisterChannel(pChannel); pChannel->destroy(); Network::Channel::reclaimPoolObject(pChannel); } } void CguiconsoleDlg::OnMenu_Update() { _networkInterface.deregisterAllChannels(); Components::getSingleton().clear(); Components::getSingleton().delComponent(Components::ANY_UID, LOGGER_TYPE, 0, true, false); Components::getSingleton().delComponent(Components::ANY_UID, BOTS_TYPE, 0, true, false); ::SetTimer(m_hWnd, 2, 100, NULL); } void CguiconsoleDlg::autoShowWindow() { switch(m_tab.GetCurSel()) { case 0: m_statusWnd.ShowWindow(SW_SHOW); m_debugWnd.ShowWindow(SW_HIDE); m_logWnd.ShowWindow(SW_HIDE); m_profileWnd.ShowWindow(SW_HIDE); m_watcherWnd.ShowWindow(SW_HIDE); m_spaceViewWnd.ShowWindow(SW_HIDE); m_graphsWindow.ShowWindow(SW_HIDE); break; case 1: m_statusWnd.ShowWindow(SW_HIDE); m_debugWnd.ShowWindow(SW_SHOW); m_logWnd.ShowWindow(SW_HIDE); m_profileWnd.ShowWindow(SW_HIDE); m_watcherWnd.ShowWindow(SW_HIDE); m_spaceViewWnd.ShowWindow(SW_HIDE); m_graphsWindow.ShowWindow(SW_HIDE); break; case 2: m_statusWnd.ShowWindow(SW_HIDE); m_debugWnd.ShowWindow(SW_HIDE); m_logWnd.ShowWindow(SW_SHOW); m_profileWnd.ShowWindow(SW_HIDE); m_watcherWnd.ShowWindow(SW_HIDE); m_spaceViewWnd.ShowWindow(SW_HIDE); m_graphsWindow.ShowWindow(SW_HIDE); break; case 3: m_statusWnd.ShowWindow(SW_HIDE); m_debugWnd.ShowWindow(SW_HIDE); m_logWnd.ShowWindow(SW_HIDE); m_profileWnd.ShowWindow(SW_SHOW); m_watcherWnd.ShowWindow(SW_HIDE); m_spaceViewWnd.ShowWindow(SW_HIDE); m_graphsWindow.ShowWindow(SW_HIDE); break; case 4: m_statusWnd.ShowWindow(SW_HIDE); m_debugWnd.ShowWindow(SW_HIDE); m_logWnd.ShowWindow(SW_HIDE); m_profileWnd.ShowWindow(SW_HIDE); m_watcherWnd.ShowWindow(SW_SHOW); m_spaceViewWnd.ShowWindow(SW_HIDE); m_graphsWindow.ShowWindow(SW_HIDE); break; case 5: m_statusWnd.ShowWindow(SW_HIDE); m_debugWnd.ShowWindow(SW_HIDE); m_logWnd.ShowWindow(SW_HIDE); m_profileWnd.ShowWindow(SW_HIDE); m_watcherWnd.ShowWindow(SW_HIDE); m_spaceViewWnd.ShowWindow(SW_SHOW); m_graphsWindow.ShowWindow(SW_HIDE); break; case 6: m_statusWnd.ShowWindow(SW_HIDE); m_debugWnd.ShowWindow(SW_HIDE); m_logWnd.ShowWindow(SW_HIDE); m_profileWnd.ShowWindow(SW_HIDE); m_watcherWnd.ShowWindow(SW_HIDE); m_spaceViewWnd.ShowWindow(SW_HIDE); m_graphsWindow.ShowWindow(SW_SHOW); break; }; } void CguiconsoleDlg::OnTcnSelchangeTab1(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: Add your control notification handler code here *pResult = 0; autoShowWindow(); } void CguiconsoleDlg::OnNMClickTree1(NMHDR *pNMHDR, LRESULT *pResult) { // TODO: Add your control notification handler code here *pResult = 0; TVHITTESTINFO hittestInfo; GetCursorPos(&hittestInfo.pt); m_tree.ScreenToClient(&hittestInfo.pt); HTREEITEM hItem = m_tree.HitTest(&hittestInfo); if(hItem == NULL || TVHT_NOWHERE & hittestInfo.flags) return; bool changeToChecked = false; // 复选框被选中就连接否则断开连接 if(TVHT_ONITEMSTATEICON & hittestInfo.flags) { m_tree.SelectItem(hItem); BOOL checked = !m_tree.GetCheck(hItem); if(checked) { if(!connectTo()) return; changeToChecked = true; } else { closeCurrTreeSelChannel(); } } COMPONENT_TYPE debugComponentType = getTreeItemComponent(hItem); BOOL isread_only = debugComponentType != CELLAPP_TYPE && debugComponentType != BASEAPP_TYPE && debugComponentType != BOTS_TYPE; m_debugWnd.sendbufferWnd()->SetReadOnly(isread_only || !changeToChecked && !m_tree.GetCheck(hItem)); if(!isread_only && changeToChecked) { CString s; m_debugWnd.displaybufferWnd()->GetWindowTextW(s); if(s.GetLength() <= 0) s += L">>>请在下面的窗口写python代码来调试服务端。\r\n>>>ctrl+enter 发送\r\n>>>↑↓使用历史命令\r\n\r\n"; else s += L">>>"; m_debugWnd.displaybufferWnd()->SetWindowTextW(s); } Network::Address currAddr = this->getTreeItemAddr(hItem); if(currAddr.ip == 0) return; CString title; wchar_t* tbuf = strutil::char2wchar(currAddr.c_str()); title.Format(L"guiconsole : selected[%s]", tbuf); free(tbuf); this->SetWindowTextW(title.GetBuffer(0)); m_watcherWnd.clearAllData(); if(debugComponentType == LOGGER_TYPE && changeToChecked) { HTREEITEM hItem = m_tree.GetSelectedItem(); KBEngine::Network::Address addr = getTreeItemAddr(hItem); m_logWnd.onConnectionState(changeToChecked, addr); } } void CguiconsoleDlg::OnConnectRemoteMachine() { // TODO: Add your command handler code here CConnectRemoteMachineWindow dlg; dlg.DoModal(); } void CguiconsoleDlg::OnHelpAbout() { // TODO: Add your command handler code here ::CAboutDlg dlg; dlg.DoModal(); } void CguiconsoleDlg::OnToolBar_Find() { OnConnectRemoteMachine(); } void CguiconsoleDlg::OnToolBar_StartServer() { /* COMPONENT_TYPE startComponentTypes[] = {BASEAPP_TYPE, CELLAPP_TYPE, BASEAPPMGR_TYPE, CELLAPPMGR_TYPE, LOGINAPP_TYPE, DBMGR_TYPE, BOTS_TYPE, UNKNOWN_COMPONENT_TYPE}; int i = 0; while(1) { srand(KBEngine::getSystemTime()); uint16 nport = KBE_PORT_START + (rand() % 1000); Network::BundleBroadcast bhandler(_networkInterface, nport); if(!bhandler.good()) { KBEngine::sleep(10); nport = KBE_PORT_START + (rand() % 1000); continue; } if(bhandler.pCurrPacket() != NULL) { bhandler.pCurrPacket()->resetPacket(); } COMPONENT_TYPE componentType = startComponentTypes[i++]; if(componentType == UNKNOWN_COMPONENT_TYPE) break; bhandler.newMessage(MachineInterface::startserver); bhandler << KBEngine::getUserUID(); bhandler << componentType; uint32 ip = _networkInterface.intaddr().ip; uint16 port = bhandler.epListen().addr().port; bhandler << ip << port; if(!bhandler.broadcast()) { ERROR_MSG("CguiconsoleDlg::OnToolBar_StartServer: broadcast error!\n"); //::AfxMessageBox(L"不能发送服务器启动包。"); break; } if(!bhandler.receive(NULL, 0, 1000000)) { ERROR_MSG("CguiconsoleDlg::OnToolBar_StartServer: recv error!\n"); //::AfxMessageBox(L"接收服务器启动包错误。"); break; } bool success; bhandler >> success; } _networkInterface.deregisterAllChannels(); Components::getSingleton().clear(); Components::getSingleton().delComponent(Components::ANY_UID, LOGGER_TYPE, 0, true, false); Components::getSingleton().delComponent(Components::ANY_UID, BOTS_TYPE, 0, true, false); ::SetTimer(m_hWnd, 2, 1000, NULL); */ CStartServerWindow dlg; dlg.DoModal(); } void CguiconsoleDlg::OnToolBar_StopServer() { COMPONENT_TYPE startComponentTypes[] = {BASEAPP_TYPE, CELLAPP_TYPE, BASEAPPMGR_TYPE, CELLAPPMGR_TYPE, LOGINAPP_TYPE, DBMGR_TYPE, BOTS_TYPE, UNKNOWN_COMPONENT_TYPE}; int i = 0; while(1) { srand(KBEngine::getSystemTime()); uint16 nport = KBE_PORT_START + (rand() % 1000); Network::BundleBroadcast bhandler(_networkInterface, nport); if(!bhandler.good()) { KBEngine::sleep(10); nport = KBE_PORT_START + (rand() % 1000); continue; } if(bhandler.pCurrPacket() != NULL) { bhandler.pCurrPacket()->resetPacket(); } COMPONENT_TYPE componentType = startComponentTypes[i++]; if(componentType == UNKNOWN_COMPONENT_TYPE) break; bhandler.newMessage(MachineInterface::stopserver); bhandler << KBEngine::getUserUID(); bhandler << componentType; KBEngine::COMPONENT_ID cid = 0; bhandler << cid; uint32 ip = _networkInterface.intaddr().ip; uint16 port = bhandler.epListen().addr().port; bhandler << ip << port; if(!bhandler.broadcast()) { ERROR_MSG("CguiconsoleDlg::OnToolBar_StartServer: broadcast error!\n"); //::AfxMessageBox(L"不能发送服务器启动包。"); break; } if(!bhandler.receive(NULL, 0, 3000000)) { ERROR_MSG("CguiconsoleDlg::OnToolBar_StartServer: recv error!\n"); //::AfxMessageBox(L"接收服务器启动包错误。"); break; } bool success; bhandler >> success; } } void CguiconsoleDlg::OnClose() { // TODO: Add your message handler code here and/or call default g_isDestroyed = true; //threadPool_.finalise(); CDialog::OnClose(); } void CguiconsoleDlg::onReceiveWatcherData(MemoryStream& s) { m_watcherWnd.onReceiveWatcherData(s); } bool CguiconsoleDlg::startProfile(std::string name, int8 type, uint32 timinglen) { if(type == 0) { if(getTreeItemComponent(m_tree.GetSelectedItem()) != BASEAPP_TYPE && getTreeItemComponent(m_tree.GetSelectedItem()) != CELLAPP_TYPE && getTreeItemComponent(m_tree.GetSelectedItem()) != BOTS_TYPE) { ::AfxMessageBox(L"not support!"); return false; } } Network::Channel* pChannel = _networkInterface.findChannel(this->getTreeItemAddr(m_tree.GetSelectedItem())); if(pChannel) { Network::Bundle* pBundle = Network::Bundle::createPoolObject(); if(getTreeItemComponent(m_tree.GetSelectedItem()) == BASEAPP_TYPE) (*pBundle).newMessage(BaseappInterface::startProfile); else if(getTreeItemComponent(m_tree.GetSelectedItem()) == BASEAPPMGR_TYPE) (*pBundle).newMessage(BaseappmgrInterface::startProfile); else if(getTreeItemComponent(m_tree.GetSelectedItem()) == CELLAPP_TYPE) (*pBundle).newMessage(CellappInterface::startProfile); else if(getTreeItemComponent(m_tree.GetSelectedItem()) == CELLAPPMGR_TYPE) (*pBundle).newMessage(CellappmgrInterface::startProfile); else if(getTreeItemComponent(m_tree.GetSelectedItem()) == DBMGR_TYPE) (*pBundle).newMessage(DbmgrInterface::startProfile); else if(getTreeItemComponent(m_tree.GetSelectedItem()) == LOGINAPP_TYPE) (*pBundle).newMessage(LoginappInterface::startProfile); else if(getTreeItemComponent(m_tree.GetSelectedItem()) == LOGGER_TYPE) (*pBundle).newMessage(LoggerInterface::startProfile); else if(getTreeItemComponent(m_tree.GetSelectedItem()) == BOTS_TYPE) (*pBundle).newMessage(BotsInterface::startProfile); else { ::AfxMessageBox(L"not support!"); Network::Bundle::reclaimPoolObject(pBundle); return false; } (*pBundle) << name; (*pBundle) << type; (*pBundle) << timinglen; pChannel->send(pBundle); return true; } return false; } void CguiconsoleDlg::OnDestroy() { CDialog::OnDestroy(); // TODO: Add your message handler code here threadPool_.finalise(); }
c3024e072729588b721e9971f69cf404e37ac4b2
b677894966f2ae2d0585a31f163a362e41a3eae0
/ns3/ns-3.26/src/flow-monitor/model/flow-probe.cc
5b07632463d3cb8dc9cd4709cb11c4912478842b
[ "LicenseRef-scancode-free-unknown", "GPL-2.0-only", "Apache-2.0" ]
permissive
cyliustack/clusim
667a9eef2e1ea8dad1511fd405f3191d150a04a8
cbedcf671ba19fded26e4776c0e068f81f068dfd
refs/heads/master
2022-10-06T20:14:43.052930
2022-10-01T19:42:19
2022-10-01T19:42:19
99,692,344
7
3
Apache-2.0
2018-07-04T10:09:24
2017-08-08T12:51:33
Python
UTF-8
C++
false
false
3,575
cc
flow-probe.cc
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ // // Copyright (c) 2009 INESC Porto // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License version 2 as // published by the Free Software Foundation; // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Author: Gustavo J. A. M. Carneiro <gjc@inescporto.pt> <gjcarneiro@gmail.com> // #include "ns3/flow-probe.h" #include "ns3/flow-monitor.h" namespace ns3 { /* static */ TypeId FlowProbe::GetTypeId (void) { static TypeId tid = TypeId ("ns3::FlowProbe") .SetParent<Object> () .SetGroupName ("FlowMonitor") // No AddConstructor because this class has no default constructor. ; return tid; } FlowProbe::~FlowProbe () { } FlowProbe::FlowProbe (Ptr<FlowMonitor> flowMonitor) : m_flowMonitor (flowMonitor) { m_flowMonitor->AddProbe (this); } void FlowProbe::DoDispose (void) { m_flowMonitor = 0; Object::DoDispose (); } void FlowProbe::AddPacketStats (FlowId flowId, uint32_t packetSize, Time delayFromFirstProbe) { FlowStats &flow = m_stats[flowId]; flow.delayFromFirstProbeSum += delayFromFirstProbe; flow.bytes += packetSize; ++flow.packets; } void FlowProbe::AddPacketDropStats (FlowId flowId, uint32_t packetSize, uint32_t reasonCode) { FlowStats &flow = m_stats[flowId]; if (flow.packetsDropped.size () < reasonCode + 1) { flow.packetsDropped.resize (reasonCode + 1, 0); flow.bytesDropped.resize (reasonCode + 1, 0); } ++flow.packetsDropped[reasonCode]; flow.bytesDropped[reasonCode] += packetSize; } FlowProbe::Stats FlowProbe::GetStats () const { return m_stats; } void FlowProbe::SerializeToXmlStream (std::ostream &os, int indent, uint32_t index) const { #define INDENT(level) for (int __xpto = 0; __xpto < level; __xpto++) os << ' '; INDENT (indent); os << "<FlowProbe index=\"" << index << "\">\n"; indent += 2; for (Stats::const_iterator iter = m_stats.begin (); iter != m_stats.end (); iter++) { INDENT (indent); os << "<FlowStats " << " flowId=\"" << iter->first << "\"" << " packets=\"" << iter->second.packets << "\"" << " bytes=\"" << iter->second.bytes << "\"" << " delayFromFirstProbeSum=\"" << iter->second.delayFromFirstProbeSum << "\"" << " >\n"; indent += 2; for (uint32_t reasonCode = 0; reasonCode < iter->second.packetsDropped.size (); reasonCode++) { INDENT (indent); os << "<packetsDropped reasonCode=\"" << reasonCode << "\"" << " number=\"" << iter->second.packetsDropped[reasonCode] << "\" />\n"; } for (uint32_t reasonCode = 0; reasonCode < iter->second.bytesDropped.size (); reasonCode++) { INDENT (indent); os << "<bytesDropped reasonCode=\"" << reasonCode << "\"" << " bytes=\"" << iter->second.bytesDropped[reasonCode] << "\" />\n"; } indent -= 2; INDENT (indent); os << "</FlowStats>\n"; } indent -= 2; INDENT (indent); os << "</FlowProbe>\n"; } } // namespace ns3
d18f2a33bb6ecc5eeab306581847a5ac8f49af89
7f4ced713c77090b7b00b8a35fd627ccbe7c46df
/fir/src/Error.h
28a1afac99876f32d0d2746b34d145d5921bbe56
[ "MIT" ]
permissive
wahudson/fpgadata
73fd935c348a20c61b846c696470e9cdbfb663d5
affc89b29df357b3d0b0f8c7101faba10532018b
refs/heads/master
2021-05-23T05:46:11.072392
2020-07-03T23:15:06
2020-07-03T23:15:06
94,909,726
3
1
null
null
null
null
UTF-8
C++
false
false
494
h
Error.h
#ifndef Error_P #define Error_P //-------------------------------------------------------------------------- // Error class //-------------------------------------------------------------------------- class Error { private: static int Error_cnt; static std::ostream *cErr; public: // Class Methods static void Init_ostream( std::ostream* erx ); static int has_err(); static std::ostream& msg(); static std::ostream& msg( const char* text ); }; #endif
7a9a0149a205ac031995cfdd931b1f6f0d84a47c
3f6fe98e64f6ddbc409379f2ad9a5964208792dd
/DynammicProgramming/maximum_non_negative_product.cpp
a556444c9950c0b41d62170b95e9176a7a42bc84
[]
no_license
pranav1698/Competitive-Programming
2ca9fa65ea381c283f163ff4992a2903f6d8a6b3
67faa52c59a2c8683bc94a7a0e13aed4481d1243
refs/heads/master
2022-12-27T21:51:54.048922
2020-10-04T18:41:53
2020-10-05T18:41:53
265,039,796
1
0
null
null
null
null
UTF-8
C++
false
false
1,623
cpp
maximum_non_negative_product.cpp
// Maximum Non Negative Product // SlothyCoder16 // September 27, 2020 class Solution { public: int mod=1e9+7; int maxProductPath(vector<vector<int>>& grid) { int m=grid.size(); int n=grid[0].size(); vector<vector<long long>> minDp(m, vector<long long>(n, LONG_MAX)); vector<vector<long long>> maxDp(m, vector<long long>(n, LONG_MIN)); minDp[0][0]=grid[0][0]; maxDp[0][0]=grid[0][0]; for(int i=1; i<m; i++) { minDp[i][0] = min(((minDp[i-1][0]%mod)*(grid[i][0]%mod)%mod), ((maxDp[i-1][0]%mod)*(grid[i][0]%mod)%mod)); maxDp[i][0] = max(((minDp[i-1][0]%mod)*(grid[i][0]%mod)%mod), ((maxDp[i-1][0]%mod)*(grid[i][0]%mod)%mod)); } for(int j=1; j<n; j++) { minDp[0][j] = min(((minDp[0][j-1]%mod)*(grid[0][j]%mod)%mod), ((maxDp[0][j-1]%mod)*(grid[0][j]%mod)%mod)); maxDp[0][j] = max(((minDp[0][j-1]%mod)*(grid[0][j]%mod)%mod), ((maxDp[0][j-1]%mod)*(grid[0][j]%mod)%mod)); } for(int i=1; i<m; i++) { for(int j=1; j<n; j++) { maxDp[i][j] = max(max(((maxDp[i-1][j]%mod)*(grid[i][j]%mod))%mod, ((maxDp[i][j-1]%mod)*(grid[i][j]%mod))%mod), max((minDp[i-1][j]%mod)*(grid[i][j]%mod)%mod, ((minDp[i][j-1]%mod)*(grid[i][j]%mod))%mod)); minDp[i][j] = min(min(((maxDp[i-1][j]%mod)*(grid[i][j]%mod))%mod, ((maxDp[i][j-1]%mod)*(grid[i][j]%mod))%mod), min((minDp[i-1][j]%mod)*(grid[i][j]%mod)%mod, ((minDp[i][j-1]%mod)*(grid[i][j]%mod))%mod)); } } if(maxDp[m-1][n-1] < 0) return -1; return maxDp[m-1][n-1]; } };
0ccc4f3219de674c4a9c4eff7d4b79ef6b15eac6
2b32dc262038a24e8145d4895eb93032e4dfe9ed
/Emulation-of-AIMD-algorithm/32plots.cpp
32a5e5026c85b88811d89683d82d429297d4c29c
[]
no_license
sagar324/Computer-Networks-JAN-MAY-2021
9533f30f5cd74071d0fcfc9c447b05f83cfa97fc
aece227aafe9a3e9e851cc4e9c0dc1bbd12f8b91
refs/heads/main
2023-07-02T05:21:44.981306
2021-08-10T14:39:19
2021-08-10T14:39:19
394,685,271
0
0
null
null
null
null
UTF-8
C++
false
false
1,907
cpp
32plots.cpp
#include <bits/stdc++.h> #include <random> using namespace std; double Ki,Km,Kn,Kf,Ps; double MSS=1; double RWS = 1000; double tot; double itr=0; string filename; double cwnd; double ssthresh=0; int prob(){ std::random_device rd; std::mt19937 generator(rd()); std::bernoulli_distribution distribution(Ps); if(distribution(generator)){ return 1; } return 0; } void write(string filename,double cwnd,int itr){ ofstream fout; fout.open(filename+".txt",ios::app); string output; output = std::to_string(cwnd); fout<<output<<endl; fout.close(); } int main(){ string di,dm,dn,df,ds,dT,d0; //cin>>di>>Ki>>dm>>Km>>dn>>Kn>>df>>Kf>>ds>>Ps>>dT>>tot>>d0>>filename; tot = 2500; double KI[2] = {1.0,4.0}; double KM[2] = {1.0,1.5}; double KN[2] = {0.5,1.0}; double KF[2] = {0.1,0.3}; double PS[2] = {0.01,0.0001}; int number = 0; for(int a1=0;a1<2;a1++){ for(int a2=0;a2<2;a2++){ for(int a3=0;a3<2;a3++){ for(int a4=0;a4<2;a4++){ for(int a5=0;a5<2;a5++){ Ki=KI[a1]; Km=KM[a2]; Kn=KN[a3]; Kf=KF[a4]; Ps=PS[a5]; filename = "outfile"+std::to_string(number); cwnd = Ki*MSS; ssthresh=0; //write(filename,cwnd,itr); int flag=0; for(itr=0;itr<=tot;itr++){ //check for timeout; int timeout = prob(); if(timeout == 1){ write(filename,cwnd,itr); ssthresh = cwnd/2; cwnd = max(1.0,Kf*cwnd); flag++; continue; } write(filename,cwnd,itr); if(flag==0||cwnd<ssthresh){ cwnd = min(cwnd + Km*MSS, RWS); } else{ cwnd = min((cwnd + Kn*MSS*(MSS/cwnd)),RWS); } } number++; } } } } } // return 0; }
0085cdb089a83f9ba3abb0da7f7fa775cf53e49e
8b7820d05f983f60d82030cfe210cdaf3e3591f0
/inc/blocked_container.h
0748bf4b68db17657f014fd6ae6bc533138a7d98
[]
no_license
neverlandjt/sheeppl
381df1bb204f6ae2ad055f7a8ae130ef74f91763
8550253f09a7012976ba4b9ca62c879763a995cf
refs/heads/main
2023-04-25T06:53:14.597746
2021-05-20T10:17:00
2021-05-20T10:17:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,314
h
blocked_container.h
// // Created by ytymchenko on 07.05.2021. // #ifndef SHEEPPL_BLOCKED_CONTAINER_H #define SHEEPPL_BLOCKED_CONTAINER_H #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/access.hpp> #include "sheeppl_stddef.h" namespace sheeppl { template<typename T> class blocked_container { public: // types typedef size_t size_type; typedef T const_iterator; blocked_container() = default; blocked_container(T &container, size_t size_) : container(container), size_(size_) {} blocked_container(typename T::const_iterator begin, typename T::const_iterator end) : container(T(begin, end)), size_(container.size()) {}; template<class Archive> void serialize(Archive &ar, const unsigned int version) { ar & container; ar & size_; } auto begin() const { return container.begin(); }; auto end() const{ return container.end(); }; T container; private: friend class boost::serialization::access; size_t size_; }; } #endif //SHEEPPL_BLOCKED_CONTAINER_H
3e0e27c933292e09e0e1ce017ee80af802b6c2c0
7157875cf79cc8b5d926307d9a8c774ba6d99523
/menu_diagnosisRepairSystemRetrieveData.h
d923afbfec376853ffba3d4ff6643aa86b6013ee
[]
no_license
Tomev/NASA-Universal-Tool-Pro
19a6495ceb390a7960f1950ccb4af14175004dae
9fba886133dd999ef011d5a3b443b58fc0705ae1
refs/heads/master
2021-01-15T18:50:53.618200
2015-07-23T20:16:09
2015-07-23T20:16:09
39,590,169
2
0
null
null
null
null
UTF-8
C++
false
false
1,559
h
menu_diagnosisRepairSystemRetrieveData.h
#ifndef MENU_DIAGNOSISREPAIRSYSTEMRETRIEVEDATA_H #define MENU_DIAGNOSISREPAIRSYSTEMRETRIEVEDATA_H #include <QDialog> #include <QSize> #include <QTimer> #include <QStringList> #include <QDirIterator> namespace Ui { class menu_diagnosisRepairSystemRetrieveData; } class menu_diagnosisRepairSystemRetrieveData : public QDialog { Q_OBJECT public: explicit menu_diagnosisRepairSystemRetrieveData(QWidget *parent = 0); menu_diagnosisRepairSystemRetrieveData(int i); ~menu_diagnosisRepairSystemRetrieveData(); private slots: void on_startButton_clicked(); void on_detailsButton_clicked(); void on_cancelButton_clicked(); void onCurrentTimerTick(); void onStatusTimerTick(); void onOverallTimerTick(); private: Ui::menu_diagnosisRepairSystemRetrieveData *ui; QSize size; QString repairMsg; QString detailedMsg; QTimer* currentTimer; QTimer* statusTimer; QTimer* overallTimer; QStringList viruses; QStringList drives; QDirIterator* iterator; int applicationType; int currentProgress; int overallProgress; int driveCounter; static const int currentTimerInterval = 12; static const int statusTimerInterval = 250; static const int overallTimerInterval = 60000; //static const int overallTimerInterval = 111; void fillVirusesList(); void defineVariables(int i=0); void updateDiagnosisMessage(); void updateRepairMessage(); void updateRetrieveMessage(); void updateEraseMessage(); void updateDetailsMessage(); }; #endif
859907147e0fe95224f58f72c0a158503d0f0eb8
82c41f5231a8d022b675e5e0718680bebf48c8ce
/level2/recursionAndBacktracking/coinchangeComb_1.cpp
0cb640e9db65cb8deb3155f6fb0088ae7dc5405d
[]
no_license
Namanmittal0007/DsaLevel1
9a5a5e2239eeae764a7512769db9528dd767929e
fd9e3df1bbe61c1d6ced9cc67c67798cb057cf96
refs/heads/master
2023-07-15T03:32:05.287858
2021-08-25T20:27:18
2021-08-25T20:27:18
320,229,954
0
0
null
null
null
null
UTF-8
C++
false
false
597
cpp
coinchangeComb_1.cpp
#include<bits/stdc++.h> using namespace std; void coincomb1(int idx,vector<int> coins, string ans, int cursum, int tarsum){ if(idx==coins.size() || cursum>tarsum){ if(cursum==tarsum){ cout<<ans<<"."<<endl; } return; } coincomb1(idx+1, coins, ans+to_string(coins[idx])+"-", cursum+coins[idx], tarsum); coincomb1(idx+1, coins, ans, cursum, tarsum); } int main(){ int n; cin>>n; vector<int> coins(n); for(int i=0; i<n; i++){ cin>>coins[i]; } int tarsum; cin>>tarsum; coincomb1(0,coins,"",0,tarsum); }
03b547c0ef64fd43d07a635400fa2908f15a1440
7b91434d55d6bef1e3b2fdcd26b07fd62e3b73b1
/UnnamedEngine/Sources/Engine/Base/Resource/Serializer.h
180aa5de9b56b5f665b2dfda05f1350b98fc10bd
[ "MIT" ]
permissive
ryanannis/UnnamedEngine
9af75727f4fff3b8b1a0035f56e5079306185c9e
44a9eaaef6284f7d93e7f42fd2e693d37d528e0f
refs/heads/master
2022-08-13T10:41:54.776792
2020-05-21T06:53:02
2020-05-21T06:53:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,296
h
Serializer.h
#pragma once #include "Engine/Base/Common/Common.h" #include "PropTree.h" #include "Engine/Base/Resource/ResourceType.h" #include <string> #include <vector> class Resource; class ComponentBase; class EntityResource; #define SERIALIZE(serializer, name, var) \ if(serializer.GetSerializationState() == SerializationState::SERIALIZING){ \ serializer.Serialize(name, var); \ } \ else{ \ serializer.Deserialize(name, var); \ } \ class ResourceManager; enum class SerializationState { SERIALIZING, DESERIALIZING }; class Serializer { public: // Serializes with an empty proptree Serializer(); SerializationState GetSerializationState(); Serializer& Serialize(ComponentBase& c); Serializer& Serialize(std::string tag, std::string s); Serializer& Serialize(std::string tag, int i); Serializer& Serialize(std::string tag, const Vector3f& vec); template <typename T> Serializer& Serialize(std::string tag, ResourceType<T>& res) { mSerializationTree.AddLeaf(tag, res.GetURI()); return(*this); } template <typename T> void Deserialize(std::string name, ResourceType<T>& ref) { auto leaf = mSerializationTree.leaves.find(name); if(leaf != mSerializationTree.leaves.end()) { auto typedLeaf = dynamic_cast<PropTreeLeaf<URI>*>(leaf->second); if(typedLeaf) { ref = ResourceType<T>(typedLeaf->Get()); } } // otherwise, the component doesn't exist - this is ok, just means we use default } template <typename T> void Deserialize(std::string name, T& ref) { auto leaf = mSerializationTree.leaves.find(name); if(leaf != mSerializationTree.leaves.end()) { auto typedLeaf = dynamic_cast<PropTreeLeaf<T>*>(leaf->second); if(typedLeaf) { ref = typedLeaf->Get(); } } // otherwise, the component doesn't exist - this is ok, just means we use default } private: Serializer(PropTree tree, SerializationState s = SerializationState::SERIALIZING); std::string Serialize(std::string s) const; std::string Serialize(int i) const; template <typename T> std::string Serialize(ResourceType<T>& res) const { return(res.mURI.GetSerialized()); } PropTree mSerializationTree; SerializationState mSerializationState; friend EntityResource; };
bfda70d6d83ac508f7342601649fd6cba6bd164e
af473fdef22da719c79362d19faba6512f04e1d7
/src/ix_pagehandle.cc
6d0d8bb09039836cec22015af3ef3c965839aa68
[]
no_license
deadstone03/RedBase
037b724e5f0f5c19ccd077d258bfd65da947acbf
72f007dadc5753bd8b846f786d5bf00f19f67c76
refs/heads/master
2021-01-11T02:24:00.826915
2016-11-01T06:21:09
2016-11-01T06:21:09
70,967,483
0
0
null
null
null
null
UTF-8
C++
false
false
3,724
cc
ix_pagehandle.cc
#include "ix.h" #include "ix_internal.h" #include <cstring> IX_PageHandle::IX_PageHandle() { } IX_PageHandle::~IX_PageHandle() { } RC IX_PageHandle::InsertEntry(void *pData, const RID &rid) { if (this->phdr->slotCount == this->m) { return IX_PAGE_FULL; } // insert should be keep the order. int i; for (i = 0; i < this->phdr->slotCount; ++i) { if (compare(pData, this->pData + i * this->slotSize, this->attrType, this-> attrLength) <= 0) { break; } } memmove(this->pData + (i + 1) * this->slotSize, this->pData + i * this->slotSize, (this->phdr->slotCount - i) * this->slotSize); this->phdr->slotCount++; return this->SetThisSlot(i, pData, rid); } RC IX_PageHandle::GetPageNum(PageNum &pageNum) { pageNum = this->pageNum; return 0; } RC IX_PageHandle::Split(IX_PageHandle &newIxPageHandle) { RC rc; PageNum newPageNum; if ((rc = newIxPageHandle.GetPageNum(newPageNum))) { return rc; } newIxPageHandle.phdr->isRoot = FALSE; newIxPageHandle.phdr->sibling = this->phdr->sibling; this->phdr->sibling = newPageNum; newIxPageHandle.phdr->isLeaf = this->phdr->isLeaf; int leftSize = this->phdr->slotCount / 2; int rightSize = this->phdr->slotCount - leftSize; memcpy(newIxPageHandle.pData, this->pData + leftSize * this->slotSize, rightSize * this->slotSize); this->phdr->slotCount = leftSize; newIxPageHandle.phdr->slotCount = rightSize; return 0; } RC IX_PageHandle::GetThisSlot(SlotNum slotNum, void* &pData, RID &rid) const { if (!this->IsValidSlotNum(slotNum)) { return IX_INVALID_SLOTNUM; } pData = new char[this->attrLength]; memcpy(pData, this->pData + this->slotSize * slotNum, this->attrLength); memcpy(&rid, this->pData + this->slotSize * slotNum + this->attrLength, sizeof(RID)); return 0; } RC IX_PageHandle::GetLastSlot(void* &pData, RID &rid) const { return this->GetThisSlot(this->phdr->slotCount, pData, rid); } RC IX_PageHandle::SetThisSlot(SlotNum slotNum, const void* pData, const RID &rid) { if (!this->IsValidSlotNum(slotNum)) { return IX_INVALID_SLOTNUM; } memcpy(this->pData + this->slotSize * slotNum, pData, this->attrLength); memcpy(this->pData + this->slotSize * slotNum + this->attrLength, &rid, sizeof(RID)); return 0; } // To handle duplicate values, there are a few thing we need to do. // A slot points to a page. the correspond value will be the new value in it's // child page. The 'new' means the first value in the child page which not equal // to the previous page's last value. // If the whole child page is the same values, then current value should be some // dummy value. But it's hard to set up a dummy value since every possible value // will be used. But for internal pages, the rid's slot part is actually not // used, we can use it to mark dummy value. Normall rid's slot will be // NON_DUMMY, dummy one will be DUMMY. RC IX_PageHandle::GetNextSlot(const void* pData, void* &pNextData, RID &rid) const { int i; void* pSlotData; RID* pSlotRid; RC rc; for (i = 0; i < this->phdr->slotCount - 1; ++i) { pSlotData = this->pData + this->slotSize * i; pSlotRid = (RID*)(this->pData + this->slotSize * i + this->attrLength); SlotNum slotNum; if ((rc = pSlotRid->GetSlotNum(slotNum)) && rc != RM_RID_NOTINIT) { return rc; } if (slotNum == IX_DUMMY) { continue; } if (compare(pData, pSlotData, this->attrType, this->attrLength) < 0) { continue; } } int IX_PageHandle::IsValidSlotNum(SlotNum slotNum) const { return slotNum >=0 && slotNum < this->phdr->slotCount; }
42a5a075f6c138c707278cef3def5526af23a2f0
10ed4e10d25c7a059a6c03370b5b5239ef28c6ef
/GameTemplate/Game/main_processing.h
5998b4290dd8283e93dbc420361a4d5a50d26c34
[]
no_license
kbc23/SchoolFestivalGame
5ce8fef2f516a049235a9a33b3c52b4e05d757df
980951db690281b62f929ead240cf2a546e3b937
refs/heads/master
2023-09-05T02:12:16.904380
2021-10-18T03:25:08
2021-10-18T03:25:08
373,381,747
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
7,305
h
main_processing.h
#pragma once #include "font_render.h" #include "sprite_render.h" #include "fade.h" #include "sound_BGM.h" #include "sound_SE.h" #include "constant.h" class Title; class ModeSelect; class PlayerSelect; class CPUStrengthSelect; class Game; class Result; class GameCamera; class MainProcessing : public IGameObject { public: MainProcessing(); ~MainProcessing(); bool Start() override final; void Update() override final; private: //////////////////////////////////////////////////////////// // 毎フレームする処理 //////////////////////////////////////////////////////////// /** * @brief 背景画像を移動させる処理 */ void DrawBackground(); //////////////////////////////////////////////////////////// // シーンごとの処理 //////////////////////////////////////////////////////////// ////////////////////////////// // ゲーム開始時のロードの処理 ////////////////////////////// /** * @brief ゲーム開始時のロード */ void StartLoading(); ////////////////////////////// // タイトルシーンの処理 ////////////////////////////// /** * @brief タイトルシーンの処理 */ void TitleScene(); /** * @brief 決定選択時 */ void DecisionTitleScene(); ////////////////////////////// // モードセレクトシーンの処理 ////////////////////////////// /** * @brief モードセレクトシーンの処理 */ void ModeSelectScene(); /** * @brief 決定選択時 */ void DecisionModeSelectScene(); /** * @brief キャンセル選択時 */ void CancelModeSelectScene(); ////////////////////////////// // プレイヤーセレクトシーンの処理 ////////////////////////////// /** * @brief プレイヤーセレクトシーンの処理 */ void PlayerSelectScene(); /** * @brief 決定選択時 */ void DecisionPlayerSelectScene(); /** * @brief キャンセル選択時 */ void CancelPlayerSelectScene(); ////////////////////////////// // CPUの難易度選択シーンの処理 ////////////////////////////// /** * @brief タイトルシーンの処理 */ void CPUStrengthSelectScene(); /** * @brief 決定選択時 */ void DecisionCPUStrengthSelectScene(); /** * @brief キャンセル選択時 */ void CancelCPUStrengthSelectScene(); ////////////////////////////// // ゲームシーンのためのロード ////////////////////////////// /** * @brief ロードの処理 */ void LoadingGameScene(); /** * @brief ロードの準備 */ void PreparingForLoading(); /** * @brief ロード */ void Loading(); /** * @brief ロードの終わり */ void EndOfLoading(); ////////////////////////////// // ゲームシーンの処理 ////////////////////////////// /** * @brief ゲームシーンの処理 */ void GameScene(); /** * @brief ゲームシーン終了時 */ void FinishGameScene(); ////////////////////////////// // リザルトシーンの処理 ////////////////////////////// /** * @brief リザルトシーンの処理 */ void ResultScene(); public: //Pause関連 /** * @brief ポーズ画面でリトライを選択 */ void PauseRetry(); /** * @brief ポーズ画面でタイトルに戻るを選択 */ void PauseTitle(); public: //Get関数 /** * @brief m_StopOperationのGet関数 * @return プレイヤーの操作処理をできなくしているか */ const bool GetStopOperation() const { return m_StopOperation; } public: //Set関数 /** * @brief プレイヤーの順位をセット * @param playerNum プレイヤーの番号 * @param rank 順位 */ void SetRank(const int playerNum, const int rank) { m_rank[playerNum] = rank; } /** * @brief リザルト画面でどの選択肢を選んだかをセット * @param select リザルト画面でどの選択肢を選んだか */ void SetResultSelect(const int select) { m_resultselect = select; } /** * @brief ゲームの処理が終わっているか * @param flagGameEnd ゲームの処理が終わっているか */ void SetGameEnd(const bool flagGameEnd) { m_gameEnd = flagGameEnd; } private: //enum enum class GameStatus { startLoading, title, modeSelect, playerSelect, CPUStrengthSelect, loadingGame, game, result, GameStatusMax }; enum class StartLoadingStatus { preparation, //ロードの準備 loading, //ロード中 finish, //ロード終了 StartLoadingStatusMax }; enum class LoadingStatus { doNothing, //何もしていない preparingForLoading, //ロードの準備 loading, //ロード中 endOfLoading, //ロード終了 LoadingStatusMax }; public: //constant static const int m_MAX_BACKGROUND = 7; //背景画像の最大枚数 private: //data menber //////////////////////////////////////////////////////////// // クラスのオブジェクト //////////////////////////////////////////////////////////// Title* m_title = nullptr; ModeSelect* m_modeSelect = nullptr; PlayerSelect* m_playerSelect = nullptr; CPUStrengthSelect* m_CPUStrengthSelect = nullptr; Game* m_game = nullptr; Result* m_result = nullptr; GameCamera* m_gameCamera = nullptr; SpriteRender* m_spriteBackground[m_MAX_BACKGROUND] = { nullptr }; Fade* m_fade = nullptr; SoundBGM* m_bgmTitle = nullptr; SoundSE* m_seCancel = nullptr; //////////////////////////////////////////////////////////// // タイマー関連 //////////////////////////////////////////////////////////// bool m_StopOperation = true; //プレイヤーの操作ができるか bool m_gameSceneFlagFinish = false; //ゲームシーンでやることが終わっているか //////////////////////////////////////////////////////////// // フラグ関連 //////////////////////////////////////////////////////////// GameStatus m_gameStatus = GameStatus::title; StartLoadingStatus m_startLoadingStatus = StartLoadingStatus::preparation; LoadingStatus m_loadStatus = LoadingStatus::doNothing; bool m_startPreparingForLoading = false; bool m_startEndOfLoading = false; bool m_flagGameStart = false; bool m_gameEnd = false; //ゲームシーンのゲームが終了したか //////////////////////////////////////////////////////////// // その他 //////////////////////////////////////////////////////////// int m_maxPlayer = 0; //操作しているプレイヤーの数 int m_rank[con::PlayerNumberMax] = { 0,0,0,0 }; int m_resultselect = 0; //リザルトで何選んだか };
3308abf9289404adbb73e853d35da1a3a657f322
00d5f08d7e17c09a302ac540053525080152a870
/LeetCode/lc_238.cpp
c251403938d5ffe901626c30da27fd8b6517e72b
[]
no_license
HubbardHuang/data_structures_and_algorithms
6fea8670ed909e89ff5206c09cec61ee1ede71e2
b50552383420e263c95dd02f81e0bf2478b4679c
refs/heads/master
2020-04-19T14:33:59.847703
2019-08-12T13:11:38
2019-08-12T13:11:38
168,221,800
0
0
null
null
null
null
UTF-8
C++
false
false
968
cpp
lc_238.cpp
/* Title: Product of Array Except Self Description: Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Note: Please solve it without division and in O(n). Follow up: Could you solve it with constant space complexity? (The output array does not count as extra space for the purpose of space complexity analysis.) */ class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { if (nums.size() <= 1) { return nums; } vector<int> result(nums.size(), 1); for (int i = 1; i < result.size(); i++) { result[i] = result[i - 1] * nums[i - 1]; } int addition = 1; for (int i = result.size() - 1; i >= 0; i--) { result[i] *= addition; addition *= nums[i]; } return result; } };
3f61cea4aa00ead0f95b90f869f88e2b39df2125
b4f42eed62aa7ef0e28f04c1f455f030115ec58e
/messagingfw/msgtestproduct/email/imap/src/T_IsImapMessageHeaderOnly.cpp
1a2a611ab5e8acaeb063a8e089f583a364d9c586
[]
no_license
SymbianSource/oss.FCL.sf.mw.messagingmw
6addffd79d854f7a670cbb5d89341b0aa6e8c849
7af85768c2d2bc370cbb3b95e01103f7b7577455
refs/heads/master
2021-01-17T16:45:41.697969
2010-11-03T17:11:46
2010-11-03T17:11:46
71,851,820
1
0
null
null
null
null
UTF-8
C++
false
false
6,832
cpp
T_IsImapMessageHeaderOnly.cpp
// Copyright (c) 2007-2009 Nokia Corporation and/or its subsidiary(-ies). // All rights reserved. // This component and the accompanying materials are made available // under the terms of "Eclipse Public License v1.0" // which accompanies this distribution, and is available // at the URL "http://www.eclipse.org/legal/epl-v10.html". // // Initial Contributors: // Nokia Corporation - initial contribution. // // Contributors: // // Description: // [TestStep Name] // IsImapMessageHeaderOnly // [Paramaters] // ImapAccountName :Name of the Imap account. // ImapFolderName :Name of the remote folder that the message resides. // Subject :Subject of the received message to be checked. // HeaderOnly :The state to test: // :ETrue(1) => Header only message expected. // :EFalse(0) => Message with header and some or all content (body and/or attachments) expected. // Checks if the fetched IMAP message for a given account is header only // or content for it has been downloaded such as body and attachments . // // //User includes #include "T_IsImapMessageHeaderOnly.h" #include <t_utilscentralrepository.h> #include <t_utils.h> //Epoc inlcudes #include <msvids.h> #include <mmsvattachmentmanager.h> #include <miutmsg.h> //Literals used _LIT(KImapAccountName,"ImapAccountName"); _LIT(KImapFolderName,"ImapFolderName"); _LIT(KSubject,"Subject"); _LIT(KHeaderOnly,"HeaderOnly"); /** Function : CT_MsgIsImapMessageHeaderOnly Description : Constructor @param : aSharedDataIMAP Reference to CT_MsgSharedDataImap @return : N/A */ CT_MsgIsImapMessageHeaderOnly::CT_MsgIsImapMessageHeaderOnly(CT_MsgSharedDataImap& aSharedDataIMAP) :CT_MsgAsyncStepIMAP(aSharedDataIMAP) ,iOperation(NULL) ,iRecvMessageInfo(NULL) { SetTestStepName(KIsImapMessageHeaderOnly); } /** Function : ~CT_MsgIsImapMessageHeaderOnly Description : Destructor @return : N/A */ CT_MsgIsImapMessageHeaderOnly::~CT_MsgIsImapMessageHeaderOnly() { delete iOperation; delete iRecvMessageInfo; } /** Function : NewL Description : Creates an object of CT_MsgIsImapMessageHeaderOnly @param : aSharedDataIMAP Reference to CT_MsgSharedDataImap @return : Pointer to CT_MsgIsImapMessageHeaderOnly */ CT_MsgIsImapMessageHeaderOnly* CT_MsgIsImapMessageHeaderOnly::NewL(CT_MsgSharedDataImap& aSharedDataIMAP) { CT_MsgIsImapMessageHeaderOnly* self = new(ELeave) CT_MsgIsImapMessageHeaderOnly(aSharedDataIMAP); CleanupStack::PushL(self); self->ConstructL(); CleanupStack::Pop(self); return self; } /** Function : ReadIni Description :Reads the corresponding .ini file and returns EPass or EFail if any of the inputs are missing @return : TBool */ TBool CT_MsgIsImapMessageHeaderOnly::ReadIni() { TBool result = ETrue; if(!GetStringFromConfig(ConfigSection(), KImapAccountName, iImapAccountName)) { ERR_PRINTF1(_L("Imap account name is not specified")); SetTestStepResult(EFail); result = EFalse; } if(!GetStringFromConfig(ConfigSection(), KImapFolderName, iImapFolderName)) { ERR_PRINTF1(_L("Remote Imap folder name is not specified")); SetTestStepResult(EFail); result = EFalse; } if(!GetStringFromConfig(ConfigSection(), KSubject, iSubject)) { ERR_PRINTF1(_L("Subject name of the received message to be checked is not specified")); SetTestStepResult(EFail); result = EFalse; } if(!GetBoolFromConfig(ConfigSection(), KHeaderOnly, iHeaderOnly)) { ERR_PRINTF1(_L("An expected \"ETrue\" or \"EFalse\" boolean value is not specified for checking header only state")); SetTestStepResult(EFail); result = EFalse; } return result; } /** Function : doTestStepL Description : Checks if the fetched IMAP message for a given account is header only or content for it has been downloaded such as body and attachments. @return : TVerdict - Test step result */ TVerdict CT_MsgIsImapMessageHeaderOnly::doTestStepL() { INFO_PRINTF1(_L("Test Step : IsImapMessageHeaderOnly")); if(ReadIni()) { // Retrieve the Imap service Id for the given Imap account TMsvId imapServiceId = CT_MsgUtilsCentralRepository::GetImapServiceIdL((TDes&)iImapAccountName); INFO_PRINTF2(_L("Imap service id is %d"),imapServiceId ); // If the IMAP Service Id is KMsvNullIndexEntryId then an invalid IMAP account name is specified if(imapServiceId == KMsvNullIndexEntryId) { ERR_PRINTF1(_L("Invalid IMAP account name is specified")); SetTestStepResult(EFail); } // Retrieve the message Id based on the message subject TMsvId messageId = CT_MsgUtils::FindEntryByNameL(iSharedDataIMAP.iSession, imapServiceId, (TDesC&)iSubject, (TDesC&)iImapFolderName); if(messageId == KMsvNullIndexEntryId) { ERR_PRINTF1(_L("The given message is not found")); SetTestStepResult(EFail); } // Message found else { INFO_PRINTF2(_L("The message Id is %d"),messageId ); } CMsvEntry* recvMsvEntry = (iSharedDataIMAP.iSession)->GetEntryL(KMsvRootIndexEntryId); CleanupStack::PushL(recvMsvEntry); //Set the context to the sent message entry recvMsvEntry->SetEntryL(messageId); iRecvMessageInfo = CT_MsgUtilsEmailMessage::NewL(*recvMsvEntry,*this); TBool headerOnly = EFalse; TInt32 bodyTextSize = iRecvMessageInfo->GetBodyTextSize(); // Get attachment list for the received message CImEmailMessage* recvEmailMessage = iRecvMessageInfo->GetEmailMessageL(); // Call the asynchronous function to get the attachment list TInt err = iRecvMessageInfo->GetMessageAttachmentListL(); if (err != KErrNone) { SetTestStepResult(EFail); return TestStepResult(); } // Get the list of attachments present in received message MMsvAttachmentManager& recvManager = recvEmailMessage->AttachmentManager(); TInt recvMsgAttachmentCount = recvManager.AttachmentCount(); if (bodyTextSize == 0 && recvMsgAttachmentCount == 0) { headerOnly = ETrue; } else if (bodyTextSize > 0 || recvMsgAttachmentCount > 0) { headerOnly = EFalse; } // Test expected state if (iHeaderOnly == headerOnly) { INFO_PRINTF1(_L("State of received message is as expected")); } else { ERR_PRINTF1(_L("State of received message is not as expected")); SetTestStepResult(EFail); } CleanupStack::PopAndDestroy(recvMsvEntry); // recvMsvEntry } return TestStepResult(); } /** Function : ProgressL Description : Displays the progress information of the asynchronous operation @return : void */ void CT_MsgIsImapMessageHeaderOnly::ProgressL(TBool bFinal) { // Stub if ( bFinal ) { /* Display final progress iOperation */ } else { /* Display current progress iOperation */ } } /** Function : CancelStep Description : Cancels the asynchronous operation @return : void */ void CT_MsgIsImapMessageHeaderOnly::CancelStep() { iOperation->Cancel(); }
25c0bb1b408b5c8706402713a6396b079439b309
71fd4437ce3c964dde078b9a13d6e89a27a08e3a
/LaumioAnimator/animations/pulsingcoloranimation.h
c26d7ed2dfe1759bd3502500106cbd4d4ddd5aea
[]
no_license
haum/laumio_animator
107b512e80f2d845ce9e8305b07907f16881497a
365d7a56ccdc8863546a1230793b48b48c055055
refs/heads/master
2020-04-06T07:11:41.271954
2016-08-27T04:19:35
2016-08-27T04:25:58
65,077,356
0
0
null
null
null
null
UTF-8
C++
false
false
2,131
h
pulsingcoloranimation.h
#ifndef PULSINGCOLORANIMATION_H #define PULSINGCOLORANIMATION_H #include <QObject> #include <QColor> #include <memory> #include <cmath> #include "animation.h" /* JSON format : { "delay" = <NB>, "duration" = <NB>, "frequency" = <NB>, "fromStart" = <NB>, "lowerColor" = "<COLOR>", "pulseSignal" = "<SIGNAL>", "upperColor" = "<COLOR>" } */ /** Animation which set a laumio to a pulsing color **/ class PulsingColorAnimation : public Animation { Q_OBJECT /** Property storing rectangle color in timeline **/ PROP(QColor, rectangleColor, "#8800FF") /** Property storing color to set **/ PROP(QColor, color, "black") /** Property storing mean color parameter **/ PROP(QColor, meanColor, QColor(0x80,0x80,0x80)) /** Property storing amplitude parameter of color variation **/ PROP(QColor, varColor, QColor(0x7f,0x7f,0x7f)) /** Property storing pulsation signal, in rad/s **/ PROP(double, pulsation, 2 * M_PI) /** Property storing phase-delay signal from start, in seconds **/ PROP(double, delay, 0.0) public: /** Factory function to create the animation * @return New animation wrapped in unique_ptr */ static std::unique_ptr <Animation> factory(); /** Constructor * @param parent QObject's parent if memory ownership is managed by Qt, * nullptr otherwise */ explicit PulsingColorAnimation(QObject * parent = nullptr); virtual bool animationStart(Laumio & laumio) override; virtual bool animationUpdate(Laumio & laumio, double time) override; virtual void animationStop(Laumio & laumio) override; virtual void loadFromJSON(const QJsonObject & obj) override; virtual void saveToJSON(QJsonObject & obj) override; QString pulseSignalName() { return m_pulseSignalName ; } void set_pulseSignal(QString name); private: bool done = false; QString m_pulseSignalName = "sinus"; void (PulsingColorAnimation::*pulseSignal)(double time) = &PulsingColorAnimation::sinusSignal; void sinusSignal(double time); }; #endif // PULSINGCOLORANIMATION_H
84af4a6ec7b7dea667dc65682e93f51ddd4d39af
fa5a51b8a1ea1e6d97d2c8831c72f5b1b5aaca74
/Game/AnimationSprite.cpp
9f7812627b88ee12dc90de1102ebeddd4b2fbafe
[]
no_license
otakuto/STG
6ab15162a5df9485837fc4549e7e7d8998f20d0b
c3f1f7872fa677199ffc4d275d4a6b29112663f6
refs/heads/master
2016-09-05T17:24:37.347679
2014-05-27T17:44:47
2014-05-27T17:44:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,713
cpp
AnimationSprite.cpp
#pragma once #include "stdafx.hpp" #include "AnimationSprite.hpp" AnimationSprite::AnimationSprite(LPDIRECT3DDEVICE9 const & direct3DDevice, std::vector<LPDIRECT3DTEXTURE9 const> const & texture, RECT const & range, D3DXVECTOR3 const&center, bool const additive, int const interval) : direct3DDevice(direct3DDevice), texture(texture), range(range), center(center), additive(additive), interval(interval), count(0) { D3DXCreateSprite(direct3DDevice, &sprite); } AnimationSprite::~AnimationSprite() { } void AnimationSprite::Draw(D3DXVECTOR3 const&position) const { /* D3DXVECTOR3 p = position; p.x = (int)p.x; p.y = (int)p.y; p.z = (int)p.z; */ sprite->Begin(D3DXSPRITE_ALPHABLEND); setRenderState(); sprite->Draw(texture[count / interval], &range, &center, &position, D3DCOLOR_ARGB(0xFF, 0xFF, 0xFF, 0xFF)); sprite->End(); } void AnimationSprite::Draw(D3DXVECTOR3 const&position, float const angle) const { sprite->Begin(D3DXSPRITE_ALPHABLEND); D3DXMATRIX matRotation; D3DXMatrixRotationZ(&matRotation, angle); D3DXMATRIX matTranslation; D3DXMatrixTranslation(&matTranslation, position.x, position.y, 0); D3DXMATRIX matWorld; D3DXMATRIX matIdentity; D3DXMatrixIdentity(&matIdentity); matWorld = matRotation*matTranslation; sprite->SetTransform(&matWorld); setRenderState(); sprite->Draw(texture[count / interval], &range, &center, 0, D3DCOLOR_ARGB(0xFF, 0xFF, 0xFF, 0xFF)); sprite->SetTransform(&matIdentity); sprite->End(); } void AnimationSprite::Draw(D3DXVECTOR3 const&position, float const angle, float const scale, int const alpha) const { sprite->Begin(D3DXSPRITE_ALPHABLEND); D3DXMATRIX matScale, matRotation, matTranslation, matWorld, matIdentity; D3DXMatrixScaling(&matScale, scale, scale, scale); D3DXMatrixRotationZ(&matRotation, angle); D3DXMatrixTranslation(&matTranslation, position.x, position.y, 0); D3DXMatrixIdentity(&matIdentity); matWorld = matScale * matRotation * matTranslation; sprite->SetTransform(&matWorld); setRenderState(); if (additive) { sprite->Draw(texture[count / interval], &range, &center, 0, D3DCOLOR_ARGB(alpha, alpha, alpha, alpha)); } else { sprite->Draw(texture[count / interval], &range, &center, 0, D3DCOLOR_ARGB(alpha, 0xFF, 0xFF, 0xFF)); } sprite->SetTransform(&matIdentity); sprite->End(); } void AnimationSprite::CountUp() { ++count; } void AnimationSprite::setRenderState() const { DWORD src, dest; if (additive) { src = D3DBLEND_ONE; dest = D3DBLEND_ONE; } else { src = D3DBLEND_SRCALPHA; dest = D3DBLEND_INVSRCALPHA; } direct3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, true); direct3DDevice->SetRenderState(D3DRS_SRCBLEND, src); direct3DDevice->SetRenderState(D3DRS_DESTBLEND, dest); }
11934a0df6d1a97b196c72fcaf3b6b907611098d
db5faa187eacebd8be27bdd971bba455aa30cd55
/cpp/algo/itrv/mincount.cpp
36d7cb4f71a956910fa676793731416836ab9100
[]
no_license
ajaygh/go
7a9eb303b28770778993c91df8e62f32d0ee65cb
6057017eb38fea669396832a15dd2aa43f652e2e
refs/heads/master
2020-12-30T16:14:29.603814
2017-12-12T07:49:35
2017-12-12T07:49:35
90,964,485
0
0
null
null
null
null
UTF-8
C++
false
false
331
cpp
mincount.cpp
#include <iostream> #include <map> #include <limits.h> using namespace std; int main() { int n; cin >> n; int tmp; map<int, int> mapNum; for(int i = 0; i < n; i++){ cin >> tmp; mapNum[tmp]++; } int min = INT_MAX; for(auto el: mapNum){ if(min > el.second) min = el.second; } cout << min << endl; return 0; }
13b21d618272a0058adad6aaf85632128bb06a54
7f4346156601c4b43f879294bda58baefa10d820
/MessageHandler.h
7934bdbeac403f015c4ae0c7aec02afb898088d0
[ "MIT" ]
permissive
andreasabt/linux-abt
8b3361fbe4d99548f5d4bf5e402e2dfd07e32d04
8ed377b983540f3c462aedfddc170c8e5a1cad8a
refs/heads/master
2021-01-15T18:46:30.074464
2013-06-14T20:04:14
2013-06-14T20:04:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
359
h
MessageHandler.h
#ifndef MESSAGEHANDLER_H #define MESSAGEHANDLER_H #include <vector> #include <ctime> #include <sstream> #include <stdio.h> #include <string> using namespace std; class MessageHandler { public: MessageHandler(string msg); ~MessageHandler() {}; string sender; vector<string> message; int atPosition(string msgVar); }; #endif
b2150a2ad981ca2b59ed1be391b1d970fe5317b9
c5af905e54185fb350b969d9a1c7abbc5bfd5cc1
/Milestone-3-Managers/CustomerItem.cpp
9307405104676358d2acc0389d5f5b0cfc008211
[]
no_license
PhillypHenning/OOP345-MileStones--1-4
3ed4950e0a221ccbe6f8e498e6620071635f1e4a
501c24afbef3328a00b24c8cba538130aa9eecbc
refs/heads/master
2021-01-12T09:33:11.878550
2016-12-11T18:43:19
2016-12-11T18:43:19
76,192,347
2
1
null
null
null
null
UTF-8
C++
false
false
1,503
cpp
CustomerItem.cpp
// Phillyp Henning // 055829147 #include <iomanip> #include <iostream> #include "CustomerItem.h" #include "Item.h" CustomerItem::CustomerItem(const std::string& pName){ // Task 1 : Sets name to the name received or to an empty state if no name was specified. // Task 2 : initalizes filled to false and code to 0. name = ""; if (!pName.empty()){ // Task 1. name = pName; } filled = false; code = 0; // Task 2. } bool CustomerItem::asksFor(const Item& item) const{ //returns true if the current objects asks for item return name == item.getName()? true : false; } bool CustomerItem::isFilled() const{ //returns true if the current object's request has been filled' return filled; } void CustomerItem::fill(const unsigned int fill){ code = fill; filled = true; } void CustomerItem::clear(){ code = 0; filled = false; } const std::string& CustomerItem::getName() const{ return name; } void CustomerItem::display(std::ostream& os) const{ /* Display customer order Task 1 : the symbol + or - identifying the fill status of the item request Task 2 : the code printed on the item if filled or 0 if not filled in a field width of CODE_WIDTH padded with 0s and enclosed within brackets Task 3 : the name of the customer item */ if (isFilled()){ os << " + "; } else{ os << " - "; } os << "[" << std::setw(CODE_WIDTH) << std::setfill('0') << std::right << code << "] " << name << std::endl; }
5662a7ef7f27e5cb97cb518b4467b90e300fcad7
3edc52629e045938eb0db853a64ebd488df33209
/OpenGlEngine/main.cpp
3c0e918c25d533d39db9dc61a05fa1e10bc90658
[]
no_license
paulbaudy/OpenGlEngine
7cbc07ff899ead5f49c584264214921568082988
2149185fdf66825f6b1f9bf462357730f16fabd3
refs/heads/master
2021-01-13T15:05:41.178216
2016-12-15T17:18:08
2016-12-15T17:18:08
76,302,625
0
0
null
null
null
null
UTF-8
C++
false
false
5,778
cpp
main.cpp
// Include standard headers #include <stdio.h> #include <stdlib.h> // Include GLEW #include "glew.h" // Include GLFW #include <glfw3.h> GLFWwindow* window; #define TINYOBJLOADER_IMPLEMENTATION #include "Mesh.h" #include "Camera.h" GLuint LoadShaders(const char * vertex_file_path, const char * fragment_file_path) { // Create the shaders GLuint VertexShaderID = glCreateShader(GL_VERTEX_SHADER); GLuint FragmentShaderID = glCreateShader(GL_FRAGMENT_SHADER); // Read the Vertex Shader code from the file std::string VertexShaderCode; std::ifstream VertexShaderStream(vertex_file_path, std::ios::in); if (VertexShaderStream.is_open()) { std::string Line = ""; while (getline(VertexShaderStream, Line)) VertexShaderCode += "\n" + Line; VertexShaderStream.close(); } else { printf("Impossible to open %s. Are you in the right directory ? Don't forget to read the FAQ !\n", vertex_file_path); getchar(); return 0; } // Read the Fragment Shader code from the file std::string FragmentShaderCode; std::ifstream FragmentShaderStream(fragment_file_path, std::ios::in); if (FragmentShaderStream.is_open()) { std::string Line = ""; while (getline(FragmentShaderStream, Line)) FragmentShaderCode += "\n" + Line; FragmentShaderStream.close(); } GLint Result = GL_FALSE; int InfoLogLength; // Compile Vertex Shader printf("Compiling shader : %s\n", vertex_file_path); char const * VertexSourcePointer = VertexShaderCode.c_str(); glShaderSource(VertexShaderID, 1, &VertexSourcePointer, NULL); glCompileShader(VertexShaderID); // Check Vertex Shader glGetShaderiv(VertexShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(VertexShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(VertexShaderID, InfoLogLength, NULL, &VertexShaderErrorMessage[0]); printf("%s\n", &VertexShaderErrorMessage[0]); } // Compile Fragment Shader printf("Compiling shader : %s\n", fragment_file_path); char const * FragmentSourcePointer = FragmentShaderCode.c_str(); glShaderSource(FragmentShaderID, 1, &FragmentSourcePointer, NULL); glCompileShader(FragmentShaderID); // Check Fragment Shader glGetShaderiv(FragmentShaderID, GL_COMPILE_STATUS, &Result); glGetShaderiv(FragmentShaderID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> FragmentShaderErrorMessage(InfoLogLength + 1); glGetShaderInfoLog(FragmentShaderID, InfoLogLength, NULL, &FragmentShaderErrorMessage[0]); printf("%s\n", &FragmentShaderErrorMessage[0]); } // Link the program printf("Linking program\n"); GLuint ProgramID = glCreateProgram(); glAttachShader(ProgramID, VertexShaderID); glAttachShader(ProgramID, FragmentShaderID); glLinkProgram(ProgramID); // Check the program glGetProgramiv(ProgramID, GL_LINK_STATUS, &Result); glGetProgramiv(ProgramID, GL_INFO_LOG_LENGTH, &InfoLogLength); if (InfoLogLength > 0) { std::vector<char> ProgramErrorMessage(InfoLogLength + 1); glGetProgramInfoLog(ProgramID, InfoLogLength, NULL, &ProgramErrorMessage[0]); printf("%s\n", &ProgramErrorMessage[0]); } glDetachShader(ProgramID, VertexShaderID); glDetachShader(ProgramID, FragmentShaderID); glDeleteShader(VertexShaderID); glDeleteShader(FragmentShaderID); return ProgramID; } int main(void) { // Initialise GLFW if (!glfwInit()) { fprintf(stderr, "Failed to initialize GLFW\n"); getchar(); return -1; } glfwWindowHint(GLFW_SAMPLES, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Open a window and create its OpenGL context window = glfwCreateWindow(1024, 768, "Tutorial 02 - Red triangle", NULL, NULL); if (window == NULL) { fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n"); getchar(); glfwTerminate(); return -1; } glfwMakeContextCurrent(window); // Initialize GLEW glewExperimental = true; // Needed for core profile if (glewInit() != GLEW_OK) { fprintf(stderr, "Failed to initialize GLEW\n"); getchar(); glfwTerminate(); return -1; } // Ensure we can capture the escape key being pressed below glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE); // Dark blue background glClearColor(0.0f, 0.0f, 0.4f, 0.0f); // Enable depth test glEnable(GL_DEPTH_TEST); // Accept fragment if it closer to the camera than the former one glDepthFunc(GL_LESS); GLuint VertexArrayID; glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); // Create and compile our GLSL program from the shaders GLuint programID = LoadShaders("TransformVertexShader.vertexshader", "ColorFragmentShader.fragmentshader"); Mesh rabbit("models/Rabbit/Rabbit.obj"); Camera _camera(-5, 0, 0); GLuint MatrixID = glGetUniformLocation(programID, "MVP"); do { // Clear the screen glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glUseProgram(programID); glUniformMatrix4fv(MatrixID, 1, GL_FALSE, &_camera.getMVP()[0][0]); rabbit.render(); // Swap buffers glfwSwapBuffers(window); glfwPollEvents(); } // Check if the ESC key was pressed or the window was closed while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0); // Close OpenGL window and terminate GLFW glfwTerminate(); return 0; }
d13e7c6848e9d00130c62a846ca0de746bdfae73
60dff076fae5d36af71af1066ac7eb4f833d2f2f
/onnxruntime/test/util/include/test_utils.h
388db559fc82d8c273be3c49311c97c1d475bd0d
[ "MIT" ]
permissive
NervanaSystems/onnxruntime
79e60f9c6feb8c147868d27de8077a276755cc90
96b3c09e2a5e0a5b4f98ed9059a719d9c7b73724
refs/heads/master
2023-06-22T02:55:35.250834
2023-01-03T22:54:46
2023-01-03T22:54:46
162,268,647
1
3
MIT
2021-01-14T12:56:23
2018-12-18T10:09:13
C++
UTF-8
C++
false
false
1,008
h
test_utils.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #include "core/framework/framework_common.h" #include "core/framework/execution_provider.h" #include <memory> #include <string> #include <vector> namespace onnxruntime { class Graph; namespace test { // return number of nodes in the Graph and any subgraphs that are assigned to the specified execution provider int CountAssignedNodes(const Graph& current_graph, const std::string& ep_type); // run the model using the CPU EP to get expected output, comparing to the output when the 'execution_provider' // is enabled. requires that at least one node is assigned to 'execution_provider' void RunAndVerifyOutputsWithEP(const ORTCHAR_T* model_path, const char* log_id, std::unique_ptr<IExecutionProvider> execution_provider, const NameMLValMap& feeds); } // namespace test } // namespace onnxruntime
0a5f75a2ad220e35a3e0b982348334a6d1c8b61c
3959f58fceadfdcde967863e8f5b995971bde489
/Babbar_series/Sets and Map/Basic/kthMissingUnsortedO_n.cpp
3128a3cf68ab07f07ac7511f7ac544d2472b5243
[]
no_license
ParagSaini/Competitive-Practice
4591ad85455c37f54b6251ff00f1a7766bd68ea5
02b0f22269c4ce0646ddfb2c3c04edded9d08e17
refs/heads/master
2023-06-23T18:22:25.811560
2021-07-23T18:36:49
2021-07-23T18:36:49
367,043,724
0
0
null
null
null
null
UTF-8
C++
false
false
793
cpp
kthMissingUnsortedO_n.cpp
#include<vector> #include<iostream> #include<algorithm> #include<unordered_set> using namespace std; void findMissing(vector<int> ar, int k) { unordered_set<int> missing; for(int i=0; i<ar.size(); i++ ) { missing.insert(ar[i]); } int maxi = *max_element(ar.begin(), ar.end()); // finding max in vector ar int mini = *min_element(ar.begin(), ar.end()); // finding min in vector ar int count = 0; for(int i=mini; i<=maxi; i++) { if(!missing.count(i)) { count++; if(count == k) { cout<<i<<endl; return; } } } cout<<-1<<endl; } int main() { system("cls"); vector<int> ar = {2,4,10,7}; int k = 2; findMissing(ar,k); return 0; }
c0477f3e43efdad496f7fbd35bef030acb3390a8
8824d24b73a355e41e9914280ee1e46f3163f457
/tmp/grog-dialoguejs/dialogue.cpp
ec8953db007ec2a4e64151e706262298dd05d51b
[ "Zlib" ]
permissive
pombredanne/EDGE-2
fe621cbab7c189cd91e2514a946e0f355a82c010
b09f82a65a7ee594f1a544141814647e087b250a
refs/heads/master
2020-12-28T06:57:04.628369
2015-12-29T13:49:37
2015-12-29T20:57:20
48,853,467
1
0
null
2015-12-31T15:20:00
2015-12-31T15:20:00
null
UTF-8
C++
false
false
8,527
cpp
dialogue.cpp
/* gnu.txt 0 Hi! Welcome to OSSland! Is this your first visit? [1,2] 1 Yes, I just arrived -> 3 2 No, I've been here before -> 4 3 Awesome! Have fun! -> 5 4 Hey, welcome back -> 5 5 Do you want to be my friend? [6,7,8,9] 6 Yes -> 10 7 No -> 11 8 Maybe -> 12 9 Not sure -> 12 10 Great! -> 13 11 Awwww -> 13 12 Please! -> 5 13 Oh hi -> 13 banana: I hate bananas */ #include <string> #include <map> #include <functional> #include <sstream> #include <iostream> #include <deque> #include <vector> #include <algorithm> #include <fstream> #include "wire/wire.hpp" struct dialogue { struct guide { // union would fit better std::string text; std::string script; std::map<std::string, std::string> choices; bool eof = 0; template<typename T> inline friend T &operator <<( T &os, const guide &l ) { if( l.eof ) { os << "eof|"; } if( !l.script.empty() ) { os << "script:" << l.script; os << "|"; } if( !l.choices.empty() ) { os << "choices:"; for( auto &kv : l.choices ) { os << kv.first << "->" << kv.second << ","; } os << "|"; } if( !l.text.empty() ) { os << "text: '" << l.text << "'"; } return os; } }; using guides = std::deque< guide >; using guideline = std::map< std::string, guides >; guideline plot; int state = 0, substate = 0, initialized = 0; std::function< void() > on_begin; std::function< void() > on_end; std::function< void(const std::map<std::string,std::string> &choices) > on_choice; std::function< void(const char *) > on_text; std::function< void(const char *) > on_script; bool load( const std::string &fname ) { return load( std::ifstream( fname.c_str(), std::ios::binary ) ); } bool load( std::istream &is ) { plot.clear(); std::stringstream ss; ss << is.rdbuf(); if( ss.good() && is.good() ) { auto lines = wire::string( ss.str() ).tokenize("\r\n"); for( auto &line : lines ) { // comment? if( line.starts_with("--") ) { continue; } // text | texts... -> action bool has_action = line.left_of("->") != line; std::string action; if( has_action ) { action = line.right_of("->").trim(); action = &action[2]; action = wire::string( action ).trim(); } auto text = line.left_of("->").tokenize("|"); for( auto &t : text ) { t = t.trim(); } // key auto key = text[0].tokenize(":")[0]; text[0] = wire::string( text[0].substr( key.size() + 1 ) ).trim(); // inscribe texts auto &guides = plot[ key.trim() ]; for( auto &t : text ) { if( !t.empty() ) { guides.push_back( guide() ); switch( t[0] ) { break; default : guides.back().text = t; break; case '<': guides.back().script = t; } } } // inscribe action if( action.empty() ) action = "!"; auto parse = []( const std::string &text ) { std::map<std::string, std::string> out; auto wr = wire::string( text ); if( wr.back() == '?' || wr.back() == '!' ) wr.pop_back(); for( auto &it : wr.tokenize( " " ) ) { out[ it ]; } return out; }; if( !action.empty() ) { guides.push_back( guide() ); guides.back().choices = parse( action ); guides.back().eof = ( action.back() == '!' && !guides.back().eof ); } } // resolve choices for( auto &it : plot ) { for( auto &jt : it.second ) { for( auto &choice : jt.choices ) { std::string number = choice.first; choice.second = plot[ number ].begin()->text; } } } return true; } return false; } void debug( std::ostream &out = std::cout ) const { for( auto &kv : plot ) { out << kv.first << std::endl; for( auto &v : kv.second ) { out << "L" << __LINE__ << "\t" << v << std::endl; } } } guideline::const_iterator get_state() const { auto it = plot.begin(); return std::advance( it, state ), it; } guides::const_iterator get_substate() const { auto it = get_state(); auto jt = it->second.begin(); return std::advance( jt, substate ), jt; } bool jump( const std::string &text ) { if( !text.empty() ) { auto find = plot.find( text ); auto found = find != plot.end(); if( found ) { // topic state = std::distance( plot.begin(), find ); substate = 0; // std::cout << "jump to " << state << std::endl; return true; } } return false; } void interact( const std::string &text ) { // is it registered topic (word) or jump state (number) ? jump(text); if( 1 ) { if( !initialized ) { initialized = 1; if( on_begin ) { on_begin(); } } auto it = get_state(); auto jt = get_substate(); if( !jt->script.empty() ) { if( on_script ) { on_script( jt->script.c_str() ); } } if( !jt->text.empty() ) { if( on_text ) { on_text( jt->text.c_str() ); } } if( jt->eof ) { if( on_end ) { on_end(); } initialized = 0; } // advance if possible, else restart state if( (++substate) >= it->second.size() ) { --substate; } if( !jt->choices.empty() ) { if( jt->choices.size() == 1 ) { jump( jt->choices.begin()->first ); } if( on_choice && jt->choices.size() > 1 ) { on_choice( jt->choices ); } } // std::cout << state << ',' << substate << ',' << *jt << std::endl; } } }; #include <fstream> int main() { auto prompt = []( const std::string &prompt ) { std::cout << "L" << __LINE__ << "\t" << prompt; std::string input; std::getline(std::cin, input); return input; }; dialogue gnu; gnu.load( "gnu.txt" ); gnu.debug(); std::string status = "wandering"; gnu.on_begin = [&] { status = "talking"; std::cout << "L" << __LINE__ << "\t" << "-- begin of conversation" << std::endl; }; gnu.on_end = [&] { status = "wandering"; std::cout << "L" << __LINE__ << "\t" << "-- end of conversation" << std::endl; }; gnu.on_script = [&]( const char *text ) { std::cout << "L" << __LINE__ << "\t" << "adding topics: " << text << std::endl; }; gnu.on_text = [&]( const char *text ) { std::cout << "L" << __LINE__ << "\t" << text << std::endl; }; gnu.on_choice = [&]( const std::map<std::string, std::string> &items ) { for( auto &it : items ) { std::cout << "L" << __LINE__ << "\t" << it.first << "\t" << it.second << std::endl; } }; for(;;) { auto text = prompt(status + ">"); if( text == "debug" ) { gnu.debug(); continue; } if( status == "talking" || (status == "wandering" && text == "talk") ) { gnu.interact( text ); } } }
07d0ca5208133b206ba5e6d5b0b33f1ae806a33a
70a59f9585056ea09cb79b99af1ca79fa4fa5ff8
/src/utils/exception/InvalidIntegerNumberExcep.cpp
5a0f5871c69c35bf3ac0f4a49acc38d87aad34bc
[]
no_license
chris-ondemand3d/MPS-Qt5
564df86c587d7a860f25eab62ec9e96fa97aea5c
c4cde85b2481c944f14f0c3bb0daf9ef33675e22
refs/heads/master
2021-01-23T16:12:29.728967
2013-10-07T11:14:04
2013-10-07T11:14:04
49,045,479
2
1
null
2016-01-05T06:00:01
2016-01-05T05:59:59
null
UTF-8
C++
false
false
396
cpp
InvalidIntegerNumberExcep.cpp
#include "InvalidIntegerNumberExcep.h" InvalidIntegerNumberExcep::InvalidIntegerNumberExcep(const string& message, ExcepType execpType, const string& strValue): Exception(message, execpType), m_strValue(strValue) { }
a7203465590be47f3660cd0fb764ec136921aaba
0cbbdadd92428cb18fc0c53cd7c94a94cff16c3a
/SourceCodes/BirdsWatchingApp/hmi/mainwindow.cpp
0653fe4848669ea075c7a2d787de67069b93f071
[]
no_license
FoMB/BirdsWatching
eced7e2c4021cef3a51d171cd6795087c2bfaf8c
eca6e82194e7ae85a239b836966c22a109ddc321
refs/heads/master
2020-07-13T09:39:04.932320
2015-07-20T10:02:53
2015-07-20T10:02:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,464
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include "windows.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) //, dlgChooseBird(new QChooseBird(this)) { ui->setupUi(this); serviceThread = new QThread(); qDebug()<<"main thread id = "<<QThread::currentThreadId(); serviceObject = new QServiceObject(); serviceObject->moveToThread(serviceThread); connect(serviceThread, SIGNAL(started()), serviceObject, SLOT(slotOfThread())); serviceObject->showObjectThreadID(); serviceThread->start(); connect(ui->btn_chooseBird, SIGNAL(clicked()), this, SLOT(ShowChooseBirdDlg())); //connect(ui->btn_chooseBird, SIGNAL(clicked()), dlgChooseBird, SLOT(show())); connect(this, SIGNAL(sig_getBirdsList()), serviceObject, SLOT(slot_getBirdsList())); connect(serviceObject, SIGNAL(sig_finishReading()), this, SLOT(slot_finishReading())); ui->lbl_currentBird->setText("NONE"); qDebug()<<"before emitting, str is "<<serviceObject->m_birdKinds; emit sig_getBirdsList(); } MainWindow::~MainWindow() { delete ui; } void MainWindow::slot_finishReading() { qDebug()<<"MainWindow::slot_finishReading() thread id = "<<QThread::currentThreadId(); qDebug()<<"after emitting, str is "<<serviceObject->m_birdKinds; } void MainWindow::ShowChooseBirdDlg() { if(!dlgChooseBird) dlgChooseBird = new QChooseBird(this); dlgChooseBird->show(); }
488fc46b048b5d4feac90651ffbb6ecc607315d1
7afe8e3343c33c9be3289416349f61fb5757be29
/repos/homeworkLab2303/homeworkLab2303/Vehicle.cpp
3160595e17873d7fe9c5a78b5f1f05a80ee9c847
[]
no_license
agenta007/Coding-Exercises-CPP
5555e2f934f93b1c05b44dc58e8eb0c9b0203725
6e02ecfd98f91c561413f7bd1ba97ece6a0e5e60
refs/heads/master
2023-05-06T08:35:28.756116
2021-05-31T12:28:20
2021-05-31T12:28:20
372,497,353
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
Vehicle.cpp
#include "Vehicle.h" Vehicle::Vehicle(string vehType, int tyres, int doors) { this->vehType = vehType; this->tyres = tyres; this->doors = doors; } Vehicle::Vehicle(const Vehicle& objRef) { vehType = objRef.vehType; tyres = objRef.tyres; doors = objRef.doors; } void Vehicle::operator=(const Vehicle& rhs) { vehType = rhs.vehType; tyres = rhs.tyres; doors = rhs.doors; } ostream& operator<<(ostream& out, const Vehicle& rhs) { out << "Vehicle Type: " << rhs.vehType << " Tyres: " << rhs.tyres << " Doors: " << rhs.doors; }
00265559ec4ef77b841255c3fa96d67ad872d970
902cd44ea6d0fb5b98b5d24ef9500525616e398f
/CPP/uglynumber.cpp
cfc54c5bb970c5532ded187f5a477b6820f525eb
[]
no_license
aparna2198/datastructures
911470d3a8cfc3af1de5aa2ae3a780a701879ace
9440fe09802a02cdebb30f9a587e9f3c1175d1f2
refs/heads/master
2023-08-05T22:57:04.428377
2021-10-06T14:01:30
2021-10-06T14:01:30
414,234,127
0
0
null
null
null
null
UTF-8
C++
false
false
988
cpp
uglynumber.cpp
#include<stdio.h> /*algorithm implies take two variables i and count loop until count is less than nth position of ugly number increment i evertime of the loop increment count only when ugly fucntion returns 1 keep on incrementing i untill n>count and upuntill count is greater than n increment count only when ugly fucntion returns 1 */ int max(int a,int b) { while(a%b==0)//perfect divisible a=a/b; return a; } int ugly(int no) { no=max(no,2);//max(300,2);no=150 1 no=max(no,3);//max(150,3) no=75 no=max(no,5);//max(75,5) no 1 return (no==1)?1:0; //so returned 1 meaning number is ugly } int nth(int n) { // suppose n=7 int i=1; int count=1;//ugly no count while(n>count)// count tell 1 to 149 { i++;//2 3 4 5 6 7 8 if(ugly(i))// ugly of 2 count++;//increase the count if number is ugly meaning if(1) //2 3 4 5 6 } return i; } int main() {int c; printf("enter the pos"); scanf("%d",&c); unsigned no=nth(c); printf("%d thn ugly no is %d",c,no); return 0; }
629e0fb6be5428184519f7e5f5e240ab74e5dd58
d5c25932f52e7e06b405f799dc21c573baff4c20
/ch2/s3/nocows.cpp
c8b7b5244107fc0f3b23712163ef919d71f7fe99
[]
no_license
sketchc89/usaco
672b5e2b83049adaaa16e04aeea472703f696649
1d265b58d363d471dd870d4c0ef05d3d8f1bfbde
refs/heads/main
2023-04-18T18:38:19.860841
2021-04-28T16:15:01
2021-04-28T16:15:01
318,516,494
0
0
null
null
null
null
UTF-8
C++
false
false
919
cpp
nocows.cpp
/* ID: sketchc1 LANG: C++14 TASK: nocows */ #include <bits/stdc++.h> using namespace std; constexpr int64_t MOD = 9901; int main() { // i/o ifstream fin("nocows.in"); ofstream fout("nocows.out"); int numNodes, height; fin >> numNodes >> height; vector<vector<int64_t>> dp(height + 1, vector<int64_t>(numNodes + 1, 0)); for (int h = 1; h <= height; ++h) { dp[h][1] = 1; } for (int totalNodes = 3; totalNodes <= numNodes; totalNodes += 2) { for (int h = 1; h <= height; ++h) { for (int leftNodes = 1; leftNodes <= totalNodes - 2; ++leftNodes) { dp[h][totalNodes] += dp[h - 1][leftNodes] * dp[h - 1][totalNodes - leftNodes - 1]; dp[h][totalNodes] %= MOD; } } } int64_t res = ((dp[height][numNodes] - dp[height - 1][numNodes]) + MOD) % MOD; fout << res << '\n'; return EXIT_SUCCESS; }
d5a99143460312cc2427833d240ff177d9135c7e
78db5d2e4350a4f950efb78a76608b6cbc999e46
/BuilderPattern.cpp
c6486cfb75ee03773de8df93b35d334ad477cf38
[]
no_license
zhuoshen617/DesignPatterns
65f029a9c8ac67a087e4a33663ed521a33f59bc0
e57cc500a84b00a13827958a2f5ec394c4953673
refs/heads/master
2021-07-21T22:55:23.682762
2017-10-31T18:56:31
2017-10-31T18:56:31
107,199,409
0
0
null
null
null
null
UTF-8
C++
false
false
2,287
cpp
BuilderPattern.cpp
#include <iostream> #include <string> #include <memory> using namespace std; //Builder Pattern (Has A) //when you want to build an object which is made up from other set of objects //this pattern usually are used together with template pattern as shown below //we are building a Robot here //the Robot is composed of a list of object(Head, body, Arms, Legs) //we are clearly making use of "Has A" rules //builder class encapsulate all the details of how to build a robot //only builder knows how to build and no one else knows class Robot { public: string head; string body; /* string arms; string legs; */ Robot() {} void setHead(string h) {head = h;} void setBody(string b) {body = b;} void print() { cout << "My Head: " << head << endl; cout << "My Body: " << body << endl; } }; class RobotBuilder { protected: Robot robot; public: //template method here void buildRobot() { buildRobotHead(); buildRobotBody(); //buildRobotArms(); //buildRobotLegs(); } virtual void buildRobotHead() = 0; virtual void buildRobotBody() = 0; //void buildRobotArms(); //void buildRobotLegs(); Robot getRobot() { return robot;} }; //"Is A" //this is using the template pattern //we can just build one type of robot here //but there is no point to use builder pattern anyway class LegacyRobotBuilder : public RobotBuilder { public: void buildRobotHead() { robot.setHead("Tin Head"); } void buildRobotBody() { robot.setBody("Tin Body"); } }; //"Is A" class ModernRobotBuilder : public RobotBuilder { public: void buildRobotHead() { robot.setHead("Electronic Head"); } void buildRobotBody() { robot.setBody("Electronic Body"); } }; int main() { cout << "Hello world!" << endl; shared_ptr<RobotBuilder> robotBuilder = make_shared<LegacyRobotBuilder>(); robotBuilder.get()->buildRobot(); Robot aRobot = robotBuilder.get()->getRobot(); aRobot.print(); cout << endl; robotBuilder = make_shared<ModernRobotBuilder>(); robotBuilder.get()->buildRobot(); Robot anotherRobot = robotBuilder.get()->getRobot(); anotherRobot.print(); return 0; }
bb054b275f1104a2c052c58b103aad779604d691
e71a818ff8eee7b3ef74610130b02f23924c10a7
/examples/BlockingProgramMemoryRtttl/BlockingProgramMemoryRtttl.ino
cf28266d55526553ace58fdf3062d6de96b0a26f
[ "MIT" ]
permissive
end2endzone/AnyRtttl
8dca13436260b8d026017d10704f13612a38ca8f
1bd707cd6ebea7bc8f840d1656b0c84959c117f8
refs/heads/master
2023-08-17T04:40:51.378057
2023-08-07T19:36:12
2023-08-07T19:36:12
151,838,849
3
1
null
null
null
null
UTF-8
C++
false
false
1,629
ino
BlockingProgramMemoryRtttl.ino
#include <anyrtttl.h> #include <binrtttl.h> #include <pitches.h> //project's constants #define BUZZER_PIN 8 const char tetris[] PROGMEM = "tetris:d=4,o=5,b=160:e6,8b,8c6,8d6,16e6,16d6,8c6,8b,a,8a,8c6,e6,8d6,8c6,b,8b,8c6,d6,e6,c6,a,2a,8p,d6,8f6,a6,8g6,8f6,e6,8e6,8c6,e6,8d6,8c6,b,8b,8c6,d6,e6,c6,a,a"; const char arkanoid[] PROGMEM = "Arkanoid:d=4,o=5,b=140:8g6,16p,16g.6,2a#6,32p,8a6,8g6,8f6,8a6,2g6"; const char mario[] PROGMEM = "mario:d=4,o=5,b=140:16e6,16e6,32p,8e6,16c6,8e6,8g6,8p,8g,8p,8c6,16p,8g,16p,8e,16p,8a,8b,16a#,8a,16g.,16e6,16g6,8a6,16f6,8g6,8e6,16c6,16d6,8b,16p,8c6,16p,8g,16p,8e,16p,8a,8b,16a#,8a,16g.,16e6,16g6,8a6,16f6,8g6,8e6,16c6,16d6,8b,8p,16g6,16f#6,16f6,16d#6,16p,16e6,16p,16g#,16a,16c6,16p,16a,16c6,16d6,8p,16g6,16f#6,16f6,16d#6,16p,16e6,16p,16c7,16p,16c7,16c7,p,16g6,16f#6,16f6,16d#6,16p,16e6,16p,16g#,16a,16c6,16p,16a,16c6,16d6,8p,16d#6,8p,16d6,8p,16c6"; // James Bond theme defined in inline code below (also stored in flash memory) void setup() { pinMode(BUZZER_PIN, OUTPUT); Serial.begin(115200); Serial.println("ready"); } void loop() { anyrtttl::blocking::playProgMem(BUZZER_PIN, tetris); delay(1000); anyrtttl::blocking::play_P(BUZZER_PIN, arkanoid); delay(1000); #if defined(ESP8266) anyrtttl::blocking::play(BUZZER_PIN, FPSTR(mario)); delay(1000); #endif anyrtttl::blocking::play(BUZZER_PIN, F("Bond:d=4,o=5,b=80:32p,16c#6,32d#6,32d#6,16d#6,8d#6,16c#6,16c#6,16c#6,16c#6,32e6,32e6,16e6,8e6,16d#6,16d#6,16d#6,16c#6,32d#6,32d#6,16d#6,8d#6,16c#6,16c#6,16c#6,16c#6,32e6,32e6,16e6,8e6,16d#6,16d6,16c#6,16c#7,c.7,16g#6,16f#6,g#.6")); delay(1000); while(true) { } }
9253206433a96acc88646245fb629212c3cc787b
284adc59ad34aaaae545182cd72cc46397d05e77
/Timer.h
eaa9a09d3e491b3df7785a358d49aff796d5d6e0
[]
no_license
syifan/CRVehicle
a7eed14e3bf27c5e0626e44d9e008e9a851f00dc
590d69a5b30cb2ab6be04c09a74de6d6c47f7f3f
refs/heads/master
2021-05-27T20:38:30.000631
2013-12-01T01:52:18
2013-12-01T01:52:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
394
h
Timer.h
#ifndef TIMER_H #define TIMER_H /** * A singleton that controls the simulation time */ class Timer{ public: static Timer& getInstance(); static bool advance(); static double getTimeStep(); static double getCurrentTime(); private: Timer(); Timer( Timer const& ); void operator=(Timer const&); double nowTime; double lastTime; double timeStep; double maxTime; }; #endif
1ffc3a7897e99e412c19fb148b422db8aa782c04
c28715501f479c441feaa472c4d4e10037fe8a11
/IntModel/main.cpp
081bb2e68c44c56ce020502b3ce913877e645111
[]
no_license
abbaril/Qt-C-
b5ac635e4ebf52074c0150799cce221efdd9e2c2
4484633e2874c68fd8dc95ef03816eed17bb35ea
refs/heads/master
2021-05-01T07:35:29.915709
2018-02-11T19:41:04
2018-02-11T19:41:04
121,159,608
1
0
null
null
null
null
UTF-8
C++
false
false
265
cpp
main.cpp
#include "intmodel.h" #include <QApplication> #include <QListView> #include <QtGui> int main(int argc, char *argv[]) { QApplication a(argc, argv); IntModel model(25); QListView list; list.setModel(&model); list.show(); return a.exec(); }
29f2b12fc1ecdbea829dd0e31875d615a7f106c5
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Event/EventInfoMgt/EventInfoMgt/ITagInfoMgr.h
c8ecb2b9cd36d610e43a1200798916d9f5e8b3dc
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
3,583
h
ITagInfoMgr.h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef EVENTINFOMGT_ITAGINFOMGR_H # define EVENTINFOMGT_ITAGINFOMGR_H /** * @file TagInfoMgr.h * * @brief This is a Athena service which manages detector description * tag information. It maintains a TagInfo object in the Detector * Store with current tag values. * * @author RD Schaffer <R.D.Schaffer@cern.ch> * * $Id: ITagInfoMgr.h,v 1.4 2009-04-29 07:47:39 schaffer Exp $ */ //<<<<<< INCLUDES >>>>>> #include "AthenaKernel/IOVSvcDefs.h" #include "GaudiKernel/Service.h" #include "GaudiKernel/IIncidentListener.h" #include "AthenaKernel/IAddressProvider.h" #include "AthenaKernel/IOVSvcDefs.h" //<<<<<< PUBLIC TYPES >>>>>> class StoreGateSvc; class IGeoModelSvc; class TagInfo; //<<<<<< CLASS DECLARATIONS >>>>>> /** * @class ITagInfoMgr * * @brief This is a Athena service which manages detector description * tag information. It maintains a TagInfo object in the Detector * Store with current tag values. * * The tags to fill the TagInfo object may come from a variety of * sources: i.e. the tags specified by the GeoModelSvc and IOVDbSvc, * or the tags stored in the incoming EventInfo object, or the * TagInfo object itself may be in the IOV DB. The exact combination * is controlled by job options. * * This interface also provides a 'input' method to allow client to * add in their own tags: * * virtual StatusCode addTag(const std::string& tagName, * const std::string& tagValue) = 0; * * The full set of tags in TagInfo are copied each event into * EventInfo (specifically EventType) to be written out in the event * stream. Currently, the tags are NOT written to the IOV DB via the * TagInfoMgr. * * Some clients need to know when detector description tags change * so that they may update their descriptions, such as the geometry * description. The TagInfo object will change in this case. So * clients that need to know when tags change should set up a * callback to the TagInfo object. This is done with regFcn of the * StoreGate service (for the DetectorStore). The method * * virtual std::string& tagInfoKey() = 0; * * provides access to the SG key of TagInfo which is needed to * register a data handle for the callback. * */ class ITagInfoMgr : virtual public IInterface { public: /// Retrieve interface ID static const InterfaceID& interfaceID(); /// Method to allow clients to add in tags as: tag name, tag value virtual StatusCode addTag(const std::string& tagName, const std::string& tagValue) = 0; /// Method to allow clients to remove a tag which may have come in /// on the input virtual StatusCode removeTagFromInput(const std::string& tagName) = 0; /// Method to allow clients to access the TagInfo object key. virtual std::string& tagInfoKey() = 0; /// callback from IOVSvc - only used as test of callback virtual StatusCode checkTagInfo(IOVSVC_CALLBACK_ARGS) = 0; }; //<<<<<< INLINE PUBLIC FUNCTIONS >>>>>> //<<<<<< INLINE MEMBER FUNCTIONS >>>>>> inline const InterfaceID& ITagInfoMgr::interfaceID() { static const InterfaceID IID_ITagInfoMgr("ITagInfoMgr", 1 , 0); return IID_ITagInfoMgr; } #endif // EVENTINFOMGT_ITAGINFOMGR_H
eead4677c72cd7262592b9863a8275758aa8b413
42447a20673b1ca9b3abf818182c125e4ee4dcfd
/Src/Application/FaceBeautificationAppUI.cpp
b0e3b083e98bfab8bab0b196ea7159e8f1f12732
[]
no_license
feengg/magic3d
3a3da02872f148a389a4a2789ff63ba2f271d3aa
f5bf517d6a1d1d5fbcb49a50b3db4d42e41cd692
refs/heads/master
2020-04-15T05:59:15.543318
2014-08-16T09:19:59
2014-08-16T09:19:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,800
cpp
FaceBeautificationAppUI.cpp
#include "FaceBeautificationAppUI.h" #include "../Common/ResourceManager.h" #include "Tool/LogSystem.h" #include "../Common/AppManager.h" #include "../Common/ToolKit.h" #include "FaceBeautificationApp.h" namespace MagicApp { FaceBeautificationAppUI::FaceBeautificationAppUI() : mpLeftImageTexture(NULL), mpMiddleImageTexture(NULL), mpRightImageTexture(NULL) { } FaceBeautificationAppUI::~FaceBeautificationAppUI() { if (mpLeftImageTexture != NULL) { MyGUI::RenderManager::getInstance().destroyTexture(mpLeftImageTexture); mpLeftImageTexture = NULL; } if (mpMiddleImageTexture != NULL) { MyGUI::RenderManager::getInstance().destroyTexture(mpMiddleImageTexture); mpMiddleImageTexture = NULL; } if (mpRightImageTexture != NULL) { MyGUI::RenderManager::getInstance().destroyTexture(mpRightImageTexture); mpRightImageTexture = NULL; } } void FaceBeautificationAppUI::Setup(int* maxFaceWidth, int* maxFaceHeight) { InfoLog << "FaceBeautificationAppUI::Setup" << std::endl; *maxFaceWidth = 300; *maxFaceHeight = 375; MagicCore::ResourceManager::LoadResource("../../Media/FaceBeautificationApp", "FileSystem", "FaceBeautificationApp"); mRoot = MyGUI::LayoutManager::getInstance().loadLayout("FaceBeautificationApp.layout"); mRoot.at(0)->findWidget("But_Open")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::OpenImage); mRoot.at(0)->findWidget("But_EditFeature")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::EditFeaturePoint); mRoot.at(0)->findWidget("But_AutoAlignFeature")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::AutoAlignFeature); mRoot.at(0)->findWidget("But_DeformFeature")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::DeformImageFeature); mRoot.at(0)->findWidget("But_DeformColor")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::DeformImageColor); mRoot.at(0)->findWidget("But_OpenReference")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::OpenReferenceImage); mRoot.at(0)->findWidget("But_CalReferenceImage")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::CalReferenceImage); mRoot.at(0)->findWidget("But_DoFeaturePCA")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::DoFeaturePca); mRoot.at(0)->findWidget("But_DoColorPCA")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::DoColorPca); mRoot.at(0)->findWidget("But_DoMixPca")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::DoMixPca); mRoot.at(0)->findWidget("But_CalMeanFace")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::CalMeanFace); mRoot.at(0)->findWidget("But_DeformFeatureToMeanFace")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::DeformFeatureToMeanFace); mRoot.at(0)->findWidget("But_DeformColorToMeanFace")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::DeformColorToMeanFace); mRoot.at(0)->findWidget("But_DeformToMeanFace")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::DeformToMeanFace); mRoot.at(0)->findWidget("But_Home")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::BackHome); mRoot.at(0)->findWidget("But_Contact")->castType<MyGUI::Button>()->eventMouseButtonClick += MyGUI::newDelegate(this, &FaceBeautificationAppUI::Contact); } void FaceBeautificationAppUI::Shutdown() { MyGUI::LayoutManager::getInstance().unloadLayout(mRoot); mRoot.clear(); MagicCore::ResourceManager::UnloadResource("FaceBeautificationApp"); } void FaceBeautificationAppUI::UpdateLeftImage(const cv::Mat& image) { UpdateImageTexture(&mpLeftImageTexture, image, std::string("LeftImageTexture")); MyGUI::ImageBox* pIB = mRoot.at(0)->findWidget("Image_Left")->castType<MyGUI::ImageBox>(); pIB->setVisible(true); pIB->setImageTexture("LeftImageTexture"); } void FaceBeautificationAppUI::UpdateMiddleImage(const cv::Mat& image) { UpdateImageTexture(&mpMiddleImageTexture, image, std::string("MiddleImageTexture")); MyGUI::ImageBox* pIB = mRoot.at(0)->findWidget("Image_Middle")->castType<MyGUI::ImageBox>(); pIB->setVisible(true); pIB->setImageTexture("MiddleImageTexture"); } void FaceBeautificationAppUI::UpdateRightImage(const cv::Mat& image) { UpdateImageTexture(&mpRightImageTexture, image, std::string("RightImageTexture")); MyGUI::ImageBox* pIB = mRoot.at(0)->findWidget("Image_Right")->castType<MyGUI::ImageBox>(); pIB->setVisible(true); pIB->setImageTexture("RightImageTexture"); } void FaceBeautificationAppUI::HideLeftImage(void) { MyGUI::ImageBox* pIB = mRoot.at(0)->findWidget("Image_Left")->castType<MyGUI::ImageBox>(); pIB->setVisible(false); } void FaceBeautificationAppUI::HideMiddleImage(void) { MyGUI::ImageBox* pIB = mRoot.at(0)->findWidget("Image_Middle")->castType<MyGUI::ImageBox>(); pIB->setVisible(false); } void FaceBeautificationAppUI::HideRightImage(void) { MyGUI::ImageBox* pIB = mRoot.at(0)->findWidget("Image_Right")->castType<MyGUI::ImageBox>(); pIB->setVisible(false); } void FaceBeautificationAppUI::UpdateImageTexture(MyGUI::ITexture** pImageTex, const cv::Mat& image, const std::string& texName) { int texW = image.cols; int texH = image.rows; if ((*pImageTex) != NULL) { MyGUI::RenderManager::getInstance().destroyTexture(*pImageTex); (*pImageTex) = NULL; } (*pImageTex) = MyGUI::RenderManager::getInstance().createTexture(texName); (*pImageTex)->createManual(texW, texH, MyGUI::TextureUsage::Static | MyGUI::TextureUsage::Write, MyGUI::PixelFormat::R8G8B8A8); MyGUI::uint8* pDest = static_cast<MyGUI::uint8*>((*pImageTex)->lock(MyGUI::TextureUsage::Write)); for (int yid = 0; yid < texH; yid++) { for (int xid = 0; xid < texW; xid++) { const unsigned char* pixel = image.ptr(yid, xid); *pDest++ = pixel[0]; *pDest++ = pixel[1]; *pDest++ = pixel[2]; *pDest++ = 255; } } (*pImageTex)->unlock(); } void FaceBeautificationAppUI::OpenImage(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { if (pFB->OpenImage()) { mRoot.at(0)->findWidget("But_EditFeature")->castType<MyGUI::Button>()->setEnabled(true); mRoot.at(0)->findWidget("But_AutoAlignFeature")->castType<MyGUI::Button>()->setEnabled(true); mRoot.at(0)->findWidget("But_OpenReference")->castType<MyGUI::Button>()->setEnabled(true); mRoot.at(0)->findWidget("But_CalReferenceImage")->castType<MyGUI::Button>()->setEnabled(true); } } } void FaceBeautificationAppUI::EditFeaturePoint(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { pFB->EditFeaturePoint(); } } void FaceBeautificationAppUI::AutoAlignFeature(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { pFB->AutoAlignFeature(); } } void FaceBeautificationAppUI::DeformImageFeature(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { pFB->DeformImageFeature(); } } void FaceBeautificationAppUI::DeformImageColor(MyGUI::Widget* pSender) { } void FaceBeautificationAppUI::OpenReferenceImage(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { if (pFB->OpenReferenceImage()) { mRoot.at(0)->findWidget("But_DeformFeature")->castType<MyGUI::Button>()->setEnabled(true); mRoot.at(0)->findWidget("But_DeformColor")->castType<MyGUI::Button>()->setEnabled(true); } } } void FaceBeautificationAppUI::CalReferenceImage(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { if (pFB->CalReferenceImage()) { mRoot.at(0)->findWidget("But_DeformFeature")->castType<MyGUI::Button>()->setEnabled(true); mRoot.at(0)->findWidget("But_DeformColor")->castType<MyGUI::Button>()->setEnabled(true); } } } void FaceBeautificationAppUI::DoFeaturePca(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { pFB->DoFeaturePca(); } } void FaceBeautificationAppUI::DoColorPca(MyGUI::Widget* pSender) { } void FaceBeautificationAppUI::DoMixPca(MyGUI::Widget* pSender) { } void FaceBeautificationAppUI::CalMeanFace(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { pFB->CalMeanFace(); } } void FaceBeautificationAppUI::DeformFeatureToMeanFace(MyGUI::Widget* pSender) { FaceBeautificationApp* pFB = dynamic_cast<FaceBeautificationApp* >(MagicCore::AppManager::GetSingleton()->GetApp("FaceBeautificationApp")); if (pFB != NULL) { pFB->DeformFeatureToMeanFace(); } } void FaceBeautificationAppUI::DeformColorToMeanFace(MyGUI::Widget* pSender) { } void FaceBeautificationAppUI::DeformToMeanFace(MyGUI::Widget* pSender) { } void FaceBeautificationAppUI::BackHome(MyGUI::Widget* pSender) { MagicCore::AppManager::GetSingleton()->SwitchCurrentApp("Homepage"); } void FaceBeautificationAppUI::Contact(MyGUI::Widget* pSender) { MagicCore::ToolKit::OpenWebsite(std::string("http://magic3dcn.wix.com/magic3d#!form__map/c24vq")); } }
dc262b37f8e894c79f0b396f3c8b700ffc32cc00
dc1e3c2f4c6190ce5b3672970fa3c46de5481f96
/2020-11-20/array_adress/main.cpp
a5997900a8f2f19af4e6247b3a722722704b3f8b
[]
no_license
ing181/Programmering-1-20-21
b5e96bf148d45765bad622b9698422437f10ebb8
37af5fb30a2e2cc9329fc343842bcc28e55df7cd
refs/heads/master
2023-03-08T02:40:54.696757
2021-02-26T09:05:27
2021-02-26T09:05:27
289,943,351
0
0
null
null
null
null
UTF-8
C++
false
false
1,885
cpp
main.cpp
#include <iostream> using namespace std; // Arayer som argument till funktioner // Som visas i exemplet nedan // när en array skickas som invärde till en funktion // KOPIERAS INTE ARRAYEN // VI TALAR OM FÖR FUNKTIONEN VAR ARRAYEN FINNS // FUNKTIONEN PÅVERKAR DET SOM FINNS PÅ ADRESSEN // VI SKICKAT TILL FUNKTIONEN void faltFunktion(int falt[]); int main() { int tal; tal = 7; // Adressen (i ram-minnet) till platsen // där värdet finns, i detta exempel 7 cout << &tal << endl; // Ett hexadecimalt tal // * betyder att vi vill skriva ut det som finns // på adressen till variabeln tal cout << *(&tal) << endl; // 7 cout << tal << endl; // Ett enklare sätt att göra samma sak som på rad 19 /* */ int falt[] = {99,2,3}; // En array deklareras och den får värden // Vad betyder namnet på arrayen? cout << falt << endl; // Adressen till arrayen falt, ett hexadecimalt tal cout << *falt << endl; // Vad finns på den adressen? 99 // Vi ser att "falt" är adressen till första värdet i arrayen falt // Vad vi skickar till funktionen är alltså adressen till // första värdet. Funktionen vet att det är en array, vi har // det med i deklarationen "falt[]" faltFunktion(falt); for (int i=0; i<3; i++) { cout << falt[i] << " "; // 99 101 3 } cout << endl; return 0; } // Ingenting kopieras till funktionen // Funktionen har fått en adress. // Samma adress som används i huvudprogrammet (main) // Så det som funktionen gör med det som finns på adressen // märks också i huvudprogrammet. void faltFunktion(int f[]) { for (int i=0; i<3; i++) { cout << f[i] << " "; // 99, 2, 3 } cout << endl; f[1] = 101; // Här förändras det som finns på // adressen f[1] // f[1] i funktionen och falt[1] i huvudprogrammet // samma sak. }
c2bf723d29e357da820ab15e80ccbe9dd49d40e7
bda34633491b808b2dddd292a885186b4dedc7e6
/304/num_matrix.cpp
8b988847eb6613ace4a73b0ebf79097c052df61a
[]
no_license
berneylin/LeetCode2019Spring
3990561862faddf8f294d5750e4ac4c5fcba2953
000f8fb2b00d4d5c6bfec9abb11b7f6158ad9ba8
refs/heads/master
2021-07-07T00:14:10.898739
2020-08-17T18:03:23
2020-08-17T18:03:23
167,664,035
0
0
null
null
null
null
UTF-8
C++
false
false
1,086
cpp
num_matrix.cpp
#include<vector> using namespace std; class NumMatrix { public: NumMatrix(vector<vector<int>>& matrix) { this->mMatrix = matrix; if(!this->mMatrix.empty() && !this->mMatrix[0].empty()){ vector<vector<int> > sumArray(matrix.size(), vector<int>(matrix[0].size(), 0)); for(int i=1; i<=matrix.size(); i++){ for(int j=1; j<=matrix[0].size(); j++){ sumArray[i][j] = sumArray[i-1][j] + sumArray[i][j-1] - sumArray[i-1][j-1] + matrix[i-1][j-1]; } } dp = sumArray; } } int sumRegion(int row1, int col1, int row2, int col2) { if(this->mMatrix.empty() || this->mMatrix[0].empty()) return 0; return dp[row2+1][col2+1] - dp[row1][col2+1] - dp[row2+1][col1] + dp[row1][col1]; } private: vector<vector<int> > mMatrix; vector<vector<int> > dp; }; /** * Your NumMatrix object will be instantiated and called as such: * NumMatrix* obj = new NumMatrix(matrix); * int param_1 = obj->sumRegion(row1,col1,row2,col2); */
99aac93cfe78e5a99a944ea664fb2978fd177e3a
46dbf792b70d765364d9af64a4b97df91c23e2a6
/Project2/BulletObject.cpp
e7fce50a04a5efb20c8660287f0266a0818ec791
[]
no_license
minhhieu3001/game_tank
e371876e8f3180a1955f0be6e60cd0167459db48
612fbea4ff94add41be16e3a78bfa665ef22b56c
refs/heads/master
2022-08-21T18:10:13.980849
2020-05-18T13:50:16
2020-05-18T13:50:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,939
cpp
BulletObject.cpp
#include"BulletObject.h" BulletObject::BulletObject() { rect_.x = 0; rect_.y = 0; x_change = 0; y_change = 0; is_move_ = false; } BulletObject::~BulletObject() { } void BulletObject::Move(const int& x_max_, const int& y_max_) //di chuyển trong phạm vi map { if (bullet_direction == DIR_RIGHT) { rect_.x += x_change; if (rect_.x > SCREEN_WIDTH) { is_move_ = false; } } else if (bullet_direction == DIR_LEFT) { rect_.x -= x_change; if (rect_.x < 0) { is_move_ = false; } } else if (bullet_direction == DIR_UP) { rect_.y -= y_change; if (rect_.y < 0) { is_move_ = false; } } else if (bullet_direction == DIR_DOWN) { rect_.y += y_change; if (rect_.y > SCREEN_HEIGHT) { is_move_ = false; } } } bool BulletObject::CheckMapForBullet(Map& map_data, const SDL_Rect& object1) { int left = 0; int right = 0; int top = 0; int down = 0; //check theo chieu ngang left = (object1.x + x_change) / TILE_SIZE; right = (object1.x + x_change + 30 - 1) / TILE_SIZE; top = object1.y / TILE_SIZE; down = (object1.y + 30 - 1) / TILE_SIZE; if (left >= 0 && right < (MAX_MAP_X) && top >= 0 && down < MAX_MAP_Y) { if (is_move_ == true) { if (map_data.tile[top][right] == 1 || map_data.tile[down][right] == 1) { return true; } if (map_data.tile[top][left] == 1 || map_data.tile[down][left] == 1) { return true; } } } //check theo chieu doc left = (object1.x) / TILE_SIZE; right = (object1.x + 30) / TILE_SIZE; top = (object1.y + y_change) / TILE_SIZE; down = (object1.y + y_change + 30 - 1) / TILE_SIZE; if (left >= 0 && right < MAX_MAP_X && top >= 0 && down < MAX_MAP_Y) { if (is_move_ == true) { if (map_data.tile[down][left] == 1 || map_data.tile[down][right] == 1) { return true; } if (map_data.tile[top][left] == 1 || map_data.tile[top][right] == 1) { return true; } } } return false; }
bc5a84d54eec8681e1a01b580e59de5e43898b9e
5a1876836b8014111363eaf52120fc5e05dd40d2
/Petrozavodsk Winter-2021. North American Contest/C.cpp
aae57b48af53bf6d51f0454b01a8a7e7856f52e3
[]
no_license
wcysai/Continued-Story
afb197ef8393882595a7a0579e3a11026dd8ecca
e7845f9c65e8eb837ab6f923676851e06453681d
refs/heads/main
2023-06-18T00:58:25.364645
2021-07-14T07:35:27
2021-07-14T07:35:27
301,825,686
7
0
null
null
null
null
UTF-8
C++
false
false
1,509
cpp
C.cpp
#include<bits/stdc++.h> #define MAXN 300005 #define INF 1000000000 #define MOD 1000000007 #define F first #define S second using namespace std; typedef long long ll; typedef pair<int,int> P; int n; string str; ll ans[4][MAXN];//LRUD int calc_score(int x,int y) { return (max(-x,x)+1)^(max(-y,y)+1); } int x[MAXN],y[MAXN]; map<P,int> cnt; map<char,int> mp; int dx[4]={1,-1,0,0}; int dy[4]={0,0,-1,1}; int main() { mp['L']=0; mp['R']=1; mp['U']=2; mp['D']=3; scanf("%d",&n); cin>>str; x[0]=0; y[0]=0; for(int i=0;i<n;i++) { x[i+1]=x[i]; y[i+1]=y[i]; if(str[i]=='L') x[i+1]--; else if(str[i]=='R') x[i+1]++; else if(str[i]=='U') y[i+1]++; else y[i+1]--; } ll score=0; for(int tot=0;tot<4;tot++) { score=0; cnt.clear(); for(int i=0;i<n;i++) { cnt[P(x[i],y[i])]++; int t=cnt[P(x[i],y[i])]; score+=t*calc_score(x[i],y[i])+t; } ans[tot][n]=score; for(int i=n-1;i>=1;i--)//delete point i, add point i+1 with a shift { int t=cnt[P(x[i],y[i])]; score-=t*calc_score(x[i],y[i])+t; cnt[P(x[i],y[i])]--; cnt[P(x[i+1]+dx[tot],y[i+1]+dy[tot])]++; t=cnt[P(x[i+1]+dx[tot],y[i+1]+dy[tot])]; score+=t*calc_score(x[i+1]+dx[tot],y[i+1]+dy[tot])+t; ans[tot][i]=score; } } for(int i=1;i<=n;i++) printf("%lld\n",ans[mp[str[i-1]]][i]); return 0; }
a918e01aed290bc80c2bb58f221344217abcf84e
44cb8e84cd090115b18b046d7d403ae841dc0fd1
/Problem9/main.cpp
4fe43e650a330725f8bc19747a7a1e11cb41961f
[]
no_license
mnuecht/ProjectEuler
58bd5ae3e06caf56ba45ee04afbc27a508677569
aa9e4f63bbe81375e03aafcd96262d857f221724
refs/heads/master
2020-03-28T01:14:27.677277
2018-02-11T03:08:53
2018-02-11T03:08:53
63,992,388
0
0
null
null
null
null
UTF-8
C++
false
false
463
cpp
main.cpp
#include <stdlib.h> #include <stdio.h> using namespace std; #define RESULT 1000 bool isPythTriplet(int a, int b, int c) { return (a * a == b * b + c * c); } int main() { for (int a = 1; a <= RESULT; a++) { for (int b = 1; b <= RESULT - a; b++) { int c = RESULT - a - b; if (isPythTriplet(a, b, c)) { printf("a = %i, b = %i, c = %i\n", a, b, c); printf ("Product = %i\n", a * b * c); return 0; } } } printf("No result found.\n"); }
f1d9800a3ff2867f0e5c0bdbe8f4b182ac4ff24e
d9d4a9c18e5a473e60fc34afff8ec4aaa2f88707
/examples/Terminal_MP3_Player/Terminal_MP3_Player.ino
573e4488e7a508ef2ef31c9cde3f97f501e53bbb
[]
no_license
mu-opensource/MoonBot
f9e4ccd12ac3c67b882e9e4f591b823784a587db
41c01289d5ea710eaa492dbbca00f95e6b92e074
refs/heads/master
2020-05-17T10:57:24.413805
2019-12-20T07:53:52
2019-12-20T07:53:52
183,672,017
3
1
null
null
null
null
UTF-8
C++
false
false
6,138
ino
Terminal_MP3_Player.ino
/* WT2003 S Terminal_MP3_Player This example makes an MP3 player that can be controlled from the terminal window on a computer. It exposes the full set of commands that are available for the WT2003S Using the WT2003S MP3 Decoder IC on the SparkFun breakout board with Arduino Uno Hardware Connections: WT2003S Breakout Pin ---> MoonBot Port ------------------------------------- WT2003S ---> Port7(Serial1) WT2003S ---> Port2(Serial2) WT2003S ---> Port9(Serial3) */ #include "MoonBot.h" // Defining some status codes from the WT2003S #define STATUS_PLAY 0x01 #define STATUS_STOP 0x02 #define STATUS_PAUSE 0x03 bool autoplay = true; void setup() { Serial.begin(9600); while (!Serial) { }; speaker.begin(Serial2); // Beginning the MP3 player requires a serial port (either hardware or software!!!) Serial.println("MP3 Breakout - Example1 Serial Control"); Serial.println(); printMenu(); Serial.print("Number of tracks on SD card: "); Serial.println(speaker.getSongCount()); if (speaker.getSongCount() == 0) { Serial.println( "Oh no! No songs found... try adding songs or plugging in the sd card then try again"); while (1); // Hold here } speaker.setVolume(4); speaker.playTrackNumber(1); } void loop() { if (Serial.available()) { char cmd = Serial.read(); if (cmd == '+') { Serial.print("Volume up: "); uint8_t volume = speaker.getVolume(); speaker.setVolume(++volume); Serial.print(volume); Serial.println("/31"); } else if (cmd == '-') { Serial.print("Volume down: "); uint8_t volume = speaker.getVolume(); if (--volume > 31) { volume = 0; } speaker.setVolume(volume); Serial.print(volume); Serial.println("/31"); } else if (cmd == 'n') { Serial.println("Next track:"); speaker.playNext(); delay(200); // It takes a moment for the device to start playing the next song speaker.getSongName(); Serial.print("Playing: "); Serial.write(speaker.songName, 8); Serial.println(); } else if (cmd == 'l') { Serial.println("Last track:"); speaker.playPrevious(); delay(200); // It takes a moment for the device to know the next song name speaker.getSongName(); Serial.print("Playing: "); Serial.write(speaker.songName, 8); Serial.println(); } else if (cmd == 'p') { uint8_t status = speaker.getPlayStatus(); if (status == STATUS_PLAY) { Serial.println("Paused: ('p' to resume)"); autoplay = false; speaker.pause(); // Should pause when currently playing } else if (status == STATUS_PAUSE) { speaker.pause(); // Should play when already paused delay(200); // It takes a moment for the device to know the next song name Serial.print("Resuming: "); speaker.getSongName(); Serial.write(speaker.songName, 8); Serial.println(); } else if (status == STATUS_STOP) { speaker.pause(); // Plays from beginning of current track delay(200); // It takes a moment for the device to know the next song name speaker.getSongName(); Serial.print("Playing: "); Serial.write(speaker.songName, 8); Serial.println(); } } else if (cmd == 's') { Serial.println("Stopping: ('p' to play)"); autoplay = false; speaker.stop(); } else if (cmd == 'a') { autoplay = !autoplay; Serial.print("Autoplay is "); if (autoplay) { Serial.println(" on"); } else { Serial.println(" off"); } } else if (cmd == '?') { uint8_t status = speaker.getPlayStatus(); if (status == STATUS_PLAY) { speaker.getSongName(); autoplay = true; Serial.print("Playing: "); Serial.write(speaker.songName, 8); Serial.println(); } else if (status == STATUS_STOP) { Serial.println("MP3 player is stopped"); } else { Serial.println("MP3 player is paused"); } } else if (cmd == 'w') { autoplay = false; speaker.setPlayMode(0); // set play mode: Single No Loop } else if (cmd == 'x') { autoplay = false; speaker.setPlayMode(1); // set play mode: Single Loop } else if (cmd == 'y') { autoplay = true; // set play mode: Loop All speaker.setPlayMode(2); } else if (cmd == 'z') { autoplay = false; speaker.setPlayMode(3); // set play mode: Random } else { printMenu(); } } // Autoplay controller uint8_t playStatus = speaker.getPlayStatus(); if ((playStatus == STATUS_STOP) && (autoplay == true)) { speaker.playNext(); delay(250); // It takes a moment for the device to know the next song name speaker.getSongName(); Serial.print("Playing: "); Serial.write(speaker.songName, 8); Serial.println(); } } void printMenu(void) { Serial.println("MP3 Command List:"); Serial.println("-----------------"); Serial.println("'+' or '-' : raise/lower volume"); Serial.println("'n' or 'l' : next/last song"); Serial.println("'p' : play or pause"); Serial.println("'s' : stop playing"); Serial.println("'a' : toggle autoplay"); Serial.println("'?' : what is playing?"); Serial.println("'w' : set playmode single no loop"); Serial.println("'x' : set playmode single loop"); Serial.println("'y' : set playmode paly all"); Serial.println("'z' : set playmode random"); Serial.println(); }