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
eaa23685a47565678885f9df943118ce4cc63105
63e3e57aac8f082eeea8cbf8bae56d2bad0a566f
/brain/sw/components/iso/include/iso-control-state.h
58eab96ebb0eccb988ff3786f46ef8e0c0ac7e93
[ "MIT" ]
permissive
baaahs/sparklemotion
2f9086c2c50c4841a644640a3dcf04cde567f7b3
51f73a56fda7d5ab04e58cf970155266f9051ca6
refs/heads/main
2023-08-31T17:31:42.238686
2023-08-20T16:18:35
2023-08-20T16:18:35
174,897,412
38
11
MIT
2023-09-14T17:57:35
2019-03-11T00:16:35
Kotlin
UTF-8
C++
false
false
1,103
h
iso-control-state.h
#pragma once #include "brain_common.h" // Include led-renderer.h to get the NeoPixelBus stuff with the ported bits #include "led-renderer.h" #include "iso-palette.h" #include "iso-time-loop.h" /** * An instance of IsoControlState holds the state information that is * used by the various shaders during the rendering process. This * information is separate from the particular shader which interprets * the things here as the shader sees fit. * * The idea is that this holds things like colors the user has selected, * the current palette, geometry, etc. */ class IsoControlState { public: IsoControlState(uint8_t maxChoices = 2); RgbColor chosenColor(uint8_t ix); void setChosenColor(uint8_t ix, RgbColor color); IsoPalette& currentPalette() { return m_currentPalette; } /** * For looping animations this is the overarching time loop at which * the animation should repeat. */ IsoTimeLoop m_masterAnimationLoop; private: uint8_t m_maxChoices; RgbColor *m_pColorChoices; IsoPalette &m_currentPalette = gPaletteRYBRainbow; };
bf7f840132010a04d538b027c493ff118db866fd
2f557f60fc609c03fbb42badf2c4f41ef2e60227
/TopQuarkAnalysis/TopEventSelection/src/TtHadLRSignalSelObservables.cc
1c7161a2a80eef43d549aea65ebfcc7236c5c2cf
[ "Apache-2.0" ]
permissive
CMS-TMTT/cmssw
91d70fc40a7110832a2ceb2dc08c15b5a299bd3b
80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7
refs/heads/TMTT_1060
2020-03-24T07:49:39.440996
2020-03-04T17:21:36
2020-03-04T17:21:36
142,576,342
3
5
Apache-2.0
2019-12-05T21:16:34
2018-07-27T12:48:13
C++
UTF-8
C++
false
false
12,663
cc
TtHadLRSignalSelObservables.cc
#include "TopQuarkAnalysis/TopEventSelection/interface/TtHadLRSignalSelObservables.h" #include "FWCore/Utilities/interface/isFinite.h" TtHadLRSignalSelObservables::TtHadLRSignalSelObservables() { } TtHadLRSignalSelObservables::~TtHadLRSignalSelObservables() { } void TtHadLRSignalSelObservables::operator() (TtHadEvtSolution &TS) { evtselectVarVal.clear(); std::vector<pat::Jet> topJets; topJets.clear(); topJets.push_back(TS.getHadp()); topJets.push_back(TS.getHadq()); topJets.push_back(TS.getHadj()); topJets.push_back(TS.getHadk()); topJets.push_back(TS.getHadb()); topJets.push_back(TS.getHadbbar()); //Assume the highest Et jets are the b-jets, the others the jets from the W - but how to work out which two are from which W? FIXME!!! for now don't sort jets in Et before after this... TLorentzVector *Hadp = new TLorentzVector(); TLorentzVector *Hadq = new TLorentzVector(); TLorentzVector *Hadj = new TLorentzVector(); TLorentzVector *Hadk = new TLorentzVector(); TLorentzVector *Hadb = new TLorentzVector(); TLorentzVector *Hadbbar = new TLorentzVector(); Hadp->SetPxPyPzE(topJets[0].px(),topJets[0].py(),topJets[0].pz(),topJets[3].energy()); Hadq->SetPxPyPzE(topJets[1].px(),topJets[1].py(),topJets[1].pz(),topJets[2].energy()); Hadj->SetPxPyPzE(topJets[2].px(),topJets[2].py(),topJets[2].pz(),topJets[2].energy()); Hadk->SetPxPyPzE(topJets[3].px(),topJets[3].py(),topJets[3].pz(),topJets[3].energy()); Hadb->SetPxPyPzE(topJets[4].px(),topJets[4].py(),topJets[4].pz(),topJets[1].energy()); Hadbbar->SetPxPyPzE(topJets[4].px(),topJets[4].py(),topJets[4].pz(),topJets[1].energy()); //sort the topJets in Et std::sort(topJets.begin(),topJets.end(),EtComparator); //Et-Sum of the lightest jets double EtSum = topJets[5].et()+topJets[5].et(); double Obs1 = (EtSum>0 ? EtSum : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(1,Obs1)); //Log of the difference in Bdisc between the 2nd and the 3rd jets (ordered in Bdisc) - does that still //make sense for the fully hadronic channel as well?FIXME!!! //sort the jets in Bdiscriminant std::sort(topJets.begin(),topJets.end(),BdiscComparator); double BGap = topJets[1].bDiscriminator("trackCountingJetTags") - topJets[2].bDiscriminator("trackCountingJetTags"); double Obs2 = (BGap>0 ? log(BGap) : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(2,Obs2)); //Circularity of the event double N=0,D=0,C_tmp=0,C=1000; double nx,ny,nz; // C = 2min(E(pt.n)^2/E(pt)^2) = 2*N/D but it is theorically preferable to use C'=PI/2*min(E|pt.n|/E|pt|), sum over all jets+lepton+MET (cf PhysRevD 48 R3953(Nov 1993)) for(unsigned int i=0;i<6;i++){ D += fabs(topJets[i].pt()); } if((D>0)){ // Loop over all the unit vectors in the transverse plane in order to find the miminum : for(unsigned int i=0; i<360; i++){ nx = cos((2*PI/360)*i); ny = sin((2*PI/360)*i); nz = 0; N=0; for(unsigned int i=0;i<4;i++){ N += fabs(topJets[i].px()*nx+topJets[i].py()*ny+topJets[i].pz()*nz); } C_tmp = 2*N/D; if(C_tmp<C) C = C_tmp; } } double Obs3 = ( C!=1000 ? C : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(3,Obs3)); //HT variable (Et-sum of the six jets) double HT=0; for(unsigned int i=0;i<6;i++){ HT += topJets[i].et(); } double Obs4 = ( HT!=0 ? HT : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(4,Obs4)); //Transverse Mass of the system math::XYZTLorentzVector pjets; // for the six jets for(unsigned int i=0;i<6;i++){ pjets += topJets[i].p4(); } double MT = sqrt(std::pow(pjets.mass(),2)); double Obs5 = ( MT>0 ? MT : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(5,Obs5)); //CosTheta(Hadp,Hadq) and CosTheta(Hadj,Hadq) //sort the lightJets in Et std::sort(topJets.begin(),topJets.end(),EtComparator); double px1 = topJets[2].px(); double px2 = topJets[3].px(); double py1 = topJets[2].py(); double py2 = topJets[3].py(); double pz1 = topJets[2].pz(); double pz2 = topJets[3].pz(); double E1 = topJets[2].energy(); double E2 = topJets[3].energy(); double px3 = topJets[4].px(); double px4 = topJets[5].px(); double py3 = topJets[4].py(); double py4 = topJets[5].py(); double pz3 = topJets[4].pz(); double pz4 = topJets[5].pz(); double E3 = topJets[4].energy(); double E4 = topJets[5].energy(); TLorentzVector *LightJet1 = new TLorentzVector(); TLorentzVector *LightJet2 = new TLorentzVector(); TLorentzVector *LightJet3 = new TLorentzVector(); TLorentzVector *LightJet4 = new TLorentzVector(); LightJet1->SetPxPyPzE(px1,py1,pz1,E1); //LightJet1->Boost(BoostBackToCM); LightJet2->SetPxPyPzE(px2,py2,pz2,E2); //LightJet2->Boost(BoostBackToCM); LightJet3->SetPxPyPzE(px3,py3,pz3,E3); //LightJet1->Boost(BoostBackToCM); LightJet4->SetPxPyPzE(px4,py4,pz4,E4); //LightJet2->Boost(BoostBackToCM); double CosTheta1 = cos(LightJet2->Angle(LightJet1->Vect())); double CosTheta2 = cos(LightJet4->Angle(LightJet3->Vect())); double Obs6 = ( -1<CosTheta1 ? CosTheta1 : -2); evtselectVarVal.push_back(std::pair<unsigned int,double>(6,Obs6)); double Obs7 = ( -1<CosTheta2 ? CosTheta2 : -2); evtselectVarVal.push_back(std::pair<unsigned int,double>(7,Obs7)); delete LightJet1; delete LightJet2; delete LightJet3; delete LightJet4; // try to find out more powerful observables related to the b-disc //sort the jets in Bdiscriminant std::sort(topJets.begin(),topJets.end(),BdiscComparator); double BjetsBdiscSum = topJets[0].bDiscriminator("trackCountingJetTags") + topJets[1].bDiscriminator("trackCountingJetTags"); double Ljets1BdiscSum = topJets[2].bDiscriminator("trackCountingJetTags") + topJets[3].bDiscriminator("trackCountingJetTags"); double Ljets2BdiscSum = topJets[4].bDiscriminator("trackCountingJetTags") + topJets[5].bDiscriminator("trackCountingJetTags"); //std::cout<<"BjetsBdiscSum = "<<BjetsBdiscSum<<std::endl; //std::cout<<"LjetsBdiscSum = "<<LjetsBdiscSum<<std::endl; double Obs8 = (Ljets1BdiscSum !=0 ? log(BjetsBdiscSum/Ljets1BdiscSum) : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(8,Obs8)); double Obs9 = (Ljets2BdiscSum !=0 ? log(BjetsBdiscSum/Ljets2BdiscSum) : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(9,Obs9)); double Obs10 = (BGap>0 ? log(BjetsBdiscSum*BGap) : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(10,Obs10)); // Et-Ratio between the two highest in Et jets and four highest jets double Obs11 = (HT!=0 ? (HT-EtSum)/HT : -1); evtselectVarVal.push_back(std::pair<unsigned int,double>(11,Obs11)); //Sphericity and Aplanarity without boosting back the system to CM frame TMatrixDSym Matrix(3); double PX2 = std::pow(Hadp->Px(),2)+std::pow(Hadq->Px(),2)+std::pow(Hadb->Px(),2)+ std::pow(Hadj->Px(),2)+std::pow(Hadk->Px(),2)+std::pow(Hadbbar->Px(),2); double PY2 = std::pow(Hadp->Py(),2)+std::pow(Hadq->Py(),2)+std::pow(Hadb->Py(),2)+ std::pow(Hadj->Py(),2)+std::pow(Hadk->Py(),2)+std::pow(Hadbbar->Py(),2); double PZ2 = std::pow(Hadp->Pz(),2)+std::pow(Hadq->Pz(),2)+std::pow(Hadb->Pz(),2)+ std::pow(Hadj->Pz(),2)+std::pow(Hadk->Pz(),2)+std::pow(Hadbbar->Pz(),2); double P2 = PX2+PY2+PZ2; double PXY = Hadp->Px()*Hadp->Py()+Hadq->Px()*Hadq->Py()+Hadb->Px()*Hadb->Py()+ Hadj->Px()*Hadj->Py()+Hadk->Px()*Hadk->Py()+Hadbbar->Px()*Hadbbar->Py(); double PXZ = Hadp->Px()*Hadp->Pz()+Hadq->Px()*Hadq->Pz()+Hadb->Px()*Hadb->Pz()+ Hadj->Px()*Hadj->Pz()+Hadk->Px()*Hadk->Pz()+Hadbbar->Px()*Hadbbar->Pz(); double PYZ = Hadp->Py()*Hadp->Pz()+Hadq->Py()*Hadq->Pz()+Hadb->Py()*Hadb->Pz()+ Hadj->Py()*Hadj->Pz()+Hadk->Py()*Hadk->Pz()+Hadbbar->Py()*Hadbbar->Pz(); Matrix(0,0) = PX2/P2; Matrix(0,1) = PXY/P2; Matrix(0,2) = PXZ/P2; Matrix(1,0) = PXY/P2; Matrix(1,1) = PY2/P2; Matrix(1,2) = PYZ/P2; Matrix(2,0) = PXZ/P2; Matrix(2,1) = PYZ/P2; Matrix(2,2) = PZ2/P2; TMatrixDSymEigen pTensor(Matrix); std::vector<double> EigValues; EigValues.clear(); for(int i=0;i<3;i++){ EigValues.push_back(pTensor.GetEigenValues()[i]); } std::sort(EigValues.begin(),EigValues.end(),dComparator); double Sphericity = 1.5*(EigValues[1]+EigValues[2]); double Aplanarity = 1.5*EigValues[2]; double Obs12 = (edm::isNotFinite(Sphericity) ? -1 : Sphericity); evtselectVarVal.push_back(std::pair<unsigned int,double>(12,Obs12)); double Obs13 = (edm::isNotFinite(Aplanarity) ? -1 : Aplanarity); evtselectVarVal.push_back(std::pair<unsigned int,double>(13,Obs13)); //Sphericity and Aplanarity with boosting back the system to CM frame TLorentzVector *TtbarSystem = new TLorentzVector(); TtbarSystem->SetPx(Hadp->Px()+Hadq->Px()+Hadb->Px()+Hadj->Px()+Hadk->Px()+Hadbbar->Px()); TtbarSystem->SetPy(Hadp->Py()+Hadq->Py()+Hadb->Py()+Hadj->Py()+Hadk->Py()+Hadbbar->Py()); TtbarSystem->SetPz(Hadp->Pz()+Hadq->Pz()+Hadb->Pz()+Hadj->Pz()+Hadk->Pz()+Hadbbar->Pz()); TtbarSystem->SetE(Hadp->E()+Hadq->E()+Hadb->E()+Hadj->E()+Hadk->E()+Hadbbar->E()); TVector3 BoostBackToCM = -(TtbarSystem->BoostVector()); Hadp->Boost(BoostBackToCM); Hadq->Boost(BoostBackToCM); Hadb->Boost(BoostBackToCM); Hadj->Boost(BoostBackToCM); Hadk->Boost(BoostBackToCM); Hadbbar->Boost(BoostBackToCM); double BOOST_PX2 = std::pow(Hadp->Px(),2)+std::pow(Hadq->Px(),2)+std::pow(Hadb->Px(),2)+ std::pow(Hadj->Px(),2)+std::pow(Hadk->Px(),2)+std::pow(Hadbbar->Px(),2); double BOOST_PY2 = std::pow(Hadp->Py(),2)+std::pow(Hadq->Py(),2)+std::pow(Hadb->Py(),2)+ std::pow(Hadj->Py(),2)+std::pow(Hadk->Py(),2)+std::pow(Hadbbar->Py(),2); double BOOST_PZ2 = std::pow(Hadp->Pz(),2)+std::pow(Hadq->Pz(),2)+std::pow(Hadb->Pz(),2)+ std::pow(Hadj->Pz(),2)+std::pow(Hadk->Pz(),2)+std::pow(Hadbbar->Pz(),2); double BOOST_P2 = BOOST_PX2+BOOST_PY2+BOOST_PZ2; double BOOST_PXY = Hadp->Px()*Hadp->Py()+Hadq->Px()*Hadq->Py()+Hadb->Px()*Hadb->Py()+ Hadj->Px()*Hadj->Py()+Hadk->Px()*Hadk->Py()+Hadbbar->Px()*Hadbbar->Py(); double BOOST_PXZ = Hadp->Px()*Hadp->Pz()+Hadq->Px()*Hadq->Pz()+Hadb->Px()*Hadb->Pz()+ Hadj->Px()*Hadj->Pz()+Hadk->Px()*Hadk->Pz()+Hadbbar->Px()*Hadbbar->Pz(); double BOOST_PYZ = Hadp->Py()*Hadp->Pz()+Hadq->Py()*Hadq->Pz()+Hadb->Py()*Hadb->Pz()+ Hadj->Py()*Hadj->Pz()+Hadk->Py()*Hadk->Pz()+Hadbbar->Py()*Hadbbar->Pz(); TMatrixDSym BOOST_Matrix(3); BOOST_Matrix(0,0) = BOOST_PX2/BOOST_P2; BOOST_Matrix(0,1) = BOOST_PXY/BOOST_P2; BOOST_Matrix(0,2) = BOOST_PXZ/BOOST_P2; BOOST_Matrix(1,0) = BOOST_PXY/BOOST_P2; BOOST_Matrix(1,1) = BOOST_PY2/BOOST_P2; BOOST_Matrix(1,2) = BOOST_PYZ/BOOST_P2; BOOST_Matrix(2,0) = BOOST_PXZ/BOOST_P2; BOOST_Matrix(2,1) = BOOST_PYZ/BOOST_P2; BOOST_Matrix(2,2) = BOOST_PZ2/BOOST_P2; TMatrixDSymEigen BOOST_pTensor(BOOST_Matrix); std::vector<double> BOOST_EigValues; BOOST_EigValues.clear(); for(int i=0;i<3;i++){ BOOST_EigValues.push_back(BOOST_pTensor.GetEigenValues()[i]); } std::sort(BOOST_EigValues.begin(),BOOST_EigValues.end(),dComparator); double BOOST_Sphericity = 1.5*(BOOST_EigValues[1]+BOOST_EigValues[2]); double BOOST_Aplanarity = 1.5*BOOST_EigValues[2]; double Obs14 = ( edm::isNotFinite(BOOST_Sphericity) ? -1 : BOOST_Sphericity ); evtselectVarVal.push_back(std::pair<unsigned int,double>(14,Obs14)); double Obs15 = ( edm::isNotFinite(BOOST_Aplanarity) ? -1 : BOOST_Aplanarity ); evtselectVarVal.push_back(std::pair<unsigned int,double>(15,Obs15)); // Centrality of the six jets double H=0; for(unsigned int i=0;i<6;i++){ H += topJets[i].energy(); } double Obs16 = ( H != 0 ? HT/H : -1 ); evtselectVarVal.push_back(std::pair<unsigned int,double>(16,Obs16)); // distance from the origin in the (BjetsBdiscSum, Ljets1BdiscSum) and (BjetsBdiscSum, Ljets2BdiscSum) double Obs17 = ( BjetsBdiscSum != 0 && Ljets1BdiscSum != 0 ? 0.707*(BjetsBdiscSum-Ljets1BdiscSum) : -1 ); evtselectVarVal.push_back(std::pair<unsigned int,double>(17,Obs17)); double Obs18 = ( BjetsBdiscSum != 0 && Ljets2BdiscSum != 0 ? 0.707*(BjetsBdiscSum-Ljets2BdiscSum) : -1 ); evtselectVarVal.push_back(std::pair<unsigned int,double>(18,Obs18)); // Ratio of the Et Sum of the two lightest jets over HT=Sum of the Et of the six highest jets in Et double Obs19 = ( HT != 0 ? EtSum/HT : -1 ); evtselectVarVal.push_back(std::pair<unsigned int,double>(19,Obs19)); // Put the vector in the TtHadEvtSolution TS.setLRSignalEvtObservables(evtselectVarVal); }
ffbe5414686bb401fd8565b5f181ee8087e39bcb
e5f4f37d941ceb8145d65f92028cc54658b1ac01
/Code/ThirdParty/RmlUi/Include/RmlUi/Core/Variant.inl
b3b602b32e3fbfb5fed98c3769876e78f527eadb
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
ezEngine/ezEngine
19983d2733a5409fb2665c6c3a0a575dadcefb50
c46e3b4b2cd46798e4abb4938fbca281c054b039
refs/heads/dev
2023-09-06T02:17:28.152665
2023-09-05T18:25:43
2023-09-05T18:25:43
18,179,848
1,050
165
MIT
2023-09-14T21:44:39
2014-03-27T15:02:16
C++
UTF-8
C++
false
false
4,234
inl
Variant.inl
/* * This source file is part of RmlUi, the HTML/CSS Interface Middleware * * For the latest information, see http://github.com/mikke89/RmlUi * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * Copyright (c) 2019 The RmlUi Team, and contributors * * 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. * */ namespace Rml { inline Variant::Type Variant::GetType() const { return type; } template< typename T > Variant::Variant(T&& t) : type(NONE) { Set(std::forward<T>(t)); } template< typename T > Variant& Variant::operator=(T&& t) { Clear(); Set(std::forward<T>(t)); return *this; } // Templatised data accessor. template< typename T > bool Variant::GetInto(T& value) const { switch (type) { case BOOL: return TypeConverter< bool, T >::Convert(*(bool*)data, value); break; case BYTE: return TypeConverter< byte, T >::Convert(*(byte*)data, value); break; case CHAR: return TypeConverter< char, T >::Convert(*(char*)data, value); break; case FLOAT: return TypeConverter< float, T >::Convert(*(float*)data, value); break; case DOUBLE: return TypeConverter< double, T >::Convert(*(double*)data, value); break; case INT: return TypeConverter< int, T >::Convert(*(int*)data, value); break; case INT64: return TypeConverter< int64_t, T >::Convert(*(int64_t*)data, value); break; case UINT: return TypeConverter< unsigned int, T >::Convert(*(unsigned int*)data, value); break; case UINT64: return TypeConverter< uint64_t, T >::Convert(*(uint64_t*)data, value); break; case STRING: return TypeConverter< String, T >::Convert(*(String*)data, value); break; case VECTOR2: return TypeConverter< Vector2f, T >::Convert(*(Vector2f*)data, value); break; case VECTOR3: return TypeConverter< Vector3f, T >::Convert(*(Vector3f*)data, value); break; case VECTOR4: return TypeConverter< Vector4f, T >::Convert(*(Vector4f*)data, value); break; case COLOURF: return TypeConverter< Colourf, T >::Convert(*(Colourf*)data, value); break; case COLOURB: return TypeConverter< Colourb, T >::Convert(*(Colourb*)data, value); break; case SCRIPTINTERFACE: return TypeConverter< ScriptInterface*, T >::Convert(*(ScriptInterface * *)data, value); break; case VOIDPTR: return TypeConverter< void*, T >::Convert(*(void**)data, value); break; case TRANSFORMPTR: return TypeConverter< TransformPtr, T >::Convert(*(TransformPtr*)data, value); break; case TRANSITIONLIST: return TypeConverter< TransitionList, T >::Convert(*(TransitionList*)data, value); break; case ANIMATIONLIST: return TypeConverter< AnimationList, T >::Convert(*(AnimationList*)data, value); break; case DECORATORSPTR: return TypeConverter< DecoratorsPtr, T >::Convert(*(DecoratorsPtr*)data, value); break; case FONTEFFECTSPTR: return TypeConverter< FontEffectsPtr, T >::Convert(*(FontEffectsPtr*)data, value); break; case NONE: break; } return false; } // Templatised data accessor. template< typename T > T Variant::Get(T default_value) const { GetInto(default_value); return default_value; } template<typename T> inline const T& Variant::GetReference() const { return *(T*)data; } } // namespace Rml
c92a3105e81b95ace78e7a01b8039389610faaf6
9763d937ce3cc6a7278af735bbd05363d9c21abb
/Camera/perspectivecamera.h
2e9d138aebc224f5585be5046d602428a78a2346
[]
no_license
TheSlothExperience/SheepBattleBoats
9ee86bbb30699af74d1cbf07e2f1c907d10242f1
45f6b3364aeff9b50270b64efdd9b103caedbc68
refs/heads/master
2021-01-19T08:42:56.565654
2014-07-23T21:47:37
2014-07-23T21:47:37
19,927,076
1
0
null
2014-07-21T18:29:28
2014-05-19T02:38:41
C++
UTF-8
C++
false
false
513
h
perspectivecamera.h
#ifndef PERSPECTIVECAMERA_H #define PERSPECTIVECAMERA_H #include "camera.h" class PerspectiveCamera : public Camera { public: PerspectiveCamera(double x, double y, double z, double width, double height); PerspectiveCamera(QVector3D position, double width, double height); void resize(double width, double height); void zoom(double z); QMatrix4x4 getProjectionMatrix(); void reset(); void setPointOfInterest(QVector3D poi); double width; double height; double fov; QVector3D up; }; #endif
47c0a5ab3f95b9178ca083e1ed8aea0b5cbcd4f4
77e9c971ef1dffd71bbec28489db186abfdeda9c
/include/gtorrent/Log.hpp
3a2364d9c96a4fc3b3dce8999a74579997cd1686
[]
no_license
charles-ramsey/gtorrent-core
040572d037c6d7d0a08e377403cc77e329b628fd
7f8d0c7de151df07c365676532e51d45592a1cba
refs/heads/master
2021-01-18T07:25:58.306688
2014-07-22T03:23:14
2014-07-22T03:23:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
174
hpp
Log.hpp
#pragma once using namespace std; #include <string> namespace gt { class Log { public: static string getTimeStamp(); static void Debug(const char *fmt, ...); }; }
b5077560c4b2129310eadc2b410b6027859142f3
bfdfb7c406c318c877b7cbc43bc2dfd925185e50
/vcproj/hydll/hydll.cpp
3fec01dc15070f7de80980bbacc642b6397bf7a8
[ "MIT" ]
permissive
ysei/Hayat
74cc1e281ae6772b2a05bbeccfcf430215cb435b
b32ed82a1c6222ef7f4bf0fc9dedfad81280c2c0
refs/heads/master
2020-12-11T09:07:35.606061
2011-08-01T12:38:39
2011-08-01T12:38:39
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,818
cpp
hydll.cpp
// hydll.cpp : DLL の初期化ルーチンです。 // #include "stdafx.h" #include "hydll.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // //TODO: この DLL が MFC DLL に対して動的にリンクされる場合、 // MFC 内で呼び出されるこの DLL からエクスポートされたどの関数も // 関数の最初に追加される AFX_MANAGE_STATE マクロを // 持たなければなりません。 // // 例: // // extern "C" BOOL PASCAL EXPORT ExportedFunction() // { // AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // 通常関数の本体はこの位置にあります // } // // このマクロが各関数に含まれていること、MFC 内の // どの呼び出しより優先することは非常に重要です。 // これは関数内の最初のステートメントでなければな // らないことを意味します、コンストラクタが MFC // DLL 内への呼び出しを行う可能性があるので、オブ // ジェクト変数の宣言よりも前でなければなりません。 // // 詳細については MFC テクニカル ノート 33 および // 58 を参照してください。 // // ChydllApp BEGIN_MESSAGE_MAP(ChydllApp, CWinApp) END_MESSAGE_MAP() namespace Hayat { namespace Engine { class HClass; extern const HClass* HC_Int; }} // ChydllApp コンストラクション ChydllApp::ChydllApp() { // TODO: この位置に構築用コードを追加してください。 // ここに InitInstance 中の重要な初期化処理をすべて記述してください。 } // 唯一の ChydllApp オブジェクトです。 ChydllApp theApp; // ChydllApp 初期化 BOOL ChydllApp::InitInstance() { CWinApp::InitInstance(); return TRUE; }
8e992820d0366daaf8f6caeb3c74b1945014ea6a
c0210cb2b2a25123d45821cb8f38ba844aa8f4dc
/Classes/SampleScene/SoundMenuSampleScene.cpp
bfd346b7cae2301b0466a02dce98993cd8641361
[]
no_license
anzfactory/SampleForCocos
327ca160542679a5e224fb841bd8ca6f81cbc1de
98e9eca62f50b251ad43a38970966748b14ed92b
refs/heads/master
2021-01-23T15:53:37.605812
2014-06-23T06:25:50
2014-06-23T06:25:50
19,498,776
1
0
null
null
null
null
UTF-8
C++
false
false
2,648
cpp
SoundMenuSampleScene.cpp
// // SoundMenuSampleScene.cpp // cocos3 // // Created by ANZ on 2014/05/07. // // #include "SoundMenuSampleScene.h" #include "AnzMenu.h" USING_NS_CC; using namespace std; SoundMenuSampleScene::SoundMenuSampleScene() { } SoundMenuSampleScene::~SoundMenuSampleScene() { } Scene* SoundMenuSampleScene::createScene() { auto scene = CCScene::create(); auto layer = SoundMenuSampleScene::create(); scene->addChild(layer); return scene; } bool SoundMenuSampleScene::init() { if (! Layer::init()) { return false; } setupMenu(); return true; } void SoundMenuSampleScene::setupMenu() { map<int, const char*> anotherSounds; auto size = getContentSize(); auto clickMe = createMenuItem("SE_CLICK_1"); clickMe->setPosition(Point(size.width * 0.5, size.height * 0.7)); clickMe->setCallback([](Ref *sender) { log("%d", sender->_ID); }); auto clickMe2 = createMenuItem("SE_CKICK_1(2)"); clickMe2->setPosition(Point(clickMe->getPositionX(), size.height * 0.6)); clickMe2->setCallback([](Ref *sender) { log("%d", sender->_ID); }); auto clickMe3 = createMenuItem("SE_CLICK_2"); clickMe3->setPosition(clickMe2->getPositionX(), size.height * 0.5); clickMe3->setCallback([](Ref *sender){ log("%d", sender->_ID); }); // 音かえたい clickMe3->setTag(10); anotherSounds[clickMe3->getTag()] = "se_click_1.mp3"; auto clickMe4 = createMenuItem("SE_TE"); clickMe4->setPosition(clickMe3->getPositionX(), size.height * .4f); clickMe4->setCallback([](Ref *sender){ log("%d", sender->_ID); }); // 音変えたい clickMe4->setTag(20); anotherSounds[clickMe4->getTag()] = "se_te.mp3"; auto back = createMenuItem("back"); back->setAnchorPoint(Point::ANCHOR_MIDDLE_BOTTOM); back->setPosition(Point(clickMe->getPosition().x, 0)); back->setCallback([](Ref *sender) { log("%d", sender->_ID); Director::getInstance()->popScene(); }); auto menu = AnzMenu::create(clickMe, clickMe2, clickMe3, clickMe4, back, NULL); menu->setPosition(Point::ZERO); menu->setSoundFilePath("click.mp3"); // 効果音設定 menu->setSoundList(anotherSounds); // 別音 addChild(menu); } MenuItem* SoundMenuSampleScene::createMenuItem(const char *text) { auto normal = Label::createWithSystemFont(text, "Arial", 50); auto selected = Label::createWithSystemFont(text, "Arial", 50); selected->setColor(Color3B::GRAY); auto item = MenuItemSprite::create(normal, selected); return item; }
231df02be0961fb2c105062ed22aad3a249c5c38
18571b48f98c4a077ccab1565e9e50e5625c1907
/thirdSrc/ffmpeg/ffmpegreplay.h
decabc4e9f3d7b87a0b48ec344488c1aaa702d6d
[]
no_license
xiaoxiaodx/DoubleLight
e0452b0a50da71c0c451fe66d82cc9fac541a627
984ef4a0c76b9cb5b84d88f0e55bae7865d08cc2
refs/heads/master
2021-05-17T12:13:45.798837
2020-05-12T01:46:18
2020-05-12T01:46:18
250,769,472
1
4
null
null
null
null
UTF-8
C++
false
false
1,730
h
ffmpegreplay.h
#ifndef FFMPEGREPLAY_H #define FFMPEGREPLAY_H extern "C"{ #include "libavformat/avformat.h" #include "libavutil/mathematics.h" #include "libavutil/time.h" #include "libswscale/swscale.h" #include "libswresample/swresample.h" #include "libavutil/opt.h" #include "libavcodec/avcodec.h" } #include <QObject> #include <QDebug> #include <QString> #include <QImage> #include <QThread> #include <QMutex> #include <QMutexLocker> #include <QFile> #include <QObject> class FFmpegReplay : public QObject { Q_OBJECT public: explicit FFmpegReplay(QObject *parent = nullptr); ~FFmpegReplay(); public slots: void slot_openFile(QString path); private: void initVariable(); void consoleDebug(QString str); AVPacket m_AVPacket; AVFrame *m_pAVFrame; AVFormatContext *m_pAvformatCtx; //视频 AVCodecContext *m_pVCodecCtx; AVCodec *m_pVCodec; uint8_t *m_pVoutBuffer; AVFrame *m_pVFrameBGR; SwsContext *m_pImg_convert_ctx ; //音频 AVCodec *m_pACodec; AVCodecContext *m_pACodecCtx; //音频重采样 // 设置数据源src和dst声道布局 int64_t src_ch_layout , dst_ch_layout; // 设置src和dst采样率 int src_rate , dst_rate ; uint8_t **src_data , **dst_data ; int src_nb_channels, dst_nb_channels; int src_linesize, dst_linesize; int src_nb_samples , dst_nb_samples, max_dst_nb_samples; // 设置src和dst音频格式 enum AVSampleFormat src_sample_fmt , dst_sample_fmt ; int dst_bufsize; struct SwrContext *swr_ctx; QMutex finishMutex; QMutex pauseMutex; int m_VstreamIndex; int m_AstreamIndex; bool isPlay; bool isPause; }; #endif // FFMPEGREPLAY_H
8aa538b115506e445b97db634a3ac3c1219ec305
ef9e061eaed20e9e9c1469e7edfe1b20ff972d03
/services/core/jni/com_android_server_radio_Tuner_TunerCallback.h
35a4d695bef37f00326575a8a8f393ce1e3df782
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
Fabulous-Oreo/frameworks_base
52cbed9490a3306303ad956b9d197b99a10788c6
c11d8b576b22e6318014496f85154e8533da22e4
refs/heads/oreo
2021-09-29T01:18:15.502131
2017-11-14T05:13:46
2017-11-14T05:13:46
104,632,272
2
4
null
2017-11-06T13:35:34
2017-09-24T09:17:27
Java
UTF-8
C++
false
false
1,459
h
com_android_server_radio_Tuner_TunerCallback.h
/** * Copyright (C) 2017 The Android Open Source Project * * 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. */ // TODO(b/36863239): rename s/_Tuner_TunerCallback/_TunerCallback/, as this // module is no longer a part of Tuner - it's an independent java class. #ifndef _ANDROID_SERVER_RADIO_TUNERCALLBACK_H #define _ANDROID_SERVER_RADIO_TUNERCALLBACK_H #include "JavaRef.h" #include "NativeCallbackThread.h" #include "com_android_server_radio_types.h" #include <android/hardware/broadcastradio/1.1/ITunerCallback.h> #include <jni.h> namespace android { void register_android_server_radio_TunerCallback(JavaVM *vm, JNIEnv *env); namespace server { namespace radio { namespace TunerCallback { sp<hardware::broadcastradio::V1_1::ITunerCallback> getNativeCallback(JNIEnv *env, jobject jTunerCallback); } // namespace TunerCallback } // namespace radio } // namespace server } // namespace android #endif // _ANDROID_SERVER_RADIO_TUNERCALLBACK_H
8cfd310d82cc9e5430bbe6da19fead9ef96b5010
9db77c7864666916058d32f60ec1605b87242af4
/src/include/SFMLView.hpp
e27bfb7dd77164c8f2bf2fe8594d52ca2723b080
[]
no_license
Loulfy/Shootemup
bc0cf3aa40419b6128065ab2cd645201bf2188d1
0aee103224ffcced5787845a5792d901dd188f31
refs/heads/master
2016-08-02T23:18:15.389058
2015-04-17T15:43:32
2015-04-17T15:43:32
33,564,813
0
0
null
null
null
null
UTF-8
C++
false
false
517
hpp
SFMLView.hpp
#ifndef VIEW_SFML_H #define VIEW_SFML_H #include <iostream> #include <SFML/Graphics.hpp> #include "View.hpp" #include "SFMLFrame.hpp" #include "AssetManager.hpp" class SFMLView : public View { public: SFMLView(); ~SFMLView(); bool run() override; void setModel(Model* m) override; void draw() override; void update() override; void add(Bullet* bullet) override; void add(Entity* entity) override; private: sf::RenderWindow* m_window; sf::Clock m_clock; AssetManager m_assets; }; #endif
282f3c256d608193322a64d386e52a7bd1daa4a2
d0e4b8320277c825a1842c709d243a603e4427ef
/code/threads/boundedbuffer.h
7ab810689f9fd844379eb3a24306c6d4d856325c
[ "MIT-Modern-Variant" ]
permissive
xmuliushuo/nachos
b70a902996dbe9794c17c5e4f3780bd79005b9d4
bf0ff71243abfad334c2c21de5127a187ca8fd5e
refs/heads/master
2021-01-01T19:23:41.317257
2013-07-22T09:10:03
2013-07-22T09:10:03
9,319,860
8
5
null
null
null
null
UTF-8
C++
false
false
775
h
boundedbuffer.h
#ifndef BOUNDEDBUFFER_H #define BOUNDEDBUFFER_H #include "synch.h" class BoundedBuffer { public: // create a bounded buffer with a limit of 'maxsize' bytes BoundedBuffer(int maxsize); ~BoundedBuffer(); // read 'size' bytes from the bounded buffer, storing into 'data'. // ('size' may be greater than 'maxsize') void Read(void *data, int size); // write 'size' bytes from 'data' into the bounded buffer. // ('size' may be greater than 'maxsize') void Write(void *data, int size); private: void *m_buffer; Lock *m_lock; int m_bufferSize; int m_count; int m_nextin; int m_nextout; Condition *m_bufferEmpty; Condition *m_bufferFull; }; #endif
7ad11f626b764d00a08b98f9f031929e0877ca0a
c171a150366abed28087c4852ff7f887d6e233b6
/Greedy/moscas.cpp
ed6863d7875f211376f779abe897e2f51af8ec4f
[]
no_license
Delciuxs/Competitive-Programming-Problems
495853d401594d5129f234a0d74be9facc1c3ea1
be04901b5b8ed602a2063b117fe1997eb446b8ca
refs/heads/master
2021-06-14T09:20:21.476095
2019-09-23T23:03:05
2019-09-23T23:03:05
104,252,071
0
0
null
null
null
null
UTF-8
C++
false
false
1,282
cpp
moscas.cpp
//LINK to the Problem: //https://omegaup.com/arena/problem/moscas#problems //Problem type: Greedy #include<iostream> #include<vector> #include<map> #include<algorithm> using namespace std; int main() { int num_flies, aux; cin >> num_flies; vector<pair<int, char> > time; for(int i = 0; i < num_flies; i++) { cin >> aux; time.push_back(make_pair(aux, 'l'));//LIVE cin >> aux; time.push_back(make_pair(aux, 'd'));//DEAD } sort(time.begin(), time.end()); map<int, int> living_flies; int flies = 0, max_flies = -1; for(int i = 0; i < time.size(); i++) { if(time[i].second == 'l') { flies++; if(living_flies.count(time[i].first) == 0) living_flies[time[i].first] = flies; else living_flies[time[i].first] = flies; } else { flies--; if(living_flies.count(time[i].first) == 0) living_flies[time[i].first] = flies; else living_flies[time[i].first] = flies; } max_flies = max(flies, max_flies); } cout << max_flies << "\n"; auto it = living_flies.cbegin(); while(it != living_flies.cend()) { if(it->second == max_flies) { cout << it->first << " "; while(it->second == max_flies) it++; cout << it->first << "\n"; } else it++; } return 0; }
8026739ac51879b5de5299ca9d2d986421969dc6
5588c6f0e065c2556eda02305bb4353cd3d7fa6a
/ftec-core/src/graphics/Image.cpp
105422e4be98f45f4920e2546786b02ed2e9adf3
[]
no_license
folkerthoogenraad/PotatoEngine
9ecc0f98d9cbc9cdff85c70aa11d19d1f9f5b609
daf1807d18cc3cd518d34318da3d4d68d4d93cc4
refs/heads/master
2020-07-25T17:11:12.319159
2017-10-09T13:08:24
2017-10-09T13:08:24
67,635,766
1
0
null
null
null
null
UTF-8
C++
false
false
331
cpp
Image.cpp
#include "Image.h" namespace ftec { Image::Image(int width, int height) : m_Width(width), m_Height(height) { m_Data.resize(m_Width * m_Height); } Color32 Image::getColor(int x, int y) const { return m_Data[x + y * m_Width]; } void Image::setColor(int x, int y, Color32 c) { m_Data[x + y * m_Width] = c; } }
e2a5005dde3f60a64a9c283157380412fa010378
19ed4c1bb2c4386eb98201e1b50ffc91549174dc
/Source/Platform/Vulkan/VulkanDeviceObject.h
ac0ea928c0201df397770721f170e1c3e6d7c811
[]
no_license
mRooky/Rooky
81742fffd72700b3423802702ffc9e5658151f75
401bd515e42873b268395c1bc96fbb4982c83875
refs/heads/master
2020-04-19T11:43:43.985899
2019-08-27T06:27:46
2019-08-27T06:27:46
168,174,259
0
0
null
null
null
null
UTF-8
C++
false
false
542
h
VulkanDeviceObject.h
/* * VulkanDeviceObject.h * * Created on: Aug 14, 2018 * Author: rookyma */ #ifndef VULKAN_VULKANDEVICEOBJECT_H_ #define VULKAN_VULKANDEVICEOBJECT_H_ #include "VulkanObject.h" namespace Vulkan { class Device; class VULKAN_EXPORT DeviceObject: public Object { protected: explicit DeviceObject(Device* device); virtual ~DeviceObject(void) override; public: inline Device* GetDevice(void) const { return mDevice; } protected: Device* mDevice = nullptr; }; } /* namespace Vulkan */ #endif /* VULKAN_VULKANDEVICEOBJECT_H_ */
7ca49c17e469059152916b221dd5c75b17d1a2ed
00d5cd399405500ffef11d4d17b43b836cb5c964
/src/vizier/services/agent/shared/manager/exec.h
2e935fd8f898972367d09e0375560f04a0c6f277
[ "Apache-2.0" ]
permissive
doytsujin/pixie
0b1105105d0f05cf320cdd7bea55c360d1d01925
cfe6c966fac18ac0c6e4a28b4f51f3be7553e30b
refs/heads/main
2023-06-10T00:09:33.784394
2023-06-06T00:05:07
2023-06-06T00:05:07
364,398,868
0
0
Apache-2.0
2021-05-04T22:12:14
2021-05-04T22:12:13
null
UTF-8
C++
false
false
2,193
h
exec.h
/* * Copyright 2018- The Pixie Authors. * * 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. * * SPDX-License-Identifier: Apache-2.0 */ #pragma once #include <memory> #include <absl/container/flat_hash_map.h> #include <prometheus/registry.h> #include "src/carnot/plan/plan.h" #include "src/vizier/services/agent/shared/manager/manager.h" namespace px { namespace vizier { namespace agent { /** * ExecuteQueryMessageHandler takes execute query results and performs them. * If a qb_stub is specified the results will also be RPCd to the query broker, * otherwise only query execution is performed. * * This class runs all of it's work on a thread pool and tracks pending queries internally. */ class ExecuteQueryMessageHandler : public Manager::MessageHandler { public: ExecuteQueryMessageHandler() = delete; ExecuteQueryMessageHandler(px::event::Dispatcher* dispatcher, Info* agent_info, Manager::VizierNATSConnector* nats_conn, carnot::Carnot* carnot); ~ExecuteQueryMessageHandler() override = default; Status HandleMessage(std::unique_ptr<messages::VizierMessage> msg) override; protected: /** * HandleQueryExecutionComplete can be called by the async task to signal that work has been * completed. */ virtual void HandleQueryExecutionComplete(sole::uuid query_id); private: // Forward declare private task class. class ExecuteQueryTask; carnot::Carnot* carnot_; // Map from query_id -> Running query task. absl::flat_hash_map<sole::uuid, px::event::RunnableAsyncTaskUPtr> running_queries_; prometheus::Gauge& num_queries_in_flight_; }; } // namespace agent } // namespace vizier } // namespace px
6d83f15cb18c79e893b681d28341b9e17e99070f
dd45746e20d7e2a74fa7646866ca58deb6f48e53
/161044054_CSE241_HW5/PolygonDyn.h
d05b2bcf85da2fe0f0f711b369b549aca52bcf7b
[]
no_license
fatihselimyakar/CppProjects
c64c6e27e10fa82b183e856357abca5ef9ec793a
c59e84b60a7e9a81ac00cfe9f81521f6ca7904b2
refs/heads/master
2020-04-12T21:23:42.900600
2019-01-19T17:07:04
2019-01-19T17:07:04
162,760,952
0
0
null
null
null
null
UTF-8
C++
false
false
1,372
h
PolygonDyn.h
#ifndef POLYGON_DYN_H #define POLYGON_DYN_H #include "Polygon.h" namespace SHAPE{ class PolygonDyn : public Polygon{ public: PolygonDyn()noexcept; PolygonDyn(vector<Point2d>pointVector)throw(MyException);//GENERATES A POLYGONDYN RESPECT TO POINT2D VECTOR PolygonDyn(int newCapacity,int newSize)throw(MyException);//GENERATES A POLYGONDYN RESPECT TO CAPACITY AND SIZE PolygonDyn(Rectangle rec)throw(MyException);//GENERATES A POLYGONDYN RESPECT TO PARAMETER RECTANGLE PolygonDyn(Triangle tri)throw(MyException);//GENERATES A POLYGONDYN RESPECT TO PARAMETER TRIANGLE PolygonDyn(Circle cir)throw(MyException);//GENERATES A POLYGONDYN RESPECT TO PARAMETER CIRCLE virtual void draw(ostream& outputStream)const throw(MyException) override final;//DRAW A POLYGON SHAPE IN SVG FILE Point2d& operator[](int index)const throw(MyException);//RETURNS points[index] int getCapacity()const noexcept; int getSize()const noexcept; PolygonDyn& operator=(const PolygonDyn& rightSide)noexcept;//assignment for big three PolygonDyn(const PolygonDyn& object)noexcept;//copy constructor ~PolygonDyn()noexcept;//destructor private: Point2d *points; int capacity;//IT IS THE CAPACITY OF "*points" int size;//IT IS THE SIZE OF "*points" }; } #endif
267296552ddf3889117d23ed3baa00c608cd43df
703ec46ee5493dcd169e8100d0cfd3555c719144
/d3d12/LabProjects/LabProject03/LabProject03/GraphicsPipeline.cpp
2bdbab80662b6beaab54cfc661f7786f93f89b80
[]
no_license
kimduuukbae/Today-I-Learned
e8ca001c815fc7fb02a738bc3eb564e89791bb6a
496a3603f65bedfba83d1a9f2f2fd83b4d0c0269
refs/heads/master
2022-08-07T03:52:46.875576
2022-08-01T05:45:55
2022-08-01T05:45:55
214,361,320
4
0
null
null
null
null
UTF-8
C++
false
false
936
cpp
GraphicsPipeline.cpp
#include "stdafx.h" #include "GraphicsPipeline.h" using namespace DirectX; XMFLOAT4X4* CGraphicsPipeline::pWorldMatrix = nullptr; XMFLOAT4X4* CGraphicsPipeline::pViewProjectMatrix = nullptr; CViewport* CGraphicsPipeline::pViewport = nullptr; XMFLOAT3 CGraphicsPipeline::ScreenTransform(const XMFLOAT3& f3Project){ XMFLOAT3 f3Screen{ f3Project }; float fHalfWidth{ pViewport->m_nWidth * 0.5f }; float fHalfHeight{ pViewport->m_nHeight * 0.5f }; f3Screen.x = pViewport->m_nLeft + (f3Project.x * fHalfWidth) + fHalfWidth; f3Screen.y = pViewport->m_nTop + (-f3Project.y * fHalfHeight) + fHalfHeight; return f3Screen; } XMFLOAT3 CGraphicsPipeline::Project(XMFLOAT3& f3Model) { XMMATRIX tModelToProject{ XMMatrixMultiply(XMLoadFloat4x4(pWorldMatrix), XMLoadFloat4x4(pViewProjectMatrix)) }; XMFLOAT3 tProject{}; XMStoreFloat3(&tProject, XMVector3TransformCoord(XMLoadFloat3(&f3Model), tModelToProject)); return tProject; }
4d7c9d5280dc6d92ca159006c9b38836ede72f75
4554bf2ef932f3356deed0c7a896a01f2a72003f
/RenderEngine/Include/RenderEngine/IHardwareCursorManager.h
f10fd8b4af1a1f224fed687d08e2c89da3b2b667
[]
no_license
kevinchen2015/xgame
61364bf24daae2b69202df609b1e4c52a821fd46
e4cc0916923c624beedd17592a6dd89ff30525af
refs/heads/master
2021-01-23T18:45:07.418341
2017-09-08T02:09:48
2017-09-08T02:09:48
102,805,922
0
0
null
2017-09-08T02:08:11
2017-09-08T02:08:11
null
GB18030
C++
false
false
1,716
h
IHardwareCursorManager.h
#ifndef __IHardwareCursorManager_H__ #define __IHardwareCursorManager_H__ /* 硬件光标 */ namespace xs { struct IHardwareCursorManager { /************************************************************************/ /* 设置是否显示鼠标 @param show 是否显示鼠标 */ /************************************************************************/ virtual void showCursor( bool show) = 0; /************************************************************************/ /* 设置光标的位置 @param x 屏幕横坐标 @param y 屏幕纵坐标 @param updateImmediate 是否立即重绘光标 */ /************************************************************************/ virtual void setCursorPosition( int x, int y, bool updateImmediate) = 0; /************************************************************************/ /* 设置鼠标热点 */ /************************************************************************/ virtual void setCursorHotspot(uint x, uint y) = 0; /************************************************************************/ /* 设置鼠标图片 @param pTexture 鼠标图片,要释放pTexure,先取消图片设置 */ /************************************************************************/ virtual void setCursorImage(ITexture* pTexture) = 0; /************************************************************************/ /*设置是否可用 */ /************************************************************************/ virtual bool isAvailable()=0; }; } #endif
dfd93dc3f08a4d7708fe040a5807f33b64000fe5
a7650c90721c56766e3cec2a1ab6fe6ceaf7fa5d
/WICLL/CSWoman.h
3a92013f4cf2719afbb26e5c9d9ecd7eeef7f128
[ "MIT" ]
permissive
Loganhurst/CST126SRS04
0b5b96d91bf461d46af95c6df46bdf180c622d5e
e363122d6801d5b8837f472211fa2a67df1d7d72
refs/heads/master
2021-04-03T05:02:57.512521
2018-03-16T06:31:57
2018-03-16T06:31:57
124,465,180
0
0
null
2018-03-09T00:33:55
2018-03-09T00:33:55
null
UTF-8
C++
false
false
285
h
CSWoman.h
#pragma once #include "stdafx.h" #include <iostream> class CSWoman { private: const std::string name_; const unsigned birthYear_; const std::string fact_; public: CSWoman(const char* const name, const unsigned birthYear, const char* const fact); // ... and other methods };
64320795f94d2a33545140266c7aa08aa23deb8f
4c035144fb3a4ab3fbc4c779c1a8ec1d1d97c682
/Z15哈希表查找/Z15哈希表查找.cpp
e406c037ee84499a2dab35264d15f1b84acb0bf7
[]
no_license
xingos123/Algorithms-study
921534d8d7301122c2e2818e01039b7f0d040ca3
42dd893ff972601bf2af39ebf2a9b018addfb009
refs/heads/master
2022-03-25T04:46:58.377389
2019-12-17T09:20:45
2019-12-17T09:20:45
222,379,448
0
0
null
null
null
null
UTF-8
C++
false
false
2,033
cpp
Z15哈希表查找.cpp
// Z15哈希表查找.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 //---链地址法又叫拉链法 #include <iostream> #include <cstring> #include <cmath> using namespace std; #define M 15 #define NULLKey 0 typedef struct OVnode { int v; struct OVnode* next; }OVnode; typedef struct Hnode { int data; OVnode* next; }Hnode; typedef struct { Hnode Hash[M]; }HashTable; void InitH(HashTable& H) { for (int i = 0; i < M; i++) { H.Hash[i].data = NULLKey; H.Hash[i].next = NULL; } } int HK(int key) { return key % 13; } bool InsertHash(HashTable& H, int key) { int h0 = HK(key); if (H.Hash[h0].data == NULLKey) { H.Hash[h0].data = key; return true; } else { OVnode* h = new OVnode; h->v = key; h->next = H.Hash[h0].next; H.Hash[h0].next = h; return true; } return false; } int SearchHash(HashTable H, int key) { int h0 = HK(key); int x = 1; if (H.Hash[h0].data == NULLKey) return -1; else if (H.Hash[h0].data == key) return x; else { OVnode* p; p = H.Hash[h0].next; while (p != NULL) { x++; if (p->v == key) return x; p = p->next; } return -1; } } void PrintH(HashTable H) { for (int i = 0; i < M; i++) { if (H.Hash[i].data != NULLKey) { cout << "第" << i + 1 << "位:" << H.Hash[i].data << " "; OVnode* p = H.Hash[i].next; while (p != NULL) { cout << p->v << " "; p = p->next; } cout << endl; } } } int main() { std::cout << "Hello World!\n"; HashTable H; int x; InitH(H); cout << "输入12个关键字,存入哈希表中:" << endl; for (int i = 0; i < 12; i++) { cin >> x; if (!InsertHash(H, x)) { cout << "创建哈希表失败!" << endl; return 0; } } cout << "输出哈希表:" << endl; PrintH(H); cout << "输入要查找的关键字" << endl; cin >> x; int y = HK(x); int result = SearchHash(H, x); if (result != -1) cout << "在第" << y + 1 << "-" << result << "位置找到" << endl; else cout << "未找到" << endl; return 0; }
64326d2aa06b1ea8a65b470a3ada0bdac4d269df
865f1460acd8bd14b4e2b9b64b393a84c7ad8db6
/accept/leetcode_53.cpp
6e12439e1ddc9429a64e36b478a5aeddc3b9e01e
[]
no_license
zhangliukun/leetcode_solution
a76326ee7e444e4b56961c5208fa3119b5a1c945
2df943b580983a57375c6b3c427aa08364cb0ec9
refs/heads/master
2020-03-23T01:59:47.327062
2018-07-14T14:02:40
2018-07-14T14:02:40
140,950,149
0
0
null
null
null
null
UTF-8
C++
false
false
2,016
cpp
leetcode_53.cpp
/*Find the contiguous subarray within an array (containing at least one number) which has the largest sum. For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.*/ #include <iostream> #include <limits> #include <vector> #include <string> using namespace std; class Solution { public: //分治法 int maxSubArray(vector<int>& nums) { if(nums.size()==0)return INT_MIN; if(nums.size()==1)return nums[0]; int mid = nums.size()>>1; vector<int> left(nums.begin(),nums.begin()+mid); int l = maxSubArray(left); int l_mid_max=nums[mid-1],l_mid=l_mid_max; for(int i=mid-2;i>=0;i--){ l_mid += nums[i]; if(l_mid>l_mid_max){ l_mid_max = l_mid; } } vector<int> right(nums.begin()+mid,nums.begin()+nums.size()); int r = maxSubArray(right); int r_mid_max=nums[mid], r_mid=r_mid_max; for(int i=mid+1;i<nums.size();i++){ r_mid += nums[i]; if(r_mid>r_mid_max){ r_mid_max = r_mid; } } cout << l <<" "<<r<<endl; if(l>=r && l>(l_mid_max+r_mid_max))return l; else if(r>=l && r>(l_mid_max+r_mid_max))return r; else return l_mid_max+r_mid_max; } //贪心法 /* int maxSubArray(vector<int>& nums) { if(nums.size()==0)return 0; int max =nums[0]; int result = nums[0]; for(int i=1;i<nums.size();i++){ if(nums[i] > nums[i]+result){ result = nums[i]; }else{ result = nums[i]+result; } max = max > result ? max:result; } return max; } */ }; int main() { Solution s; //int num[] = {-2,1,-3,4,-1,2,1,-5,4}; //int num[] = {1,2}; int num[]={-1,-1,-2,-2}; //int num[]={-2,1}; vector<int> vc(num,num+4); cout<<s.maxSubArray(vc); return 0; }
902f246d31dbbb60be096178b0691cac7fb8ca91
1f949981d661817415244f4afa4fb33935aaccb6
/Villain CES/Villain CES/ProjectileSystem.h
7b52387ebed2b58cd33df142ea2d492b85f85f93
[]
no_license
fullsaildevelopment/projectherostudios
93bf28e6b070ac15dee08a1f1fc933bb58afa4ce
d422f328d8ffe1e2a2d05015d6501b5ad7d53f7b
refs/heads/master
2020-03-18T22:11:10.768771
2018-11-15T18:04:53
2018-11-15T18:04:53
135,330,546
0
0
null
null
null
null
UTF-8
C++
false
false
496
h
ProjectileSystem.h
#pragma once #include"Projectile_Component.h" #include"Entity.h" class CProjectileSystem { public: CProjectileSystem(); ~CProjectileSystem(); int CreateBulletProjectile(int indexofBullet, Clips* Gun); bool Reload(Clips* Gun); int ExtractMaterial(TWorld *tThisWorld, Clips* Gun, int currentEntity); XMVECTOR FindBeamEndPoint(XMVECTOR pointInScreenSpace, XMMATRIX in_WorldMatrix, XMMATRIX in_ViewMatrix, XMMATRIX in_ProjectionMatrix, HWND in_WindowHandle, D3D11_VIEWPORT m_d3dViewport); };
fd30052183d1856c4868acda7e0003b1573675df
5a56f135f03dffdb637e8bd76eae4e7b9bf5d704
/snakes/include/point.h
80cf91eb0dec92d7f4ad47f024954af33d1a1178
[]
no_license
scri/snake
8f4a1a6e0fa53cd145759038ba96b6fa76df949d
32f4e03107dc9c136682b285e3001ff16fbf7a87
refs/heads/master
2022-11-10T20:43:47.250801
2020-06-26T12:43:26
2020-06-26T12:43:26
268,734,358
1
0
null
null
null
null
UTF-8
C++
false
false
625
h
point.h
// // Created by Dragon on 2020/5/27. // #ifndef SNAKES_POINT_H #define SNAKES_POINT_H #include "../include/tool.h" #include <iostream> using namespace std; class Point{ public: enum Type{ EMPTY, WALL, FOOD }; public: Point(); Point(const int x, const int y); ~Point(); void pPrint(); void pClear(); void pPrintCir(); void setType(Type _type); Type getType() const; bool operator==(const Point& A) const; const int getX(); const int getY(); private: Type type = EMPTY; const int bis = 9; int x; int y; }; #endif //SNAKES_POINT_H
4fc6cfc26c12a188ca7d332402d052e0dbfeb33f
fc007c2a21d25815c26141de6b1d00b4dc6af68d
/LeetCode_Problems/union_find/Lexicographically_Smallest_Equivalent_String.cpp
160aed0d6a04928542e3779ae5b76a765d087cc5
[]
no_license
gurusarath1/Algorithms_2
6c3786862d7ef8f384da45baa7b711926db1103e
2303db8d145da9641bcf9b37cc830548f77bd413
refs/heads/master
2023-04-08T14:24:59.156991
2023-03-16T19:02:12
2023-03-16T19:02:12
227,998,339
1
0
null
null
null
null
UTF-8
C++
false
false
1,570
cpp
Lexicographically_Smallest_Equivalent_String.cpp
class Solution { public: class UnionFind { public: vector<int> root; vector<int> rank; UnionFind(int n) { for(int i=0; i<n; i++) { root.push_back(i); rank.push_back(1); } } int find(int node) { if(root[node] == node) { return node; } return root[node] = find(root[node]); } bool union_nodes(int node1, int node2) { int root1 = find(node1); int root2 = find(node2); if(root1 == root2) { return false; } else { // Min Node always becomes the root node int min_node = min(min(min(node1, node2), root1), root2); root[node1] = min_node; root[node2] = min_node; root[root1] = min_node; root[root2] = min_node; } return true; } }; string smallestEquivalentString(string s1, string s2, string baseStr) { int str_size = s1.size(); UnionFind uf('z' - 'a' + 1); for(int i=0; i<str_size; i++) { uf.union_nodes(s1[i] - 'a', s2[i] - 'a'); } string ansStr = ""; for(char c : baseStr) { ansStr += (char)uf.find(c - 'a') + 'a'; } return ansStr; } };
d6bd7375c7f2e9c56ff3e4e55834b21625edb7bd
d8cea15cbaa45293ffe8e23d13e4d0b173b70056
/Ovepoch Origins/MPMissions/DayZ_Epoch_24.Napf/CONFIGS/MissionInit.hpp
c3ba5efa3ac7570ab3e4641430c5cd94f5a6ca29
[]
no_license
quitanddead/DayZEpoch1Click
89708d49ee021314498b6c593edb7c2af0d9e0a6
fa5b514dcb97fa2c4d3a744b5e9c5950445fb7bb
refs/heads/master
2020-04-03T09:03:10.489683
2015-04-16T03:43:45
2015-04-16T03:43:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
375
hpp
MissionInit.hpp
//Traders #include "TRADERS\cfgServerTrader.hpp" //Loot #include "LOOT\CfgBuildingLoot.hpp" //Base Mission Defines #include "BaseDefines.hpp" //Defines #include "defines.hpp" //RSCTITLES #include "RcsTitles.hpp" //Extra RC #include "extra_rc.hpp" //GroupManagement //#include "GROUPMANAGEMENT\groupManagement.hpp" //SnapBuild //#include "SNAPBUILD\snappoints.hpp"
4f6bc0900759caf6829c8d284eff3b6db04e71ef
defef01067fbfa4b7a0a21e220926770d54eaee6
/Oscilloscope/transducersetupdialog.h
45f981cfc5194948f1dd176edc1a4d546176f1db
[]
no_license
jiwon8578/Oscilloscope
41ad440c56a52aabc834b2186971e6573556dcad
5dd1757ab1709959392bdb02c43d491adc64a3eb
refs/heads/master
2020-04-24T14:38:06.548493
2019-03-30T07:45:54
2019-03-30T07:45:54
172,028,338
0
0
null
null
null
null
UTF-8
C++
false
false
441
h
transducersetupdialog.h
#ifndef TRANSDUCERSETUPDIALOG_H #define TRANSDUCERSETUPDIALOG_H #include <QDialog> namespace Ui { class TransducerSetupDialog; } class TransducerSetupDialog : public QDialog { Q_OBJECT public: explicit TransducerSetupDialog(QWidget *parent = nullptr); ~TransducerSetupDialog(); public slots: void on_resetBtn_clicked(); private slots: private: Ui::TransducerSetupDialog *ui; }; #endif // TRANSDUCERSETUPDIALOG_H
60597f14448311148f0ab1551d51578d476dc27d
00e1a79ac0fa048234ae897bdff5970921376cf1
/include/utility/RspMgr.h
60035b38b0c6f2b12639cc915b6389552be3c92c
[ "MIT" ]
permissive
cshuazhang/libsimulator
e3528f3dfb266199dde9ad01ca3f8c1059efcebd
83be3e948674e158b588303819d721159086c475
refs/heads/master
2021-05-29T23:41:46.314179
2015-07-21T09:37:53
2015-07-21T09:37:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,665
h
RspMgr.h
#ifndef _SIMU_UTILITY_RSP_MGR_H_ #define _SIMU_UTILITY_RSP_MGR_H_ #include <map> #include <string> #include <fstream> #include <stdint.h> #include <std/functional.h> #include <std/smart_ptr.h> #include <ext/Singleton.h> #include "common/StdoutMsg.h" #include "utility/PlayerImpl.h" namespace simulator { template<typename TMsgID, typename TMsg, typename TPlayer> class RspMgr: public Singleton<RspMgr<TMsgID, TMsg, TPlayer> > { public: typedef TMsgID msg_id_t; typedef std::function<void (std::shared_ptr<TPlayer>, const TMsg&)> callback_func_type; typedef std::function<std::string (const TMsg&)> serialize_fn_t; typedef std::function<msg_id_t (std::shared_ptr<TPlayer>, const TMsg&)> pick_msgid_fn_t; public: RspMgr(){} ~RspMgr(){} int Init(serialize_fn_t fn_e, pick_msgid_fn_t fn_p) { m_pMsgSerializeFn = fn_e; m_pMsgPickMsgIDFn = fn_p; return 0; } void SetProcessFunc(msg_id_t uKey, const callback_func_type& stCaller) { m_stRspCmds[uKey] = stCaller; } int ProcessOnePkg(std::shared_ptr<TPlayer> pstPlayer, const TMsg& stPkg) { //打开proto日志文件 if (!AppConfig::m_strProtoLogFile.empty() && m_pMsgSerializeFn) { std::ofstream stProtoLog; stProtoLog.open(AppConfig::m_strProtoLogFile.c_str(), std::ios::app | std::ios::out); if (stProtoLog.is_open()) { stProtoLog<< " ================ Response Pkg Begin ================ "<< std::endl << m_pMsgSerializeFn(stPkg)<< " ================ Response Pkg End ================ "<< std::endl; } } // 控制台输出 std::cout << ShellFont::GenerateString("response ", SHELL_FONT_SPEC_BOLD | SHELL_FONT_COLOR_RED) << std::endl << m_pMsgSerializeFn(stPkg) << std::endl; // 回调查找和调用 typename std::map<msg_id_t, callback_func_type >::iterator iter = m_stRspCmds.find(m_pMsgPickMsgIDFn(pstPlayer, stPkg)); if (iter == m_stRspCmds.end()) { return -1; } iter->second(pstPlayer, stPkg); return 0; } private: std::map<msg_id_t, callback_func_type > m_stRspCmds; serialize_fn_t m_pMsgSerializeFn; pick_msgid_fn_t m_pMsgPickMsgIDFn; }; } #endif
566bf425c6a4e3cbadbaeb62358439c0c990e227
f9997f9ddd28605d672ebbb85c32efc50bf17203
/Testing/TimeTest2/TimeTest2.ino
f5a4f1d0c8bec62cb4601a708845ea1130fac68a
[ "MIT" ]
permissive
barankin/outdoorlightstimer
9a84d0f8d2f2fda03c9a747796bc8da4b5016c05
f8de38f3907c3fb03b019b1de826a55b8cd5b789
refs/heads/master
2021-05-13T22:37:35.140570
2018-03-22T00:41:40
2018-03-22T00:41:40
116,493,935
0
0
null
null
null
null
UTF-8
C++
false
false
2,618
ino
TimeTest2.ino
/* * will use https://github.com/stelgenhof/NTPClient.git */ /* This file is part of the NTPClient library. Copyright 2016 - 2018 Sacha Telgenhof (stelgenhof@gmail.com). All rights reserved. For the full copyright and license information, please view the LICENSE file that was distributed with this source code. */ #include <ESP8266WiFi.h> #include <NTPClient.h> #include <Time.h> const char *WIFI_SSID = "ford_prefect_2.4"; // Your WiFi network SSID (name) const char *WIFI_PSK = "annabanana"; // Your WiFi network PSK (password) // Event Handler when an IP address has been assigned // Once connected to WiFi, start the NTP Client void onSTAGotIP(WiFiEventStationModeGotIP event) { Serial.printf("Got IP: %s\n", event.ip.toString().c_str()); NTP.init((char *)"pool.ntp.org", UTC_0500); //NTP.setPollingInterval(60); // Poll every minute } // Event Handler when WiFi is disconnected void onSTADisconnected(WiFiEventStationModeDisconnected event) { Serial.printf("WiFi connection (%s) dropped.\n", event.ssid.c_str()); Serial.printf("Reason: %d\n", event.reason); } void setup() { static WiFiEventHandler gotIpEventHandler, disconnectedEventHandler; Serial.begin(115200); Serial.println(); Serial.println("Serial up and running"); NTP.onSyncEvent([](NTPSyncEvent_t ntpEvent) { switch (ntpEvent) { case NTP_EVENT_INIT: break; case NTP_EVENT_STOP: break; case NTP_EVENT_NO_RESPONSE: Serial.printf("NTP server not reachable.\n"); break; case NTP_EVENT_SYNCHRONIZED: Serial.println(NTP.getLastSync()); Serial.printf("Got NTP time: %s\n", NTP.getTimeDate(NTP.getLastSync())); break; } }); gotIpEventHandler = WiFi.onStationModeGotIP(onSTAGotIP); disconnectedEventHandler = WiFi.onStationModeDisconnected(onSTADisconnected); // Connecting to a WiFi network Serial.printf("Connecting to WiFi network: %s \n", WIFI_SSID); WiFi.begin(WIFI_SSID, WIFI_PSK); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } } void loop() { static int previousMillis = 0; // Update time status every 5 seconds if ((millis() - previousMillis) > 5000) { previousMillis = millis(); // Output only when time is set if (timeStatus() != timeSet) { return; } time_t t = now(); Serial.printf("Current time: %s - First synchronized at: %s.\n", NTP.getTimeDate(t), NTP.getTimeDate(NTP.getFirstSync())); Serial.printf("The hour is %d, the minute is %d and seconds are %d.\n",hour(t),minute(t),second(t)); Serial.println(); } }
31fd0612d86dbf7875a0732aead44d5e9a14295e
5a7b697ad71c7f1547196831aec5dc6286969d81
/StuCppSecond/MyArrays.cpp
1d50f44310fa2d27864c02a3b7b8f89786a93750
[]
no_license
VonsName/StuCppSecond
8c98e377d2701f24e243c0b1487245d41578465b
df4ab8678241408d6ffab357142262aee398b970
refs/heads/master
2020-03-27T19:44:21.663463
2018-10-08T09:02:15
2018-10-08T09:02:15
147,008,716
0
0
null
null
null
null
GB18030
C++
false
false
1,640
cpp
MyArrays.cpp
#include "MyArrays.h" #include "SizeError.h" #pragma warning (disable:4390) template <typename T, typename I> MyArrays<T,I>::MyArrays() { this->size = 5; this->data = new T[this->size]; } template <typename T, typename I> MyArrays<T,I>::~MyArrays() { if (this->data != NULL); { delete[] this->data; this->data = NULL; } } //重载[]操作符 只能使用成员函数重载 ,还有 = -> () template<typename T, typename I> T & MyArrays<T, I>::operator[](I index) { return this->data[index]; } /** * 重载=号操作符深拷贝 * 拷贝构造函数,如果元素要向容器中存储,元素必须要有深拷贝 */ template<typename T, typename I> MyArrays<T, I> & MyArrays<T, I>::operator=(const MyArrays<T,I> & arr) { if (this->data != NULL) { delete[] this->data; this->size = 0; this->data = NULL; } this->size = arr.size; this->data = new T[arr.size]; for (int i = 0; i < this->size; i++) { this->data[i] = arr.data[i]; } return *this; } template <typename T, typename I> MyArrays<T, I>::MyArrays(I size) { if (size <= 0) { throw tooSmallError("this index no prent -1"); } if (size >= 1000) { throw tooSmallError::TooBig("this index is too big"); } if (size == 0) { this->size = 5; } else { this->size = size; } this->data = new T[this->size]; } /** * 拷贝构造函数,如果元素要向容器中存储,必须重写拷贝构造函数进行深拷贝 */ template<typename T, typename I> MyArrays<T, I>::MyArrays(const MyArrays & arr) { this->size = arr.size; this->data = new T[arr.size]; for (int i = 0; i < this->size; i++) { this->data[i] = arr.data[i]; } }
591056ec927545565e34f18d548736bef975c693
aac8c5cadb249aecedc7b0ccd51010ff5e7bf3b2
/LeetCode/19.cpp
a574a7583cb54794694c15c7a34b6272ee7165fe
[]
no_license
furkanusta/Competitive-Programming
1b74f1cfc2e6049565d9b31950b325b2b21d2bca
06582650a77ba003cdef31995763100721b399c8
refs/heads/master
2022-05-28T07:18:44.670839
2022-05-19T20:28:11
2022-05-19T20:28:11
37,484,205
1
0
null
null
null
null
UTF-8
C++
false
false
1,308
cpp
19.cpp
#include "include/LinkedList.hpp" class Solution { private: int getSize(ListNode* head) { int i = 0; while (head) { i++; head = head->next; } return i; } public: ListNode* removeNthFromEnd_multiPass(ListNode* head, int n) { int size = getSize(head); int pos = size - n; if (pos == 0) return head->next; ListNode* temp = head; for (int i = 1; i < pos; i++) { head = head->next; } head->next = head->next->next; return temp; } ListNode* removeNthFromEnd_singlePass(ListNode* head, int n) { auto temp = head; auto orig = head; for (int i = 0; i < n; i++) { temp = temp->next; } if (!temp) { return head->next; } while (temp->next) { head = head->next; temp = temp->next; } head->next = head->next->next; return orig; } ListNode* removeNthFromEnd(ListNode* head, int n) { return removeNthFromEnd_singlePass(head, n); } }; int main() { int N = 5; LinkedList ll({1, 2, 3, 4, 5}); ll.dump(); Solution s; auto head = s.removeNthFromEnd(ll.head, 4); LinkedList::dump(head); }
a13661a12ac70ca25459c111a128bb182c21d4ab
a3f24d09734df2080d23af39a502990e6c0f5d7d
/1.detect-capital.cpp
508c5fe9aaf345e2e833fe6f9dd97f4711078c3a
[]
no_license
kameshkotwani/august-leetcode-challenge
dd9ef1cf7ba54441fe819d5da9a846d7a0d5c4df
832aa71957037ef8947b1593106523604fda72e9
refs/heads/master
2022-12-08T06:37:27.424663
2020-08-30T07:01:29
2020-08-30T07:01:29
283,769,334
0
0
null
null
null
null
UTF-8
C++
false
false
212
cpp
1.detect-capital.cpp
class Solution { public: bool detectCapitalUse(string word) { int c=0; for(auto x:word) if(isupper(x)) c++; return c==word.length() ||c==0 || c==1 && isupper(word[0]); } };
d1e62367e3566ac55a6d420cfbb6ff6b29d42701
b19d0d25823bb0e6f1f7362eea610ef9f67442e0
/include/tweedledum/IR/WireStorage.h
6542a5844758fb118796c3a73caa149e899aa0af
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
boschmitt/tweedledum
c0278b5f0a94ce1b14b60fe6e30be430eed92c7d
9d3a2fab17e8531e1edc0ab927397d449b9942a4
refs/heads/master
2023-07-19T20:59:19.871570
2022-11-03T14:30:01
2022-11-24T00:42:05
140,888,411
92
34
MIT
2023-07-13T00:34:12
2018-07-13T20:03:36
C++
UTF-8
C++
false
false
3,613
h
WireStorage.h
/*------------------------------------------------------------------------------ | Part of Tweedledum Project. This file is distributed under the MIT License. | See accompanying file /LICENSE for details. *-----------------------------------------------------------------------------*/ #pragma once #include "Cbit.h" #include "Qubit.h" #include <cassert> #include <limits> #include <string> #include <vector> namespace tweedledum { class WireStorage { public: WireStorage() = default; uint32_t num_wires() const { return num_qubits() + num_cbits(); } uint32_t num_qubits() const { return qubits_.size(); } uint32_t num_cbits() const { return cbits_.size(); } Cbit cbit(uint32_t const uid) const { assert(uid < num_cbits()); return Cbit(uid); } std::vector<Cbit> cbits() const { return cbits_; } Qubit qubit(uint32_t const uid) const { assert(uid < num_qubits()); return Qubit(uid); } std::vector<Qubit> qubits() const { return qubits_; } std::string_view name(Cbit cbit) const { return cbit_names_.at(cbit); } std::string_view name(Qubit qubit) const { return qubit_names_.at(qubit); } template<typename Fn> void foreach_cbit(Fn&& fn) const { // clang-format off static_assert(std::is_invocable_r_v<void, Fn, Cbit> || std::is_invocable_r_v<void, Fn, std::string_view> || std::is_invocable_r_v<void, Fn, Cbit, std::string_view>); // clang-format on if constexpr (std::is_invocable_r_v<void, Fn, Cbit>) { for (Cbit const& cbit : cbits_) { fn(cbit); } } else if constexpr (std::is_invocable_r_v<void, Fn, std::string_view>) { for (std::string const& name : cbit_names_) { fn(name); } } else { for (uint32_t i = 0; i < num_cbits(); ++i) { fn(cbits_.at(i), cbit_names_.at(i)); } } } template<typename Fn> void foreach_qubit(Fn&& fn) const { // clang-format off static_assert(std::is_invocable_r_v<void, Fn, Qubit> || std::is_invocable_r_v<void, Fn, std::string_view> || std::is_invocable_r_v<void, Fn, Qubit, std::string_view>); // clang-format on if constexpr (std::is_invocable_r_v<void, Fn, Qubit>) { for (Qubit const& qubit : qubits_) { fn(qubit); } } else if constexpr (std::is_invocable_r_v<void, Fn, std::string_view>) { for (std::string const& name : qubit_names_) { fn(name); } } else { for (uint32_t i = 0; i < num_qubits(); ++i) { fn(qubits_.at(i), qubit_names_.at(i)); } } } protected: Cbit do_create_cbit(std::string_view name) { uint32_t const uid = cbits_.size(); cbits_.push_back(Cbit(uid)); cbit_names_.emplace_back(name); return cbits_.back(); } Qubit do_create_qubit(std::string_view name) { uint32_t const uid = qubits_.size(); qubits_.push_back(Qubit(uid)); qubit_names_.emplace_back(name); return qubits_.back(); } private: std::vector<Cbit> cbits_; std::vector<std::string> cbit_names_; std::vector<Qubit> qubits_; std::vector<std::string> qubit_names_; }; } // namespace tweedledum
0a2554218b3614c1a6560d569ac351c3cd52fa5e
8cb01266f06178a148c215d1e16abda2d9738f39
/try.cpp
bb22fffdee00d129ffef97a1988b6e62cbbb5ff6
[ "MIT" ]
permissive
kennethpat/CPP-Keywords-Testing
593d5c3270fdfd16366e7ce19b0eda6dba607351
8108c65c723ea139de165862c6911d8b2165b571
refs/heads/main
2023-03-26T08:15:11.783054
2021-03-29T00:06:23
2021-03-29T00:06:23
352,184,657
0
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
try.cpp
#include <cstdio> using namespace std; int main() { int a = 10; try { throw &a; } catch (char *c) { printf("Caught char: %c\n", *c); } catch (int *i) { printf("Caught int: %d\n", *i); } catch (...) { printf("Default Exception\n"); } return 0; }
06979689b2312cfd6e624a997603608c53065296
4019d98ce38791a4e145c639d48aef5666a3fd5c
/probs/bzoj2014.cpp
13a8f4748cb37e3138efe56ba53d0596c04649e2
[]
no_license
karin0/problems
c099ded507fabc08d5fe6a234d8938575e9628b7
b60ffaa685bbeb4a21cde518919cdd2749086846
refs/heads/master
2023-02-09T21:55:24.678019
2021-01-08T16:46:54
2021-01-08T16:46:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,085
cpp
bzoj2014.cpp
#include <cstdio> #include <cctype> #include <algorithm> #define rep(__i,__s,__t) for((__i)=(__s);(__i)<=(__t);++(__i)) #define re(__i,__s,__t) for((__i)=(__s);(__i)<(__t);++(__i)) #define per(__i,__s,__t) for((__i)=(__s);(__i)>=(__t);--(__i)) #define pe(__i,__s,__t) for((__i)=(__s);(__i)>(__t);--(__i)) struct IO { static const int L = 1000000; char a[L], b[L], *s, *t, *p; IO() : p(b) {} inline char gc() { if (s == t) t = (s = a) + fread(a, 1, L, stdin); return *s++; // return s == t ? -1 : *s++; } void gs(char *st) { static char c; for (c = gc(); !isgraph(c); c = gc()); *st++ = c; for (c = gc(); isgraph(c); c = gc()) *st++ = c; *st++ = 0; } template <class T> operator T() { static T x; static char c; static bool neg; for (c = gc(); c != '-' && !isdigit(c); c = gc()); if (c == '-') neg = true, c = gc(); else neg = false; x = c - '0'; for (c = gc(); isdigit(c); c = gc()) x = x * 10 + (c - '0'); return neg ? -x : x; } inline void pc(const char c) { if (p == b + L) fwrite(b, 1, L, stdout), p = b; *p++ = c; } template<class T> void print(T x, const bool nl = true) { static char c[30], *q; static T y; if (x == 0) pc('0'); else { if (x < 0) pc('-'), x = -x; for (q = c; x; x = y) y = x / 10, *q++ = x - y * 10 + '0'; while (q != c) pc(*--q); } if (nl) pc('\n'); } void ps(const char *st, const bool nl = true) { while (*st) pc(*st++); if (nl) pc('\n'); } inline void flush() const { fwrite(b, 1, p - b, stdout); // p = b; } } io; typedef long long ll; struct Ir int main() { static i;q nt n, i; static ll b; rep () io.flush(); // *** return 0; }
87c3c1cf032a893fdb3df138c68bd712ea06fba7
8b79dfcc5fd3a180d98de21989d4564e7d5bde5f
/src/FloorBuildingB.cpp
0feed45e09521c50570952028ba97d083f45d5f1
[]
no_license
sgerin/mifcity
ce07b6e1c0533056309902e6a29a44cbd557176a
c61475fbc78e3d6460e46624cd07ae50aed45435
refs/heads/master
2020-04-28T06:07:11.133454
2013-06-16T16:24:26
2013-06-16T16:24:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,770
cpp
FloorBuildingB.cpp
#include "FloorBuildingB.h" FloorBuildingB::FloorBuildingB(const Vector& a, const Vector& b, float* height) { // dl = a; // ur = b; // ul = a; // ul[1] = ur[1]; // dr = b; // dr[1] = dl[1]; dl = a; dr = b; ul = a; ur = b; dl[1] += *height; dr[1] += *height; *height += STOREY_HEIGHT; ul[1] += *height; ur[1] += *height; } Mesh* FloorBuildingB::toMesh() { //ROOF2_LEFT_UL_X; Mesh* m = new Mesh(); m->addVertex(ul, ROOF2_LEFT_UL_X/divide, ROOF2_LEFT_UL_Y/divide); //0 m->addVertex(ur, ROOF2_RIGHT_UR_X/divide, ROOF2_RIGHT_UR_Y/divide); //1 m->addVertex(dr, ROOF2_RIGHT_DR_X/divide, ROOF2_RIGHT_DR_Y/divide); //2 m->addVertex(dl, ROOF2_LEFT_DL_X/divide, ROOF2_LEFT_DL_Y/divide); //3 Vector border_ul, border_ur, border_dr, border_dl, norm; norm = ur - ul; norm = Normalized(norm); border_ul = ul + norm*BORDER; //border_ul[2] += BORDER; border_dl = border_ul; border_dl[1] = dl[1]; border_ur = ur; //border_ur[2] -= BORDER; border_ur = ur - norm*BORDER; border_dr = border_ur; border_dr[1] = dr[1]; m->addVertex(border_ul, ROOF2_LEFT_UR_X/divide, ROOF2_LEFT_UR_Y/divide); //4 m->addVertex(border_ur, ROOF2_RIGHT_UL_X/divide, ROOF2_RIGHT_UL_Y/divide); //5 m->addVertex(border_dr, ROOF2_RIGHT_DL_X/divide, ROOF2_RIGHT_DL_Y/divide); //6 m->addVertex(border_dl, ROOF2_LEFT_DR_X/divide, ROOF2_LEFT_DR_Y/divide); //7 // m->addVertex(border_ul, ROOF2_MID_UL_X/divide, ROOF2_MID_UL_Y/divide); //8 // m->addVertex(border_ur, ROOF2_MID_UR_X/divide, ROOF2_MID_UR_Y/divide); //9 // m->addVertex(border_dr, ROOF2_MID_DR_X/divide, ROOF2_MID_DR_Y/divide); //10 // m->addVertex(border_dl, ROOF2_MID_DL_X/divide, ROOF2_MID_DL_Y/divide); //11 // m->addFace(0, 1, 3); // m->addFace(1, 2, 3); /* m->addVertex(ul, ROOF2_LEFT_UL_X/divide, ROOF2_LEFT_UL_Y/divide); //0 m->addVertex(ur, ROOF2_RIGHT_UR_X/divide, ROOF2_RIGHT_UR_Y/divide); //1 m->addVertex(dr, ROOF2_RIGHT_DR_X/divide, ROOF2_RIGHT_DR_Y/divide); //2 m->addVertex(dl, ROOF2_LEFT_DL_X/divide, ROOF2_LEFT_DL_Y/divide); //3 m->addVertex(border_ul, ROOF2_LEFT_UR_X/divide, ROOF2_LEFT_UR_Y/divide); //4 m->addVertex(border_ur, ROOF2_RIGHT_UL_X/divide, ROOF2_RIGHT_UL_Y/divide); //5 m->addVertex(border_dr, ROOF2_RIGHT_DL_X/divide, ROOF2_RIGHT_DL_Y/divide); //6 m->addVertex(border_dl, ROOF2_LEFT_DR_X/divide, ROOF2_LEFT_DR_Y/divide); //7 m->addVertex(border_ul, ROOF2_MID_UL_X/divide, ROOF2_MID_UL_Y/divide); //8 m->addVertex(border_ur, ROOF2_MID_UR_X/divide, ROOF2_MID_UR_Y/divide); //9 m->addVertex(border_dr, ROOF2_MID_DR_X/divide, ROOF2_MID_DR_Y/divide); //10 m->addVertex(border_dl, ROOF2_MID_DL_X/divide, ROOF2_MID_DL_Y/divide); //11 */ m->addFace(0, 4, 3);//, ROOF2_LEFT_UL_X/divide, ROOF2_LEFT_UL_Y/divide, ROOF2_LEFT_UR_X/divide, ROOF2_LEFT_UR_Y/divide, ROOF2_LEFT_DL_X/divide, ROOF2_LEFT_DL_Y/divide); m->addFace(3, 4, 7);//, ROOF2_LEFT_DL_X/divide, ROOF2_LEFT_DL_Y/divide, border_ul, ROOF2_LEFT_UR_X/divide, ROOF2_LEFT_UR_Y/divide, ROOF2_LEFT_DR_X/divide, ROOF2_LEFT_DR_Y/divide); m->addFace(5, 1, 6);//, ROOF2_RIGHT_UL_X/divide, ROOF2_RIGHT_UL_Y/divide, ur, ROOF2_RIGHT_UR_X/divide, ROOF2_RIGHT_UR_Y/divide, ROOF2_RIGHT_DL_X/divide, ROOF2_RIGHT_DL_Y/divide); m->addFace(6, 1, 2);//, ROOF2_RIGHT_DL_X/divide, ROOF2_RIGHT_DL_Y/divide, ROOF2_RIGHT_UR_X/divide, ROOF2_RIGHT_UR_Y/divide, ROOF2_RIGHT_DR_X/divide, ROOF2_RIGHT_DR_Y/divide); m->addFace(4, 5, 7);//, ROOF2_MID_UL_X/divide, ROOF2_MID_UL_Y/divide, ROOF2_MID_UR_X/divide, ROOF2_MID_UR_Y/divide, ROOF2_MID_DL_X/divide, ROOF2_MID_DL_Y/divide); m->addFace(7, 5, 6);//, ROOF2_MID_DL_X/divide, ROOF2_MID_DL_Y/divide, ROOF2_MID_UR_X/divide, ROOF2_MID_UR_Y/divide, ROOF2_MID_DR_X/divide, ROOF2_MID_DR_Y/divide); return m; //m->addVertex(0.0, height/2, 0.0); //m->addFace(0, 2+i, 2+i+1); }
c44ccba76c8a83db37d2e25ba76f0d92d0234601
3615e7a2da642b5c039378d055f89365c6dbba5b
/src/server/main.cpp
2daa28247d8c485527f525c1457c64af1d510bf0
[]
no_license
shimoncohen/Reversi
09ea75c2fb00adce65c3bcfa2e41e7a54994dc97
349fa5cf2fd0279238a9ae6cc1708863db31512b
refs/heads/master
2021-09-04T22:32:06.867138
2018-01-22T18:38:13
2018-01-22T18:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,394
cpp
main.cpp
// 315383133 shimon cohen // 302228275 Nadav Spitzer #include <string> #include "Server.h" #include <fstream> #define ENDPORTWORD 5 using namespace std; int settingsReading(); int main() { int port; port = settingsReading(); Server server(port); try { // run the server server.runServer(); } catch (const char *msg) { cout << "Cannot start server. Reason: " << msg << endl; exit(-1); } // stop the server from running server.stop(); cout << "Server closed." << endl; } /* * function name: settingsReading. * input: none. * output: int the port number. * operation: reads the port number of the server from a file. */ int settingsReading() { //port number int port; //reader for the file string reader; //inpout streamer ifstream serverInfo; serverInfo.open("serverSettings.txt", ios::in); //error opening file will give a proper message if(!serverInfo.is_open()) { cout << "Error reading from file" << endl; //file opening was succssesful } else { //reading from the file while(!serverInfo.eof()) { serverInfo >> reader; } //removing "Port:" from the string reader = reader.erase(0, ENDPORTWORD); } //converting to int port = atoi(reader.c_str()); serverInfo.close(); return port; }
d5b04f0a0246a7382fb14f7340a116dfaa79c516
c32ee8ade268240a8064e9b8efdbebfbaa46ddfa
/Libraries/m2sdk/game/ai/C_GoalParser_DesireCloseCombatBlock.h
acb1fec7bb4ed6fc13c9e2ff9333c3cb57725abb
[]
no_license
hopk1nz/maf2mp
6f65bd4f8114fdeb42f9407a4d158ad97f8d1789
814cab57dc713d9ff791dfb2a2abeb6af0e2f5a8
refs/heads/master
2021-03-12T23:56:24.336057
2015-08-22T13:53:10
2015-08-22T13:53:10
41,209,355
19
21
null
2015-08-31T05:28:13
2015-08-22T13:56:04
C++
UTF-8
C++
false
false
697
h
C_GoalParser_DesireCloseCombatBlock.h
// auto-generated file (rttidump-exporter by h0pk1nz) #pragma once #include <game/ai/braincfg/C_GoalParser_DefaultDesire.h> namespace game { namespace ai { /** game::ai::C_GoalParser_DesireCloseCombatBlock (VTable=0x01E40300) */ class C_GoalParser_DesireCloseCombatBlock : public game::ai::braincfg::C_GoalParser_DefaultDesire { public: virtual void vfn_0001_E624DAF1() = 0; virtual void vfn_0002_E624DAF1() = 0; virtual void vfn_0003_E624DAF1() = 0; virtual void vfn_0004_E624DAF1() = 0; virtual void vfn_0005_E624DAF1() = 0; virtual void vfn_0006_E624DAF1() = 0; virtual void vfn_0007_E624DAF1() = 0; virtual void vfn_0008_E624DAF1() = 0; }; } // namespace ai } // namespace game
6504c440b146a66d8290ce385797e5be4c4e5256
1a33cfaedb8d07c22ebbb5dcf4c281203b6fa3e3
/Exception_Handling7.cpp
cfdbc621b219c28c47b76d9f6dbe7eeb9279b83b
[]
no_license
ShubhamRasal/2-Cplus-plus-Programs
bec823c0ec4456548690179789e164aade521622
68fa0ecb532e308128bd59d2704ac22576bd83bf
refs/heads/master
2022-08-04T14:47:17.694313
2020-06-01T19:07:46
2020-06-01T19:07:46
268,599,631
1
0
null
null
null
null
UTF-8
C++
false
false
1,327
cpp
Exception_Handling7.cpp
// eg. of user defined exceptions // create an object of type queue and throw qfull and // qempty exceptions as and when reqd #include <iostream.h> #define SIZE 5 class queue { private : int data[SIZE]; int front, rear; public : // exception classes are defined as // nested classes class qfull { }; class qempty { }; // default constructor queue() { front = rear = -1; } void addq(int no) { // validation if (rear == SIZE-1) throw qfull(); rear++; data[rear] = no; // check whether it is 1st element if (front == -1) front = 0; cout << "Element " << no << " inserted successfully" << endl; } int delq() { if (front == -1 || front > rear) throw qempty(); return data[front++]; } }; void main() { queue q; // add nos 10-50 in queue int no = 10; for (int i=1;i<=10;i++) { try { q.addq(no); no = no + 10; } catch (queue::qfull) { cout << "Queue is full" << endl; break; } } // delete all el's from queue for (i=1;i<=10;i++) { try { cout << "Element deleted is " << q.delq() << endl; } catch (queue::qempty) { cout << "Queue is empty" << endl; break; } } }
618269e314ad4ab98d1649d2c8904e289b92d6ca
359f7c0dd68410faf66bb243d2bcf38f397d30cc
/src/squeltch.hpp
65ddfb51bbcc59894ea38db3fb8e0127387e60d2
[]
no_license
tomeserver/tome2
fac3633ac65ec3777cd77239bf80199a79110ec6
5bc01c584066a0cea37021eb6e13bd96d74de7b5
refs/heads/master
2021-01-24T04:01:32.360898
2017-02-28T18:44:12
2017-02-28T18:44:12
49,040,854
0
0
null
null
null
null
UTF-8
C++
false
false
394
hpp
squeltch.hpp
#pragma once #include "h-basic.h" #include "object_type_fwd.hpp" #include <boost/filesystem.hpp> extern void squeltch_inventory(void); extern void squeltch_grid(void); extern void do_cmd_automatizer(void); extern void automatizer_add_rule(object_type *o_ptr); extern bool_ automatizer_create; extern void automatizer_init(); extern bool automatizer_load(boost::filesystem::path const &path);
1747719621a8907a1a26a7c6eb03fefb91675634
1e2c9c7553919d9ad1ae9506a727c78a59b2ca0d
/4.16/source/main.cpp
42841fcf047ce5b3ce77deb119a871f671777efb
[]
no_license
421jessie/CH2-homework
6d2fc86f273e5d84ca5aab6a40f3ad87ae6a4f8f
9e26be2c2a52e8a1f3fac864544c4a921e193b76
refs/heads/master
2023-08-22T08:56:41.421736
2021-10-26T01:39:11
2021-10-26T01:39:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
697
cpp
main.cpp
#include <stdio.h> #include <stdlib.h> int main(void) { int i, j, k; printf("(A)\n"); for (i = 1; i <= 10; i++) { for (j = 0; j < i; j++) { printf("%s", "*"); } printf("\n"); } printf("(B)\n"); for (i = 0; i <= 10; i++) { for (j = 0; j < (10-i); j++) { printf("%s", "*"); } printf("\n"); } printf("(C)\n"); for (i = 0; i < 10; i++) { for (j = 1; j <= i; j++) { printf(" "); } for(j = 10;j>i; j--) { printf("%s", "*"); } printf("\n"); } printf("(D)\n"); for (i = 0; i < 10; i++) { for (j = 9; j > i; j--) { printf(" "); } for (k = 0; k <= i; k++) { printf("%s", "*"); } printf("\n"); } return 0; }
ae61265d9ad1d0f14c79c69daed6f4d36fb5252c
b26317a356123a24589ed04219e9ad7ce8374ffd
/Source/Source/NuRenderer.h
9b89ad428656f642cde4f09a5b2b0972c3996e3d
[ "MIT" ]
permissive
JuanDiegoMontoya/Voxel_Engine
64ec89290c892bfd15d154182058fd4dc6e38e86
0d837ca6c7c659c92fbf518f61a9659d60a133df
refs/heads/master
2023-06-22T03:27:58.450501
2023-06-14T11:21:08
2023-06-14T11:21:08
182,210,012
8
2
null
null
null
null
UTF-8
C++
false
false
407
h
NuRenderer.h
#pragma once class TextureArray; namespace NuRenderer { TextureArray* GetBlockTextures(); void Init(); void CompileShaders(); void Clear(); void DrawAll(); void drawChunks(); void splatChunks(); void drawChunksWater(); inline int drawCalls = 0; struct Settings { bool gammaCorrection = true; float fogStart = 500.f; float fogEnd = 3000.f; }inline settings; }
20254e50efd9ea57282f1bbd52203d1401dd4b67
e57abb7c7fbd73924d9daad36841b87d799ee727
/test/__fixtures__/projects/symlink/main-project/app.ino
2f1ba5d409c108a89750edb4d7ab7cca246a7850
[ "Apache-2.0" ]
permissive
particle-iot/particle-cli
dcd0219c96db8f113c9e429455d87c3b70607e28
64aca50447f949de0b8c8ccc100befc6b25be160
refs/heads/master
2023-09-01T11:50:30.907958
2023-08-30T20:46:25
2023-08-30T20:46:25
35,562,367
57
37
Apache-2.0
2023-09-14T16:01:27
2015-05-13T17:05:39
JavaScript
UTF-8
C++
false
false
199
ino
app.ino
#include "shared/sub_dir/helper.h" // Demo app with an include that points to a symlink void setup() { if (DOIT) { Particle.function("test", testFn); } } int testFn(String) { return 0; }
8d8d2f393da23472b813cf703f7aa0864d63f6b7
b1ecf5efbcacbb274898e29e7ee542e59ef93916
/AAA (CODE) Programming tools(Fuad)/Binary lifting/BINARY LIFTING OWN.CPP
1c987be357f369354b0e6a3ab2253000df30cabe
[]
no_license
abufarhad/Programming
92160c224578be116b2bb1e957ea105640a83ee6
282bf4df6c47817cb5d96ccee7dc2953438e8e11
refs/heads/master
2021-06-16T17:07:14.095691
2021-03-23T17:22:13
2021-03-23T17:22:13
180,426,830
3
0
null
null
null
null
UTF-8
C++
false
false
2,027
cpp
BINARY LIFTING OWN.CPP
#include<bits/stdc++.h> using namespace std; #define rep(i,a,b) for(i=a;i<b;i++) #define repr(i,a,b) for(i=a;i>=b;i--) #define LL long long #define ull unsigned long long #define scl(n) scanf("%lld", &n) #define scf(n) scanf("%lf", &n) #define sci(n) scanf("%d", &n) #define scii(n,m) scanf("%d %d",&n,&m) #define sciii(n,m,p) scanf("%d %d %d",&n,&m,&p) #define scs(n) scanf("%s", n) #define pb push_back #define ff first #define ss second #define mp make_pair #define memo(a,b) memset(a,b,sizeof(a)) #define INF 1e9 #define EPS 1e-8 #define Pi acos(-1.0) #define N 1000 #define LG 20 vector<int>v[N]; int p[N][LG]; int level[N]; void dfs(int u,int par) { level[u]=level[par]+1; p[u][0]=par; for(int i=0;i<v[u].size();i++) { int now=v[u][i]; if(now==par) continue; dfs(now,u); } } int lca(int u,int v) { if(level[u]<level[v]) swap(u,v); int lg; for(lg=0;(1<<lg)<=level[u];lg++ ); lg--; for(int i=lg;i>=0;i--) ///after this u and v must be in same level { if(level[u]-(1<<i)>=level[v]) u=p[u][i]; } if(u==v) return u; for(int i=lg;i>=0;i-- ) { if(p[u][i]!=-1 and ( p[v][i]!=p[u][i] )) { u=p[u][i]; v=p[v][i]; } } return p[u][0]; } int dis(int u,int v) { int lca_of_u_v=lca(u,v); return level[u]+level[v]-2*level[lca_of_u_v]; } int main() { int n,m; cin>>n; cin>>m; for(int i=1;i<n;i++) { int a, b; cin>>a>>b; v[a].pb(b); v[b].pb(a); } level[0]=-1; memo(p,-1); dfs(1,-1); for(int i=1;i<LG;i++) { for(int j=1;j<=n;j++) { if(p[j][i-1]!=-1) p[j][i]=p[ p[j][i-1] ][i-1]; } } while(m--) { int u,v; scii(u,v); cout<<" lca : "<<lca(u,v)<<" dis :"<<dis(u,v)<<endl; } return 0; } ///input /* 10 1 3 1 2 2 6 2 7 3 4 3 5 4 8 5 9 8 10 */
32bc53556fa782cf7bb60d0a37be8213b7f26c7d
d4667eeb25575d0dca8e087e90a7935032a01130
/assignment2/source/exercise21-anton.cpp
66203e7e1d08ebc8fedd03dd52e7f462f3718147
[]
no_license
AnBenLa/Realtime-Rendering
ce74142f95fc38a441b183eba3125ee668cfacad
c0250867d76e794d835d9069da06b1cc01324016
refs/heads/master
2022-04-03T18:05:41.065062
2020-02-04T17:18:43
2020-02-04T17:18:43
218,351,515
0
0
null
null
null
null
UTF-8
C++
false
false
3,533
cpp
exercise21-anton.cpp
// // Created by Mortiferum on 25.11.2019. // #include <iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; struct point{ int x,y; }; struct segment{ point a,b; }; bool operator == (point const& a, point const& b){ return a.x == b.x && a.y == b.y; } //returns -1 for ccw, +1 for cw and 0 if b is collinear with the line through a and c int ORI(point const& a, point const& b, point const& c){ double dx21 = b.x - a.x; double dy21 = b.y - a.y; double dx31 = c.x - a.x; double dy31 = c.y - a.y; if(dy31*dx21 > dx31*dy21) return - 1; if(dy31*dx21 < dx31*dy21) return +1; return 0; } bool compare(point const& a, point const& b){ if(a.y < b.y) return true; if(a.y == b.y) return a.x < b.x; return false; } double dist_p_s(point const& p, segment const& s){ return ((s.b.y-s.a.y)*p.x-(s.b.x-s.a.x)*p.y+s.b.x*s.a.y-s.b.y*s.a.x)/(sqrt(pow(s.b.y-s.a.y,2) + pow(s.b.x-s.a.x,2))); } point find_max_dis_p(vector<point> const& points, segment const& s){ double dist = 0, tmp_dist; point max_dist_p{}; for(int i = 0; i < points.size(); ++i){ tmp_dist = abs(dist_p_s(points.at(i),s)); if(tmp_dist > dist) { max_dist_p = points.at(i); dist = tmp_dist; } } return max_dist_p; } vector<point> compute_con_hull(vector<point> const& points, bool first){ point a = *points.begin(); point b = *points.rbegin(); point d{}; segment ab{a,b}; vector<point> left,right; if(points.size() == 2){ return points; } if(first) { left.push_back(a); right.push_back(b); for(int i = 1; i < points.size() - 1; ++i){ int ori = ORI(a, b, points.at(i)); if(ori == -1){ left.push_back(points.at(i)); }else if(ori == 1){ right.push_back(points.at(i)); } } left.push_back(b); right.push_back(a); } else { d = find_max_dis_p(points, ab); left.push_back(a); right.push_back(d); for(int i = 1; i < points.size() - 1; ++i){ int ori = ORI(a, d, points.at(i)); if(ori == -1){ left.push_back(points.at(i)); } ori = ORI(d, b, points.at(i)); if(ori == -1){ right.push_back(points.at(i)); } } left.push_back(d); right.push_back(b); } left = compute_con_hull(left, false); right = compute_con_hull(right, false); left.insert(left.end(), right.begin(), right.end()); if(first){ left.erase(unique(left.begin(),left.end()),left.end()); if(left.size() > 1 && left.at(0) == left.at(left.size()-1)) { left.pop_back(); } } return left; } int main() { int n,x,y; vector<point> con_hull; cin >> n; while(n--){ cin >> x >> y; if(x < -350 || x > 350 || y < -350 || y > 350){ cout << "Error in the input"; continue; } con_hull.push_back(point{x,y}); } sort(con_hull.begin(), con_hull.end(), compare); if(con_hull.size() >= 3){ con_hull = compute_con_hull(con_hull, true); } if(true/*con_hull.size() >= 3*/) { cout << con_hull.size() << "\n"; for (int i = 0; i < con_hull.size(); ++i) { cout << con_hull.at(i).x << " " << con_hull.at(i).y << "\n"; } } }
3ff081f4becfeb696db90b1991dacd8a3b9b7026
c1671bd042b11704cc7d8c545d023e718ae99a09
/eMu - GameServer Sapphire S0/GameServer/Privilege.h
25e963c72548ae5c9c1a9a75249ca4636e54c57c
[]
no_license
Sogues/mu1.1
e9a31864b2ebc2517f5aeba1ead735d3fedfcfba
58de7aeee6ca26be861b0f0a81cf0cbf5ad8db11
refs/heads/master
2022-04-08T13:32:57.142927
2020-03-29T15:13:46
2020-03-29T15:13:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,241
h
Privilege.h
#ifndef _PRIVILEGE_H #define _PRIVILEGE_H // --- enum GM_MANAGER_COMMANDS { COMMAND_RELOAD, COMMAND_DISCONNECT, COMMAND_BLOCK, COMMAND_UNBLOCK, COMMAND_SKIN, COMMAND_MAKE, COMMAND_GMOVE, COMMAND_MOVEALL, COMMAND_REWARD, COMMAND_SETZEN, COMMAND_SETLEVEL, COMMAND_SETPK, COMMAND_SETDROP, COMMAND_HIDE, }; // --- struct PRIVILEGE_DATA { int iType; char szName[11]; int iCommand[40]; // --- char szSintax[50]; }; // --- class CPrivilege { public: void Load(); // --- int IsCheck(LPOBJ lpObj); // --- bool IsCommand(LPOBJ lpObj, int Command); // --- int iCount; // --- void Reload(int aIndex, char *szMsg); void Disconnect(int aIndex, char *szMsg); void Block(int aIndex, char *szMsg); void UnBlock(int aIndex, char *szMsg); void Skin(int aIndex, char *szMsg); void Make(int aIndex, char *szMsg); void Move(int aIndex, char *szMsg); void MoveAll(int aIndex, char *szMsg); void Reward(int aIndex, char *szMsg); void SetZen(int aIndex, char * szMsg); void SetLevel(int aIndex, char * szMsg); void SetPKLevel(int aIndex, char * szMsg); void SetDrop(int aIndex, char *szMsg); void Hide(int aIndex, char * szMsg); // --- PRIVILEGE_DATA m_Data[30]; }; // --- extern CPrivilege gPrivilege; // --- #endif
328ed8e0ff1cbad45b0e1d28b79fe57ad5de4ca3
651c2031f1864b9d3e7262f1802130ac359946a1
/client.cpp
9a6a4e57539df1fd57379e684e0e2a954e40dfe5
[]
no_license
Davt2000/forsys_test
e1e2361f056e93f72878c44f974b41f5e68541b2
4dee1b3bbe6d94fc52ba81d3692ed4418fae7089
refs/heads/master
2023-02-24T21:06:57.487026
2021-01-30T22:13:21
2021-01-30T22:13:21
333,749,580
0
0
null
2021-01-30T21:52:04
2021-01-28T12:17:41
CMake
UTF-8
C++
false
false
1,699
cpp
client.cpp
// // Created by perturabo on 28.01.2021. // #include <zmq.hpp> #include <string.h> #include <stdio.h> #include <unistd.h> #include "common.hpp" bool student_cmp(const student& a, const student& b){ return a.fullName < b.fullName; } int main (void) { zmq::context_t context(1); const char * protocol = "tcp://localhost:5555"; printf ("Connecting to server..."); zmq::socket_t sock (context, ZMQ_SUB); sock.connect(protocol); sock.setsockopt (ZMQ_SUBSCRIBE, "", 0); printf ("done. \n"); std::string recvdData; std::string line; student_list finalStudentList; student buf; while(true){ zmq::message_t reply; sock.recv (&reply, 0); if(VERBOSE){ printf("Received Word %d bytes: \"%s\"\n", reply.size(), reply.data()); } recvdData = reply.to_string(); if(recvdData[0] == '^'){ printf("Session ended, disconnecting from server..."); break; } if(recvdData[0] == '%'){ if(!line.empty()){ parse_string(buf, line); finalStudentList.push_back(buf); } line.clear(); } else { recvdData.erase(std::find(recvdData.begin(), recvdData.end(), '\0'), recvdData.end()); line.erase(std::find(line.begin(), line.end(), '\0'), line.end()); line += recvdData; } } sock.close(); printf ("done. \n\n"); sort(finalStudentList.begin(), finalStudentList.end(), student_cmp); for(auto item : finalStudentList) printf("%2i %20s %10s\n", item.id, item.fullName.c_str(), item.dateOfBirth.c_str()); return 0; }
3512ed18659e4accfb41ae55c6d01534c341ea89
6d54584c31ea20963dd49496c036b7fdae0f5645
/protocol/protocol.cpp
9121b021a13e7eaf62bec58b7f047cc7e575e73d
[ "MIT" ]
permissive
ValerioLuconi/Key-Exchange-Protocol
48726bd68f0367ceb6b4abbf9faa42a70157c375
247f5f09ad9f972f0a04b9fe8e1447e9397bf937
refs/heads/master
2021-01-01T04:26:14.984020
2016-05-18T10:27:45
2016-05-18T10:27:45
59,101,852
0
0
null
null
null
null
UTF-8
C++
false
false
27,800
cpp
protocol.cpp
/** * @file protocol.cpp * @brief Protocol class methods definition. * * @author Valerio Luconi * @version 1.0 */ #include "protocol.h" Protocol::Protocol (int type, string logfile) { log = logfile; LOG(log, "** Protocol Constructor **\n"); if (type == CLIENT) { int fd = open("key_client", O_RDONLY); read(fd, (void *) &client_id, sizeof(uint32_t)); read(fd, (void *) shared_key, EVP_MAX_KEY_LENGTH); close(fd); generate_nonce((char *) &client_nonce); // log LOG(log, "\t\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\t\tShared key: " + stringbyte(shared_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "\t\tClient nonce: " + utos(client_nonce) + "\n"); } server_id = ID_SERVER; md_ctx = create_md_context(); md_len = EVP_MD_size(md_ctx->digest); // log LOG(log, "\t\tServer ID: " + utos(server_id) + "\n"); LOG(log, "** End constructor **\n\n"); } Protocol::~Protocol () { // garbage collection EVP_CIPHER_CTX_cleanup(enc_ctx); EVP_CIPHER_CTX_cleanup(dec_ctx); EVP_MD_CTX_destroy(md_ctx); } int Protocol::send_message (int sd, int type) { uint32_t length; int len; int ret; int p = 0; if (type == M1) { // log LOG(log, "** Sending Message M1 **\n"); // Send to server: // M1 = C_ID, S_ID, Na len = sizeof(uint32_t); length = 3 * len; int b_len = 4 * len; // message buffer char *buffer = new char[b_len]; // length bcopy ((void *) &length, (void *) &buffer[p], len); p += len; // client_id bcopy ((void *) &client_id, (void *) &buffer[p], len); p += len; // server id bcopy ((void *) &server_id, (void *) &buffer[p], len); p += len; // client nonce bcopy ((void *) &client_nonce, (void *) &buffer[p], len); // send p = 0; do { ret = write (sd, (void *) &buffer[p], b_len - p); if (ret == -1) return ret; p += ret; } while (p != b_len); // log LOG(log, "\tLength: " + utos(length) + "\n"); LOG(log, "\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\tServer ID: " + utos(server_id) + "\n"); LOG(log, "\tClient Nonce: " + utos(client_nonce) + "\n"); LOG(log, "** Message M1 sent **\n\n"); // garbage collection delete[] buffer; } if (type == M2) { // log LOG(log, "** Sending Messagge M2 **\n"); // buffers int td_len = 3 * sizeof(uint32_t) + EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH; int p_len = td_len + md_len - EVP_MAX_IV_LENGTH; int c_len; int b_len; char *todigest = new char[td_len]; char *md; char *plaintxt = new char[p_len]; char *ciphertxt; char *buffer; // to digest: S_ID, C_ID, Na, K, IV len = sizeof(uint32_t); bcopy ((void *) &server_id, (void *) &todigest[p], len); p += len; bcopy ((void *) &client_id, (void *) &todigest[p], len); p += len; bcopy ((void *) &client_nonce, (void *) &todigest[p], len); p += len; bcopy ((void *) session_key, (void *) &todigest[p], EVP_MAX_KEY_LENGTH); p += EVP_MAX_KEY_LENGTH; select_random_iv(iv, EVP_MAX_IV_LENGTH); bcopy ((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH); // hash md = digest(md_ctx, todigest, td_len); // plaintext: S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV) p = 0; bcopy ((void *) todigest, (void *) &plaintxt[p], td_len - EVP_MAX_IV_LENGTH); p += td_len - EVP_MAX_IV_LENGTH; bcopy ((void *) md, (void *) &plaintxt[p], md_len); // ciphertext: {S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)} enc_ctx = create_context(shared_key, iv, ENC); ciphertxt = encrypt(enc_ctx, plaintxt, p_len, &c_len); // M2 length length = c_len + EVP_MAX_IV_LENGTH; // Send to client: // M2 = IV, {S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)} p = 0; b_len = length + sizeof(length); buffer = new char[b_len]; bcopy ((void *) &length, (void *) &buffer[p], sizeof(length)); p += sizeof(length); bcopy ((void *) iv, (void *) &buffer[p], EVP_MAX_IV_LENGTH); p += EVP_MAX_IV_LENGTH; bcopy ((void *) ciphertxt, (void *) &buffer[p], c_len); // send p = 0; do { ret = write (sd, (void *) &buffer[p], b_len - p); if (ret == -1) return ret; p += ret; } while (p != b_len); // log LOG(log, "\tLength: " + utos(length) + "\n"); LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n"); LOG(log, "\tServer ID: " + utos(server_id) + "\n"); LOG(log, "\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\tClient Nonce: " + utos(client_nonce) + "\n"); LOG(log, "\tSession Key: " + stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n"); LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) + "\n"); LOG(log, "\tShared Key (encrypt): " + stringbyte(shared_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "** Message M2 sent **\n\n"); // garbage collection delete[] todigest; delete[] md; delete[] plaintxt; delete[] ciphertxt; delete[] buffer; } if (type == M3) { // log LOG(log, "** Sending Message M3 **\n"); // buffers int td_len = 2 * sizeof(uint32_t) + EVP_MAX_IV_LENGTH; int p_len = td_len + md_len - EVP_MAX_IV_LENGTH; int c_len; int b_len; char *todigest = new char[td_len]; char *md; char *plaintxt = new char[p_len]; char *ciphertxt; char *buffer; // to digest: C_ID, S_ID, IV len = sizeof(uint32_t); bcopy ((void *) &client_id, (void *) &todigest[p], len); p += len; bcopy ((void *) &server_id, (void *) &todigest[p], len); p += len; select_random_iv(iv, EVP_MAX_IV_LENGTH); bcopy ((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH); // hash md = digest(md_ctx, todigest, td_len); // plaintext: C_ID, S_ID, h(C_ID, S_ID, IV) p = 0; bcopy ((void *) todigest, (void *) &plaintxt[p], td_len - EVP_MAX_IV_LENGTH); p += td_len - EVP_MAX_IV_LENGTH; bcopy ((void *) md, (void *) &plaintxt[p], md_len); // ciphertext: {C_ID, S_ID, h(C_ID, S_ID, IV)} enc_ctx = create_context(session_key, iv, ENC); ciphertxt = encrypt(enc_ctx, plaintxt, p_len, &c_len); // M3 length length = c_len + EVP_MAX_IV_LENGTH; // Send to server: // M3 = IV, {C_ID, S_ID, h(C_ID, S_ID, IV)} p = 0; b_len = length + sizeof(length); buffer = new char[b_len]; bcopy ((void *) &length, (void *) &buffer[p], sizeof(length)); p += sizeof(length); bcopy ((void *) iv, (void *) &buffer[p], EVP_MAX_IV_LENGTH); p += EVP_MAX_IV_LENGTH; bcopy ((void *) ciphertxt, (void *) &buffer[p], c_len); // send p = 0; do { ret = write (sd, (void *) &buffer[p], b_len - p); if (ret == -1) return ret; p += ret; } while (p != b_len); // log LOG(log, "\tLength: " + utos(length) + "\n"); LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n"); LOG(log, "\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\tServer ID: " + utos(server_id) + "\n"); LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n"); LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) + "\n"); LOG(log, "\tSession Key (encrypt): " + stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "** Message M3 sent **\n\n"); // garbage collection delete[] todigest; delete[] md; delete[] plaintxt; delete[] ciphertxt; delete[] buffer; } return 0; } int Protocol::receive_message (int sd, int type) { uint32_t length; uint32_t tmp; int len; int ret; int p = 0; int r; if (type == M1) { // log LOG(log, "** Receiving Message M1 **\n"); // Receive from client: // M1 = C_ID, S_ID, Na // receive length len = sizeof(length); r = 0; do { ret = read(sd, (void *) (&length + r), len - r); if (ret == -1) return ret; r += ret; } while (r != len); if (length != 3 * len) return -1; // buffer char *buffer = new char[length]; r = 0; do { ret = read(sd, (void *) &buffer[r], length - r); if (ret == -1) return ret; r += ret; } while (r != length); // client id bcopy((void *) &buffer[p], (void *) &client_id, len); if (client_id < 0) return -1; p += len; // server id bcopy((void *) &buffer[p], (void *) &tmp, len); if (tmp != server_id) return -1; p += len; // client nonce bcopy((void *) &buffer[p], (void *) &client_nonce, len); // get pre-shared key with client get_key(shared_key, "key_server", client_id); // log LOG(log, "\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\tServer ID: " + utos(server_id) + "\n"); LOG(log, "\tClient Nonce: " + utos(client_nonce) + "\n"); LOG(log, "\tShared Key: " + stringbyte(shared_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "** Message M1 Received **\n\n"); // garbage collection delete[] buffer; } if (type == M2) { // log LOG(log, "** Receiving Message M2 **\n"); // Receive from Server: // M2 = IV, {S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)} // receive length len = sizeof(length); r = 0; do { ret = read(sd, (void *) (&length + r), len - r); if (ret == -1) return ret; r += ret; } while (r != len); if (length < (EVP_MAX_IV_LENGTH + EVP_MAX_KEY_LENGTH + 3 * len + md_len)) return -1; // buffers int td_len = 3 * sizeof(uint32_t) + EVP_MAX_KEY_LENGTH + EVP_MAX_IV_LENGTH; int p_len; int c_len = length - EVP_MAX_IV_LENGTH; char *todigest = new char[td_len]; char *md; char *r_md = new char[md_len]; char *plaintxt; char *ciphertxt = new char[c_len]; char *buffer = new char[length]; // receive message r = 0; do { ret = read(sd, (void *) &buffer[r], length - r); if (ret == -1) return ret; r += ret; } while (r != length); // iv bcopy((void *) &buffer[p], (void *) iv, EVP_MAX_IV_LENGTH); p += EVP_MAX_IV_LENGTH; // ciphertext: {S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV)} bcopy((void *) &buffer[p], (void *) ciphertxt, c_len); // plaintext: S_ID, C_ID, Na, K, h(S_ID, C_ID, Na, K, IV) dec_ctx = create_context(shared_key, iv, DEC); plaintxt = decrypt(dec_ctx, ciphertxt, c_len, &p_len); // store & check p = 0; bcopy((void *) &plaintxt[p], (void *) &tmp, len); if (tmp != server_id) return -1; p += len; bcopy((void *) &plaintxt[p], (void *) &tmp, len); if (tmp != client_id) return -1; p += len; bcopy((void *) &plaintxt[p], (void *) &tmp, len); if (tmp != client_nonce) return -1; p += len; bcopy((void *) &plaintxt[p], (void *) session_key, EVP_MAX_KEY_LENGTH); p += EVP_MAX_KEY_LENGTH; // received hash bcopy((void *) &plaintxt[p], (void *) r_md, md_len); // to digest: S_ID, C_ID, Na, K, IV p = 0; len = sizeof(uint32_t); bcopy ((void *) &server_id, (void *) &todigest[p], len); p += len; bcopy ((void *) &client_id, (void *) &todigest[p], len); p += len; bcopy ((void *) &client_nonce, (void *) &todigest[p], len); p += len; bcopy ((void *) session_key, (void *) &todigest[p], EVP_MAX_KEY_LENGTH); p += EVP_MAX_KEY_LENGTH; bcopy ((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH); // hash md = digest(md_ctx, todigest, td_len); // check digest for (int i = 0; i < md_len; i++) { if (md[i] != r_md[i]) return -1; } // log LOG(log, "\tLength: " + utos(length) + "\n"); LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n"); LOG(log, "\tServer ID: " + utos(server_id) + "\n"); LOG(log, "\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\tClient Nonce: " + utos(client_nonce) + "\n"); LOG(log, "\tSession Key: " + stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n"); LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) + "\n"); LOG(log, "\tShared Key (decrypt): " + stringbyte(shared_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "** Message M2 Received **\n\n"); // garbage collection delete[] buffer; delete[] ciphertxt; delete[] plaintxt; delete[] r_md; delete[] todigest; delete[] md; } if (type == M3) { // log LOG(log, "** Receiving Message M3 **\n"); // Receive from client: // M3 = IV, {C_ID, S_ID, h(C_ID, S_ID, IV)} // receive length len = sizeof(length); r = 0; do { ret = read(sd, (void *) (&length + r), len - r); if (ret == -1) return ret; r += ret; } while (r != len); if (length < (EVP_MAX_IV_LENGTH + 2 * len + md_len)) return -1; // buffers int td_len = 2 * sizeof(uint32_t) + EVP_MAX_IV_LENGTH; int p_len; int c_len = length - EVP_MAX_IV_LENGTH; char *todigest = new char[td_len]; char *md; char *r_md = new char[md_len]; char *plaintxt; char *ciphertxt = new char[c_len]; char *buffer = new char[length]; // read message r = 0; do { ret = read(sd, (void *) &buffer[r], length - r); if (ret == -1) return ret; r += ret; } while (r != length); // iv bcopy((void *) &buffer[p], (void *) iv, EVP_MAX_IV_LENGTH); p += EVP_MAX_IV_LENGTH; // ciphertext: {C_ID, S_ID, h(C_ID, S_ID, IV)} bcopy((void *) &buffer[p], (void *) ciphertxt, c_len); // plaintext: C_ID, S_ID, h(C_ID, S_ID, IV) dec_ctx = create_context(session_key, iv, DEC); plaintxt = decrypt(dec_ctx, ciphertxt, c_len, &p_len); // check p = 0; len = sizeof(uint32_t); bcopy((void *) &plaintxt[p], (void *) &tmp, len); if (tmp != client_id) return -1; p += len; bcopy((void *) &plaintxt[p], (void *) &tmp, len); if (tmp != server_id) return -1; p += len; // received hash bcopy((void *) &plaintxt[p], (void *) r_md, md_len); // to digest: C_ID, S_ID, IV p = 0; bcopy ((void *) &client_id, (void *) &todigest[p], len); p += len; bcopy ((void *) &server_id, (void *) &todigest[p], len); p += len; bcopy ((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH); // hash md = digest(md_ctx, todigest, td_len); // check digest for (int i = 0; i < md_len; i++) { if (md[i] != r_md[i]) return -1; } // log LOG(log, "\tLength: " + utos(length) + "\n"); LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n"); LOG(log, "\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\tServer ID: " + utos(server_id) + "\n"); LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n"); LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) + "\n"); LOG(log, "\tSession Key (decrypt): " + stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "** Message M3 sent **\n\n"); // garbage collection delete[] buffer; delete[] ciphertxt; delete[] plaintxt; delete[] r_md; delete[] todigest; delete[] md; } return 0; } int Protocol::send_data (int sd, char *buf, int len) { // log LOG(log, "** Sending Data **\n"); int n = sizeof(uint32_t); int p = 0; uint32_t length; // buffers int td_len = 2 * n + len + EVP_MAX_IV_LENGTH; int p_len = td_len + md_len - EVP_MAX_IV_LENGTH; int c_len; int b_len; char *todigest = new char[td_len]; char *md; char *plaintxt = new char[p_len]; char *ciphertxt; char *buffer; // to digest: C_ID, S_ID, buf, IV bcopy((void *) &client_id, (void *) &todigest[p], n); p += n; bcopy((void *) &server_id, (void *) &todigest[p], n); p += n; bcopy((void *) buf, (void *) &todigest[p], len); p += len; select_random_iv(iv, EVP_MAX_IV_LENGTH); bcopy((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH); // hash md = digest(md_ctx, todigest, td_len); // plaintext: C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV) p = 0; bcopy((void *) todigest, (void *) &plaintxt[p], p_len - md_len); p += p_len - md_len; bcopy((void *) md, (void *) &plaintxt[p], md_len); // ciphertext: {C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)} enc_ctx = create_context(session_key, iv, ENC); ciphertxt = encrypt(enc_ctx, plaintxt, p_len, &c_len); EVP_CIPHER_CTX_cleanup(enc_ctx); // Message length length = c_len + EVP_MAX_IV_LENGTH; // Send: // M = IV, {C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)} p = 0; b_len = length + n; buffer = new char[b_len]; bcopy((void *) &length, (void *) &buffer[p], n); p += n; bcopy((void *) iv, (void *) &buffer[p], EVP_MAX_IV_LENGTH); p += EVP_MAX_IV_LENGTH; bcopy((void *) ciphertxt, (void *) &buffer[p], c_len); // send p = 0; int ret; do { ret = write (sd, (void *) &buffer[p], b_len - p); if (ret == -1) return ret; p += ret; } while (p != b_len); // log LOG(log, "\tLength: " + utos(length) + "\n"); LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n"); LOG(log, "\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\tServer ID: " + utos(server_id) + "\n"); LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n"); LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) + "\n"); LOG(log, "\tData: " + stringbyte(buf, len) + "\n"); LOG(log, "\tSession Key (encrypt): " + stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "** Data Sent **\n\n"); // garbage collection delete[] todigest; delete[] md; delete[] plaintxt; delete[] ciphertxt; delete[] buffer; return 0; } int Protocol::receive_data (int sd, char *&buf, int *len) { // log LOG(log, "** Receiving Data **\n"); int n = sizeof(uint32_t); int p = 0; uint32_t length; // Receive: // M = IV, {C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)} // receive length int ret, r = 0; do { ret = read(sd, (void *) (&length + r), n - r); if (ret == -1) return ret; r += ret; } while (r != n); if (length <= (EVP_MAX_IV_LENGTH + 2 * n + md_len)) return -1; // buffers int td_len; int p_len; int c_len = length - EVP_MAX_IV_LENGTH; char *todigest; char *md; char *r_md = new char[md_len]; char *plaintxt; char *ciphertxt = new char[c_len]; char *buffer = new char[length]; // read message r = 0; do { ret = read(sd, (void *) &buffer[r], length - r); if (ret == -1) return ret; r += ret; } while (r != length); // iv bcopy((void *) &buffer[p], (void *) iv, EVP_MAX_IV_LENGTH); p += EVP_MAX_IV_LENGTH; // ciphertext: {C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV)} bcopy((void *) &buffer[p], (void *) ciphertxt, c_len); // plaintext: C_ID, S_ID, buf, h(C_ID, S_ID, buf, IV) dec_ctx = create_context(session_key, iv, DEC); plaintxt = decrypt(dec_ctx, ciphertxt, c_len, &p_len); EVP_CIPHER_CTX_cleanup(dec_ctx); // check uint32_t tmp; p = 0; bcopy((void *) &plaintxt[p], (void *) &tmp, n); if (tmp != client_id) { printf("esco qui\n"); return -1; } p += n; bcopy((void *) &plaintxt[p], (void *) &tmp, n); if (tmp != server_id) return -1; p += n; // data *len = p_len - (2 * n + md_len); buf = new char[*len]; bcopy((void *) &plaintxt[p], (void *) buf, *len); p += *len; // received hash bcopy((void *) &plaintxt[p], (void *) r_md, md_len); // todigest: C_ID, S_ID, buf, IV p = 0; td_len = 2 * n + *len + EVP_MAX_IV_LENGTH; todigest = new char[td_len]; bcopy((void *) &client_id, (void *) &todigest[p], n); p += n; bcopy((void *) &server_id, (void *) &todigest[p], n); p += n; bcopy((void *) buf, (void *) &todigest[p], *len); p += *len; bcopy((void *) iv, (void *) &todigest[p], EVP_MAX_IV_LENGTH); // hash md = digest(md_ctx, todigest, td_len); // check hash for (int i = 0; i < md_len; i++) { if (md[i] != r_md[i]) return -1; } // log LOG(log, "\tLength: " + utos(length) + "\n"); LOG(log, "\tIV: " + stringbyte(iv, EVP_MAX_IV_LENGTH) + "\n"); LOG(log, "\tClient ID: " + utos(client_id) + "\n"); LOG(log, "\tServer ID: " + utos(server_id) + "\n"); LOG(log, "\tMD: " + stringbyte(md, md_len) + "\n"); LOG(log, "\tCipher Text: " + stringbyte(ciphertxt, c_len) + "\n"); LOG(log, "\tData: " + stringbyte(buf, *len) + "\n"); LOG(log, "\tSession Key (decrypt): " + stringbyte(session_key, EVP_MAX_KEY_LENGTH) + "\n"); LOG(log, "** Data Received **\n\n"); // garbage collection delete[] todigest; delete[] md; delete[] r_md; delete[] plaintxt; delete[] ciphertxt; delete[] buffer; return 0; }
c227011678a6c13d39b463ae742b9e371d5d33f2
d094454929537f90fdbb57420255f764eb9a15da
/19.cpp
803d8347fed2af7ddc65186cca4a3d50a83155de
[]
no_license
JiangXiang1925/Practice-cpp
c255bbbd36e1da98c32eef256cb31b636c37690d
f3397a8b64c9a2d5cb2e098c1bb3b1f4cc1239d5
refs/heads/master
2020-07-07T23:24:04.442954
2019-08-31T08:50:40
2019-08-31T08:50:40
203,504,391
1
0
null
null
null
null
UTF-8
C++
false
false
699
cpp
19.cpp
bool match(char* str,char* pattern) { if(str == nullptr || pattern == nullptr) return false; return matchCore(str,pattern); } bool matchCore(char* str,char* pattern) { if(*str=='\0' && *pattern=='\0') return true; if(*str!=='\0' && *pattern=='\0') return false; if(*(pattern+1)=='*') { if(*pattern==*str || (*pattren == '.' && *str!='\0')) return matchCore(str+1,pattern+2) || matchCore(str+1,pattern) || matchCore(str,pattern+2) } if(*str == *pattern || (*pattern=='.' && *str!='\0')) return matchCore(str+1,pattern+1); return false; }
cb39e543e27c9644945d92c3559e0673a963cfad
41839db0f0ee8ea9bbd516566a458794710a2cda
/src/Coroutine.h
5731ec77c0ba7f8cf101bc22167b138adb41f4f3
[ "MIT" ]
permissive
tvanslyke/avr-coro
b249ba812511122b50b5e000e370b64ec2711001
efa8e1dc03e53d918c39dc9f42e391f9b63c56e7
refs/heads/master
2020-04-27T18:51:27.104184
2019-03-10T17:09:19
2019-03-10T17:09:19
174,590,421
1
0
null
null
null
null
UTF-8
C++
false
false
8,289
h
Coroutine.h
/** * Copyright 2019 Timothy J. VanSlyke * * 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. */ #ifndef TIM_CORO_COROUTINE_H #define TIM_CORO_COROUTINE_H #include <stddef.h> #include <stdint.h> #include <setjmp.h> #include "assert.h" #include "type_traits.h" namespace tim::coro { enum class YieldResult: int { // Indicates that the resumed coroutine should continue running. Continue=1, // Indicates Terminate=2, Terminated=3 }; struct Coroutine; /** * Yield execution of the currently-running coroutine to the given coroutine. * It is NOT safe for a coroutine to use this function to yield to itself. */ [[nodiscard]] YieldResult yield_fast_to(Coroutine& coro); /** * Yield execution of the currently-running coroutine to the given coroutine. * It is safe for a coroutine to use this function to yield to itself. */ [[nodiscard]] YieldResult yield_to(Coroutine& coro); /** * Send a 'Terminate' signal to the coroutine. After calling * terminate on a coroutine object, the coroutine must be 'start()'ed * again before resuming it. */ void terminate(Coroutine& coro); namespace detail { template <class Callable> void start_coroutine(Coroutine* caller, Callable* callable); [[noreturn]] void coro_start( uint16_t coroutine_addr, uint16_t callable_addr, uint16_t stack_ptr, uint16_t start_fn ); } /* namespace detail */ struct Coroutine { static Coroutine main; Coroutine() = delete; Coroutine(const Coroutine&) = delete; Coroutine(Coroutine&&) = delete; Coroutine& operator=(const Coroutine&) = delete; Coroutine& operator=(Coroutine&&) = delete; /** True if this coroutine is the currently-running coroutine. */ bool is_running() const; /** True if this coroutine is NOT the currently-running coroutine. */ bool is_suspended() const; /** True if this coroutine must be started before resuming. */ bool is_done() const; /** Terminate the coroutine if it is running. */ void end() { terminate(*this); } /** * Start the coroutine. * Initializes the coroutine such that other coroutines can * begin yielding to this coroutine object. The actual callable * object is not invoked until the first time this coroutine * is resumed. */ void begin() { assert(this->start_fn_); this->start_fn_(*this); } protected: Coroutine(void (*start_fn)(Coroutine&)): start_fn_(start_fn), context_(nullptr) { } static Coroutine* currently_running; /** * Set up all the necessary machinery to allow other coroutines * to start yielding to this one. */ template <class Callable> void initialize(Callable& callable, char* stack_ptr) { assert((not this->context_) and "Attempt to start an already-started coroutine!"); // This jmp_buf will be used to allow the coroutine we're starting to jump back // to this execution context once it's started. jmp_buf context; // Save the currently-running coroutine. Coroutine* caller = Coroutine::currently_running; // Save the current context to the currently-running coroutines context_ pointer. caller->context_ = &context; // Make this coroutine the currently-running coroutine and jump to it. Coroutine::currently_running = this; if(not setjmp(context)) { // Start the coroutine. detail::coro_start( reinterpret_cast<uint16_t>(caller), reinterpret_cast<uint16_t>(&callable), reinterpret_cast<uint16_t>(stack_ptr), reinterpret_cast<uint16_t>(detail::start_coroutine<Callable>) ); } else { // All done, this coroutine is now resumable. Coroutine::currently_running = caller; } } template <class Callable> friend void detail::start_coroutine(Coroutine* coro, Callable* callable); friend [[nodiscard]] YieldResult yield_fast_to(Coroutine&); friend [[nodiscard]] YieldResult yield_to(Coroutine&); friend void terminate(Coroutine&); protected: /** * Pointer to function that starts the coroutine. */ void (*start_fn_)(Coroutine&); /** * If this coroutine is the currently-running coroutine, then 'context_' is the * context of whoever most-recently resumed this coroutine. * Otherwise 'context_' holds the context needed to resume the coroutine. */ jmp_buf* context_ = nullptr; }; namespace detail { /** * Entry point for all coroutines besides main. */ template <class Callable> void start_coroutine(Coroutine* caller, Callable* callable) { assert(Coroutine::currently_running); assert(Coroutine::currently_running != caller); // Immediately yield to the caller. The first time this coroutine // is resumed, we jump right into the callable. switch(yield_to(*caller)) { case YieldResult::Continue: // Start the actual coroutine. (*callable)(*Coroutine::currently_running); [[fallthrough]] case YieldResult::Terminate: default: (void)0; } // The coroutine has finished executing, clean up and then jump to the caller. // Note that the caller in this case is whomever lsat resumed this coroutine. jmp_buf* caller_ctx = Coroutine::currently_running->context_; assert(caller_ctx and "Coroutine terminated with no caller context to yield to."); Coroutine::currently_running->context_ = nullptr; // Jump back to whomever last resumed this coroutine. longjmp(*caller_ctx, static_cast<int>(YieldResult::Terminated)); } } /* namespace detail */ /** * Tag type used to specify static stack size for a coroutine. */ template <size_t N> struct stack_size { static constexpr size_t value = N; }; template <size_t N> inline constexpr auto stack_size_v = stack_size<N>{}; /** * Coroutine type that invokes an object of type 'Callable' with * a stack of 'StackSz' bytes. */ template <class Callable, size_t StackSz> struct BasicCoroutine: Coroutine { static_assert( traits::is_same_v<void, decltype(traits::declval<Callable&>()(traits::declval<Coroutine&>()))>, "BasicCoroutine callable object must have signature 'void(Coroutine&)'" ); static_assert(StackSz != 0u, "Stack size cannot be zero for BasicCoroutine."); /** * Create a BasicCoroutine instance from the object of type 'Callable'. */ BasicCoroutine(Callable callable): BasicCoroutine(callable, stack_size_v<StackSz>) { } /** * Constructor to support deducing StackSz with CTAD deduction guides. */ BasicCoroutine(Callable callable, stack_size<StackSz>): Coroutine(BasicCoroutine::start_function), callable_(callable), stack_{0} { } ~BasicCoroutine() { end(); } private: void start_coroutine() { assert(this->context_); this->initialize(callable_, &stack_[StackSz - 1u]); } static void start_function(Coroutine& self) { static_cast<BasicCoroutine&>(self).start_coroutine(); } // Callable object that is invoked upon starting. Callable callable_; // Call stack for this coroutine. char stack_[StackSz]; }; /** Deduction guides for BasicCoroutine. */ template <class Callable, size_t StackSz> BasicCoroutine(const Callable&, stack_size<StackSz>) -> BasicCoroutine<Callable, StackSz>; template <class Callable> BasicCoroutine(const Callable&) -> BasicCoroutine<Callable, 128u>; template <size_t StackSz> BasicCoroutine(void (Coroutine&), stack_size<StackSz>) -> BasicCoroutine<void (*)(Coroutine&), StackSz>; BasicCoroutine(void (Coroutine&)) -> BasicCoroutine<void (*)(Coroutine&), 128u>; } /* namespace tim::coro */ #endif /* INO_CORO_COROUTINE_H */
a79d7d5e319fdf24a64fc47f1c598dc7db89531e
5ab7032615235c10c68d738fa57aabd5bc46ea59
/rating.cpp
c1227da0f52b094c95ee803e0765288865fad34b
[]
no_license
g-akash/spoj_codes
12866cd8da795febb672b74a565e41932abf6871
a2bf08ecd8a20f896537b6fbf96a2542b8ecf5c0
refs/heads/master
2021-09-07T21:07:17.267517
2018-03-01T05:41:12
2018-03-01T05:41:12
66,132,917
2
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
rating.cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { int n; cin>>n; vector<int> v; v.resize(n); for(int i=0;i<n;i++)cin>>v[i]; int maxx=0,curr=0; for(int i=0;i<n;i++) { curr+=v[i]; if(curr<0)curr=0; maxx=max(curr,maxx); } cout<<maxx<<endl; }
fc839e2b20f2c1e89eea01310425ebc674bbfc3b
bafca10defdfdf5c931b2b580b0f8c083d63eedf
/src/hwenc_v4l2/v4l2_runner.h
1a077e1edb9aac9e2d5ba062ba8e5148027c0264
[ "BSD-3-Clause", "OpenSSL", "LicenseRef-scancode-protobuf", "Zlib", "GPL-1.0-or-later", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-takuya-ooura", "MIT", "ISC", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-nvidia-video-codec-agreement", "LicenseRef-scancode-openssl", "LicenseRef-scancode-ssleay-windows" ]
permissive
shiguredo/momo
3ffc9cd8d5d39627b3190e0c37c98e94f62c142b
f31a4d5c40fa2d54df548995b6dda08ffac594cf
refs/heads/develop
2023-09-06T02:47:20.802000
2023-09-06T02:28:26
2023-09-06T02:28:26
152,563,246
741
190
Apache-2.0
2023-08-27T15:03:54
2018-10-11T09:09:56
C++
UTF-8
C++
false
false
1,755
h
v4l2_runner.h
#ifndef V4L2_RUNNER_H_ #define V4L2_RUNNER_H_ #include <atomic> #include <functional> #include <mutex> #include <optional> #include <queue> #include <string> // Linux #include <linux/videodev2.h> // WebRTC #include <rtc_base/platform_thread.h> template <class T> class ConcurrentQueue { public: void push(T t) { std::lock_guard<std::mutex> lock(mutex_); queue_.push(t); } std::optional<T> pop() { std::lock_guard<std::mutex> lock(mutex_); if (queue_.empty()) { return std::nullopt; } T t = queue_.front(); queue_.pop(); return t; } bool empty() { std::lock_guard<std::mutex> lock(mutex_); return queue_.empty(); } size_t size() { std::lock_guard<std::mutex> lock(mutex_); return queue_.size(); } void clear() { std::lock_guard<std::mutex> lock(mutex_); queue_ = std::queue<T>(); } private: std::queue<T> queue_; std::mutex mutex_; }; class V4L2Runner { public: ~V4L2Runner(); static std::shared_ptr<V4L2Runner> Create( std::string name, int fd, int src_count, int src_memory, int dst_memory, std::function<void()> on_change_resolution = nullptr); typedef std::function<void(v4l2_buffer*, std::function<void()>)> OnCompleteCallback; int Enqueue(v4l2_buffer* v4l2_buf, OnCompleteCallback on_complete); std::optional<int> PopAvailableBufferIndex(); private: void PollProcess(); private: std::string name_; int fd_; int src_count_; int src_memory_; int dst_memory_; std::function<void()> on_change_resolution_; ConcurrentQueue<int> output_buffers_available_; ConcurrentQueue<OnCompleteCallback> on_completes_; std::atomic<bool> abort_poll_; rtc::PlatformThread thread_; }; #endif
0aa72a2fdf8716a01581bfce0764b530e58dbc64
dae7287c216b870ad6ea33bea7765abd51888274
/cpp/allocators/pool.h
85beb8632cd526f1dddd95ba930dffa648dde7a8
[]
no_license
dataartisan/prg
d907336aba0fa2c0ab19d92d1d9ffce88a4a7a6e
cbc39b0b9c6c6bc06b45dbed8a096b9b37095eaf
refs/heads/master
2021-01-20T19:06:47.657035
2011-10-15T13:55:10
2011-10-15T13:55:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,306
h
pool.h
#ifndef POOL_H_INCLUDED_GF #define POOL_H_INCLUDED_GF #ifdef _WIN32 #pragma warning(push) #pragma warning(disable:4018) //signed/unsigned mismatch #pragma warning(disable:4290) // exception spec ignored #endif #include <exception> #include <list> #include <algorithm> #include <iostream> //for dump() class pool { class logic_error:public std::exception { public: logic_error(const char *what):what_(what){} const char* what(){return what_;} private: const char *what_; }; enum pool_defaults{ init_size = 0xffffff, min_size = 0xf }; public: pool(size_t size = init_size):size_(size) { if(size_-sizeof(block) < min_size) throw logic_error("Initial pool size too small"); pool_mem_.push_back(new char[size_]); blocks_ = reinterpret_cast<block*>(*(pool_mem_.begin())); blocks_->prev_= 0; blocks_->next_= 0; blocks_->free_= 1; blocks_->size_= size_-sizeof(block); }; ~pool() { std::for_each(pool_mem_.begin(), pool_mem_.end(), killer()); } void* allocate(size_t size) { if(size>size_- sizeof(block)) { std::cout <<"size: " << size << std::endl; std::cout <<"size_: " << size_ << std::endl; std::cout <<"sizeof(block): " << sizeof(block) << std::endl; throw std::bad_alloc(); } block *b = blocks_; while(1){ while(!b->free_){ if(!b->next_) grow(b); b=b->next_; } if(b->size_<size) continue; break; } if(b->size_ - size < 2*sizeof(block)){ b->free_=0; return reinterpret_cast<char *>(b) + sizeof(block); } else{ block * new_block = (reinterpret_cast<block *>(reinterpret_cast<char *>(b) + size + sizeof(block))); if(b->next_) b->next_->prev_ = new_block; new_block->next_ = b->next_; b->next_ = new_block; new_block->prev_ = b; b->free_ = 0; new_block->size_= b->size_ - size - sizeof(block); b->size_ = size; new_block->free_ = 1; return reinterpret_cast<char *>(b) + sizeof(block); } } void deallocate(void *p, size_t = 0) { if(!p) return; block *b = reinterpret_cast<block *>(static_cast<char*>(p) - sizeof(block)); if(b->prev_ && b->next_){ if(b->prev_->free_ && b->next_->free_){ b->prev_->size_ += b->size_ + b->next_->size_ + 2*sizeof(block); b->prev_->next_ = b->next_->next_; if(b->next_->next_)b->next_->next_->prev_ = b->prev_; return; } } if(b->prev_){ if(b->prev_->free_){ b->prev_->size_ += b->size_ + sizeof(block); b->prev_->next_=b->next_; if(b->next_) b->next_->prev_ = b->prev_; b->free_= 1; return; } } if(b->next_){ if(b->next_->free_){ b->size_ += b->next_->size_ + sizeof(block); b->next_ = b->next_->next_; if(b->next_) b->next_->prev_ = b; b->free_= 1; return; } } b->free_ = 1; } void dump() { using namespace std; block *b = blocks_; while(1){ cout<<"Size="<<b->size_<<", free="<<b->free_<< ", prev="<<b->prev_<<", next="<<b->next_<<endl; if(b->next_) b = b->next_; else break; } } private: size_t size_; std::list<char *> pool_mem_; struct block{ block *prev_; block *next_; size_t size_; int free_; block(block *prev, block *next, size_t size, int free): prev_(prev), next_(next), size_(size), free_(free){} ~block(){} }; block * blocks_; pool(const pool &); pool& operator=(const pool&); struct killer { void operator()(char *p){delete [] p;} }; static void kill(char *p){delete [] p;} void grow(block *b) { block *new_block; char *p = new char[size_]; pool_mem_.push_back(p); new_block = reinterpret_cast<block*>(p); new_block->prev_= b; new_block->next_= 0; new_block->free_= 1; new_block->size_= size_-sizeof(block); b->next_ = new_block; } }; #ifdef _WIN32 #pragma warning(pop) #endif #endif
23a530160b69b2775dcd8e83303e062deea0a4c1
7c54c995c386b773259455301abdfd74b95b80d7
/src/cpp/gui/screens/GamePauseMenu.cpp
902ad852d2357d0953ca4f37bc56d49390af7b6b
[]
no_license
CHAZICLE/MuseumGuard
4b581bee6bfacbb20b326649388f27b6a9d0b18e
c923bbc10c4898b2acbdaafbf07c5fb35089a094
refs/heads/master
2020-12-03T01:49:44.917633
2017-06-30T09:30:58
2017-06-30T09:30:58
95,872,536
0
0
null
null
null
null
UTF-8
C++
false
false
2,298
cpp
GamePauseMenu.cpp
#include "gui/elements/Button.hpp" #include "input/Controls.hpp" #include "gui/ScreenManager.hpp" #include "gui/screens/PathTest.hpp" #include "gui/screens/GameView.hpp" #include "render/BasicShapes.hpp" #include "render/shaders/ShaderUtils.hpp" #include "render/RenderManager.hpp" #include "util/gl.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/matrix.hpp> #include <iostream> #include "GamePauseMenu.hpp" using namespace screens; GamePauseMenu::GamePauseMenu() : Screen() { this->resumeButton = new Button("Resume"); this->pathTestButton = new Button("???"); this->exitButton = new Button("Quit"); this->resumeButton->setY(20); this->pathTestButton->setY(10); //this->exitButton->setY(0); this->addElement(this->resumeButton); this->addElement(this->pathTestButton); this->addElement(this->exitButton); this->font = new render::Font("cour.ttf", 22); } GamePauseMenu::~GamePauseMenu() { delete this->resumeButton; delete this->pathTestButton; delete this->exitButton; } void GamePauseMenu::render(util::DeltaTime &deltaTime, render::RenderManager &rManager) { super::render(deltaTime, rManager); glm::mat4 boxMat = glm::mat4(1.0f); double s = (1+std::sin(deltaTime.getTime()*4))/20; boxMat = glm::translate(boxMat, glm::vec3(rManager.getWidthMM()/2, rManager.getHeightMM()/2, 0)); boxMat = glm::scale(boxMat, glm::vec3(1+s, 1+s, 0)); //boxMat = glm::translate(boxMat, glm::vec3(this->font->getTextWidth("Paused", rManager)/4, 22/2, 0)); boxMat = glm::translate(boxMat, glm::vec3(-this->font->getTextWidth("Paused", rManager)/4, 0, 0)); rManager.M = boxMat; rManager.markMDirty(); this->font->printf("Paused", rManager); } bool GamePauseMenu::onControlEvent(Control control, int action) { if(action==CONTROL_KEYACTION_RELEASE && control==CONTROL_GUI_ESCAPE) { this->manager->closeScreen(this); return true; } if((action&CONTROL_MOUSEBUTTONACTION_PRESS) && control==CONTROL_GUI_SELECT) { if(this->selectedElement==this->resumeButton) { this->manager->closeScreen(this); return true; } else if(this->selectedElement==this->pathTestButton) { this->manager->openRootScreen(new PathTest()); return true; } else if(this->selectedElement==this->exitButton) { this->manager->close(); return true; } } return true; }
e233cf275331a2edb47777e33c37f678d9d3a5d4
1bbdecb6de9fd654c7a3598662641198038faec2
/game.cpp
faeb52215c74046594a6e15aadf7f0dbae86788a
[]
no_license
lsmieszkowicz/rogalik
0be56b1efa2d3b4fbb97a20458f3fc97b92881a0
a0193f4e93f23be6d93295f4e49a683d79aaa41f
refs/heads/master
2021-07-20T21:53:09.877473
2017-10-28T07:22:23
2017-10-28T07:22:23
108,628,947
0
0
null
null
null
null
UTF-8
C++
false
false
486
cpp
game.cpp
#include "game.h" #include <iostream> #include <SDL2/SDL.h> using namespace std; Game::Game() { this->gamePreferences = new GamePreferences(); this->gameWindow = new GameWindow(); SDL_Init(SDL_INIT_EVERYTHING); } Game::~Game() { SDL_Quit(); } void Game::run() { while(this->gamePreferences->isRunning()) { } } void Game::handleEvents() { cout << "Handling events" << endl; } void Game::renderAll() { cout << "Rendering all objects" << endl; }
b3e5140cf5d72d898cb936f497b13a622edc078e
dd3d11771fd5affedf06f9fcf174bc83a3f2b139
/BotCore/DofusProtocol/ClientKeyMessage.cpp
e7d80d5895ebf594f4d43d52b0eb25ee7ae10cb6
[]
no_license
Arkwell9112/arkwBot
d3f77ad3874e831594bd5712705983618e94f258
859f78dd5c777077b3005870800cb62eec1a9587
refs/heads/master
2023-03-17T12:45:07.560436
2021-03-16T11:22:35
2021-03-16T11:22:35
338,042,990
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
ClientKeyMessage.cpp
#include "ClientKeyMessage.h" void ClientKeyMessage::deserialize(ICustomDataInput &input) { this->deserializeAs_ClientKeyMessage(input); } void ClientKeyMessage::deserializeAs_ClientKeyMessage(ICustomDataInput &input) { this->_keyFunc(input); } void ClientKeyMessage::_keyFunc(ICustomDataInput &input) { this->key = input.readUTF(); }
381ec059161006d9c9b80a2b9e9e1142678d364b
3872740bc8ab30db1e645c4c0da62ce4eb11f0fc
/munplanner.cpp
0a2b53274969c4b6ed6b614e48831ca4d81acd95
[]
no_license
ThatcherC/ProjectMun
cb601ddf6c862eb5a175e7f1ced21a2c030a8389
b824526554486a095e185b1cb04e2d70cb067801
refs/heads/master
2020-04-16T18:46:33.389748
2016-08-23T13:41:29
2016-08-23T13:41:29
47,838,154
0
0
null
2016-06-29T23:16:10
2015-12-11T16:37:50
Gnuplot
UTF-8
C++
false
false
11,356
cpp
munplanner.cpp
#include <iostream> #include <stdint.h> #include <cmath> #include "stdio.h" #include "stdlib.h" #include <string> #include <vmmlib/vector.hpp> #include <vmmlib/math.hpp> #include <defs.cpp> #include <basicfunctions.cpp> // g++ munplanner.cpp -I ./ -o munplanner -std=c++0x using namespace std; double desired_rm; //mun periapsis double desired_ta = 0; //time of arrival double desired_il = 0; double desired_ir = 0; double desired_rl; //Kerbin periapsis outbound double desired_rr; //Kerbin periapsis inbound double thetaFL; //Outbound and inbound angles double thetaFR; void setParamters(){ int toa[5]; //equivalences to seconds for years, days, hours, minutes, and seconds int toSeconds[5] = {9203400, 6*3600,3600,60,1}; int p = 0; printf("Time of arrival (y:d:h:m:s): "); scanf("%d:%d:%d:%d:%d", &toa[0], &toa[1], &toa[2], &toa[3], &toa[4]); printf("Initial Kerbin periapsis (m): "); scanf("%d",&p); desired_rl = (double)p+kerbinRadius; printf("Kerbin return periapsis (m): "); scanf("%d",&p); desired_rr = (double)p+kerbinRadius; printf("Mun periapsis (m): "); scanf("%d", &p); desired_rm = (double)p+munRadius; toa[0] = toa[0]-1; toa[1] = toa[1]-1; for(int i = 0; i < 5; i++){ desired_ta += toSeconds[i] * toa[i]; } //desired_ta = 0; printf("\n----------------------------\n"); } //Calculates the shape (a, e) of an orbit that satisfies the arguments //Works for both inbound and outbound Orbit getOrbit(double rl, vmml::vector<3,double> Rt, double theta){ Orbit out; out.a = semimajor(rl,Rt.length(), theta); out.e = 1-rl/out.a; //eccentricity out.p = out.a*(1-out.e*out.e); //find angle between between Rt and Mun's center, and add that to munAngle vmml::vector<3,double> munPos = munPosition(desired_ta); double smallAngle = acos( Rt.dot(munPos) / (Rt.length()*munAltitude) ); out.aop = munAngle(desired_ta)+smallAngle-theta;; return out; } //This function is very likely known to work for outbound //Returns the position and velocity conditions at the Munar patch point //Assumes an outbound trajectory MunIntercept getIntercept(double rl, vmml::vector<3,double> Rt, double toa, double angle, int situation){ vmml::vector<3,double> Rtm; vmml::vector<3,double> Vt; vmml::vector<3,double> Vtm; MunIntercept intercept; Orbit traj; //Step 1: //Choose an r_T and a t_F, then find the trajectory Rtm = Rt - munPosition(toa); double rt = Rt.length(); traj = getOrbit(rl,Rt,angle); //solved for all necessary orbital parameters //Step 2: //Find R_tm and V_tm - already have Rtm //Comes from IttMaMoA pg. 445 //should change angle for inbound orbits angle = angle - situation*(2*angle); Vt = 1.0/rt * (sqrt(muKerbin/traj.p)*traj.e*sin(angle)*Rt + sqrt(muKerbin*traj.p)/rt * i.cross(Rt) ); Vtm = Vt-munVelocity(toa); intercept.Rt = Rt; intercept.Rtm = Rtm; intercept.Vt = Vt; intercept.Vtm = Vtm; intercept.toa = toa; //is this tfl the same as tf? test intercept.tfl = tfl(rl,rt,angle); intercept.theta = angle; return intercept; } //Returns an orbit from Kerbin to Mun ending in the Mun's center Orbit findOrbit(double periapsis, double toa, double angle, int situation){ MunIntercept I1; vmml::vector<3,double> Ra; //Step 3: //Iterate over angles to guess a good starting intercept angle const double RAguessingThreshold = 20000.0*5.0/3.0*1000.0 * munRadius/1737000.0 *0.5;//times .5 for extra good guess double phi; //check one quarter of SOI for outbound, check other half for inbound for(phi = 0+situation*1.57; phi < 1.57+situation*1.57; phi += .1){ //Intercept point relative to Mun vmml::vector<3,double> RtGuess (-munSOI*sin( munAngle(toa)+phi ), munSOI*cos( munAngle(toa)+phi ), 0 ); RtGuess = RtGuess + munPosition(toa); I1 = getIntercept(periapsis, RtGuess, toa, angle, situation); Ra = I1.Rtm - I1.Rtm.dot(I1.Vtm)/I1.Vtm.dot(I1.Vtm) * I1.Vtm; //printf("Phi: %f R_a: %f\n", phi, Ra.length()); if(Ra.length()<RAguessingThreshold){ break; } } //TODO: This might be wayyy to many iterations //Forgot to account for the fact that an outbound lunar trajectory will have velocity pointing away from mun! //This was screwing up results for a while double k = 1+situation*-2; for(int x=0; x<14; x++){ //printf("%d: Ra = %f\n",x,Ra.length()); I1.Rt = munPosition(toa) - k * munSOI * I1.Vtm/I1.Vtm.length(); I1 = getIntercept(periapsis, I1.Rt, toa, angle, situation); //Ra = I1.Rtm - I1.Rtm.dot(I1.Vtm)/I1.Vtm.dot(I1.Vtm) * I1.Vtm; } Orbit O1 = getOrbit(desired_rl, I1.Rt, angle); O1.intercept = I1; return O1; } double getMunSOItime(double v){ double a_h = 1.0/(v*v/muMun - 2.0/munSOI); //What is rm? desired_rm?? Check section 9.1 double sineNu = 1.0/(1+desired_rm/a_h); double H = acosh((1+munSOI/a_h)*sineNu); double t = 2*sqrt(a_h*a_h*a_h/muMun)*(sinh(H)/sineNu - H); return t; } double getMunRm(MunIntercept munBound, MunIntercept earthBound){ double nu = asin( munBound.Vtm.cross(earthBound.Vtm).length() / munBound.Vtm.squared_length())/2; //printf("Deflection angle: %f\n", nu); double a_h = 1.0/(munBound.Vtm.squared_length()/muMun - 2.0/munSOI); //printf("A_h: %f\n", a_h); return a_h * (1.0/sin(nu) - 1); } //Not sure if this is the proper way to do this.... double getMunRa(MunIntercept munBound, MunIntercept earthBound){ double nu = asin( munBound.Vtm.cross(earthBound.Vtm).length() / munBound.Vtm.squared_length())/2; //printf("Deflection angle: %f\n", nu); double a_h = 1.0/(munBound.Vtm.squared_length()/muMun - 2.0/munSOI); //printf("A_h: %f\n", a_h); return a_h * 1.0/tan(nu); } double getMunRa2(MunIntercept m){ vmml::vector<3,double> Ra = m.Rtm - m.Rtm.dot(m.Vtm)/m.Vtm.dot(m.Vtm)*m.Vtm; return Ra.length(); } //Calculates orbits that satisfy the laws of physics and returns the Mun periapsis Orbit findConsistentOrbits(double angleFL){ Orbit O1; Orbit O2; O1 = findOrbit(desired_rl, desired_ta, angleFL, OUTBOUND); //Step 4: Get ToF through Mun SOI //Need Vtm and Rtm double tSOI = getMunSOItime(O1.intercept.Vtm.length()); //printf("Mun SOI time: %f\n", tSOI); //Step 6: Vary t_fr so that Munar entry and exit velocities match thetaFR = 3.1; for(int x = 0; x< 10; x++){ //Step 5: find return orbit O2 = findOrbit(desired_rr, desired_ta+tSOI, thetaFR, INBOUND); //printf("VTM outbound: %f VTM inbound: %f\n", O1.intercept.Vtm.length(),O2.intercept.Vtm.length()); if(abs(O1.intercept.Vtm.length()-O2.intercept.Vtm.length())<20){ break; } thetaFR -= .1; } //printf("Iteratively matching entry and exit speeds:\n"); //Bumped up number of iterations here to help convergance in main loop for(int x = 0; x < 8; x++){ double deriv = (findOrbit(desired_rr, desired_ta+tSOI, thetaFR+0.001, INBOUND).intercept.Vtm.length()-O2.intercept.Vtm.length())/0.001; thetaFR = thetaFR + (O1.intercept.Vtm.length() - O2.intercept.Vtm.length())/deriv; O2 = findOrbit(desired_rr, desired_ta+tSOI, thetaFR, INBOUND); //printf("VTM outbound: %f VTM inbound: %f\n", O1.intercept.Vtm.length(),O2.intercept.Vtm.length()); } return O2; //return getMunRm(O1.intercept, O2.intercept); } double getOutboundTFL(Orbit orbit, double angle){ double e = orbit.e; double E = acos( (e + cos(angle)) / (1+e*cos(angle)) ); //Here there was a bug! I squashed it. the '-' used to be a '*'! return sqrt(orbit.a*orbit.a*orbit.a/muKerbin)*(E - e*sin(E)); } void printVector(vmml::vector<3,double> v){ printf("{x: %f, y: %f}\n", v[0], v[1]); } vmml::vector<3,double> rotateVector(vmml::vector<3,double> v, double theta){ vmml::vector<3,double> out (0,0,0); out[0] = cos(theta)*v[0]-sin(theta)*v[1]; out[1] = sin(theta)*v[0]+cos(theta)*v[1]; return out; } //FUnction used to confirm whether our velocities match KSP's void printPolarVelocities(MunIntercept m){ double total = m.Vtm.length(); double radial = m.Vtm.dot(m.Rtm)/m.Rtm.length(); double tangential = sqrt(total*total-radial*radial); printf("Total V: %f Radial V: %f Tangential V: %f\n",total, radial,tangential); } //X_y, Xy : vector //x_y, xy : magnitude of same vector int main(){ //Set up printf("\n\nMun Planner v0.1, (June 17, 2016)\n----------------------------\n"); setParamters(); Orbit O1; Orbit O2; //Estimate for burnout-Mun angle thetaFL = 2.9; double RMthreshold = 50000; //Step 7: Vary t_fl (and repeat step 6) so that r_m matches desired value //Limit on this is currently optimized-ish to 100km, 35km, 10km target for(int c = 0; c< 30; c++){ O1 = findOrbit(desired_rl, desired_ta, thetaFL, OUTBOUND); double rm = getMunRm(O1.intercept, findConsistentOrbits(thetaFL).intercept); if(abs(rm-desired_rm) < RMthreshold){ printf("ThetaFL: %f Calculated RM: %f\n", thetaFL, rm); break; } thetaFL -= 0.01; } //Time to do a Newton's method on thetaFL - extra iterations helped a lot for(int x = 0; x < 20; x++){ O1 = findOrbit(desired_rl, desired_ta, thetaFL, OUTBOUND); O2 = findConsistentOrbits(thetaFL); double rm = getMunRm(O1.intercept, O2.intercept); double rm2 = getMunRm(O1.intercept, findConsistentOrbits(thetaFL+0.001).intercept); double deriv = (rm2-rm)/0.001; thetaFL = thetaFL + (desired_rm-rm)/deriv; // = findOrbit(desired_rr, desired_ta+tSOI, thetaFR, INBOUND); //printf("RM Desired: %f RM Calculated: %f\n", getMunRm(O1.intercept, O2.intercept), desired_rm); } printf("Rm: %f\n", getMunRm(O1.intercept, O2.intercept)); O1 = findOrbit(desired_rl, desired_ta, thetaFL, OUTBOUND); O2 = findConsistentOrbits(thetaFL); double ra = getMunRa(O1.intercept, O2.intercept); printf("Ra: %f\n", ra); printf("Ra2: %f\n", getMunRa2(O1.intercept)); printf("Rm: %f\n", getMunRm(O1.intercept, O2.intercept)); printf("Moving patch position vectors... \n"); double angle = ra/munSOI; printPolarVelocities(O1.intercept); printPolarVelocities(O2.intercept); O1.intercept.Rtm = rotateVector(O1.intercept.Rtm, -angle); O2.intercept.Rtm = rotateVector(O2.intercept.Rtm, angle); printf("Recalculating intercepts\n"); MunIntercept O1intercept = getIntercept(desired_rl, O1.intercept.Rtm+munPosition(desired_ta), desired_ta, thetaFL, OUTBOUND); double tSOI = getMunSOItime(O1intercept.Vtm.length()); MunIntercept O2intercept = getIntercept(desired_rr, O2.intercept.Rtm+munPosition(desired_ta+tSOI), desired_ta+tSOI, thetaFR, INBOUND); O1 = getOrbit(desired_rl, O1intercept.Rt, thetaFL); O2 = getOrbit(desired_rr, O2intercept.Rt, thetaFR); O1.intercept = O1intercept; O2.intercept = O2intercept; printf("Ra2: %f\n", getMunRa2(O1.intercept)); printPolarVelocities(O1.intercept); printPolarVelocities(O2.intercept); printf("Rm: %f\n", getMunRm(O1.intercept, O2.intercept)); printf("\n-------Results:--------\n"); printf("a: %f\n", O1.a); printf("e: %f\n", O1.e); printf("AoP: %f (%f°)\n", O1.aop, O1.aop*180/pi); printf("O1 TFL: %f\n", getOutboundTFL(O1,thetaFL)); printf("v: %f\n",sqrt(muKerbin * (2/desired_rl-1/O1.a))); printf("\nrun tothemun(%f, %f, %f).\n\n",O1.a,O1.aop,desired_ta-getOutboundTFL(O1,thetaFL)); printf("\n"); return 0; }
4784fc8c385b1c2267d2f3c8f9da76830ee15295
0cc2a22f7134870f12508365ec42ebe01be775ee
/ppoint.cpp
6df4a86791b010fcd8d38b21e109bee70a8e4ad6
[]
no_license
SiewMengYeong/C-plus-plus-Exersice
1925b530e8e3b7af48dc68d28d00955be6efb03e
8f53a38a99fbfec0d3d53512d683cb3554cc0f32
refs/heads/master
2020-04-28T00:38:34.504036
2019-03-10T13:45:48
2019-03-10T13:45:48
174,823,430
0
0
null
null
null
null
UTF-8
C++
false
false
259
cpp
ppoint.cpp
#include <iostream> using std::cout; using std::cin; using std::endl; void swap(int&& i,int&& j) { int temp; temp=i; i=j; j=temp; return; } int main() { int x(3); int y(5); cout<<x<<endl; cout<<y<<endl; swap(x,y); cout<<x<<endl; cout<<y<<endl; return 0; }
caa5fc80c0d32081c77c5df3a4d5acfaf6b65308
5a5349c12b7ff13ab0e892a86534c5d01692e874
/project-toolkits/toolkitc/src/backpropagation.h
ccdfa161ab4a7bb13d5df3ea3bf4d71aa6034eff
[]
no_license
mdko/byu-cs478
e4f0cdf1de8201e2a68dede993ff42568391ba3d
bfb5f5701a02f6d449acb9f7edba87d9811c0dca
refs/heads/master
2021-05-27T09:59:07.570886
2013-09-25T06:53:43
2013-09-25T06:53:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
23,084
h
backpropagation.h
/** * Author: Michael Christensen * Date: February 15, 2013 * * For BYU CS 478 Backpropagation Project */ #ifndef BACKPROPAGATION_H #define BACKPROPAGATION_H #include "learner.h" #include "rand.h" #include "error.h" #include <cmath> #include <iostream> #include <stdio.h> #include <map> #include <vector> #define DEBUG_BP 0 #define DEBUG_BP_E 1 #define INFO_OUT 1 // For printing final results // Adjust these to find best combination #define INCLUDE_MOMENTUM 1 #define MOMENTUM_TERM 0.875 // was 0.875 (best) #define LEARNING_RATE 0.05 // comment out for exper. (see L157) #define NUM_HIDDEN_LAYERS 2 // not sure if 1 or 2 best #define NUM_HIDDEN_NODE_MULTIPLIER 8 // was 16 (best) #define IGNORE_LAST_ATTRIBUTES 0 // number of columns from the end to ignore (eg pic #) #define EULER_NUM 2.71828182845904523536028747135266249775724709369995 #define NON_IMPROVEMENT_THRESHOLD 50 // For experimentation #define INCLUDE_SMALL_DELTA_MOMENTUM 0 #define SMALL_DELTA_TERM 0.05 #define CHANGE_LEARNING_RATE 0 #define LR_MULT 1.13 using namespace std; class BackpropagationLearner : public SupervisedLearner { class Node { private: Rand& m_r; double my_output; double small_delta_weight; double previous_small_delta_weight; vector<double> big_delta_weights; //These point upwards vector<double> previous_big_delta_weights; vector<double> output_weights; //These point upwards vector<double> best_weights; int num_output_weights; public: Node(int now, Rand& r) : m_r(r) { //Initializations my_output = 0; small_delta_weight = 0; previous_small_delta_weight = 0; //Set all weights going out of this node to random num, mean 0 num_output_weights = now; for (int i = 0; i < num_output_weights; i++) { double ran_num = ((double)m_r.next(10) / 10) - .5; output_weights.push_back(ran_num); best_weights.push_back(ran_num); big_delta_weights.push_back(0); previous_big_delta_weights.push_back(0); } } ~Node() { } /******************* * Getters/setters * *******************/ void set_output(double output) { my_output = output; } double get_output() { //TODO problem here, called in predict L562, when using more than 1 hidden layer return my_output; } int get_num_output_weights() { return num_output_weights; } double get_weight(int to_which_node) { return output_weights[to_which_node]; } void set_small_delta_weight(double sdw) { small_delta_weight = sdw; } double get_small_delta_weight() { return small_delta_weight; } double get_previous_small_delta() { return previous_small_delta_weight; } void remember_previous_small_delta_weight() { previous_small_delta_weight = small_delta_weight; } void set_big_delta_weight(int pos, double bdw) { big_delta_weights[pos] = bdw; } double get_previous_big_delta_weight(int pos) { return previous_big_delta_weights[pos]; } void remember_previous_weights() { for (int i = 0; i < num_output_weights; i++) previous_big_delta_weights[i] = big_delta_weights[i]; } void update_weights() { for (int i = 0; i < num_output_weights; i++) output_weights[i] += big_delta_weights[i]; } void update_best_weights() { for (int i = 0; i < num_output_weights; i++) best_weights[i] = output_weights[i]; } void use_best_weights() { for (int i = 0; i < num_output_weights; i++) output_weights[i] = best_weights[i]; } void clear_delta_weights() { for (int i = 0; i < num_output_weights; i++) big_delta_weights[i] = 0; } void print_weights() { cout << "\tWeights: "; for (int i = 0; i < num_output_weights - 1; i++) cout << output_weights[i] << ", "; cout << output_weights[num_output_weights - 1] << endl; } }; private: Rand& m_rand; // pseudo-random number generator (not actually used by the baseline learner) vector<Node*> input_nodes; vector <vector<Node*> > hidden_nodes_matrix; vector<Node*> output_nodes; int num_classes; double learning_rate = LEARNING_RATE; // for experimentation public: BackpropagationLearner(Rand& r) : SupervisedLearner(), m_rand(r) { } virtual ~BackpropagationLearner() { } virtual void train(Matrix& total_features, Matrix& total_labels) { /**************** * Declarations * ****************/ int total_num_instances = total_features.rows(); int num_features = total_features.cols() - IGNORE_LAST_ATTRIBUTES; int num_hidden_nodes = num_features * NUM_HIDDEN_NODE_MULTIPLIER; num_classes = !total_labels.valueCount(0) ? 2 : total_labels.valueCount(0); double best_accuracy_so_far = 0.0; int number_without_improvement = 0; int number_epochs_completed = 0; Matrix validation_features; Matrix validation_labels; Matrix features; //training Matrix labels; //training if (INFO_OUT) { cout << "Momentum Term: " << MOMENTUM_TERM << endl; cout << "Learning Rate: " << learning_rate << endl; cout << "Num Hidden Layers: " << NUM_HIDDEN_LAYERS << endl; cout << "Num Hidden Node Mult: " << NUM_HIDDEN_NODE_MULTIPLIER << endl; cout << "Num Instances: " << total_num_instances << endl; cout << "Num Features: " << num_features << endl; cout << "Num Hidden Nodes: " << num_hidden_nodes << endl; cout << "Num Output Classes: " << num_classes << endl; } if (DEBUG_BP) for (int i = 0; i < total_num_instances; i++) cout << total_features.attrValue(num_features, /*attr*/ total_features[i][num_features] /*value*/) << endl; if (NUM_HIDDEN_LAYERS < 1) { cout << "Error: number of hidden layers is less than 1 . . . returning" << endl; return; } /******************* * Initializations * *******************/ //Initialize input nodes (which inits their weights in constructor) for (int i = 0; i < num_features + 1; i++) { //+ 1 for bias input_nodes.push_back(new Node(num_hidden_nodes, m_rand)); } //Initialize hidden nodes (which inits their weights in constructor) hidden_nodes_matrix.resize(NUM_HIDDEN_LAYERS); for (int i = 0; i < NUM_HIDDEN_LAYERS; i ++) { for (int j = 0; j < num_hidden_nodes + 1; j++) { //+ 1 for bias if (i == (NUM_HIDDEN_LAYERS - 1)) //each node in topmost layer of hidden nodes only has output weights to # of output nodes hidden_nodes_matrix[i].push_back(new Node(num_classes, m_rand)); else hidden_nodes_matrix[i].push_back(new Node(num_hidden_nodes, m_rand)); } } //Initialize output nodes (they have no weights pointing upwards, so 0 param) for (int i = 0; i < num_classes; i++) { output_nodes.push_back(new Node(0, m_rand)); } //Initialize training, validation sets int number_rows_in_training_set = total_num_instances * 0.8; int number_rows_in_validation_set = total_num_instances - number_rows_in_training_set; if (DEBUG_BP) { cout << "Total rows: " << total_num_instances << endl; cout << "Number rows in ts: " << number_rows_in_training_set << endl; cout << "Number rows in vs: " << number_rows_in_validation_set << endl; } //Shuffle before we split into training and validation sets total_features.shuffleRows(m_rand, &total_labels); //Initialize test set features.copyPart(total_features, 0, 0, number_rows_in_training_set, num_features); labels.copyPart(total_labels, 0, 0, number_rows_in_training_set, total_labels.cols()); //Initialize validation set validation_features.copyPart(total_features, number_rows_in_training_set, 0, number_rows_in_validation_set, num_features); validation_labels.copyPart(total_labels, number_rows_in_training_set, 0, number_rows_in_validation_set, total_labels.cols()); if (DEBUG_BP_E) { cout << "Instances in test set: " << endl; for (int i = 0; i < (int)features.rows(); i++) { for (int j = 0; j < (int)features.cols(); j++) { cout << features[i][j] << " "; } cout << endl; } cout << "Instances in validation set: " << endl; for (int i = 0; i < (int)validation_features.rows(); i++) { for (int j = 0; j < (int)validation_features.cols(); j++) { cout << validation_features[i][j] << " "; } cout << endl; } } //So we don't have to change all the references in following code to num_instances int num_instances = number_rows_in_training_set; if (DEBUG_BP) { cout << "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&" << endl; for (int i = 0; i < (int)features.rows(); i++) { for (int j = 0; j < (int)features.cols(); j++) { cout << features[i][j] << ", "; } cout << endl; } cout << "++++++++++++++" << endl; for (int i = 0; i < (int)labels.rows(); i++) { for (int j = 0; j < (int)labels.cols(); j++) { cout << labels[i][j] << ", "; } cout << endl; } cout << "&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&" << endl; for (int i = 0; i < (int)validation_features.rows(); i++) { for (int j = 0; j < (int)validation_features.cols(); j++) { cout << validation_features[i][j] << ", "; } cout << endl; } cout << "++++++++++++++" << endl; for (int i = 0; i < (int)validation_labels.rows(); i++) { for (int j = 0; j < (int)validation_labels.cols(); j++) { cout << validation_labels[i][j] << ", "; } cout << endl; } } /***************** * Run algorithm * *****************/ if (INFO_OUT) cout << "Epoch Number, Training Set Acc, Validation Set Acc, MSE" << endl; do { if (DEBUG_BP) cout << "********************" << endl; //Shuffle before each epoch features.shuffleRows(m_rand, &labels); double mean_squared_error = 0.0; //Start an epoch for (int i = 0; i < num_instances; i++) { //Print out some information for debugging purposes if (DEBUG_BP) { cout << "++++++++++++++++++++++\nInstance: " << i << endl; cout << "Weights at beginning of instance: " << endl; for (int i = 0; i < num_features + 1; i++) { cout << "Input node " << i << ":" << endl; input_nodes[i]->print_weights(); } for (int i = 0; i < NUM_HIDDEN_LAYERS; i ++) { for (int j = 0; j < num_hidden_nodes + 1; j++) { cout << "Hidden layer " << i << ", node " << j << ":" << endl; hidden_nodes_matrix[i][j]->print_weights(); } } } /***************************** * Go up toward output layer * *****************************/ //Set input nodes's outputs for (int j = 0; j < num_features; j++) { input_nodes[j]->set_output(features[i][j]); if (DEBUG_BP) cout << "Input feature in node: " << input_nodes[j]->get_output() << endl; } input_nodes[num_features]->set_output(1); //Bias node //Set ouputs for each node in hidden layer based on nodes below it //For each hidden layer for (int j = 0; j < NUM_HIDDEN_LAYERS; j++) { //For each node in that layer, determine its output (so don't do this for bias nodes on end) for (int k = 0; k < num_hidden_nodes; k++) { double net = 0; if (DEBUG_BP) cout << "NET: " << net << endl; //If we're on the first hidden layer, get outputs and weights from input layer if (j == 0) { //Get output and weight from each node below that points to this one for (int l = 0; l < num_features + 1; l++) { if (DEBUG_BP) cout << "Inputs' outputs: " << input_nodes[l]->get_output() << ", inputs' weights for that output: " << input_nodes[l]->get_weight(k) << endl; net += input_nodes[l]->get_output() * input_nodes[l]->get_weight(k); } } else { //Get output and weight from each node in hidden layer below for (int l = 0; l < num_hidden_nodes + 1; l++) { net += hidden_nodes_matrix[j - 1][l]->get_output() * hidden_nodes_matrix[j - 1][l]->get_weight(k); } } double output = 1 / (1 + pow(EULER_NUM,-net)); hidden_nodes_matrix[j][k]->set_output(output); if (DEBUG_BP) cout << "Net for hidden layer " << j << ", hidden node " << k << ": " << net << endl; if (DEBUG_BP) cout << "Its output: " << hidden_nodes_matrix[j][k]->get_output() << endl; } hidden_nodes_matrix[j][num_hidden_nodes]->set_output(1); //Bias node } //Set output nodes' outputs for (int j = 0; j < num_classes; j++) { double net = 0; //Get output and weights for each node in top-most layer of hidden nodes layer for (int l = 0; l < num_hidden_nodes + 1; l++) { net += hidden_nodes_matrix[NUM_HIDDEN_LAYERS - 1][l]->get_output() * hidden_nodes_matrix[NUM_HIDDEN_LAYERS - 1][l]->get_weight(j); } double output = 1 / (1 + pow(EULER_NUM,-net)); output_nodes[j]->set_output(output); } /*********************************** * Go down back toward input layer * ***********************************/ //Set small deltas for each output node for (int j = 0; j < num_classes; j++) { double target_output = (labels[i][0] == j) ? 1 : 0; double my_output = output_nodes[j]->get_output(); if (i == (num_instances - 1)) mean_squared_error += pow((target_output - my_output), 2); double small_delta = (target_output - my_output) * my_output * (1 - my_output); if (DEBUG_BP) { cout << "Target for output node " << j << ": " << target_output << endl; cout << "Current output for output node " << j << ": " << my_output << endl; cout << "Small delta for output node " << j << ": " << small_delta << endl; } if (INCLUDE_SMALL_DELTA_MOMENTUM) { small_delta += output_nodes[j]->get_previous_small_delta() * SMALL_DELTA_TERM; } output_nodes[j]->set_small_delta_weight(small_delta); } if (i == (num_instances - 1)) mean_squared_error = mean_squared_error / num_classes; //Set big delta and small delta for each node in each layer of hidden nodes for (int j = NUM_HIDDEN_LAYERS - 1; j >= 0; j--) { //For each node in this layer of hidden nodes, including bias, change big delta weight for (int k = 0; k < num_hidden_nodes + 1; k++) { Node* hidden_node = hidden_nodes_matrix[j][k]; //Set big delta for each weight it points up to //By adding momentum, we look to previous iteration's weight update to know how much to update this one for (int l = 0; l < hidden_node->get_num_output_weights(); l++) { double small_delta = 0; if (j == (NUM_HIDDEN_LAYERS - 1)) //if we're in last hidden layer, small delta we need is in output layer list small_delta = output_nodes[l]->get_small_delta_weight(); else small_delta = hidden_nodes_matrix[j + 1][l]->get_small_delta_weight(); //else get sdw from node above me in another hidden layer double big_delta = learning_rate * small_delta * hidden_node->get_output(); if (INCLUDE_MOMENTUM) big_delta += MOMENTUM_TERM * hidden_node->get_previous_big_delta_weight(l); if (DEBUG_BP) { cout << "Small delta for node " << l << " in layer above: " << small_delta << endl; cout << "Big delta for hidden node " << k << " in layer " << j << " to node " << l << " in layer above: " << big_delta << endl; } hidden_node->set_big_delta_weight(l, big_delta); } } //For each node in this layer, excluding bias, change small delta weight for (int k = 0; k < num_hidden_nodes; k++) { Node* hidden_node = hidden_nodes_matrix[j][k]; //And set this node's small delta for use by lower layers //(Could probably combine these for loops with above for loops, but want to maintain readability) if (DEBUG_BP) cout << "Now setting hidden node " << k << "'s small delta weight." << endl; double net = 0; for (int l = 0; l < hidden_node->get_num_output_weights(); l++) { double small_delta = 0; if (j == (NUM_HIDDEN_LAYERS - 1)) small_delta = output_nodes[l]->get_small_delta_weight(); else small_delta = hidden_nodes_matrix[j + 1][l]->get_small_delta_weight(); double weight_to_upper_node = hidden_node->get_weight(l); net += small_delta * weight_to_upper_node; if (DEBUG_BP) { cout << "Small delta: " << small_delta << endl; cout << "Weight to upper node " << l << ": " << weight_to_upper_node << endl; cout << "Net so far: " << net << endl; cout << "Having added " << l << " of " << hidden_node->get_num_output_weights() << endl; } } double my_output = hidden_node->get_output(); double small_delta = my_output * (1 - my_output) * net; if (INCLUDE_SMALL_DELTA_MOMENTUM) { small_delta += hidden_node->get_previous_small_delta() * SMALL_DELTA_TERM; } hidden_node->set_small_delta_weight(small_delta); if (DEBUG_BP) { cout << "Node " << k << "'s output: " << my_output << endl; cout << "Its small delta: " << small_delta << endl; } } } //Set big deltas for each node in input layer (including bias), that each points up to for (int j = 0; j < num_features + 1; j++) { Node* input_node = input_nodes[j]; if (DEBUG_BP) cout << "For input node " << j << ":" << endl; for (int l = 0; l < input_node->get_num_output_weights(); l++) { double small_delta = hidden_nodes_matrix[0][l]->get_small_delta_weight(); //from lowest layer of hidden nodes, hence the hard-coded 0 double big_delta = learning_rate * small_delta * input_node->get_output(); if (INCLUDE_MOMENTUM) big_delta += MOMENTUM_TERM * input_node->get_previous_big_delta_weight(l); input_node->set_big_delta_weight(l, big_delta); if (DEBUG_BP) { cout << "Small delta for higher node " << l << ": " << small_delta << endl; cout << "Big delta from current input node " << j << " to node " << l << " above: " << big_delta << endl; } } } /************************************* * Change weights (stochastic update) *************************************/ if (INCLUDE_SMALL_DELTA_MOMENTUM) { for (int j = 0; j < num_classes; j++) output_nodes[j]->remember_previous_small_delta_weight(); } //Change weights, remember delta weights for each input layer node and each node in each hidden layer for (int j = 0; j < num_features + 1; j++) { //+ 1 because do it for bias too input_nodes[j]->update_weights(); input_nodes[j]->remember_previous_weights(); input_nodes[j]->clear_delta_weights(); input_nodes[j]->remember_previous_small_delta_weight(); } for (int j = 0; j < NUM_HIDDEN_LAYERS; j++) { //+ 1 because do it for bias too for (int k = 0; k < num_hidden_nodes + 1; k++) { hidden_nodes_matrix[j][k]->update_weights(); hidden_nodes_matrix[j][k]->remember_previous_weights(); hidden_nodes_matrix[j][k]->clear_delta_weights(); hidden_nodes_matrix[j][k]->remember_previous_small_delta_weight(); } } //Do another instance } number_epochs_completed++; //Done with epoch, so check accuracy double training_accuracy = measureAccuracy(features, labels, false, NULL); //This is accuracy on training set (set passed in we're training on) double validation_accuracy = measureAccuracy(validation_features, validation_labels, false, NULL); //This is accuracy on validation set if (INFO_OUT) cout << number_epochs_completed << "," << training_accuracy << "," << validation_accuracy << "," << mean_squared_error << endl; //If we're doing better, update each weight in each node if (validation_accuracy > best_accuracy_so_far) { best_accuracy_so_far = validation_accuracy; number_without_improvement = 0; for (int j = 0; j < num_features + 1; j++) input_nodes[j]->update_best_weights(); for (int j = 0; j < NUM_HIDDEN_LAYERS; j++) { for (int k = 0; k < num_hidden_nodes + 1; k++) { hidden_nodes_matrix[j][k]->update_best_weights(); } } if (CHANGE_LEARNING_RATE) { learning_rate = learning_rate * LR_MULT; //experiment--we like the way we're going, so increas0 learning rate } } else number_without_improvement++; if (DEBUG_BP) cout << "Number without improvement: " << number_without_improvement << endl; } while (number_without_improvement < NON_IMPROVEMENT_THRESHOLD); //Now that we're finally done, make sure every node is using its best set of weights for (int j = 0; j < num_features + 1; j++) input_nodes[j]->use_best_weights(); for (int j = 0; j < NUM_HIDDEN_LAYERS; j++) { for (int k = 0; k < num_hidden_nodes + 1; k++) { hidden_nodes_matrix[j][k]->use_best_weights(); } } } virtual void predict(const std::vector<double>& features, std::vector<double>& labels) { //Local variables int num_features = features.size() - IGNORE_LAST_ATTRIBUTES; int num_hidden_nodes = num_features * NUM_HIDDEN_NODE_MULTIPLIER; vector<double> possible_outputs; //Go up toward input layer //Set inputs' outputs for (int i = 0; i < num_features; i++) { input_nodes[i]->set_output(features[i]); } input_nodes[num_features]->set_output(1); //Bias node //Set ouputs for each node in hidden layer based on nodes below it //For each hidden layer for (int i = 0; i < NUM_HIDDEN_LAYERS; i++) { //For each node in that layer, determine its output (so don't do this for bias nodes on end) for (int j = 0; j < num_hidden_nodes; j++) { double net = 0; //If we're on the first hidden layer, get outputs and weights from input layer if (i == 0) { //Get output and weight from each node below that points to this one for (int k = 0; k < num_features + 1; k++) { net += input_nodes[k]->get_output() * input_nodes[k]->get_weight(j); } } else { for (int k = 0; k < num_hidden_nodes + 1; k++) { //TODO changed j - 1 to i - 1 net += hidden_nodes_matrix[i - 1][k]->get_output() * hidden_nodes_matrix[i - 1][k]->get_weight(j); } } double output = 1 / (1 + pow(EULER_NUM,-net)); hidden_nodes_matrix[i][j]->set_output(output); } hidden_nodes_matrix[i][num_hidden_nodes]->set_output(1); //Bias node } //Set output nodes' outputs for (int i = 0; i < num_classes; i++) { double net = 0; //Get output and weights for each node in top-most layer of hidden nodes layer for (int j = 0; j < num_hidden_nodes + 1; j++) { net += hidden_nodes_matrix[NUM_HIDDEN_LAYERS - 1][j]->get_output() * hidden_nodes_matrix[NUM_HIDDEN_LAYERS - 1][j]->get_weight(i); } double output = 1 / (1 + pow(EULER_NUM,-net)); possible_outputs.push_back(output); } int index_of_largest = 0; for (int i = 0; i < num_classes; i++) { if (possible_outputs[i] > possible_outputs[index_of_largest]) index_of_largest = i; } labels[0] = index_of_largest; } }; #endif // BACKPROPAGATION_H
0e938cbb88366c9f53d60970d0f5e83485dc23b2
c73cb678b0ea515a098bd63aea4e4e8f3a173905
/Board.cpp
d3cf8a490327e96242b1c501f67bc1e83e96b867
[]
no_license
orahmad/Mancala
a50a1e7e76d5f2626ce32110fa7f3e7dc354189a
dd35e40f022c3378fba59e38da68288ca083a5ab
refs/heads/master
2020-11-28T13:57:14.653895
2019-12-24T00:17:45
2019-12-24T00:17:45
229,840,179
0
0
null
null
null
null
UTF-8
C++
false
false
7,266
cpp
Board.cpp
#include"Board.h" #include <vector> #include<iostream> using namespace std; int Board::hole::holes_beans() const { //returns the # of beans return number_beans; } void Board::hole::set_holes_beans(int num) { //sets the # of beans number_beans = num; } int Board::hole::enum_getter() const { //returns the correct side return definer; } Board::hole::hole(int number, Board::type whichOne) :number_beans(number), definer(whichOne) { //constructor that sets the private members accordingly } Board::hole::hole() { // default constructor for the hole class } Board::hole::hole(const hole& src) { number_beans = src.number_beans; definer = src.definer; } Board::Board(int nHoles, int nInitialBeansPerHole) { //board's constructor that just pushes back a new hole to the according hole number and side for (int i = 0; i < nHoles; i++) { vec.push_back(new hole(nInitialBeansPerHole, SOUTHHOLE)); } vec.push_back(new hole(0, SOUTHPOT)); for (int i = 0; i < nHoles; i++) { vec.push_back(new hole(nInitialBeansPerHole, NORTHHOLE)); } vec.push_back(new hole(0, NORTHPOT)); } Board::Board(const Board& src) { // this is just a simple copy constructor for (int i = 0;i < src.vec.size(); i++) { hole* n = src.vec[i]; vec.push_back(new hole(*n)); } } Board& Board::operator=(const Board& src) { // this is just an assignment operator for (int i = 0; i < src.vec.size(); i++) { hole* n = src.vec[i]; vec.push_back(new hole(*n)); } return *this; } int Board::holes() const { return (vec.size() - 2)/2; // we subtract two because of the two pots } int Board::beans(Side s, int hole) const { if (hole < 0 || hole > holes()) { return -1; } if (s == SOUTH) { if (hole == 0) { // if the hole is the south pot, then return accordingly for (int i = 0; i < vec.size(); i++) { if (vec[i]->enum_getter() == 2) { return vec[i]->holes_beans(); } } } return vec[hole - 1]->holes_beans(); // if it isn't the pot, then it returns the right hole } if (s == NORTH) { if (hole == 0) { // if the hole is the south pot, then return accordingly for (int i = 0; i < vec.size(); i++) { if (vec[i]->enum_getter() == 3) { return vec[i]->holes_beans(); } } } return vec[vec.size() - 1 - hole]->holes_beans(); // if it isn't the pot, then it returns the right hole } } int Board::beansInPlay(Side s) const { int counter = 0; if (s == SOUTH) { for (int i = 0; i < holes(); i++) { counter = counter + vec[i]->holes_beans(); } } if (s == NORTH) { for (int i = (holes() + 1); i < (vec.size()-1); i++) { counter = counter + vec[i]->holes_beans(); } } // in order to return the amount of the beans on the respected side, a counter is kept return counter; } int Board::totalBeans() const { int counter = 0; for (int i = 0; i < holes(); i++) { counter = counter + vec[i]->holes_beans(); } for (int i = (holes() + 1); i < (vec.size() - 1); i++) { counter = counter + vec[i]->holes_beans(); } for (int i = 0; i < vec.size(); i++) { if (vec[i]->enum_getter() == 2) { counter = counter + vec[i]->holes_beans(); } } for (int i = 0; i < vec.size(); i++) { if (vec[i]->enum_getter() == 3) { counter = counter + vec[i]->holes_beans(); } } return counter; } /*If the hole indicated by (s,hole) is empty or invalid or a pot, this function returns false without changing anything. Otherwise, it will return true after sowing the beans: the beans are removed from hole (s,hole) and sown counterclockwise, including s's pot if encountered, but skipping s's opponent's pot. The parameters endSide and endHole are set to the side and hole where the last bean was placed. (This function does not make captures or multiple turns; different Kalah variants have different rules about these issues, so dealing with them should not be the responsibility of the Board class.)*/ bool Board::sow(Side s, int hole, Side& endSide, int& endHole) { // sowing was very hard because we had to figure out how to deal with the end of the vector if (hole <= 0 || hole > holes()) { return false; } if (beans(s, hole) == 0) { return false; } int amount = beans(s, hole); int counter = 0; int separate = 0; if (s == SOUTH) { counter = hole - 1; vec[counter]->set_holes_beans(0); for (int i = hole; amount != 0; i++, amount--) { if (amount == 1) { if (vec[i]->enum_getter() == 0) { endSide = SOUTH; endHole = i + 1; } if (vec[i]->enum_getter() == 2) { endSide = SOUTH; endHole = 0; } if (vec[i]->enum_getter() == 1) { endSide = NORTH; endHole = vec.size() - 1 - i; } } if (vec[i]->enum_getter() != 3) { int separate = vec[i]->holes_beans(); vec[i]->set_holes_beans(separate + 1); } else { amount++; i = -1; } } } if (s == NORTH) { counter = vec.size() - 1 - hole; vec[counter]->set_holes_beans(0); for (int i = counter + 1; amount != 0; i++, amount--) { if (amount == 1) { if (vec[i]->enum_getter() == 0) { endSide = SOUTH; endHole = i + 1; } if (vec[i]->enum_getter() == 1) { endSide = NORTH; endHole = vec.size() - 1 - i; } if (vec[i]->enum_getter() == 3) { endSide = NORTH; endHole = 0; } } if (vec[i]->enum_getter() != 3 && vec[i]->enum_getter() != 2) { int separate = vec[i]->holes_beans(); vec[i]->set_holes_beans(separate + 1); } else if (vec[i]->enum_getter() == 3) { int separate = vec[i]->holes_beans(); vec[i]->set_holes_beans(separate + 1); i = -1; } else { amount++; } } } return true; } bool Board::moveToPot(Side s, int hole, Side potOwner) { if (hole <= 0 || hole > holes()) { return false; } int counter = 0; int amount = 0; counter = beans(s, hole); if (potOwner == SOUTH) { amount = vec[holes()]->holes_beans(); vec[holes()]->set_holes_beans(amount + counter); if (s == SOUTH) { vec[hole - 1]->set_holes_beans(0); } else { vec[vec.size() - 1 - hole]->set_holes_beans(0); } } else { amount = vec[vec.size() - 1]->holes_beans(); vec[vec.size() - 1]->set_holes_beans(amount + counter); if (s == SOUTH) { vec[hole - 1]->set_holes_beans(0); } else { vec[vec.size() - 1 - hole]->set_holes_beans(0); } } return true; } bool Board::setBeans(Side s, int hole, int beans) { if (hole < 0 || hole > holes() || beans < 0) { return false; } if (s == SOUTH) { if (hole == 0) { vec[holes()]->set_holes_beans(beans); } vec[hole - 1]->set_holes_beans(beans); } if (s == NORTH) { if (hole == 0) { vec[vec.size() - 1]->set_holes_beans(beans); } vec[vec.size() - 1 - hole]->set_holes_beans(beans); } return true; } Board::~Board() { for (int i = 0; i < vec.size(); i++) { delete vec[i]; } }
d1533e14a5af18e810d5498231510ba1b90c60a8
85139670ac53c5df7484c7d3eb1d1284502a4a77
/client_app/evaluate_result_dlg.cpp
93dd2998a0bb5bd47c6457be387cebf5bab05f8b
[]
no_license
chinarustin/aep
f9872a1d4e82cad38d50d46f370ce0513280f40e
6bbe1b634812528c3a4a696335174ae51846d467
refs/heads/master
2020-12-27T15:17:18.706709
2014-09-27T13:50:56
2014-09-27T13:50:56
null
0
0
null
null
null
null
GB18030
C++
false
false
8,347
cpp
evaluate_result_dlg.cpp
// evaluate_result_dlg.cpp : implementation file // #include "stdafx.h" #include "client_app.h" #include "evaluate_result_dlg.h" #include "utility.h" // CEvaluateResultDlg dialog IMPLEMENT_DYNAMIC(CEvaluateResultDlg, CDialog) CEvaluateResultDlg::CEvaluateResultDlg(const vector<AlgorithmRuntime> &algorithms, const vector<AlgorithmRuntimeResult> &algorithmResults, const vector<Factor> &factors, const vector<FactorResult> &factorResults, CWnd* pParent) : CDialog(CEvaluateResultDlg::IDD, pParent) , m_Algorithms(algorithms) , m_AlgorithmResults(algorithmResults) , m_Factors(factors) , m_FactorResults(factorResults) , m_Initialized(false) , m_PadX(0) , m_PadY(0) , m_Engine(0) { } CEvaluateResultDlg::~CEvaluateResultDlg() { if (m_Engine) { engClose(m_Engine); } } void CEvaluateResultDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_ALGORITHM_RUNTIME_LIST, m_AlgorithmRuntimeList); DDX_Control(pDX, IDC_FACTOR_LIST, m_FactorList); } BEGIN_MESSAGE_MAP(CEvaluateResultDlg, CDialog) ON_NOTIFY(LVN_ITEMACTIVATE, IDC_FACTOR_LIST, &CEvaluateResultDlg::OnLvnItemActivateFactorList) ON_WM_SIZE() END_MESSAGE_MAP() // CEvaluateResultDlg message handlers BOOL CEvaluateResultDlg::OnInitDialog() { CDialog::OnInitDialog(); if (!(m_Engine = engOpen(NULL))) { Utility::PromptErrorMessage(TEXT("Matlab引擎初始化失败, 绘图功能将不可用.")); } else { engSetVisible(m_Engine, false); } RECT rect; GetWindowRect(&rect); ScreenToClient(&rect); int right = rect.right; int bottom = rect.bottom; GetDlgItem(IDOK)->GetWindowRect(&rect); ScreenToClient(&rect); m_PadX = right - rect.right; m_PadY = bottom - rect.bottom; Resize(); LONG lStyle; lStyle = GetWindowLong(m_AlgorithmRuntimeList.m_hWnd, GWL_STYLE); lStyle &= ~LVS_TYPEMASK; lStyle |= LVS_REPORT; SetWindowLong(m_AlgorithmRuntimeList.m_hWnd, GWL_STYLE, lStyle); DWORD dwStyle = m_AlgorithmRuntimeList.GetExtendedStyle(); dwStyle |= LVS_EX_FULLROWSELECT; dwStyle |= LVS_EX_GRIDLINES; m_AlgorithmRuntimeList.SetExtendedStyle(dwStyle); m_AlgorithmRuntimeList.InsertColumn(0,_T("算法名称"),LVCFMT_CENTER, 50); m_AlgorithmRuntimeList.InsertColumn(1,_T("迭代次数"),LVCFMT_CENTER, 50); m_AlgorithmRuntimeList.InsertColumn(2,_T("CPU占用率"),LVCFMT_CENTER, 50); m_AlgorithmRuntimeList.InsertColumn(3,_T("内存使用"),LVCFMT_CENTER, 100); m_AlgorithmRuntimeList.InsertColumn(4,_T("运行时间"),LVCFMT_CENTER, 100); m_AlgorithmRuntimeList.EnableWindow(TRUE); for (UINT32 i = 0; i < m_Algorithms.size(); ++i) { AddAlgorithm(m_Algorithms[i], m_AlgorithmResults[i]); } lStyle = GetWindowLong(m_FactorList.m_hWnd, GWL_STYLE); lStyle &= ~LVS_TYPEMASK; lStyle |= LVS_REPORT; SetWindowLong(m_FactorList.m_hWnd, GWL_STYLE, lStyle); dwStyle = m_FactorList.GetExtendedStyle(); dwStyle |= LVS_EX_FULLROWSELECT; dwStyle |= LVS_EX_GRIDLINES; m_FactorList.SetExtendedStyle(dwStyle); m_FactorList.InsertColumn(0,_T("指标名称"),LVCFMT_CENTER, 60); m_FactorList.InsertColumn(1,_T("指标值"),LVCFMT_CENTER, 60); for (UINT32 i = 0; i < m_Factors.size(); ++i) { AddFactor(m_FactorResults[i]); } m_Initialized = true; return TRUE; } void CEvaluateResultDlg::AddAlgorithm(const AlgorithmRuntime &algorithm, const AlgorithmRuntimeResult &result) { int n = m_AlgorithmRuntimeList.GetItemCount(); m_AlgorithmRuntimeList.InsertItem(n, algorithm.Name.c_str()); for (UINT32 i = 0; i < result.CpuPercentage.size(); ++i) { if (i > 0) { m_AlgorithmRuntimeList.InsertItem(n + i, TEXT("")); } CString temp; temp = TEXT(""); temp.AppendFormat(TEXT("%u"), i + 1); m_AlgorithmRuntimeList.SetItemText(n + i, 1, temp); temp = TEXT(""); temp.AppendFormat(TEXT("%u%%"), result.CpuPercentage[i]); m_AlgorithmRuntimeList.SetItemText(n + i, 2, temp); temp = TEXT(""); temp.AppendFormat(TEXT("%u KB"), result.MemoryUsageKB[i]); m_AlgorithmRuntimeList.SetItemText(n + i, 3, temp); temp = TEXT(""); temp.AppendFormat(TEXT("%llu NS"), result.NS[i]); m_AlgorithmRuntimeList.SetItemText(n + i, 4, temp); } } void CEvaluateResultDlg::AddFactor(const FactorResult &result) { int row = m_FactorList.GetItemCount(); m_FactorList.InsertItem(row, result.Name.c_str()); if (result.Result != NULL) { UINT32 m = mxGetM(result.Result); UINT32 n = mxGetN(result.Result); if (mxIsChar(result.Result)) { char buf[256]; mxGetString(result.Result, buf, 256); CString temp(buf); m_FactorList.SetItemText(row, 1, temp); } else if (mxIsDouble(result.Result)) { if (m == 1 && n == 1) { double *p = mxGetPr(result.Result); CString temp; temp.AppendFormat(TEXT("%f"), *p); m_FactorList.SetItemText(row, 1, temp); } else { CString temp(TEXT("双击显示曲线")); m_FactorList.SetItemText(row, 1, temp); } } } } void CEvaluateResultDlg::DrawFactor(const Factor &factor, const FactorResult &factorResult) { mwSize size = factor.AlgorithmOutputEnd - factor.AlgorithmOutputStart + 1; Array *t = mxCreateDoubleMatrix(1, size, mxREAL); double *p = mxGetPr(t); for (UINT32 i = factor.AlgorithmOutputStart; i <= factor.AlgorithmOutputEnd; ++i) { p[i - factor.AlgorithmOutputStart] = i; } engPutVariable(m_Engine, "t", t); engPutVariable(m_Engine, "factor", factorResult.Result); engEvalString(m_Engine, "plot(t, factor);"); engEvalString(m_Engine, "xlabel('t');"); engEvalString(m_Engine, "ylabel('factor');"); mxDestroyArray(t); } void CEvaluateResultDlg::OnLvnItemActivateFactorList(NMHDR *pNMHDR, LRESULT *pResult) { LPNMITEMACTIVATE pNMIA = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR); // TODO: Add your control notification handler code here if (pNMIA == NULL) { return; } const Factor &factor = m_Factors[pNMIA->iItem]; const FactorResult &result = m_FactorResults[pNMIA->iItem]; if (result.Result != NULL && mxIsDouble(result.Result)) { UINT32 m = mxGetM(result.Result); UINT32 n = mxGetN(result.Result); if (m == 1 && n == 1) { *pResult = 0; return; } } DrawFactor(factor, result); *pResult = 0; } void CEvaluateResultDlg::Resize() { RECT rect; GetDlgItem(IDC_ALGORITHM_RUNTIME_RESULT_GROUP)->GetWindowRect(&rect); ScreenToClient(&rect); int top = rect.top; int left = rect.left; GetDlgItem(IDOK)->GetWindowRect(&rect); ScreenToClient(&rect); int bottom = rect.top - m_PadY; int right = rect.right; int width = (right - left - m_PadX) / 2; int height = bottom - top; GetDlgItem(IDC_ALGORITHM_RUNTIME_RESULT_GROUP)->MoveWindow(left, top, width, height); m_AlgorithmRuntimeList.MoveWindow(left + m_PadX, top + m_PadY, width - m_PadX * 2, height - m_PadY * 2); GetDlgItem(IDC_FACTOR_GROUP)->MoveWindow(right - width, top, width, height); m_FactorList.MoveWindow(right - width + m_PadX, top + m_PadY, width - m_PadX * 2, height - m_PadY * 2); } void CEvaluateResultDlg::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); // TODO: 在此处添加消息处理程序代码 if (m_Initialized) { RECT rect; GetWindowRect(&rect); ScreenToClient(&rect); int right = rect.right - m_PadX; int bottom = rect.bottom - m_PadY; GetDlgItem(IDOK)->GetWindowRect(&rect); ScreenToClient(&rect); int width = rect.right - rect.left; int height = rect.bottom - rect.top; GetDlgItem(IDOK)->MoveWindow(right - width, bottom - height, width, height); Resize(); } }
6a61753a9d782e18008a3062ea51afa9cb10d5ab
e79b3990bc9c13117572fe4c39277b187b37bff2
/include/RE/I/ImageSpaceModifierInstance.h
92bd4a183f14238ca054557c20e0b969fbcf13b4
[ "MIT" ]
permissive
Ryan-rsm-McKenzie/CommonLibSSE
669e36cd643ea9dcc97c8e147d10ee7f6eebb8df
3282565a2c86535036f5a556758fb1cf8ab85225
refs/heads/master
2023-08-07T15:02:02.476156
2023-07-20T11:52:36
2023-07-20T12:41:44
158,496,181
178
93
MIT
2023-07-20T12:41:45
2018-11-21T05:36:24
C++
UTF-8
C++
false
false
775
h
ImageSpaceModifierInstance.h
#pragma once #include "RE/N/NiObject.h" #include "RE/N/NiSmartPointer.h" namespace RE { class NiAVObject; class ImageSpaceModifierInstance : NiObject { public: inline static constexpr auto RTTI = RTTI_ImageSpaceModifierInstance; ~ImageSpaceModifierInstance() override; // 00 // add virtual void Unk_25(void); // 25 - { return 0; } virtual void Unk_26(void) = 0; // 26 virtual void Unk_27(void); // 27 - { return 0; } virtual void Unk_28(void) = 0; // 28 // members std::uint32_t unk10; // 10 float strength; // 14 NiPointer<NiAVObject> target; // 18 float age; // 20 std::uint32_t flags; // 24 }; static_assert(sizeof(ImageSpaceModifierInstance) == 0x28); }
6fafaaf8e97a3756af36b244666eb6c749606ed2
1689e784646400eaf24a3cfeb72b273625000493
/include/DetectorMessenger.hh
830f0b96dcc06d8e13be28252135195da86f55d3
[]
no_license
Garypenman/APEXG4MC
40e1fec1cacdfd2cb34692c00c204b60d4c393eb
a70a74fedf6f16590f7e5cfd75ec0dfdbf2620d0
refs/heads/master
2023-07-25T16:47:03.289759
2021-09-06T21:15:03
2021-09-06T21:15:03
390,477,663
0
3
null
2021-08-08T19:39:13
2021-07-28T19:24:23
C++
UTF-8
C++
false
false
1,270
hh
DetectorMessenger.hh
#ifndef DetectorMessenger_h #define DetectorMessenger_h 1 #include "G4UImessenger.hh" #include "globals.hh" //--------------------------------------------------------------------------- class DetectorConstruction; class G4UIdirectory; class G4UIcommand; class G4UIcmdWithADouble; class G4UIcmdWithAString; class G4UIcmdWithABool; //--------------------------------------------------------------------------- class DetectorMessenger: public G4UImessenger { public: DetectorMessenger(DetectorConstruction*); ~DetectorMessenger(); void SetNewValue(G4UIcommand*, G4String); private: DetectorConstruction* fDetector; G4UIdirectory* fDetectorDir; G4UIcmdWithADouble* fHRSAngleCmd; G4UIcmdWithADouble* fHRSMomCmd; G4UIcmdWithADouble* fDistTPCmd; G4UIcmdWithADouble* fDistPQ1Cmd; G4UIcmdWithADouble* fSepScaleCmd; G4UIcmdWithAString* fFieldMapCmd; G4UIcmdWithABool* fSieveOnCmd; G4UIcmdWithABool* fSieveRealCmd; G4UIcmdWithADouble* fSieveAngleCmd; G4UIcmdWithAString* fTargetCmd; G4UIcommand* fUpdateCmd; }; #endif //---------------------------------------------------------------------------
359f4f1c68acd37d06ed00e0b849dd2388931bb2
b551ee4a22731025dd134494691cd63a2c796932
/GameObject.h
f71a5d75c1b1ace43a8aeb7a59f1969301948e64
[]
no_license
marktilbrook/directX-game
71badad29a85eeb0e51eff494a2687a3da0bf655
e9db343b8e0f98de843989c71aaa7de8534f27e7
refs/heads/main
2023-03-25T04:29:55.638872
2021-03-11T04:51:25
2021-03-11T04:51:25
342,120,040
0
0
null
null
null
null
UTF-8
C++
false
false
424
h
GameObject.h
#pragma once #include "vector2D.h" #include "mydrawengine.h" #include "gametimer.h" #include "myinputs.h" class GameObject { protected: Vector2D m_position; float m_angle; bool m_isActive; private: PictureIndex m_image; protected: void LoadImage(const wchar_t* image); public: virtual void Render(); virtual void Update(float frametime) = 0; Vector2D GetCurrentPosition(); };
b11c498446dce982dd1c35e88a41bc719e3b7d7a
912ec9f6e968b22f2ac77ec6084645386b70bea1
/trunk/model/EntityInstance.cpp
e96fe3f1c9c7ee1dbdf2483c136b413643453a45
[]
no_license
cpzhang/zen
9156413d93f7dc9c5b48b9bd1e5cdb5a5b1657da
6d6e06278aa37eb279e05c9097fd964bf476c939
refs/heads/master
2016-09-05T15:24:06.565446
2013-03-19T12:29:28
2013-03-19T12:29:28
7,439,357
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
11,604
cpp
EntityInstance.cpp
#include "EntityInstance.h" #include "tinyXML2/tinyxml2.h" #include "misc/FileSystem.h" #include "Entity.h" #include "Skeleton.h" #include "Skin.h" #include "ModelResManager.h" #include "Material.h" #include "render/Fx.h" #include "render/FxManager.h" #include "render/rendercontext.h" #include "ParticleEmitter.h" #include "font/FontManager.h" #include "font/FreeType.h" #include "misc/Logger.h" void EntityInstance::render() { getRenderContex()->getDxDevice()->SetSamplerState(0, D3DSAMP_MAGFILTER, D3DTEXF_LINEAR); getRenderContex()->getDxDevice()->SetSamplerState(0, D3DSAMP_MINFILTER, D3DTEXF_LINEAR); for (size_t i = 0; i != Parts_.size(); ++i) { Mesh* ms = Meshes_[i]; Material* tl = Materials_[i]; if (NULL == ms || NULL == tl || NULL == tl->getFx() || NULL == tl->getFx()->getDxEffect()) { continue; } ID3DXEffect* ef = tl->getFx()->getDxEffect(); // if (getFxManager()->getShaderType() == eFx_Shader0) { ef->SetTechnique("T0"); } else { ef->SetTechnique("T2"); } //Handles provide an efficient means for referencing effect parameters, techniques, passes, and annotations with an effect. D3DXHANDLE p = ef->GetParameterByName(NULL,Fx::getProjectionMatrixName()); D3DXHANDLE v = ef->GetParameterByName(NULL,Fx::getViewMatrixName()); D3DXHANDLE w = ef->GetParameterByName(NULL,Fx::getWorldMatrixName()); // UINT passes = 0; ef->Begin(&passes, D3DXFX_DONOTSAVESTATE); if (passes > 0) { if (v) { ef->SetMatrix(v, &getRenderContex()->getViewMatrix()); } if (p) { ef->SetMatrix(p, &getRenderContex()->getProjectionMatrix()); } if (w) { Matrix m = Matrix::Identity; m.make(Position_, Scale_, AngleY_); ef->SetMatrix(w, &m); } // std::vector<Matrix> matrices; if(SkinCurrent_ && !MatricesSkin_.empty()) { for(BoneIDReferenceMap::iterator it = ms->_bones.begin(); it != ms->_bones.end(); ++it) { matrices.push_back(MatricesSkin_[it->first]); } } else { for(BoneIDReferenceMap::iterator it = ms->_bones.begin(); it != ms->_bones.end(); ++it) { matrices.push_back(Matrix::Identity); } } tl->apply(MatricesMaterial_[i], ColorsCurrent_[i]); if (getFxManager()->getShaderType() == eFx_Shader0) { ef->CommitChanges(); for (int p = 0; p != passes; ++p) { ef->BeginPass(p); ms->render(matrices); ef->EndPass(); } } else { if (!matrices.empty()) { ef->SetMatrixArray("gSkinPalette", &matrices[0], matrices.size()); } ef->CommitChanges(); for (int p = 0; p != passes; ++p) { ef->BeginPass(p); ms->render(); ef->EndPass(); } } tl->cancel(); } ef->End(); } // getRenderContex()->getDxDevice()->SetVertexShader(NULL); getRenderContex()->getDxDevice()->SetPixelShader(NULL); for (size_t i = 0; i != Particles_.size(); ++i) { ParticleCluster& c = Particles_[i]; c.render(); } } bool EntityInstance::create( const tstring& resourceId ) { // Entity_ = ModelResManager::getInstance()->get<Entity>(resourceId); Entity_->addReference(); FileName_ = resourceId; for (size_t i = 0; i != Entity_->getPartNumber(); ++i) { Part* p = ModelResManager::getInstance()->get<Part>(Entity_->getPart(i)); p->addReference(); Parts_.push_back(p); // Mesh* m = ModelResManager::getInstance()->get<Mesh>(p->getMesh()); m->addReference(); Meshes_.push_back(m); // BoundingBox* bb = m->getAABB(); BBoxOrigional_.addBounds(bb->min_); BBoxOrigional_.addBounds(bb->max_); // Material* t = ModelResManager::getInstance()->get<Material>(p->getMaterial()); t->addReference(); Materials_.push_back(t); } // Skeleton_ = ModelResManager::getInstance()->get<Skeleton>(Entity_->getSkeleton()); Skeleton_->addReference(); // Angles_.resize(Materials_.size()); AnglesCurrent_.resize(Materials_.size(), 0.0f); Us_.resize(Materials_.size()); UsCurrent_.resize(Materials_.size(), 0.0f); Vs_.resize(Materials_.size()); VsCurrent_.resize(Materials_.size(), 0.0f); Alphas_.resize(Materials_.size()); AnglesCurrent_.resize(Materials_.size(), 1.0f); Colors_.resize(Materials_.size()); ColorsCurrent_.resize(Materials_.size(), Vector4::One); // Rows_.resize(Materials_.size(), 1.0f); Cols_.resize(Materials_.size(), 1.0f); UVSequenceTimer_.resize(Materials_.size(), 0.0f); // MatricesMaterial_.resize(Materials_.size(), Matrix::Identity); // for (size_t i = 0; i != Materials_.size(); ++i) { Material* m = Materials_[i]; Angles_[i].init(&m->RotationKFs_, 0.0f); Us_[i].init(&m->FlowUKFs_, 0.0f); Vs_[i].init(&m->FlowVKFs_, 0.0f); Alphas_[i].init(&m->AlphaKFs_, 1.0f); Colors_[i].init(&m->ColorKFs_, 1.0f); } // for (size_t i = 0; i != Entity_->getParticleNumber(); ++i) { ParticleEmitter* p = ModelResManager::getInstance()->get<ParticleEmitter>(Entity_->getParticleName(i)); p->addReference(); ParticleCluster c; c.create(p); if (!Skeleton_->_matrices.empty()) { c.setBoneID(Skeleton_->getBoneID(Entity_->getParticleBoneName(i))); } Particles_.push_back(c); } return true; } void EntityInstance::destroy() { if (Entity_) { Entity_->removeReference(); Entity_ = NULL; } // if (Skeleton_) { Skeleton_->removeReference(); Skeleton_ = NULL; } // for (size_t i = 0; i != Parts_.size(); ++i) { Part* p = Parts_[i]; p->removeReference(); Meshes_[i]->removeReference(); Materials_[i]->removeReference(); Angles_[i].clear(); Us_[i].clear(); Vs_[i].clear(); Alphas_[i].clear(); Colors_[i].clear(); } Parts_.clear(); Meshes_.clear(); Materials_.clear(); // UVSequenceTimer_.clear(); Cols_.clear(); Rows_.clear(); // if (SkinCurrent_) { SkinCurrent_->removeReference(); SkinCurrent_ = NULL; } // for (size_t i = 0; i != Particles_.size(); ++i) { Particles_[i].getEmitter()->removeReference(); } Particles_.clear(); } void EntityInstance::setAnimation( const tstring& resourceId, bool loop) { if (NULL == Skeleton_ || Skeleton_->isNullObject()) { return; } if (Skeleton_) { if (SkinCurrent_) { SkinCurrent_->removeReference(); } const tstring& res = Skeleton_->getSkin(resourceId, AnimationTime_); if (!res.empty()) { AnimationTime_.loop = loop; SkinCurrent_ = ModelResManager::getInstance()->get<Skin>(res); SkinCurrent_->addReference(); } } } void EntityInstance::update( float delta ) { delta *= Speed_; //skin if (SkinCurrent_) { AnimationTime_.update(delta); /*{ if (FontManager::getPointer()->getFont()) { std::ostringstream ss; ss<<"begin = "<<AnimationTime_.start<<std::endl; ss<<"end = "<<AnimationTime_.end<<std::endl; ss<<"current = "<<AnimationTime_.current<<std::endl; FontManager::getPointer()->getFont()->render(Vector2(10, 30), Vector4(1, 0, 0, 1), ss.str()); } }*/ Skeleton_->update(AnimationTime_, SkinCurrent_); // MatricesSkin_.clear(); MatricesSkin_.resize(Skeleton_->_matrices.size()); if (!Skeleton_->_matrices.empty()) { memcpy(&MatricesSkin_[0], &Skeleton_->_matrices[0], Skeleton_->_matrices.size() * sizeof(Matrix)); /*for (size_t i = 0; i != MatricesSkin_.size(); ++i) { Matrix& m = MatricesSkin_[i]; std::ostringstream ss; ss<<"current = "<<AnimationTime_.current<<"</br>"; ss<<m[0][0]<<" "<<m[0][1]<<" "<<m[0][2]<<" "<<m[0][3]<<"</br>"; ss<<m[1][0]<<" "<<m[1][1]<<" "<<m[1][2]<<" "<<m[1][3]<<"</br>"; ss<<m[2][0]<<" "<<m[2][1]<<" "<<m[2][2]<<" "<<m[2][3]<<"</br>"; ss<<m[3][0]<<" "<<m[3][1]<<" "<<m[3][2]<<" "<<m[3][3]<<"</br>"; if (m[3][1] > 2000) { breakable; } Record(ss); }*/ } } //material updateMaterial_(delta); // // for (size_t i = 0; i != Particles_.size(); ++i) { ParticleCluster& c = Particles_[i]; if (Skeleton_->_matrices.empty()) { c.update(delta, Matrix::Identity); } else { c.update(delta, Skeleton_->_matricesFull[c.getBoneID()]); } } } void EntityInstance::updateMaterial_( float delta ) { // for (size_t i = 0; i != Materials_.size(); ++i) { Material* tl = Materials_[i]; if (NULL == tl) { continue; } // Matrix m = Matrix::Identity; if (tl->mCols > 1 || tl->mRows > 1) { UVSequenceTimer_[i] += delta; if (UVSequenceTimer_[i] >= tl->mChangeInterval) { UVSequenceTimer_[i] = 0.0f; switch(tl->mChangeStyle) { case 0: { Rows_[i]++; if (Rows_[i] >= tl->mRows) { Rows_[i] = 0; Cols_[i]++; } if (Cols_[i] >= tl->mCols) { Cols_[i] = 0; } }break; case 1: { }break; } } // float su = 1.0f / tl->mRows; float sv = 1.0f / tl->mCols; m._11 = su; m._22 = sv; m._31 = su * Rows_[i]; m._32 = sv * Cols_[i]; MatricesMaterial_[i] = m; } else if(!Angles_[i].empty() || !Us_[i].empty() || !Vs_[i].empty()) { { Angles_[i].update(delta); AnglesCurrent_[i] += 0.0001 * delta * Angles_[i].getValue(); float c = cos(AnglesCurrent_[i]); float s = sin(AnglesCurrent_[i]); m._11 = c;m._12 = s; m._12 = -s;m._22 = c; } { Us_[i].update(delta); UsCurrent_[i] += 0.0001 * delta * Us_[i].getValue(); } { Vs_[i].update(delta); VsCurrent_[i] += 0.0001 * delta * Vs_[i].getValue(); } Matrix n = Matrix::Identity; n._31 = -0.5f;n._32 = -0.5f; Matrix ni = Matrix::Identity; ni._31 = 0.5f + UsCurrent_[i]; ni._32 = 0.5f + VsCurrent_[i]; MatricesMaterial_[i] = n * m * ni; } // ColorsCurrent_[i] = Vector4::One; if(!Alphas_[i].empty()){ Alphas_[i].update(delta); ColorsCurrent_[i].w = Alphas_[i].getValue(); } if(!Colors_[i].empty()){ Colors_[i].update(delta); Vector3 c = Colors_[i].getValue(); ColorsCurrent_[i].x = c.x; ColorsCurrent_[i].y = c.y; ColorsCurrent_[i].z = c.z; } } } void EntityInstance::setSpeed( float s ) { Speed_ = s; } void EntityInstance::renderImpT0() { } void EntityInstance::renderImpT2() { } void EntityInstance::setPosition( const Vector3& p ) { Position_ = p; updateBoundingBox_(); } void EntityInstance::rotateY( float p ) { AngleY_ = p; updateBoundingBox_(); } void EntityInstance::setScale( const Vector3& p ) { Scale_ = p; updateBoundingBox_(); } EntityInstance* EntityInstance::clone() const { EntityInstance* e = new EntityInstance; e->create(FileName_); return e; } void EntityInstance::release() { destroy(); delete this; } Skeleton* EntityInstance::getSkeleton() { return Skeleton_; } std::string EntityInstance::getResId() const { return FileName_; } Vector3 EntityInstance::getPosition() const { return Position_; } Vector3 EntityInstance::getScale() const { return Scale_; } void EntityInstance::nmAddObj( std::vector<Vector3>& vertices, std::vector<Vector3Int>& indices ) { Matrix m = Matrix::Identity; m.make(Position_, Scale_, AngleY_); for (size_t i = 0; i != Parts_.size(); ++i) { Mesh* ms = Meshes_[i]; if(ms) { ms->nmAddObj(vertices, indices, m); } } } bool EntityInstance::isPicking(const Ray& r) const { //´ÖÂÔÅжϣ¬AABB if (!BBox_.intersectsRay(r)) { return false; } //¾«×¼ÅжÏ,ÖðÈý½ÇÐÎ return true; } void EntityInstance::updateBoundingBox_() { Matrix m = Matrix::Identity; m.make(Position_, Scale_, AngleY_); BBox_.min_ = m.applyVector(BBoxOrigional_.min_); BBox_.max_ = m.applyVector(BBoxOrigional_.max_); } void EntityInstance::renderAABB(u32 color) { Matrix m = Matrix::Identity; m.make(Position_, Scale_, AngleY_); BBoxOrigional_.render(m, color); } Create_Singleton_Imp(EntityInstanceManager, ApiModel_)
48f33acbb3372b704c34a24ba79cfe18e38c268a
c980b5a13a0b1e7110bff5dab84e5d63111eaab5
/RCBot/RCBot.h
7218c07f1628a664446475fb3140e30b46b511bd
[ "MIT" ]
permissive
MindiyaCreations/RCBot_v1
4611489da65a46f80425ebe1af6bfa20f45f7daf
144d9a9a680477a453ac244e06346b0a191fc333
refs/heads/master
2022-07-28T09:08:44.702634
2022-07-06T09:55:53
2022-07-06T09:55:53
179,781,231
0
0
null
null
null
null
UTF-8
C++
false
false
2,636
h
RCBot.h
/* RCBot.h - Library for RCBot. Created by Mindiya Karunasinghe, April 13, 2019. Private library */ #ifndef RCBot_h #define RCBot_h #include "Arduino.h" #include "NewPing.h" class RCBot { public: void setMotor(int A1,int A2,int C1,int C2);//Left Plus/Left Minus/Right Plus/Right Minus void setMotors(int A1,int A2,int C1,int C2,int E1,int E2);//Left Plus/Left Minus/Right Plus/Right Minus/Left PWM/Right PWM void setSensor(int s1,int s2,int s3,int s4,int s5,int s6,int s7,int s8);//Left Sensor to Right Sensor void setLineColour(bool color);//Black = 1/White = 0 void setMotorSpeed(int max1,int max2,int min1,int min2,int norm1,int norm2);//Max L/Max R/Min L/Min R/Normal L/Normal R int GetLineError();//int Get error -2/+1 void setPID(float p,float i,float d);//P,I,D values void Forward(int time);//Go Forward until the time ends in milliseconds void Backward(int time);//Go Backward until the time ends in milliseconds void Right(int time);//Turn Right until the time ends in milliseconds void Left(int time);//Turn Left until the time ends in milliseconds void Stop();//Stop Moving long GetLine();//Get Line like 10001100 void LineFollow();//Line Follow void ForwardUntilAllBlack();//Go Forward until finds line void BackwardUntilAllBlack();//Go Backward until finds line void ForwardUntilAllWhite();//Go Forward until the all of the line is missing void BackwardUntilAllWhite();//Go Backward until the all of the line is missing void RightCorretlyToLine();//Turn Right until the line is found void LeftCorrectlyToLine();//Turn Left until the line is found void SonarSet(int trigL,int trigR,int echoL,int echoR,int error,float propotional,int zero);//trigL = pin of trig Left sensor//trigR = pin of trig Right sensor//echoL = pin of echo Left sensor//echoR = pin of echo Right sensor int SonarRaw(int i);//i == 0 shows left sensor//i == 1 shows right sensor void WallFollow(bool right);//Wall follow //if wall following right wall = true//if wall following left wall private: int LP,LM,RP,RM,Enable1,Enable2; int MaxL,MaxR,MinL,MinR,NormalL,NormalR; bool motorType; int S1,S2,S3,S4,S5,S6,S7,S8; bool LineBlack; int Threshold; float P,I,D; int Errors,PID,prevErrors; int Error; long LinePos; void run(int M1,int M2,int M3,int M4,int M5,int M6);//Motor Left Plus/Motor Left Minus/Motor Right Plus/Motor Right Minus/Left PWM/Right PWM unsigned long prevTime,Time; int SpeedL,SpeedR; int ErrorSonar,ErrorCurrentSonar,SonarP,NoSonar; int TrigL,TrigR,EchoR,EchoL; }; #endif
b81782a8fb30550089d4048100a47f99982fac54
8ce2ac605bf657e24dbb47ac439f90ec36bbf48f
/batched.hpp
e5eadf133af7f130705610b19e9e52fdaf1f643e
[ "BSD-2-Clause" ]
permissive
ryanhaining/cppitertools
b8bbf1c0fedad7c0b48b7c9b97b6cb6b686a1a22
492c15aab96f4ca3938a6b734d6a08cb7feea75a
refs/heads/master
2023-08-28T13:23:57.922416
2023-07-04T03:37:50
2023-07-04T03:37:50
12,811,614
1,200
131
BSD-2-Clause
2023-06-09T21:04:28
2013-09-13T14:37:03
C++
UTF-8
C++
false
false
4,437
hpp
batched.hpp
#ifndef ITER_BATCHED_HPP_ #define ITER_BATCHED_HPP_ #include "internal/iterator_wrapper.hpp" #include "internal/iteratoriterator.hpp" #include "internal/iterbase.hpp" #include <algorithm> #include <functional> #include <iterator> #include <memory> #include <type_traits> #include <utility> #include <vector> namespace iter { namespace impl { template <typename Container> class Batcher; using BatchedFn = IterToolFnBindSizeTSecond<Batcher>; } constexpr impl::BatchedFn batched{}; } template <typename Container> class iter::impl::Batcher { private: Container container_; std::size_t num_batches_; Batcher(Container&& container, std::size_t const num_batches) : container_(std::forward<Container>(container)), num_batches_{num_batches} {} friend BatchedFn; template <typename T> using IndexVector = std::vector<IteratorWrapper<T>>; template <typename T> using DerefVec = IterIterWrapper<IndexVector<T>>; public: Batcher(Batcher&&) = default; template <typename ContainerT> class Iterator { private: template <typename> friend class Iterator; std::shared_ptr<DerefVec<ContainerT>> batch_ = std::make_shared<DerefVec<ContainerT>>(); IteratorWrapper<ContainerT> sub_iter_; IteratorWrapper<ContainerT> sub_end_; std::size_t num_batches_; std::size_t size_; std::size_t count_; bool done() const { return batch_->empty(); } void refill_batch() { batch_->get().clear(); if (count_ < num_batches_) { std::size_t const batch_size(size_ / num_batches_ + std::min<std::size_t>(1, (size_ % num_batches_) / (count_ + 1))); batch_->get().reserve(batch_size); for (std::size_t i = 0; i < batch_size; ++i) { batch_->get().push_back(sub_iter_); ++sub_iter_; } ++count_; } } public: using iterator_category = std::input_iterator_tag; using value_type = DerefVec<ContainerT>; using difference_type = std::ptrdiff_t; using pointer = value_type*; using reference = value_type&; template <typename Iter1, typename Iter2, typename = void> struct distance_helper { static constexpr difference_type distance(Iter1 it1, Iter2 it2) { difference_type dist(0); for (; it1 != it2; ++it1) ++dist; return dist; } }; template <typename Iter1, typename Iter2> struct distance_helper<Iter1, Iter2, typename std::enable_if_t<std::is_arithmetic_v<typename Iter1::difference_type> && std::is_arithmetic_v<typename Iter2::difference_type>>> { static constexpr difference_type distance(Iter1 it1, Iter2 it2) { return std::distance(it1, it2); } }; template <typename Iter1, typename Iter2> difference_type distance(Iter1 it1, Iter2 it2) const { return distance_helper<Iter1, Iter2>::distance(it1, it2); } Iterator(IteratorWrapper<ContainerT>&& sub_iter, IteratorWrapper<ContainerT>&& sub_end, std::size_t num_batches) : sub_iter_{std::move(sub_iter)}, sub_end_{std::move(sub_end)}, num_batches_{num_batches}, size_{static_cast<std::size_t>(distance(sub_iter_, sub_end_))}, count_{0} { refill_batch(); } Iterator& operator++() { refill_batch(); return *this; } Iterator operator++(int) { auto ret = *this; ++*this; return ret; } template <typename T> bool operator!=(const Iterator<T>& other) const { return !(*this == other); } template <typename T> bool operator==(const Iterator<T>& other) const { return done() == other.done() && (done() || !(sub_iter_ != other.sub_iter_)); } DerefVec<ContainerT>& operator*() { return *batch_; } DerefVec<ContainerT>* operator->() { return batch_.get(); } }; Iterator<Container> begin() { return {get_begin(container_), get_end(container_), num_batches_}; } Iterator<Container> end() { return {get_end(container_), get_end(container_), num_batches_}; } Iterator<AsConst<Container>> begin() const { return {get_begin(std::as_const(container_)), get_end(std::as_const(container_)), num_batches_}; } Iterator<AsConst<Container>> end() const { return {get_end(std::as_const(container_)), get_end(std::as_const(container_)), num_batches_}; } }; #endif
d8370e326d716620ca6fd1f63c30839c21d1fd35
012c7909ba001da4a4d9f885108c7051065a8a21
/POJ/3636 - Nested_Dolls.cpp
239858772e766c8d6f359ab9eaa8ad91e7d9efc7
[]
no_license
ajunwalker/Competitive-Programming
0eaa299c202ed1ac7d1372a1f395179a992acf43
cb342c099bb8a9edd24f2e9e6b8fc219a7391d05
refs/heads/master
2021-01-19T07:15:10.130792
2017-08-14T11:27:41
2017-08-14T11:27:41
87,529,651
0
0
null
null
null
null
UTF-8
C++
false
false
1,021
cpp
3636 - Nested_Dolls.cpp
#include <cstdio> #include <algorithm> using namespace std; #define MAX 20001 struct doll{ int width, height; } dolls[MAX]; int cmp(doll a, doll b){ if (a.width != b.width) return a.width < b.width; else return a.height > b.height; } int main(){ int c, m; scanf("%d", &c); for(int i = 0; i < c; ++i){ scanf("%d", &m); for(int j = 0; j < m; ++j){ scanf("%d %d", &dolls[j].width, &dolls[j].height); } sort(dolls, dolls+m, cmp); int arr[MAX]; for(int j = 0; j < MAX; ++j) arr[j] = 0; int total = 1; for(int j = 0; j < m; ++j){ int left = 0, right = total; while(left < right){ int m = (left+right)/2; if (arr[m] < dolls[j].height){ right = m; } else left = m+1; } if (left == total) total++; arr[left] = dolls[j].height; } printf("%d\n", total); } }
1004f26c7b87d3d3ea5b024b9a018ea4090b53f1
0b853cec122cecdf398c9e46989b7654a296fcf8
/foxbomb/statement/Contestants/thinh/encoding.cpp
73d8af55d33d49d15143d9eb72a8aec9d13bad55
[]
no_license
KDuyVu/Problems
3eed16a64fbf09d5e978ff7a2ded65047179c097
aa7437c111d460ac1c30b759235ba41c53fb4e7f
refs/heads/master
2023-06-07T16:43:35.829948
2016-05-13T10:28:23
2016-05-13T10:28:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,267
cpp
encoding.cpp
#include <algorithm> #include <iostream> #include <cstring> #include <string> #include <cstdio> #include <cmath> #include <stack> #include <queue> #include <cstdlib> #include <list> #include <set> #include <map> #define FOR(i , a, b) for(int i = a,_b =b; i <= _b ; i++) #define FORD(i , a,b) for(int i = a,_b = b; i >= _b ; i--) #define REP(i , n) for(int i = 0,_n = n; i < _n ; i++) #define MAX 111111 using namespace std; typedef vector<int> vi; typedef pair<int , int> ii; typedef vector<ii> vii; typedef long long ll; int cnt ; string binary[MAX]; void recur(int k , int n , int len , string tmp) { if(n == k) { cnt++; binary [cnt] = tmp; if(cnt == len - 2) return ; } else { k++; REP(i , 2) { string a = tmp; char ch = i + '0'; a.push_back(ch); recur(k , n , len ,a); } } } int main() { int n , index; scanf("%d",&n); cnt = 0; FOR(i , 2 , 20) { if(n - (1 << i) - 2 >= 0) { index = i + 1; break; } } recur(1 , index , n , "1"); printf("00\n01\n"); FOR(i , 1 , n - 2) { cout << binary[i] << endl; } }
6a8de008b1ec20b9f4780631f5688f2ce6d67237
a422c5835c9da1bc17daafbdcc5899f67f3f4ea3
/eden/fs/inodes/EdenDispatcher.cpp
b38d66099c753d5815f9fff4900a07cfd70aa9b5
[ "BSD-3-Clause" ]
permissive
Happy-Ferret/eden
a2b4ffa7184cc696a25a60acad22003b2a2dafb4
0ac8eda5c8e1ca960c5579771d46e6c445c13e99
refs/heads/master
2021-09-08T13:41:43.364448
2018-03-10T00:24:40
2018-03-10T00:28:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,691
cpp
EdenDispatcher.cpp
/* * Copyright (c) 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "EdenDispatcher.h" #include <folly/Format.h> #include <folly/executors/CPUThreadPoolExecutor.h> #include <folly/executors/GlobalExecutor.h> #include <folly/experimental/logging/xlog.h> #include <gflags/gflags.h> #include <shared_mutex> #include "eden/fs/fuse/DirHandle.h" #include "eden/fs/fuse/FileHandle.h" #include "eden/fs/fuse/RequestData.h" #include "eden/fs/inodes/EdenMount.h" #include "eden/fs/inodes/FileHandle.h" #include "eden/fs/inodes/FileInode.h" #include "eden/fs/inodes/InodeMap.h" #include "eden/fs/inodes/TreeInode.h" using namespace folly; using facebook::eden::PathComponent; using facebook::eden::PathComponentPiece; using facebook::eden::RelativePath; using std::string; using std::vector; DEFINE_int32( inode_reserve, 1000000, "pre-size inode hash table for this many entries"); namespace facebook { namespace eden { EdenDispatcher::EdenDispatcher(EdenMount* mount) : Dispatcher(mount->getStats()), mount_(mount), inodeMap_(mount_->getInodeMap()) {} namespace { /** Compute a fuse_entry_out */ fuse_entry_out computeEntryParam( fusell::InodeNumber number, const fusell::Dispatcher::Attr& attr) { fuse_entry_out entry; entry.nodeid = number.get(); entry.generation = 1; auto fuse_attr = attr.asFuseAttr(); entry.attr = fuse_attr.attr; entry.attr_valid = fuse_attr.attr_valid; entry.attr_valid_nsec = fuse_attr.attr_valid_nsec; entry.entry_valid = fuse_attr.attr_valid; entry.entry_valid_nsec = fuse_attr.attr_valid_nsec; return entry; } } // namespace folly::Future<fusell::Dispatcher::Attr> EdenDispatcher::getattr( fusell::InodeNumber ino) { FB_LOGF(mount_->getStraceLogger(), DBG7, "getattr({})", ino); return inodeMap_->lookupInode(ino).then( [](const InodePtr& inode) { return inode->getattr(); }); } folly::Future<std::shared_ptr<fusell::DirHandle>> EdenDispatcher::opendir( fusell::InodeNumber ino, int flags) { FB_LOGF( mount_->getStraceLogger(), DBG7, "opendir({}, flags={:x})", ino, flags); return inodeMap_->lookupTreeInode(ino).then( [](const TreeInodePtr& inode) { return inode->opendir(); }); } folly::Future<fuse_entry_out> EdenDispatcher::lookup( fusell::InodeNumber parent, PathComponentPiece namepiece) { FB_LOGF(mount_->getStraceLogger(), DBG7, "lookup({}, {})", parent, namepiece); return inodeMap_->lookupTreeInode(parent) .then([name = PathComponent(namepiece)](const TreeInodePtr& tree) { return tree->getOrLoadChild(name); }) .then([](const InodePtr& inode) { return inode->getattr().then([inode](fusell::Dispatcher::Attr attr) { inode->incFuseRefcount(); // Preserve inode's life for the duration of the prefetch. inode->prefetch().ensure([inode] {}); return computeEntryParam(inode->getNodeId(), attr); }); }) .onError([](const std::system_error& err) { // Translate ENOENT into a successful response with an // inode number of 0 and a large entry_valid time, to let the kernel // cache this negative lookup result. if (err.code().category() == std::system_category() && err.code().value() == ENOENT) { fuse_entry_out entry = {}; entry.attr_valid = std::numeric_limits<decltype(entry.attr_valid)>::max(); entry.entry_valid = std::numeric_limits<decltype(entry.entry_valid)>::max(); return entry; } throw err; }); } folly::Future<fusell::Dispatcher::Attr> EdenDispatcher::setattr( fusell::InodeNumber ino, const fuse_setattr_in& attr) { FB_LOGF(mount_->getStraceLogger(), DBG7, "setattr({})", ino); return inodeMap_->lookupInode(ino).then( [attr](const InodePtr& inode) { return inode->setattr(attr); }); } folly::Future<folly::Unit> EdenDispatcher::forget( fusell::InodeNumber ino, unsigned long nlookup) { FB_LOGF(mount_->getStraceLogger(), DBG7, "forget({}, {})", ino, nlookup); inodeMap_->decFuseRefcount(ino, nlookup); return Unit{}; } folly::Future<std::shared_ptr<fusell::FileHandle>> EdenDispatcher::open( fusell::InodeNumber ino, int flags) { FB_LOGF(mount_->getStraceLogger(), DBG7, "open({}, flags={:x})", ino, flags); return inodeMap_->lookupFileInode(ino).then( [flags](const FileInodePtr& inode) { return inode->open(flags); }); } folly::Future<fusell::Dispatcher::Create> EdenDispatcher::create( fusell::InodeNumber parent, PathComponentPiece name, mode_t mode, int flags) { FB_LOGF( mount_->getStraceLogger(), DBG7, "create({}, {}, {:#x}, {:#x})", parent, name, mode, flags); return inodeMap_->lookupTreeInode(parent) .then([childName = PathComponent{name}, mode, flags]( const TreeInodePtr& parentInode) { return parentInode->create(childName, mode, flags); }) .then([=](TreeInode::CreateResult created) { fusell::Dispatcher::Create result; created.inode->incFuseRefcount(); result.entry = computeEntryParam(created.inode->getNodeId(), created.attr); result.fh = std::move(created.file); return result; }); } folly::Future<std::string> EdenDispatcher::readlink(fusell::InodeNumber ino) { FB_LOGF(mount_->getStraceLogger(), DBG7, "readlink({})", ino); return inodeMap_->lookupFileInode(ino).then( [](const FileInodePtr& inode) { return inode->readlink(); }); } folly::Future<fuse_entry_out> EdenDispatcher::mknod( fusell::InodeNumber parent, PathComponentPiece name, mode_t mode, dev_t rdev) { FB_LOGF( mount_->getStraceLogger(), DBG7, "mknod({}, {}, {:#x}, {:#x})", parent, name, mode, rdev); return inodeMap_->lookupTreeInode(parent).then( [childName = PathComponent{name}, mode, rdev](const TreeInodePtr& inode) { auto child = inode->mknod(childName, mode, rdev); return child->getattr().then([child](fusell::Dispatcher::Attr attr) { child->incFuseRefcount(); return computeEntryParam(child->getNodeId(), attr); }); }); } folly::Future<fuse_entry_out> EdenDispatcher::mkdir( fusell::InodeNumber parent, PathComponentPiece name, mode_t mode) { FB_LOGF( mount_->getStraceLogger(), DBG7, "mkdir({}, {}, {:#x})", parent, name, mode); return inodeMap_->lookupTreeInode(parent).then( [childName = PathComponent{name}, mode](const TreeInodePtr& inode) { auto child = inode->mkdir(childName, mode); return child->getattr().then([child](fusell::Dispatcher::Attr attr) { child->incFuseRefcount(); return computeEntryParam(child->getNodeId(), attr); }); }); } folly::Future<folly::Unit> EdenDispatcher::unlink( fusell::InodeNumber parent, PathComponentPiece name) { FB_LOGF(mount_->getStraceLogger(), DBG7, "unlink({}, {})", parent, name); return inodeMap_->lookupTreeInode(parent).then( [this, childName = PathComponent{name}](const TreeInodePtr& inode) { inode->unlink(childName); }); } folly::Future<folly::Unit> EdenDispatcher::rmdir( fusell::InodeNumber parent, PathComponentPiece name) { FB_LOGF(mount_->getStraceLogger(), DBG7, "rmdir({}, {})", parent, name); return inodeMap_->lookupTreeInode(parent).then( [childName = PathComponent{name}](const TreeInodePtr& inode) { return inode->rmdir(childName); }); } folly::Future<fuse_entry_out> EdenDispatcher::symlink( fusell::InodeNumber parent, PathComponentPiece name, StringPiece link) { FB_LOGF( mount_->getStraceLogger(), DBG7, "rmdir({}, {}, {})", parent, name, link); return inodeMap_->lookupTreeInode(parent).then( [linkContents = link.str(), childName = PathComponent{name}](const TreeInodePtr& inode) { auto symlinkInode = inode->symlink(childName, linkContents); symlinkInode->incFuseRefcount(); return symlinkInode->getattr().then([symlinkInode](Attr&& attr) { return computeEntryParam(symlinkInode->getNodeId(), attr); }); }); } folly::Future<folly::Unit> EdenDispatcher::rename( fusell::InodeNumber parent, PathComponentPiece namePiece, fusell::InodeNumber newParent, PathComponentPiece newNamePiece) { FB_LOGF( mount_->getStraceLogger(), DBG7, "rename({}, {}, {}, {})", parent, namePiece, newParent, newNamePiece); // Start looking up both parents auto parentFuture = inodeMap_->lookupTreeInode(parent); auto newParentFuture = inodeMap_->lookupTreeInode(newParent); // Do the rename once we have looked up both parents. return parentFuture.then([npFuture = std::move(newParentFuture), name = PathComponent{namePiece}, newName = PathComponent{newNamePiece}]( const TreeInodePtr& parent) mutable { return npFuture.then( [parent, name, newName](const TreeInodePtr& newParent) { parent->rename(name, newParent, newName); }); }); } folly::Future<fuse_entry_out> EdenDispatcher::link( fusell::InodeNumber ino, fusell::InodeNumber newParent, PathComponentPiece newName) { FB_LOGF( mount_->getStraceLogger(), DBG7, "link({}, {}, {})", ino, newParent, newName); // We intentionally do not support hard links. // These generally cannot be tracked in source control (git or mercurial) // and are not portable to non-Unix platforms. folly::throwSystemErrorExplicit( EPERM, "hard links are not supported in eden mount points"); } Future<string> EdenDispatcher::getxattr( fusell::InodeNumber ino, StringPiece name) { FB_LOGF(mount_->getStraceLogger(), DBG7, "getxattr({}, {})", ino, name); return inodeMap_->lookupInode(ino).then( [attrName = name.str()](const InodePtr& inode) { return inode->getxattr(attrName); }); } Future<vector<string>> EdenDispatcher::listxattr(fusell::InodeNumber ino) { FB_LOGF(mount_->getStraceLogger(), DBG7, "listxattr({})", ino); return inodeMap_->lookupInode(ino).then( [](const InodePtr& inode) { return inode->listxattr(); }); } } // namespace eden } // namespace facebook
45090152371b026f83bcb799d35b1d4d86651ab9
38e60cbbbd4caff6e85e0ccb35821fe3744c19f8
/main/lib/processors/processor_mn_mt.cpp
25d0916da30ecafea163106aff640a6f0215da35
[]
no_license
laitingsheng/2019S1-COMP90024-Project-1
7aeb4a5530183ad0e23a0d4dc10d57b423732a8f
235bda67b76d7ca6dcfdfc629d7a31485ad4907b
refs/heads/master
2023-07-11T07:04:46.155732
2021-08-24T02:36:56
2021-08-24T02:36:56
181,406,314
0
0
null
null
null
null
UTF-8
C++
false
false
6,498
cpp
processor_mn_mt.cpp
#include <omp.h> #include <boost/serialization/unordered_map.hpp> #include <boost/serialization/vector.hpp> #include <boost/sort/sort.hpp> #include "processors/processor_mn_mt.h" // @formatter:off processor_mn_mt::processor_mn_mt( char const * filename, grid const & g, boost::mpi::environment const & env, boost::mpi::communicator const & world ) : _rank(world.rank()), _size(world.size()), world(world), env(env), processor(filename, g) {} // @formatter:on void processor_mn_mt::preprocess() { auto curr = file.data(); auto total_proc = _size * num_proc, actual_thread_start = _rank * num_proc; auto block_size = file.size() / total_proc; decltype(curr) starts[num_proc], ends[num_proc]; #pragma omp parallel for for (int i = 0; i < num_proc; ++i) { auto & start = starts[i] = curr + block_size * (actual_thread_start + i); while (*start++ != '\n'); if (i > 0) { ends[i - 1] = start; if (i == num_proc - 1) if (_rank < _size - 1) { long dist; world.recv(_rank + 1, 0, dist); ends[i] = curr + dist; } else ends[i] = curr + file.size(); } else if (_rank > 0) { long dist = start - curr; world.send(_rank - 1, 0, dist); } } record_type records[num_proc]; #pragma omp parallel for for (int i = 0; i < num_proc; ++i) process_block(starts[i], ends[i], records[i]); auto pc = num_proc >> 1; while (pc > 1) { #pragma omp parallel for collapse(2) schedule(dynamic) for (int dest = 0; dest < pc; ++dest) for (unsigned int pos = 0; pos < g.count(); ++pos) { int src = dest + pc; // @formatter:off auto & [sc, sm] = records[src][pos]; // @formatter:on if (sc != 0) { // @formatter:off auto & [dc, dm] = records[dest][pos]; // @formatter:on if (dm.empty()) dm = std::move(sm); else // @formatter:off for (auto & [k, v] : sm) // @formatter::on dm[k] += v; dc += sc; } } pc >>= 1; } auto & dest = records[0], src = records[1]; #pragma omp parallel for schedule(dynamic) for (unsigned int pos = 0; pos < g.count(); ++pos) { // @formatter:off auto & [sc, sm] = src[pos]; // @formatter:on if (sc != 0) { // @formatter:off auto & [dc, dm] = dest[pos]; // @formatter::on if (dm.empty()) dm = std::move(sm); else // @formatter:off for (auto & [k, v] : sm) // @formatter::on dm[k] += v; dc += sc; } } record = std::move(dest); record_type tmp[_size]; boost::mpi::all_gather(world, record, tmp); pc = _size >> 1; while (pc > 1) { #pragma omp parallel for collapse(2) schedule(dynamic) for (int dest = 0; dest < pc; ++dest) for (unsigned int pos = 0; pos < g.count(); ++pos) { int src = dest + pc; // @formatter:off auto & [sc, sm] = tmp[src][pos]; // @formatter:on if (sc != 0) { // @formatter:off auto & [dc, dm] = tmp[dest][pos]; // @formatter:on if (dm.empty()) dm = std::move(sm); else // @formatter:off for (auto & [k, v] : sm) // @formatter::on dm[k] += v; dc += sc; } } pc >>= 1; } auto & ndest = tmp[0], nsrc = tmp[1]; #pragma omp parallel for schedule(dynamic) for (unsigned int pos = 0; pos < g.count(); ++pos) { // @formatter:off auto & [sc, sm] = nsrc[pos]; // @formatter:on if (sc != 0) { // @formatter:off auto & [dc, dm] = ndest[pos]; // @formatter::on if (dm.empty()) dm = std::move(sm); else // @formatter:off for (auto & [k, v] : sm) // @formatter::on dm[k] += v; dc += sc; } } record = std::move(ndest); } processor::result_type processor_mn_mt::operator()() const { auto block_size = g.count() / _size, remain = g.count() % _size; if (_rank < remain) ++block_size; result_type tmp(block_size); for (int i = _rank; i < g.count(); i += _size) { // @formatter:off auto & [c, m] = record[i]; auto & [rc, rv] = tmp[i / _size]; // @formatter:on rc = {i, c}; if (c == 0) continue; rv.resize(m.size()); auto it = rv.begin(); for (auto & p : m) { *it = p; ++it; } boost::sort::block_indirect_sort(rv.begin(), rv.end(), less_tag_info); int vc = 0; unsigned long lc = 0; unsigned long j = 0; while (j < rv.size()) { auto c = rv[j].second; if (c == 0) { lc = c; break; } if (c != lc) { ++vc; lc = c; if (vc > 5) break; } ++j; } if (lc != 0 && vc > 5) rv.resize(j); } std::vector<result_type> tmps; boost::mpi::gather(world, tmp, tmps, 0); if (_rank == 0) { result_type re(g.count()); int i = 0; for (auto & rs : tmps) for (auto & r : rs) re[i++] = std::move(r); boost::sort::block_indirect_sort(re.begin(), re.end(), less_cell_total_info); return re; } return {}; } int const processor_mn_mt::num_proc = omp_get_num_procs();
2f08d1fe130fb16348ab47a1a83af65a71bf2491
ff13ee3f26fcc02863ad31ea9331b20bc284fc23
/include/PrimaryGeneratorAction.hh
87e21318f9a2437203abfa87d0d728ce837db91f
[]
no_license
mengyx-work/XenonChamber_ScENE_10keVNeutron_G4Simulation
f0eff929465f147d7b6ce4be5baa05b85d3a2a5a
10141e1eb6dd586d45a1bd29ba3a27178096b9cd
refs/heads/master
2021-03-12T20:17:24.694820
2016-11-19T07:29:32
2016-11-19T07:29:32
37,139,689
0
1
null
null
null
null
UTF-8
C++
false
false
572
hh
PrimaryGeneratorAction.hh
#ifndef PRIMARYGENERATORACTION_HH #define RIMARYGENERATORACTION_HH #include "G4VUserPrimaryGeneratorAction.hh" #include "G4ThreeVector.hh" #include "globals.hh" class G4ParticleGun; //class G4GeneralParticleSource; class G4Event; class PrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction { public: // Constructor PrimaryGeneratorAction(); // Destructor virtual ~PrimaryGeneratorAction(); // Methods void GeneratePrimaries(G4Event*); private: //G4GeneralParticleSource* particleSource; G4ParticleGun* particleGun; }; #endif
d0fa5e4c735d7980454cbfc87bffe1db9d7bf351
23f902883274b72db1cd127aed2b28ed9c6e16ec
/Algorithm/BOJ/11651 좌표 정렬하기 2.cpp
e5582a90e0f378309e6cc582a112e49400875de6
[]
no_license
youseokhwan/today-i-learned
854bfc9a7ce321c8ecbc0037f67fb7217660c8a6
82d602daf129e1dbabc403f17924109e87ea2083
refs/heads/master
2021-06-16T18:56:48.313938
2021-02-11T01:30:03
2021-02-11T01:30:03
162,527,739
0
2
null
2020-01-01T14:41:15
2018-12-20T04:46:27
Jupyter Notebook
UTF-8
C++
false
false
589
cpp
11651 좌표 정렬하기 2.cpp
#include <iostream> #include <vector> #include <algorithm> struct Point { int x, y; }; bool yFirst(Point A, Point B) { if(A.y == B.y) return (A.x < B.x); else return (A.y < B.y); } int main() { std::ios_base::sync_with_stdio(false); int N; std::cin >> N; std::vector<Point> v; for(int i = 0; i < N; i++) { int x, y; std::cin >> x >> y; v.push_back(Point{x, y}); } std::sort(v.begin(), v.end(), yFirst); std::vector<Point>::iterator iter; for(iter = v.begin(); iter != v.end(); iter++) std::cout << (*iter).x << " " << (*iter).y << "\n"; return 0; }
1de8d79455a8b2ca38b94876fa5f319ee4910adf
3e0a438c91fff897d208fa235e29645c7c71bbc0
/test/manipulators/floating_point_double_manipulator_test.h
98d9181452db57cb6a892654087f6856049cbf68
[ "MIT" ]
permissive
project-eutopia/vega
6c84b5c0dcb078fd5e3399ee4cccdade6c72cee2
9b017016f15260150aa202a9513dd7c61a2c798f
refs/heads/master
2022-12-20T21:31:11.899738
2022-03-23T03:10:41
2022-03-23T03:10:41
117,390,714
27
8
MIT
2022-12-08T21:33:09
2018-01-14T00:53:28
C++
UTF-8
C++
false
false
951
h
floating_point_double_manipulator_test.h
#pragma once #include "../test_helper.h" #include "vega/manipulators/floating_point_double_manipulator.h" #include "vega/dicom/data_element.h" using namespace vega; using namespace vega::manipulators; TEST(FloatingPointDoubleManipulatorTest, constructor_test) { FloatingPointDoubleManipulator manipulator{}; manipulator.emplace_back(1.234); manipulator.emplace_back(-50000); EXPECT_EQ(manipulator.str(), "1.234e0\\-5e4"); FloatingPointDoubleManipulator manipulator2(manipulator.raw_value()); EXPECT_EQ(manipulator[0], manipulator2[0]); EXPECT_EQ(manipulator[1], manipulator2[1]); } TEST(FloatingPointDoubleManipulatorTest, data_element_test) { vega::dicom::DataElement data_element{Tag {0x0018, 0x1271}, vr::FD}; auto manipulator = data_element.get_manipulator<FloatingPointDoubleManipulator>(); manipulator->push_back(0.0000001); manipulator->push_back(-5.55e55); EXPECT_EQ(data_element.str(), "1e-7\\-5.55e55"); }
f54864ca674d63049338058bd09a58828ffbfc8d
b764131b1419321a7f3b3857e6327e7ef7543d53
/src/sdl/include/console.hpp
b29c295c16d1ee65d9989ad5858a39f35e210ff0
[]
no_license
lispberry/rogue
3703191a6a2d3603d33fe779df9a19b9ab0cd5b7
866f73561f5a9101c4dbd68f540a4c6baaef5e8f
refs/heads/main
2023-03-02T00:50:07.694589
2021-02-08T20:01:03
2021-02-08T20:01:03
324,248,717
0
0
null
null
null
null
UTF-8
C++
false
false
5,777
hpp
console.hpp
#ifndef ROGUE_CONSOLE_HPP #define ROGUE_CONSOLE_HPP #include <SDL2/SDL.h> #include <iostream> #include <SDL2/SDL_ttf.h> #include <boost/algorithm/string.hpp> #include <utility> #include <algebra.hpp> namespace rogue::console { namespace internal { template<typename T> T *logged(T *subject, const std::string &message, std::ostream &stream = std::cout) { if (subject == nullptr) stream << message << "\n" << SDL_GetError() << "\n"; return subject; } inline int logged(int subject, const std::string &message, std::ostream &stream = std::cout) { if (subject != 0) stream << message << "\n" << SDL_GetError() << "\n"; return subject; } inline void render_texture(SDL_Texture *tex, SDL_Renderer *ren, algebra::size_t2 position) { SDL_Rect dst; dst.x = position.x(); dst.y = position.y(); SDL_QueryTexture(tex, nullptr, nullptr, &dst.w, &dst.h); SDL_RenderCopy(ren, tex, nullptr, &dst); } } inline auto make_font(const std::string &path, int size) { return internal::logged( TTF_OpenFont(path.c_str(), size), "Can not open fonts at " + path ); } inline constexpr SDL_Color make_color(uint8_t r, uint8_t g, uint8_t b, uint8_t a = 255) { return {r, g, b, a}; } namespace color { constexpr SDL_Color white = make_color(255, 255, 255), black = make_color(0, 0, 0), transparent = make_color(0, 0, 0, 0); } struct colored_char { uint16_t character; SDL_Color foreground, background; colored_char()= default; constexpr colored_char(uint16_t character, SDL_Color fg, SDL_Color bg) : character(character), foreground(fg), background(bg) {} }; using colored_field = algebra::field<colored_char>; inline colored_field colored( const std::string &text, SDL_Color foreground = color::white, SDL_Color background = color::black, colored_char default_character = colored_char{static_cast<uint16_t>(' '), color::transparent, color::transparent} ) { std::vector<std::string> lines; boost::split(lines, text, boost::is_any_of("\n")); std::size_t width = 0; for (const auto &line : lines) { if (line.size() > width) width = line.size(); } algebra::field<colored_char> result{algebra::size_t2{width, lines.size()}}; algebra::size_t2 v{0, 0}; for (const auto &line : lines) { v.x() = 0; for (const auto &c : line) { result(v) = colored_char{static_cast<uint16_t>(c), foreground, background}; v.x()++; } for (; v.x() < width; v.x()++) result(v) = default_character; v.y()++; } return result; } struct sdl { sdl() { internal::logged(SDL_Init(SDL_INIT_EVERYTHING), "Can not initialize SDL"); internal::logged(TTF_Init(), "Can not initialize TTF"); } ~sdl() { SDL_Quit(); } }; struct window { TTF_Font *_font; algebra::size_t2 _glyph_size{0, 0}; SDL_Window *_window; SDL_Renderer *_renderer; inline window(const std::string &title, int w, int h) { _window = internal::logged( SDL_CreateWindow( title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL ), "Can not initialize window" ); _renderer = internal::logged( SDL_CreateRenderer( _window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC ), "Can not initialize renderer" ); _font = make_font("/home/nik/Projects/rogue/assets/fonts/consolas.ttf", 14); auto example_glyph = TTF_RenderGlyph_Shaded(_font, 21, make_color(255, 255, 255), make_color(0, 0, 0)); _glyph_size = algebra::size_t2{static_cast<size_t>(example_glyph->w), static_cast<size_t>(example_glyph->h)}; delete example_glyph; } ~window() { SDL_DestroyWindow(_window); SDL_DestroyRenderer(_renderer); } }; inline void render_field(const window &window, const colored_field &field) { SDL_RenderClear(window._renderer); algebra::size_t2 v{0, 0}; for (; v.x() < field.size().x(); ++v.x()) { for (v.y() = 0; v.y() < field.size().y(); ++v.y()) { auto surface = internal::logged( TTF_RenderGlyph_Shaded( window._font, field(v).character, field(v).foreground, field(v).background ), "Can't create surface of character " + std::to_string(field(v).character) + "'" ); auto texture = internal::logged( SDL_CreateTextureFromSurface(window._renderer, surface), "Can't create texture" ); internal::render_texture( texture, window._renderer, algebra::scaled(window._glyph_size, v) ); delete surface; } } SDL_RenderPresent(window._renderer); } } #endif //ROGUE_CONSOLE_HPP
a6b483a2700cf6adf8e3c4fba6f9d59d9a10aba4
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5640146288377856_1/C++/krienson/A.cpp
d8557536aeacc24dba4e556f5801b282498a3e10
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
320
cpp
A.cpp
#include<iostream> using namespace std; int R, C, W; int main(){ int T; cin>>T; for(int kases = 1; kases <= T; kases++){ cin>>R>>C>>W; int res = (C/W)*R + (W-1) + (W>1&&W<C&&C%W>0?1:0); //first hit + rest of the size of the ship + chance of move the ship and fail cout<<"Case #"<<kases<<": "<<res<<endl; } }
84ebd7666acdfc33bc37a2c4fa745fb37a668956
f1054053f42f64f900a1b086db0c50856f2b0af0
/PJP-semestral-work/error.cpp
6d079380646e8b7be35d341457401c9e92c97e5d
[]
no_license
stemberamichal-School/PJP-semestral-work
3953fdb0105d77133fdc6da83dbebbbac13cbc5a
99d300556b827b53c89d34654824149d97135e0e
refs/heads/master
2021-06-01T01:18:43.676868
2016-06-30T13:52:11
2016-06-30T13:52:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
276
cpp
error.cpp
// // error.cpp // PJP-semestral-work // // Created by Michal Štembera on 08/06/15. // Copyright (c) 2015 Michal Štembera. All rights reserved. // #include "error.h" #include <stdlib.h> void error(const char * text) { printf("\nERROR: %s\n", text); exit(1); }
fa4e1f672c8540667e24ef8e3a52143d64f3f131
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/Event/EventTPCnv/EventTPCnv/EventInfo_p2.h
14c8b1bd62621af8980765a37fd7f461490cc350
[]
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
648
h
EventInfo_p2.h
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ #ifndef EVENTTPCNV_EVENTINFO_P2_H #define EVENTTPCNV_EVENTINFO_P2_H /** * @file EventInfo_p2.h * * @brief This class is the persistent representation of EventInfo * @author R.D.Schaffer@cern.ch */ #include "EventTPCnv/EventID_p1.h" #include "EventTPCnv/EventType_p1.h" #include "EventTPCnv/TriggerInfo_p2.h" class EventInfo_p2 { public: EventInfo_p2() {} EventID_p1 m_event_ID; EventType_p1 m_event_type; TriggerInfo_p2 m_trigger_info; std::vector<unsigned int> m_event_flags; }; #endif
d4d1f7187e113e7eafda77bb33369978e6d5c3a8
682a576b5bfde9cf914436ea1b3d6ec7e879630a
/components/common/core/memory/SPMemUserData.cc
f32e443ac1cb056128a3df84df50f7b9a2da16d4
[ "MIT", "BSD-3-Clause" ]
permissive
SBKarr/stappler
6dc914eb4ce45dc8b1071a5822a0f0ba63623ae5
4392852d6a92dd26569d9dc1a31e65c3e47c2e6a
refs/heads/master
2023-04-09T08:38:28.505085
2023-03-25T15:37:47
2023-03-25T15:37:47
42,354,380
10
3
null
2017-04-14T10:53:27
2015-09-12T11:16:09
C++
UTF-8
C++
false
false
2,130
cc
SPMemUserData.cc
/** Copyright (c) 2019 Roman Katuntsev <sbkarr@stappler.org> 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 "SPMemUserData.h" NS_SP_EXT_BEGIN(memory) namespace pool { struct Pool_StoreHandle : AllocPool { void *pointer; memory::function<void()> callback; }; static status_t sa_request_store_custom_cleanup(void *ptr) { if (ptr) { auto ref = (Pool_StoreHandle *)ptr; if (ref->callback) { memory::pool::push(ref->callback.get_allocator()); ref->callback(); memory::pool::pop(); } } return SUCCESS; } void store(pool_t *pool, void *ptr, const StringView &key, memory::function<void()> &&cb) { memory::pool::push(pool); void * ret = nullptr; pool::userdata_get(&ret, SP_TERMINATED_DATA(key), pool); if (ret) { auto h = (Pool_StoreHandle *)ret; h->pointer = ptr; if (cb) { h->callback = std::move(cb); } else { h->callback = nullptr; } } else { auto h = new (pool) Pool_StoreHandle(); h->pointer = ptr; if (cb) { h->callback = std::move(cb); } pool::userdata_set(h, SP_TERMINATED_DATA(key), sa_request_store_custom_cleanup, pool); } memory::pool::pop(); } } NS_SP_EXT_END(memory)
6cdc8b3eb25893703b02a5a2d34805a3cb57a76a
c4535129a3913e44606fde1493f25f3886ddc77f
/Chapter06/timer/timer.cpp
80ea3f9a85024828a7fc9b8c8e7efcac1783b05c
[ "MIT" ]
permissive
abhishekchauh0n/Embedded-Programming-with-Modern-CPP-Cookbook
f7f9f0a27fdcc138693e4ec75a1243e794ba000a
80b8513c68194e4ecb31b49ae827b4fd0f8df573
refs/heads/master
2022-12-17T16:24:10.112825
2020-09-03T12:09:34
2020-09-03T12:09:34
293,453,792
0
0
null
null
null
null
UTF-8
C++
false
false
1,057
cpp
timer.cpp
#include <iostream> #include <chrono> #include <system_error> #include <thread> #include <fcntl.h> #include <sys/mman.h> constexpr uint32_t kTimerBase = 0x3F003000; struct SystemTimer { uint32_t CS; uint32_t counter_lo; uint32_t counter_hi; }; int main() { int memfd = open("/dev/mem", O_RDWR | O_SYNC); if (memfd < 0) { throw std::system_error(errno, std::generic_category(), "Failed to open /dev/mem. Make sure you run as root."); } SystemTimer *timer = (SystemTimer*)mmap(NULL, sizeof(SystemTimer), PROT_READ|PROT_WRITE, MAP_SHARED, memfd, kTimerBase); if (timer == MAP_FAILED) { throw std::system_error(errno, std::generic_category(), "Memory mapping failed"); } uint64_t prev = 0; for (int i = 0; i < 10; i++) { uint64_t time = ((uint64_t)timer->counter_hi << 32) + timer->counter_lo; std::cout << "System timer: " << time; if (i > 0) { std::cout << ", diff " << time - prev; } prev = time; std::cout << std::endl; std::this_thread::sleep_for(std::chrono::milliseconds(10)); } return 0; }
c53d29e8009eaf86e9fe5de06ad04d06050223b8
d4d06745a1ed357cad9ef1dc03462bfbe65b1d63
/day04/ex03/src/AMateria.class.cpp
366e0bd627b81b39e87ac3019eb98fdea0f9d633
[]
no_license
potatokuka/Cpp_Piscene
5d7c7b5af0691f347e5b2dde9027ea9fdacbcd00
f203d026ad0ab12d5711ddd18686e4335703a762
refs/heads/master
2022-12-16T13:44:51.960228
2020-09-18T10:09:10
2020-09-18T10:09:10
282,245,546
0
2
null
null
null
null
UTF-8
C++
false
false
1,495
cpp
AMateria.class.cpp
/* ************************************************************************** */ /* */ /* :::::::: */ /* AMateria.class.cpp :+: :+: */ /* +:+ */ /* By: greed <greed@student.codam.nl> +#+ */ /* +#+ */ /* Created: 2020/07/31 15:19:54 by greed #+# #+# */ /* Updated: 2020/07/31 15:19:55 by greed ######## odam.nl */ /* */ /* ************************************************************************** */ #include <iostream> #include "AMateria.class.hpp" AMateria::AMateria(){} AMateria::AMateria(std::string const &type) : _type(type), _xp(0){ } AMateria::~AMateria(){} AMateria::AMateria(AMateria const &src): _type(src.getType()), _xp(src.getXp()){ } AMateria &AMateria::operator=(AMateria const &rhs){ if (&rhs != this) { _type = rhs.getType(); _xp = rhs.getXp(); } return (*this); } std::string const &AMateria::getType() const{ return (_type); } unsigned int AMateria::getXp() const{ return (_xp); } void AMateria::use(ICharacter &target){ (void)target; this->_xp += 10; }
a17192532e43779991a1d91047f96bf1a418a422
022e2e472bb37ba39fbbe43c48542426ccb89e9a
/Include/result.h
20027ead8b28e8dbd2e5e73caf8cf0a22e2230ac
[]
no_license
suphus/small_x_dijets
f1a2135431709f921f0f2646db5f59af4564875d
527c85297077f7754690aac4582727fd4bc98094
refs/heads/master
2020-06-04T14:11:30.238171
2017-05-04T13:44:43
2017-05-04T13:44:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
317
h
result.h
#include<TFile.h> #include<TH1.h> #include<TGraphAsymmErrors.h> #ifndef RESULT_H #define RESULT_H using namespace std; class Result { private: public: bool calculated = false; TH1D *result; TGraphAsymmErrors *syst; TString name; Result(TString ); void WriteToFile(TString ); }; #endif // RESULT_H
c7bf694ef9395654c6ae127d3fbbdafc82c0148e
e68c1f9134b44ddea144f7efa7523076f3f12d3a
/FinalCode/Barbarian_Male_1HT_LeapAttack_End.cpp
10ec6cf705c9010b241136d999bb63f061ee01e1
[]
no_license
iso5930/Direct-3D-Team-Portfolio
4ac710ede0c9176702595cba5579af42887611cf
84e64eb4e91c7e5b4aed77212cd08cfee038fcd3
refs/heads/master
2021-08-23T08:15:00.128591
2017-12-04T06:14:39
2017-12-04T06:14:39
112,998,717
0
0
null
null
null
null
UTF-8
C++
false
false
670
cpp
Barbarian_Male_1HT_LeapAttack_End.cpp
#include "StdAfx.h" #include "Barbarian_Male_1HT_LeapAttack_End.h" CBarbarian_Male_1HT_LeapAttack_End::CBarbarian_Male_1HT_LeapAttack_End(void) { m_eStateType = STATE_TYPE_BARBARIAN_MALE_1HT_LEAPATTACK_END; } CBarbarian_Male_1HT_LeapAttack_End::~CBarbarian_Male_1HT_LeapAttack_End(void) { } void CBarbarian_Male_1HT_LeapAttack_End::Initialize() { CPlayerState::Initialize(); // SetAnimation m_pOwner->SetAnimation(10); // Clear m_pPathFindCom->Clear(); } CPlayerState* CBarbarian_Male_1HT_LeapAttack_End::Action() { if(m_pAnimController->m_dFrameTime - 0.25 <= m_pAnimController->GetTrackPos()) { return new CBarbarian_Male_1HT_Idle; } return NULL; }
2d5c2e112e0cdc421b3a00eeda7178fb36ee6532
0329788a6657e212944fd1dffb818111e62ee2b0
/docs/snippets/cpp/VS_Snippets_Winforms/Classic PropertyDescriptorCollection.Find Example/CPP/source.cpp
24c9c39e0a02181b8efe8928628916b15000bb85
[ "CC-BY-4.0", "MIT" ]
permissive
MicrosoftDocs/visualstudio-docs
3e506da16412dfee1f83e82a600c7ce0041c0f33
bff072c38fcfc60cd02c9d1d4a7959ae26a8e23c
refs/heads/main
2023-09-01T16:13:32.046442
2023-09-01T14:26:34
2023-09-01T14:26:34
73,740,273
1,050
1,984
CC-BY-4.0
2023-09-14T17:04:58
2016-11-14T19:36:53
Python
UTF-8
C++
false
false
874
cpp
source.cpp
#using <System.Windows.Forms.dll> #using <System.Drawing.dll> #using <System.dll> #using <System.Data.dll> using namespace System; using namespace System::Data; using namespace System::ComponentModel; using namespace System::Windows::Forms; public ref class Form1: public Form { protected: Button^ button1; TextBox^ textBox1; // <Snippet1> private: void FindProperty() { // Creates a new collection and assign it the properties for button1. PropertyDescriptorCollection^ properties = TypeDescriptor::GetProperties( button1 ); // Sets a PropertyDescriptor to the specific property. PropertyDescriptor^ myProperty = properties->Find( "Opacity", false ); // Prints the property and the property description. textBox1->Text = myProperty->DisplayName + "\n" + myProperty->Description; } // </Snippet1> };
64b34d01882300d8f103186ee9a2fb8eb2332ab4
3cf9f927fbc747090091642d37fb803b606b7e2f
/src/spriter/sfmlsoundfile.cpp
d193c8c93957e5f2154068bdcb05f647a9d609b4
[]
no_license
Breush/evilly-evil-villains
d734dd7ce97c727fab8e4a67097170ef7f381d22
f499963e9c2cfdc7c4fed42ca7b8c3d2bc7ecbe9
refs/heads/master
2022-07-09T18:24:18.996382
2022-06-22T07:08:38
2022-06-22T07:08:38
29,420,434
0
0
null
null
null
null
UTF-8
C++
false
false
502
cpp
sfmlsoundfile.cpp
#include "spriter/sfmlsoundfile.hpp" #include "context/context.hpp" #include "spriter/sfmlsoundobjectinforeference.hpp" #include <iostream> using namespace SpriterEngine; SfmlSoundFile::SfmlSoundFile(std::string initialFilePath) : SoundFile(initialFilePath) { m_soundID = context::context.sounds.getID(path()); } SoundObjectInfoReference* SfmlSoundFile::newSoundInfoReference() { // Note: Should be deleted by whoever calls it return new SfmlSoundObjectInfoReference(m_soundID); }
4122a868b5aa3b48559d74d163638fdd2542b8c4
1adab2d2cc6fe69dbec7c3353b98ea77e06644bb
/TASK-2/Book Library/Book.cpp
3d11c9d1c05478e5660d60a843612e53eb8c0fff
[]
no_license
BilalAli181999/OOP-IN-C_Plus_Plus
681bb28774bfe8c998456cb28f154a313f8292ae
09274e930a33b05fb6acedb9de57b8ac2f6a8e1d
refs/heads/master
2020-07-16T04:50:23.605385
2019-09-01T20:37:23
2019-09-01T20:37:23
205,723,018
0
0
null
null
null
null
UTF-8
C++
false
false
1,339
cpp
Book.cpp
//NAME:BILAL ALI //ROLL NO:BCSF16A030 #include "Book.h" Book::Book()//if we dont input by ourself ,constructor is made to auto generate default objects { bC++; strcpy_s(authorName, "Tony Gadis"); strcpy_s(bookTitle, "c++"); strcpy_s(publisherName, "Aone publishers"); bookCode = bC; } Book::Book(char* aN, char* bT, char* pN)//if we dont input by ourself ,constructor is made to auto generate objects { bC++; strcpy_s(authorName, aN); strcpy_s(bookTitle, bT); strcpy_s(publisherName, pN); bookCode = bC; } char & Book::operator[](int index) { return bookTitle[index]; } void Book::setAuthorName(char* aN) { strcpy_s(authorName, aN); } void Book::setBookTitle(char* bT) { strcpy_s(bookTitle, bT); } void Book::setPublisherName(char* pN) { strcpy_s(publisherName, pN); } void Book::setCode(int c) { bookCode = c; } char* Book::getAuthorName() { return authorName; } char* Book::getBookTitle() { return bookTitle; } char* Book::getPublisherName() { return publisherName; } int Book::getBookCode() { return bookCode; } void Book::display() { cout << "\n Book Title: " << bookTitle; cout << "\n Author Name: " << authorName; cout << "\n Publisher: " << publisherName; cout << "\n Book Code: " << bookCode; } int Book::getBookId() { return bookCode; } void Book::setBookId(int id) { bookCode = id; }
9bab334151a583d9689e46411d53c27a1dea99d8
c68cc603d13d2a2ad95ab942402f3f659f1a4a66
/tp1/src/sched_rr2.cpp
ec1e3a8073026b4f16560f74f65a1af87e005740
[ "MIT" ]
permissive
mcaravario/so-tps
06edfa4ab73181572b738beee8458e4082eadc8b
75c995f275806fa2243d857226e243a94eb82af3
refs/heads/master
2021-01-10T07:26:59.985846
2016-04-08T05:08:29
2016-04-08T05:08:29
55,750,269
0
0
null
null
null
null
UTF-8
C++
false
false
1,671
cpp
sched_rr2.cpp
#include <vector> #include <queue> #include "sched_rr2.h" #include "basesched.h" #include <algorithm> using namespace std; SchedRR2::SchedRR2(vector<int> argn) { // Round robin recibe la cantidad de cores y sus cpu_quantum por parámetro for (int i = 0; i < argn[0]; i++){ cores.push_back(core_info(argn[i + 1])); } } SchedRR2::~SchedRR2() { } int SchedRR2::min_core() { return min_element(cores.begin(), cores.end(), core_cmp()) - cores.begin(); } void SchedRR2::load(int pid) { pid_a_core.insert(pair<int,int>(pid, min_core())); cores[min_core()].ready.push(pid); } void SchedRR2::unblock(int pid) { cores[pid_a_core[pid]].ready.push(pid); cores[pid_a_core[pid]].bloqueados--; } int SchedRR2::tick(int cpu, const enum Motivo m) { if (cores[cpu].ready.empty() && !cores[cpu].corriendo){ return IDLE_TASK; } if (m == EXIT) { pid_a_core.erase(current_pid(cpu)); cores[cpu].ciclos = 0; cores[cpu].corriendo = false; if (cores[cpu].ready.empty()) { return IDLE_TASK; } } else if (m == BLOCK) { cores[cpu].bloqueados++; cores[cpu].ciclos = 0; cores[cpu].corriendo = false; if (cores[cpu].ready.empty()) { return IDLE_TASK; } } else { if (current_pid(cpu) == IDLE_TASK) { cores[cpu].ciclos = 0; } else { cores[cpu].ciclos++; } if (cores[cpu].ciclos == cores[cpu].quantum) { cores[cpu].ciclos = 0; cores[cpu].ready.push(current_pid(cpu)); } else if (current_pid(cpu) != IDLE_TASK) { return current_pid(cpu); } } cores[cpu].corriendo = true; int n = cores[cpu].ready.front(); cores[cpu].ready.pop(); return n; }
74322af477136d6e17a000e3c6621ad10556eb9a
f7dc806f341ef5dbb0e11252a4693003a66853d5
/thirdparty/oidn/mkl-dnn/src/cpu/cpu_inner_product_pd.hpp
5880d3450cc75e6d6b1c1f01f9eeb734d1a1b437
[ "LicenseRef-scancode-free-unknown", "MIT", "CC-BY-4.0", "OFL-1.1", "Bison-exception-2.2", "CC0-1.0", "LicenseRef-scancode-nvidia-2002", "LicenseRef-scancode-other-permissive", "GPL-3.0-only", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "BSL-1.0", "Apache-2.0", "BSD-3-Clause", "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unicode", "BSD-2-Clause", "FTL", "GPL-3.0-or-later", "Bitstream-Vera", "Zlib", "MPL-2.0", "MIT-Modern-Variant", "JSON", "Libpng" ]
permissive
godotengine/godot
8a2419750f4851d1426a8f3bcb52cac5c86f23c2
970be7afdc111ccc7459d7ef3560de70e6d08c80
refs/heads/master
2023-08-21T14:37:00.262883
2023-08-21T06:26:15
2023-08-21T06:26:15
15,634,981
68,852
18,388
MIT
2023-09-14T21:42:16
2014-01-04T16:05:36
C++
UTF-8
C++
false
false
3,025
hpp
cpu_inner_product_pd.hpp
/******************************************************************************* * Copyright 2016-2018 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef CPU_INNER_PRODUCT_PD_HPP #define CPU_INNER_PRODUCT_PD_HPP #include <assert.h> #include "c_types_map.hpp" #include "inner_product_pd.hpp" #include "utils.hpp" namespace mkldnn { namespace impl { namespace cpu { namespace { inline bool dense_gemm_consitency_check(const memory_desc_wrapper &src_d, const memory_desc_wrapper &wei_d, const memory_desc_wrapper &dst_d) { using namespace utils; auto strides_compatible = [&]() { bool ok = true; auto w_str = wei_d.blocking_desc().strides; auto d_str = src_d.blocking_desc().strides; for (int i = 1; i < src_d.ndims() - 1; i++) { ok = ok && w_str[i] / d_str[i] == w_str[i + 1] / d_str[i + 1]; } return ok && one_of(w_str[1] / d_str[1], 1, wei_d.padded_dims()[0]); }; return true && src_d.is_blocking_desc() && wei_d.is_blocking_desc() && src_d.ndims() == wei_d.ndims() && src_d.blocking_desc().inner_nblks == wei_d.blocking_desc().inner_nblks && utils::one_of(src_d.blocking_desc().inner_nblks, 0, 1) && array_cmp(src_d.blocking_desc().inner_blks, wei_d.blocking_desc().inner_blks, wei_d.blocking_desc().inner_nblks) && array_cmp(src_d.blocking_desc().inner_idxs, wei_d.blocking_desc().inner_idxs, wei_d.blocking_desc().inner_nblks) && strides_compatible() && dst_d.matches_tag(format_tag::nc) && src_d.only_padded_dim(1) && wei_d.only_padded_dim(1) && src_d.padded_dims()[1] == wei_d.padded_dims()[1] && src_d.is_dense(true) && dst_d.is_dense() && wei_d.is_dense(true); } } struct cpu_inner_product_fwd_pd_t: public inner_product_fwd_pd_t { using inner_product_fwd_pd_t::inner_product_fwd_pd_t; }; struct cpu_inner_product_bwd_data_pd_t: public inner_product_bwd_data_pd_t { using inner_product_bwd_data_pd_t::inner_product_bwd_data_pd_t; }; struct cpu_inner_product_bwd_weights_pd_t: public inner_product_bwd_weights_pd_t { using inner_product_bwd_weights_pd_t::inner_product_bwd_weights_pd_t; }; } } } #endif // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
9bdc6feea36427f3710868ad6062a190c67623a8
4e9cd224ff2b7ba2ee82439c03113a1c3a795762
/src/solvers/NavierStokes/luoIBM/kernels/LHS1.h
39b42c123017214ac90fcc441988c9d9e7796865
[ "MIT" ]
permissive
chrisminar/cuIBM
e7d0620579dd8759e4bffa2adb927967cb7d71fd
8d4e8004f51bfc22e079c0f3443acd18df19c2af
refs/heads/master
2020-04-03T12:24:17.581407
2017-01-06T18:33:35
2017-01-06T18:33:35
30,205,199
0
1
null
2015-02-02T19:51:24
2015-02-02T19:51:24
null
UTF-8
C++
false
false
327
h
LHS1.h
#pragma once namespace kernels { __global__ void LHS1_mid_luo_X(int *row, int *col, double *val, int *ghostTagsUV, double *dx, double *dy, double dt, double nu, int nx, int ny); __global__ void LHS1_mid_luo_Y(int *row, int *col, double *val, int *ghostTagsUV, double *dx, double *dy, double dt, double nu, int nx, int ny); }
b46efd4c5a6af7e1fe13e6d4a518c454db17eefd
b38383846d082ec4e65ac18c1582f1ce231ea0b4
/Siv3D/include/Siv3D/CommonVector.hpp
aa3c06bc2e9858a88268ea52741ec553b4d375c5
[ "MIT" ]
permissive
Siv3D/siv6
9c12427f470b65772f40504b1e5e5239a60bbe95
090e82b2f6398640638dfa43da3f829ba977d0e2
refs/heads/master
2021-02-07T05:12:41.108547
2020-10-25T05:27:11
2020-10-25T05:27:11
243,986,884
3
5
MIT
2020-09-27T14:32:38
2020-02-29T14:50:43
C++
UTF-8
C++
false
false
1,519
hpp
CommonVector.hpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2020 Ryo Suzuki // Copyright (c) 2016-2020 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Common.hpp" # include "CommonFloat.hpp" namespace s3d { template <class T, class U, bool isScalar = (std::is_arithmetic_v<T>&& std::is_arithmetic_v<U>)> struct CommonVector {}; template <class T, class U> struct CommonVector<T, U, true> { using type = CommonFloat_t<T, U>; }; template <> struct CommonVector<Point, Point, false> { using type = Vec2; }; template <> struct CommonVector<Point, Float2, false> { using type = Float2; }; template <> struct CommonVector<Point, Vec2, false> { using type = Vec2; }; template <> struct CommonVector<Float2, Point, false> { using type = Float2; }; template <> struct CommonVector<Float2, Float2, false> { using type = Float2; }; template <> struct CommonVector<Float2, Vec2, false> { using type = Vec2; }; template <> struct CommonVector<Vec2, Point, false> { using type = Vec2; }; template <> struct CommonVector<Vec2, Float2, false> { using type = Vec2; }; template <> struct CommonVector<Vec2, Vec2, false> { using type = Vec2; }; template <class T, class U, bool isScalar = (std::is_arithmetic_v<T>&& std::is_arithmetic_v<U>)> using CommonVector_t = typename CommonVector<T, U, isScalar>::type; }
acbb918622b0f0e6810b77a7177593a842208d93
ce7be8660d0a8c8b7f2e9df24fc44a6cea8222b5
/ikaros/Source/UserModules/TouchId/TouchId.cc
af92fde3ca5d51ec613477ce80fad4acf13d50d8
[]
no_license
martingkarlssonstudent/SystemAffectiveTouch
3556eb53a09f7f0760616efcc375abfea44b077f
bee4e60aeb26d6521134a90feefdbb6ea872a76e
refs/heads/main
2023-08-05T11:01:13.505135
2021-09-14T18:21:26
2021-09-14T18:21:26
369,239,727
0
0
null
null
null
null
UTF-8
C++
false
false
8,577
cc
TouchId.cc
#include <fstream> #include <utility> #include <vector> #include <iostream> using namespace std; #include "TouchId.h" #include <math.h> #include <sstream> #include <string> #include <list> using namespace ikaros; Module * TouchId::Create(Parameter * p) { return new TouchId(p); } TouchId::TouchId(Parameter * p): Module(p) { CheckParameters(); } void TouchId::Init() { Bind(touchId_matrix_NoRows, "touchId_matrix_NoRows"); Bind(touchIdBuffer_matrix_NoRows, "touchIdBuffer_matrix_NoRows"); Bind(touchCertaintyCutoff, "touchCertaintyCutoff"); Bind(touchSignalNormFactor, "touchSignalNormFactor"); Bind(touchIdStageFactor, "touchIdStageFactor"); Bind(touchIdEnvFactor, "touchIdEnvFactor"); Bind(touchIdLabelId, "touchIdLabelId"); touchSignalInput_array = GetInputArray("TOUCHSIGNAL_INPUT"); touchSignalInput_NoCols = GetInputSize("TOUCHSIGNAL_INPUT"); touchActiveOutput_array = GetOutputArray("TOUCHACTIVE_OUTPUT"); touchCertainty_matrix = GetOutputMatrix("TOUCHCERTAINTY_OUTPUT"); touchCertainty_NoRows = GetOutputSizeX("TOUCHCERTAINTY_OUTPUT"); touchIdOutput_array = GetOutputArray("TOUCHID_OUTPUT"); touchTimeOutput_array = GetOutputArray("TOUCHTIME_OUTPUT"); noTouchesIdOutput_array = GetOutputArray("NOTOUCHESID_OUTPUT"); touchIdBuffer_matrix = create_matrix(touchSignalInput_NoCols, touchIdBuffer_matrix_NoRows); //Creates a new internal matrix for (int i=0; i<touchIdBuffer_matrix_NoRows; i++) { for (int j=0; j<touchSignalInput_NoCols; j++) { touchIdBuffer_matrix[i][j] = 0; } } predictOn = true; train = true; std::string touchIdFileStr; std::string touchIdLabelFileStr; touchIdFileStr.append("/home/martin/ikaros/Source/UserModules/TouchAnalysis/Examples/touchId_"); std::ostringstream touchIdStageFactorStrS; touchIdStageFactorStrS << touchIdStageFactor; touchIdFileStr.append(touchIdStageFactorStrS.str()); touchIdFileStr.append(".csv"); touchIdLabelFileStr.append("/home/martin/ikaros/Source/UserModules/TouchAnalysis/Examples/touchIdLabel_"); touchIdLabelFileStr.append(touchIdStageFactorStrS.str()); touchIdLabelFileStr.append(".csv"); touchIdCSVfile.open(touchIdFileStr, std::ofstream::out | std::ofstream::app); touchIdLabelCSVfile.open(touchIdLabelFileStr,std::ofstream::out | std::ofstream::app); } TouchId::~TouchId() { // Destroy data structures that is allocated in Init. destroy_matrix(touchIdBuffer_matrix); touchIdCSVfile.close(); touchIdLabelCSVfile.close(); } void TouchId::Command(std::string s, float x, float y, std::string value) { if(s == "predict") Predict(); } void TouchId::Predict() { if (predictOn) { predictOn =false; } else { predictOn = true; } printf("Predict\n"); } static inline int naive_bayesian(float * buffer, float * means, float * variances, int length,int max_movements,float threshold) { float buffer_mean = mean(buffer,length); float out_prop = 0; float cat = -1; for(int i=0; i < max_movements; i++){ float m = means[i]; float v = variances[i]; float prob = 1 / sqrt(2 * pi * v) * exp(-sqr(buffer_mean-m) / (2 * v)); if(prob > out_prop){ out_prop = prob; cat = i; } } printf("out_prop: %f \n",out_prop); if(out_prop < threshold){ cat = -1; } return cat; } void TouchId::Tick() { // int touchSignal = 0; touchActive = false; touchActiveOutput_array[0] = 0; sumTouchBufferSignal = 0; changeTouchBufferSignal = 0; // float * changeTouchBufferSignal_array; // float meanChangeTouchBufferSignal = 0; // changeTouchBufferSignal = create_array(12); cout << "touchIdBuffer_matrix_row: " << touchIdBuffer_matrix_row << endl; for (int i=0; i<touchSignalInput_NoCols; i++) { touchIdBuffer_matrix[touchIdBuffer_matrix_row][i] = touchSignalInput_array[i]/touchSignalNormFactor; } touchIdBuffer_matrix_row++; if (touchIdBuffer_matrix_row == touchIdBuffer_matrix_NoRows) { touchIdBuffer_matrix_row = 0; } for (int i=0; i<touchIdBuffer_matrix_NoRows; i++) { /* int iCompare; if (i == 0) { iCompare = 9; } else { iCompare = i-1; } */ for (int j=0; j<touchSignalInput_NoCols; j++) { sumTouchBufferSignal += touchIdBuffer_matrix[i][j]; // changeTouchBufferSignal[j] += touchIdBuffer_matrix[i][j] - touchIdBuffer_matrix[iCompare][j]; } } changeTouchBufferSignal = sumTouchBufferSignal - sumTouchBufferSignalPrev; sumTouchBufferSignalPrev = sumTouchBufferSignal; // int c = naive_bayesian(buffer_angle,mean_array,variance_array,input_length,max_movements,baysian_threshold); cout << "sumTouchBufferSignal: " << sumTouchBufferSignal << endl; // meanChangeTouchBufferSignal = mean(changeTouchBufferSignal,12); // cout << "meanChangeTouchBufferSignal: " << meanChangeTouchBufferSignal << endl; cout << "changeTouchBufferSignal: " << changeTouchBufferSignal << endl; // std::cout << '\n'; if (noTicks > 0) { touchActive = true; } else { // for (int i=0; i<touchSignalInput_NoCols; i++) // { // touchSignal = touchSignalInput_array[i]; // if (touchSignal > 0.5) if (sumTouchBufferSignal > touchIdStageFactor/touchSignalNormFactor) { touchActive = true; cout << "Touch active" << endl; // break; } // } } touchEnv_Previous = touchEnv_Current; if (!touchActive) { touchEnv_Current = none; } else if (abs(changeTouchBufferSignal)<touchIdEnvFactor*touchIdStageFactor/touchSignalNormFactor) { touchEnv_Current = sustain; } else if (changeTouchBufferSignal>0) { touchEnv_Current = attack; } else if (changeTouchBufferSignal<0) { touchEnv_Current = release; } if (touchActive) { if (noTicks == 0) { touchId_matrix_NoRows = touchId_matrix_NoRows; touchId_matrix_row = 0; touchId_matrix = create_matrix(touchSignalInput_NoCols,touchId_matrix_NoRows); //Creates a new internal matrix while (touchId_matrix_row < touchId_matrix_NoRows) { for (int j=0; j<touchSignalInput_NoCols; j++) { touchId_matrix[touchId_matrix_row][j] = 0; } touchId_matrix_row++; } touchId_matrix_row = 0; } noTicks++; touchTimeOutput_array[0] = noTicks*0.035; for (int i=0; i<touchSignalInput_NoCols; i++) { touchId_matrix[touchId_matrix_row][i] = touchSignalInput_array[i]/touchSignalNormFactor; } touchId_matrix_row++; cout << "touchEnv_Current: " << touchEnv_Current << endl; cout << "touchEnv_Previous: " << touchEnv_Previous << endl; int touchId_matrix_row_tmp = 0; if (sumTouchBufferSignal < touchIdStageFactor/(2*touchSignalNormFactor)) { touchId_matrix_row = touchId_matrix_NoRows; } else if (touchEnv_Current != touchEnv_Previous && touchEnv_Previous != none && touchEnv_Current != none) { touchId_matrix_row_tmp = touchId_matrix_NoRows; } cout << "touchId_matrix_row: " << touchId_matrix_row << endl; cout << "touchId_matrix_row_tmp: " << touchId_matrix_row_tmp << endl; if (touchId_matrix_row == touchId_matrix_NoRows || (touchId_matrix_row_tmp == touchId_matrix_NoRows && predictOn)) { cout << "touchId_matrix"; std::cout << '\n'; int touchIdOutputCol = 0; for (int i=0; i<touchId_matrix_NoRows; i++) { for (int j=0; j<touchSignalInput_NoCols; j++) { cout << touchId_matrix[i][j] << " "; touchIdOutput_array[touchIdOutputCol] = touchId_matrix[i][j]; touchIdOutputCol++; } } std::cout << '\n'; if (touchId_matrix_row == touchId_matrix_NoRows) { if (train) { cout << "CSV out" << endl; int touchId_array_NoCols = touchSignalInput_NoCols*touchId_matrix_NoRows; for (int i=0; i<touchId_array_NoCols; i++) { if (i==touchId_array_NoCols-1) { touchIdCSVfile << touchIdOutput_array[i]; } else { touchIdCSVfile << touchIdOutput_array[i] << ", "; } } touchIdCSVfile << endl; touchIdLabelCSVfile << touchIdLabelId; touchIdLabelCSVfile << endl; noTouchesId++; noTouchesIdOutput_array[0] = noTouchesId; } noTicks = 0; touchId_matrix_row = 0; destroy_matrix(touchId_matrix); } if (predictOn) { touchActiveOutput_array[0] = 1; } } } } void TouchId::CheckParameters() { } static InitClass init("TouchId", &TouchId::Create, "Source/UserModules/TouchId/");
1156217c9e854a07e25885f0d0a2733d8daf26d9
0254126b4db8b5cec973c3f314241eaf874653ac
/libs/ml/include/ml/optimisation/optimiser.hpp
a631d32614620c5dcc5b7a59e0a5120a38d222b7
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
devjsc/ledger-1
3a43bc1366637675122c60cdcf5d7ecf28cb5593
2aa68e05b9f9c10a9971fc8ddf4848695511af3c
refs/heads/develop
2020-05-01T17:00:54.682373
2019-06-05T14:09:57
2019-06-05T14:09:57
177,588,292
0
0
Apache-2.0
2019-06-05T15:24:51
2019-03-25T13:06:56
C++
UTF-8
C++
false
false
4,422
hpp
optimiser.hpp
#pragma once //------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // 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 "math/base_types.hpp" #include "ml/graph.hpp" #include "ml/ops/loss_functions/criterion.hpp" namespace fetch { namespace ml { namespace optimisers { /** * Abstract gradient optimiser class * @tparam T ArrayType * @tparam C CriterionType */ template <class T, class C> class Optimiser { public: using ArrayType = T; using CriterionType = C; using DataType = typename ArrayType::Type; using SizeType = typename ArrayType::SizeType; Optimiser(std::shared_ptr<Graph<T>> graph, std::string const &input_node_name, std::string const &output_node_name, DataType const &learning_rate = DataType{0.001f}); // TODO (private 1090): Optimise TensorSlice for graph-feeding without using .Copy DataType Run(ArrayType &data, ArrayType &labels, SizeType batch_size = 0); protected: std::shared_ptr<Graph<T>> graph_; CriterionType criterion_; std::string input_node_name_ = ""; std::string output_node_name_ = ""; DataType learning_rate_ = fetch::math::numeric_max<DataType>(); std::vector<std::shared_ptr<fetch::ml::ops::Trainable<ArrayType>>> graph_trainables_; std::vector<ArrayType> gradients_; SizeType epoch_ = fetch::math::numeric_max<SizeType>(); private: virtual void ApplyGradients(SizeType batch_size) = 0; }; template <class T, class C> Optimiser<T, C>::Optimiser(std::shared_ptr<Graph<T>> graph, std::string const &input_node_name, std::string const &output_node_name, DataType const &learning_rate) : graph_(graph) , input_node_name_(input_node_name) , output_node_name_(output_node_name) , learning_rate_(learning_rate) , epoch_(0) { graph_trainables_ = graph_->get_trainables(); for (auto &train : graph_trainables_) { this->gradients_.emplace_back(ArrayType(train->get_weights().shape())); } } /** * * @tparam T ArrayType * @tparam C CriterionType * @param data training data * @param labels training labels * @param batch_size size of mini-batch, if batch_size==0 it will be set to n_data size * @return Sum of losses from all mini-batches */ // TODO (private 1090): Optimise TensorSlice for graph-feeding without using .Copy template <class T, class C> typename T::Type Optimiser<T, C>::Run(ArrayType &data, ArrayType &labels, SizeType batch_size) { // Get trailing dimensions SizeType n_data_dimm = data.shape().size() - 1; SizeType n_label_dimm = labels.shape().size() - 1; SizeType n_data = data.shape().at(n_data_dimm); // If batch_size is not specified do full batch if (batch_size == 0) { batch_size = n_data; } DataType loss; DataType loss_sum{0}; SizeType step{0}; while (step < n_data) { loss = DataType{0}; // Do batch back-propagation for (SizeType it{step}; (it < step + batch_size) && (it < n_data); ++it) { auto cur_input = data.Slice(it, n_data_dimm).Copy(); graph_->SetInput(input_node_name_, cur_input); auto cur_label = labels.Slice(it, n_label_dimm).Copy(); auto label_pred = graph_->Evaluate(output_node_name_); loss += criterion_.Forward({label_pred, cur_label}); graph_->BackPropagate(output_node_name_, criterion_.Backward({label_pred, cur_label})); } // Compute and apply gradient ApplyGradients(batch_size); FETCH_LOG_INFO("ML_LIB", "Loss: ", loss); step += batch_size; } loss_sum += loss; epoch_++; return loss_sum; } } // namespace optimisers } // namespace ml } // namespace fetch
3f27376bb1400cd7386d9afdadb1938db2bdf419
627d4d432c86ad98f669214d9966ae2db1600b31
/src/core/io/qfilesystemmetadata_p.h
57c25b2f00a4c634ec74ecffa8eeaa824a5ba18f
[]
no_license
fluxer/copperspice
6dbab905f71843b8a3f52c844b841cef17f71f3f
07e7d1315d212a4568589b0ab1bd6c29c06d70a1
refs/heads/cs-1.1
2021-01-17T21:21:54.176319
2015-08-26T15:25:29
2015-08-26T15:25:29
39,802,091
6
0
null
2015-07-27T23:04:01
2015-07-27T23:04:00
null
UTF-8
C++
false
false
12,122
h
qfilesystemmetadata_p.h
/*********************************************************************** * * Copyright (c) 2012-2015 Barbara Geller * Copyright (c) 2012-2015 Ansel Sermersheim * Copyright (c) 2012-2014 Digia Plc and/or its subsidiary(-ies). * Copyright (c) 2008-2012 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * * This file is part of CopperSpice. * * CopperSpice is free software: you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 as published by the Free Software Foundation. * * CopperSpice is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with CopperSpice. If not, see * <http://www.gnu.org/licenses/>. * ***********************************************************************/ #ifndef QFILESYSTEMMETADATA_P_H #define QFILESYSTEMMETADATA_P_H #include <qplatformdefs.h> #include <QtCore/qglobal.h> #include <QtCore/qdatetime.h> #include <QtCore/qabstractfileengine.h> // Platform-specific includes #if defined(Q_OS_WIN) #ifndef IO_REPARSE_TAG_SYMLINK #define IO_REPARSE_TAG_SYMLINK (0xA000000CL) #endif #endif QT_BEGIN_NAMESPACE class QFileSystemEngine; class QFileSystemMetaData { public: QFileSystemMetaData() : knownFlagsMask(0) { } enum MetaDataFlag { // Permissions, overlaps with QFile::Permissions OtherReadPermission = 0x00000004, OtherWritePermission = 0x00000002, OtherExecutePermission = 0x00000001, GroupReadPermission = 0x00000040, GroupWritePermission = 0x00000020, GroupExecutePermission = 0x00000010, UserReadPermission = 0x00000400, UserWritePermission = 0x00000200, UserExecutePermission = 0x00000100, OwnerReadPermission = 0x00004000, OwnerWritePermission = 0x00002000, OwnerExecutePermission = 0x00001000, OtherPermissions = OtherReadPermission | OtherWritePermission | OtherExecutePermission, GroupPermissions = GroupReadPermission | GroupWritePermission | GroupExecutePermission, UserPermissions = UserReadPermission | UserWritePermission | UserExecutePermission, OwnerPermissions = OwnerReadPermission | OwnerWritePermission | OwnerExecutePermission, ReadPermissions = OtherReadPermission | GroupReadPermission | UserReadPermission | OwnerReadPermission, WritePermissions = OtherWritePermission | GroupWritePermission | UserWritePermission | OwnerWritePermission, ExecutePermissions = OtherExecutePermission | GroupExecutePermission | UserExecutePermission | OwnerExecutePermission, Permissions = OtherPermissions | GroupPermissions | UserPermissions | OwnerPermissions, // Type LinkType = 0x00010000, FileType = 0x00020000, DirectoryType = 0x00040000, #if !defined(QWS) && !defined(Q_WS_QPA) && defined(Q_OS_MAC) BundleType = 0x00080000, AliasType = 0x08000000, #else BundleType = 0x0, AliasType = 0x0, #endif #if defined(Q_OS_WIN) WinLnkType = 0x08000000, // Note: Uses the same position for AliasType on Mac #else WinLnkType = 0x0, #endif SequentialType = 0x00800000, // Note: overlaps with QAbstractFileEngine::RootFlag LegacyLinkType = LinkType | AliasType | WinLnkType, Type = LinkType | FileType | DirectoryType | BundleType | SequentialType | AliasType, // Attributes HiddenAttribute = 0x00100000, SizeAttribute = 0x00200000, // Note: overlaps with QAbstractFileEngine::LocalDiskFlag ExistsAttribute = 0x00400000, Attributes = HiddenAttribute | SizeAttribute | ExistsAttribute, // Times CreationTime = 0x01000000, // Note: overlaps with QAbstractFileEngine::Refresh ModificationTime = 0x02000000, AccessTime = 0x04000000, Times = CreationTime | ModificationTime | AccessTime, // Owner IDs UserId = 0x10000000, GroupId = 0x20000000, OwnerIds = UserId | GroupId, PosixStatFlags = QFileSystemMetaData::OtherPermissions | QFileSystemMetaData::GroupPermissions | QFileSystemMetaData::OwnerPermissions | QFileSystemMetaData::FileType | QFileSystemMetaData::DirectoryType | QFileSystemMetaData::SequentialType | QFileSystemMetaData::SizeAttribute | QFileSystemMetaData::Times | QFileSystemMetaData::OwnerIds, SymbianTEntryFlags = QFileSystemMetaData::Permissions | QFileSystemMetaData::FileType | QFileSystemMetaData::DirectoryType | QFileSystemMetaData::SequentialType | QFileSystemMetaData::Attributes | QFileSystemMetaData::Times, #if defined(Q_OS_WIN) WinStatFlags = QFileSystemMetaData::FileType | QFileSystemMetaData::DirectoryType | QFileSystemMetaData::HiddenAttribute | QFileSystemMetaData::ExistsAttribute | QFileSystemMetaData::SizeAttribute | QFileSystemMetaData::Times, #endif AllMetaDataFlags = 0xFFFFFFFF }; using MetaDataFlags = QFlags<MetaDataFlag>; bool hasFlags(MetaDataFlags flags) const { return ((knownFlagsMask & flags) == flags); } MetaDataFlags missingFlags(MetaDataFlags flags) { return flags & ~knownFlagsMask; } void clear() { knownFlagsMask = 0; } void clearFlags(MetaDataFlags flags = AllMetaDataFlags) { knownFlagsMask &= ~flags; } bool exists() const { return (entryFlags & ExistsAttribute); } bool isLink() const { return (entryFlags & LinkType); } bool isFile() const { return (entryFlags & FileType); } bool isDirectory() const { return (entryFlags & DirectoryType); } bool isBundle() const; bool isAlias() const; bool isLegacyLink() const { return (entryFlags & LegacyLinkType); } bool isSequential() const { return (entryFlags & SequentialType); } bool isHidden() const { return (entryFlags & HiddenAttribute); } #if defined(Q_OS_WIN) bool isLnkFile() const { return (entryFlags & WinLnkType); } #else bool isLnkFile() const { return false; } #endif qint64 size() const { return size_; } QFile::Permissions permissions() const { return QFile::Permissions(Permissions & entryFlags); } QDateTime creationTime() const; QDateTime modificationTime() const; QDateTime accessTime() const; QDateTime fileTime(QAbstractFileEngine::FileTime time) const; uint userId() const; uint groupId() const; uint ownerId(QAbstractFileEngine::FileOwner owner) const; #ifdef Q_OS_UNIX void fillFromStatBuf(const QT_STATBUF &statBuffer); void fillFromDirEnt(const QT_DIRENT &statBuffer); #endif #if defined(Q_OS_WIN) inline void fillFromFileAttribute(DWORD fileAttribute, bool isDriveRoot = false); inline void fillFromFindData(WIN32_FIND_DATA &findData, bool setLinkType = false, bool isDriveRoot = false); inline void fillFromFindInfo(BY_HANDLE_FILE_INFORMATION &fileInfo); #endif private: friend class QFileSystemEngine; MetaDataFlags knownFlagsMask; MetaDataFlags entryFlags; qint64 size_; // Platform-specific data goes here: #if defined(Q_OS_WIN) DWORD fileAttribute_; FILETIME creationTime_; FILETIME lastAccessTime_; FILETIME lastWriteTime_; #else time_t creationTime_; time_t modificationTime_; time_t accessTime_; uint userId_; uint groupId_; #endif }; Q_DECLARE_OPERATORS_FOR_FLAGS(QFileSystemMetaData::MetaDataFlags) #if !defined(QWS) && ! defined(Q_WS_QPA) && defined(Q_OS_MAC) inline bool QFileSystemMetaData::isBundle() const { return (entryFlags & BundleType); } inline bool QFileSystemMetaData::isAlias() const { return (entryFlags & AliasType); } #else inline bool QFileSystemMetaData::isBundle() const { return false; } inline bool QFileSystemMetaData::isAlias() const { return false; } #endif #if (defined(Q_OS_UNIX)) || defined (Q_OS_WIN) inline QDateTime QFileSystemMetaData::fileTime(QAbstractFileEngine::FileTime time) const { switch (time) { case QAbstractFileEngine::ModificationTime: return modificationTime(); case QAbstractFileEngine::AccessTime: return accessTime(); case QAbstractFileEngine::CreationTime: return creationTime(); } return QDateTime(); } #endif #if defined(Q_OS_UNIX) inline QDateTime QFileSystemMetaData::creationTime() const { return QDateTime::fromTime_t(creationTime_); } inline QDateTime QFileSystemMetaData::modificationTime() const { return QDateTime::fromTime_t(modificationTime_); } inline QDateTime QFileSystemMetaData::accessTime() const { return QDateTime::fromTime_t(accessTime_); } inline uint QFileSystemMetaData::userId() const { return userId_; } inline uint QFileSystemMetaData::groupId() const { return groupId_; } inline uint QFileSystemMetaData::ownerId(QAbstractFileEngine::FileOwner owner) const { if (owner == QAbstractFileEngine::OwnerUser) { return userId(); } else { return groupId(); } } #endif #if defined(Q_OS_WIN) inline uint QFileSystemMetaData::userId() const { return (uint) - 2; } inline uint QFileSystemMetaData::groupId() const { return (uint) - 2; } inline uint QFileSystemMetaData::ownerId(QAbstractFileEngine::FileOwner owner) const { if (owner == QAbstractFileEngine::OwnerUser) { return userId(); } else { return groupId(); } } inline void QFileSystemMetaData::fillFromFileAttribute(DWORD fileAttribute, bool isDriveRoot) { fileAttribute_ = fileAttribute; // Ignore the hidden attribute for drives if (! isDriveRoot && (fileAttribute_ & FILE_ATTRIBUTE_HIDDEN)) { entryFlags |= HiddenAttribute; } entryFlags |= ((fileAttribute & FILE_ATTRIBUTE_DIRECTORY) ? DirectoryType : FileType); entryFlags |= ExistsAttribute; knownFlagsMask |= FileType | DirectoryType | HiddenAttribute | ExistsAttribute; } inline void QFileSystemMetaData::fillFromFindData(WIN32_FIND_DATA &findData, bool setLinkType, bool isDriveRoot) { fillFromFileAttribute(findData.dwFileAttributes, isDriveRoot); creationTime_ = findData.ftCreationTime; lastAccessTime_ = findData.ftLastAccessTime; lastWriteTime_ = findData.ftLastWriteTime; if (fileAttribute_ & FILE_ATTRIBUTE_DIRECTORY) { size_ = 0; } else { size_ = findData.nFileSizeHigh; size_ <<= 32; size_ += findData.nFileSizeLow; } knownFlagsMask |= Times | SizeAttribute; if (setLinkType) { knownFlagsMask |= LinkType; entryFlags &= ~LinkType; if ((fileAttribute_ & FILE_ATTRIBUTE_REPARSE_POINT) && findData.dwReserved0 == IO_REPARSE_TAG_SYMLINK) { entryFlags |= LinkType; } } } inline void QFileSystemMetaData::fillFromFindInfo(BY_HANDLE_FILE_INFORMATION &fileInfo) { fillFromFileAttribute(fileInfo.dwFileAttributes); creationTime_ = fileInfo.ftCreationTime; lastAccessTime_ = fileInfo.ftLastAccessTime; lastWriteTime_ = fileInfo.ftLastWriteTime; if (fileAttribute_ & FILE_ATTRIBUTE_DIRECTORY) { size_ = 0; } else { size_ = fileInfo.nFileSizeHigh; size_ <<= 32; size_ += fileInfo.nFileSizeLow; } knownFlagsMask |= Times | SizeAttribute; } #endif QT_END_NAMESPACE #endif // include guard
08fda4f9c7e86400208bcb7b8dc3c10f56055045
029b00470f7e54d2cc1e0481ea2064b670a8e08e
/src/Game/GameStates/MapEditorState.cpp
5f832d7d1b80be3f31938c7c81feaec536b5f4ad
[]
no_license
MaxBuilder/LifProjet
85f15269dc5a426028c52487494aec878651089b
ab57d855d18d370aaaf97f6dcbacdd2d667f320e
refs/heads/master
2023-04-05T02:31:42.552568
2021-05-03T06:33:45
2021-05-03T06:33:45
333,030,489
0
0
null
null
null
null
UTF-8
C++
false
false
20,373
cpp
MapEditorState.cpp
// // Created by thibaut on 01/02/2021. // #include "MapEditorState.hpp" MapEditorState::MapEditorState(StateStack &stack, Context context) : State(stack, context) , map(context.textures.get(Textures::MapGround), context.textures.get(Textures::EditorAllSoldiers), 16.f) , mPaletteBar(sf::IntRect(1130,100,150,550),4) , mBuildingbar(sf::IntRect(1130,100,150,550),4) , subBackground(getContext().textures.get(Textures::SubBackground)) { mEntity = EntityInfo::None; mTeam = EntityInfo::Team::Red; background.setTexture(context.textures.get(Textures::EditorBackground)); map.setPosition(92,90); mapPath.setFont(context.fonts.get(Fonts::Main)); mapPath.setPosition(8, 684); mapPath.setCharacterSize(20u); editorCoord.setFont(context.fonts.get(Fonts::Main)); editorCoord.setCharacterSize(20u); rotate = 0.f; MapEditorState::mMapPath = "Unsaved"; ground_selection = sf::Vector2i (1,0); lastGround = sf::Vector2i (0,0); lastTileUpdate = {-1,-1}; tool = Editor::Tool::Standard; // Edit buttons : auto backButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorBackButton); backButton->setPosition(16, 10); backButton->setCallback([this](){ requestStackPop(); getContext().sounds.play(Sounds::Menu); }); mEditBar.pack(backButton); auto newButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorNewButton); newButton->setPosition(98, 10); newButton->setCallback([this] () { map.clear(); getContext().sounds.play(Sounds::Menu); }); mEditBar.pack(newButton); auto saveButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorSaveButton); saveButton->setPosition(170, 10); saveButton->setCallback([this] () { subMenu = true; saveload = true; getContext().sounds.play(Sounds::Menu); }); mEditBar.pack(saveButton); auto loadButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorLoadButton); loadButton->setPosition(242, 10); loadButton->setCallback([this] () { subMenu = true; saveload = false; getContext().sounds.play(Sounds::Menu); }); mEditBar.pack(loadButton); auto undoButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorUndoButton); undoButton->setPosition(324, 10); undoButton->setCallback([this] () { getContext().sounds.play(Sounds::Menu); }); mEditBar.pack(undoButton); auto redoButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorRedoButton); redoButton->setPosition(396, 10); redoButton->setCallback([this] () { getContext().sounds.play(Sounds::Menu); }); mEditBar.pack(redoButton); // Soldier selection : auto teamColor = std::make_shared<GUI::CheckBox>(context, 60, 60, Textures::EditorTeamColor); teamColor->setToggle(true); teamColor->setPosition(992, 10); teamColor->activate(); teamColor->setCallback([this] (bool red) { if(red) mTeam = EntityInfo::Red; else mTeam = EntityInfo::Blue; getContext().sounds.play(Sounds::Menu); }); teamColor->activate(); mTeamSelection.pack(teamColor); // Tool bar buttons : auto smallBrushButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::ToolSmallBrush); smallBrushButton->setPosition(16, 98); smallBrushButton->setToggle(true); smallBrushButton->activate(); smallBrushButton->setCallback([this]() { tool = Editor::Tool::Standard; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(smallBrushButton); auto mediumBrushButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::ToolMediumBrush); mediumBrushButton->setPosition(16, 164); mediumBrushButton->setToggle(true); mediumBrushButton->setCallback([this]() { tool = Editor::Tool::Square3; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(mediumBrushButton); auto bigBrushButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::ToolBigBrush); bigBrushButton->setPosition(16, 230); bigBrushButton->setToggle(true); bigBrushButton->setCallback([this](){ tool = Editor::Tool::Standard; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(bigBrushButton); auto eraserButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::ToolEraser); eraserButton->setPosition(16, 296); eraserButton->setToggle(true); eraserButton->setCallback([this]() { tool = Editor::Tool::Eraser; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(eraserButton); auto fillButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::ToolFill); fillButton->setPosition(16, 362); fillButton->setToggle(true); fillButton->setCallback([this]() { tool = Editor::Tool::Fill; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(fillButton); auto knightButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorKnight); knightButton->setToggle(true); knightButton->setPosition(1064, 10); knightButton->setCallback([this] () { tool = Editor::Tool::PlaceSoldier; mEntity = EntityInfo::ID::Knight; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(knightButton); auto archerButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorArcher); archerButton->setToggle(true); archerButton->setPosition(1136, 10); archerButton->setCallback([this] () { tool = Editor::Tool::PlaceSoldier; mEntity = EntityInfo::ID::Archer; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(archerButton); auto tankButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorTank); tankButton->setToggle(true); tankButton->setPosition(1208, 10); tankButton->setCallback([this] () { tool = Editor::Tool::PlaceSoldier; mEntity = EntityInfo::ID::Tank; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(tankButton); auto buildingButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorBuilding); buildingButton->setToggle(true); buildingButton->setPosition(910, 10); buildingButton->setCallback([this] () { tool = Editor::Tool::PlaceBuilding; mEntity = EntityInfo::None; getContext().sounds.play(Sounds::Menu); }); mToolBar.pack(buildingButton); // Rotation bar buttons : auto rotateUpButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorRotateUpButton); rotateUpButton->setPosition(16, 532); rotateUpButton->setToggle(true); rotateUpButton->activate(); rotateUpButton->setCallback([this] () { rotate = 0.f; getContext().sounds.play(Sounds::Menu); }); mRotationBar.pack(rotateUpButton); auto rotateRightButton = std::make_shared<GUI::Button>(context, 60, 60, Textures::EditorRotateRightButton); rotateRightButton->setPosition(16, 598); rotateRightButton->setToggle(true); rotateRightButton->setCallback([this] () { rotate = 90.f; getContext().sounds.play(Sounds::Menu); }); mRotationBar.pack(rotateRightButton); // Texture selection buttons : for(int y(0); y < 36; y++) { for (int x(0); x < 3;x++) { addButtonTexture(sf::Vector2i(x,y), sf::Vector2i(1134+44*x,100+44*y)); } } // Buildings selection : for(int y(36); y < 46; y++) { for (int x(0); x < 3;x++) { addButtonBuilding(sf::Vector2i(x,y), sf::Vector2i(1134+44*x,100+44*(y-36))); } } // Boutons du sous-menu : auto map1 = std::make_shared<GUI::Button>(context, 500, 70, Textures::MenuButton); map1->setPosition(380, 200); map1->setText("Save 1"); map1->setCallback([this] () { mMapPath = "data/MapData/editor1.map"; subMenu = false; if(saveload) map.save(MapEditorState::mMapPath); else { map.load(MapEditorState::mMapPath); } getContext().sounds.play(Sounds::Menu); }); mSubMenu.pack(map1); auto map2 = std::make_shared<GUI::Button>(context, 500, 70, Textures::MenuButton); map2->setPosition(380, 280); map2->setText("Save 2"); map2->setCallback([this] () { mMapPath = "data/MapData/editor2.map"; subMenu = false; if(saveload) map.save(MapEditorState::mMapPath); else { map.load(MapEditorState::mMapPath); } getContext().sounds.play(Sounds::Menu); }); mSubMenu.pack(map2); auto map3 = std::make_shared<GUI::Button>(context, 500, 70, Textures::MenuButton); map3->setPosition(380, 360); map3->setText("Save 3"); map3->setCallback([this] () { mMapPath = "data/MapData/editor3.map"; subMenu = false; if(saveload) map.save(MapEditorState::mMapPath); else { map.load(MapEditorState::mMapPath); } getContext().sounds.play(Sounds::Menu); }); mSubMenu.pack(map3); auto ret = std::make_shared<GUI::Button>(context, 500, 70, Textures::MenuButton); ret->setPosition(380, 500); ret->setText("Back"); ret->setCallback([this] () { subMenu = false; getContext().sounds.play(Sounds::Menu); }); mSubMenu.pack(ret); } void MapEditorState::draw() { sf::RenderWindow& window = getContext().window; window.draw(background); window.draw(map); window.draw(mEditBar); window.draw(mToolBar); window.draw(mRotationBar); window.draw(mTeamSelection); switch (tool) { case Editor::Tool::PlaceBuilding : window.draw(mBuildingbar); break; default: window.draw(mPaletteBar); break; } mapPath.setString(mMapPath); window.draw(mapPath); if(subMenu) { window.draw(subBackground); window.draw(mSubMenu); } window.draw(editorCoord); } bool MapEditorState::update(sf::Time dt) { if(coords != sf::Vector2i(-1, -1)) { editorCoord.setString("(" + std::to_string(coords.x) + "," + std::to_string(coords.y) + ")"); reverseOrigin(editorCoord); editorCoord.setPosition(1272, 690); } else editorCoord.setString(""); return false; } bool MapEditorState::handleEvent(const sf::Event& event) { if(subMenu) { mSubMenu.handleEvent(event, getContext().window); return false; } mEditBar.handleEvent(event, getContext().window); mToolBar.handleEvent(event, getContext().window); mRotationBar.handleEvent(event, getContext().window); mTeamSelection.handleCheckBoxEvent(event,getContext().window); switch (tool) { case Editor::Tool::PlaceBuilding : mBuildingbar.handleEvent(event, getContext().window); break; default: mPaletteBar.handleEvent(event, getContext().window); break; } if (event.type == sf::Event::MouseMoved or event.type == sf::Event::MouseButtonPressed){ sf::Vector2i WindowPosition = sf::Mouse::getPosition(getContext().window); sf::Vector2i pos = static_cast<sf::Vector2i>( getContext().window.mapPixelToCoords(WindowPosition)); if (pos.x < 1116 and pos.x >= 92 and pos.y >= 90 and pos.y < 666 ) { auto caseSize = map.getBlockSize(); sf::Vector2f origin = map.getPosition(); pos.y = pos.y - origin.y; pos.x = pos.x - origin.x; coords = sf::Vector2i(pos.x / caseSize + 1, pos.y / caseSize + 1); pos.y = pos.y/caseSize; pos.x = pos.x/caseSize; if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) { if (lastTileUpdate == pos and lastGround == ground_selection) return false; else { lastTileUpdate = pos; lastGround = ground_selection; } switch (tool) { case Editor::Tool::Standard : map.getTile(pos.x,pos.y).paint(ground_selection,rotate); break; case Editor::Tool::Square3 : paintSquare3(pos); break; case Editor::Tool::Fill : paintFill(pos); break; case Editor::Tool::Eraser : if(not supressSoldier(pos) and not (supressBuildings(pos))) map.getTile(pos.x,pos.y).paint(sf::Vector2i (0,0),0); break; case Editor::Tool::PlaceSoldier : createSoldier(pos); break; case Editor::Tool::PlaceBuilding: createBuildings(pos); break; default : break; } } } else coords = sf::Vector2i(-1, -1); } return false; } void MapEditorState::addButtonBuilding(sf::Vector2i id, sf::Vector2i pos) { auto button = std::make_shared<GUI::ButtonTexture>(getContext(), 40, 40, Textures::MapGround,id); button->setPosition(pos.x, pos.y); button->setToggle(true); button->setCallback([this](sf::Vector2i bId){ EntityInfo::ID buildId = EntityInfo::ID::None; EntityInfo::Team team = EntityInfo::Team::Blue; if ((bId.y == 37 or bId.y == 36) and (bId.x == 0 or bId.x == 1)) { bId.y = 36; bId.x = 0; buildId = EntityInfo::ID::Village; team = EntityInfo::Team::Red; } else if ((bId.y == 36 or bId.y == 37) and bId.x == 2) { buildId = EntityInfo::ID::Barrier; team = EntityInfo::Team::Red; } else if ((bId.y == 39 or bId.y == 38) and (bId.x == 0 or bId.x == 1)){ bId.y = 38; bId.x = 0; buildId = EntityInfo::ID::Village; team = EntityInfo::Team::Blue; } else if ((bId.y == 39 or bId.y == 38) and bId.x == 2) { buildId = EntityInfo::ID::Barrier; team = EntityInfo::Team::Blue; } else if(bId.y >= 40 and bId.y <= 42) { bId.y = 40; bId.x = 0; buildId = EntityInfo::ID::Castle; team = EntityInfo::Team::Red; } else if(bId.y >= 43) { bId.y = 43; bId.x = 0; buildId = EntityInfo::ID::Castle; team = EntityInfo::Team::Blue; } ground_selection = bId; mEntity = buildId; mTeam = team; getContext().sounds.play(Sounds::Menu); }); mBuildingbar.pack(button); } void MapEditorState::addButtonTexture(sf::Vector2i id, sf::Vector2i pos){ auto button = std::make_shared<GUI::ButtonTexture>(getContext(), 40, 40, Textures::MapGround,id); button->setPosition(pos.x, pos.y); button->setToggle(true); button->setCallback([this](sf::Vector2i bId){ ground_selection = bId; getContext().sounds.play(Sounds::Menu); }); mPaletteBar.pack(button); } void MapEditorState::paintSquare3(sf::Vector2i pos){ map.getTile(pos.x,pos.y).paint(ground_selection,rotate); if (pos.x > 0){ map.getTile(pos.x-1,pos.y).paint(ground_selection,rotate); if (pos.y > 0) map.getTile(pos.x-1,pos.y-1).paint(ground_selection,rotate); if (pos.y < 35) map.getTile(pos.x-1,pos.y+1).paint(ground_selection,rotate); } if(pos.x < 63){ map.getTile(pos.x+1,pos.y).paint(ground_selection,rotate); if (pos.y > 0) map.getTile(pos.x+1,pos.y-1).paint(ground_selection,rotate); if (pos.y < 35) map.getTile(pos.x+1,pos.y+1).paint(ground_selection,rotate); } if (pos.y > 0) map.getTile(pos.x,pos.y-1).paint(ground_selection,rotate); if (pos.y < 35) map.getTile(pos.x,pos.y+1).paint(ground_selection,rotate); } void MapEditorState::paintFill(sf::Vector2i pos){ bool isPaint[36*64] = {false}; recPaintFill(pos, isPaint); } void MapEditorState::recPaintFill(sf::Vector2i co, bool* isPaint){ isPaint[co.x+64*co.y] = true; if ( co.x > 0 and !isPaint[co.x-1+64*co.y] and map.getTile(co.x,co.y).getGround() == map.getTile(co.x-1,co.y).getGround() ) recPaintFill( sf::Vector2i (co.x - 1, co.y), isPaint); if ( co.x < 63 and !isPaint[co.x+1+64*co.y] and map.getTile(co.x,co.y).getGround() == map.getTile(co.x+1,co.y).getGround() ) recPaintFill(sf::Vector2i (co.x + 1, co.y), isPaint); if ( co.y > 0 and !isPaint[co.x+64*(co.y-1)] and map.getTile(co.x,co.y).getGround() == map.getTile(co.x,co.y-1).getGround() ) recPaintFill( sf::Vector2i (co.x, co.y - 1), isPaint); if ( co.y < 35 and !isPaint[co.x+64*(co.y+1)] and map.getTile(co.x,co.y).getGround() == map.getTile(co.x,co.y+1).getGround() ) recPaintFill(sf::Vector2i (co.x, co.y + 1), isPaint); map.getTile(co.x,co.y).paint(ground_selection,rotate); } void MapEditorState::createBuildings(sf::Vector2i pos){ if(mEntity == EntityInfo::None) return; sf::IntRect rect1 = {pos.x, pos.y, 0, 0}; bool construtible = true; if (mEntity == EntityInfo::Barrier){ rect1.height = 1; rect1.width = 1; }else if (mEntity == EntityInfo::Village){ rect1.height = 2; rect1.width = 2; }else if (mEntity == EntityInfo::Castle){ rect1.height = 3; rect1.width = 3; } for (int y(pos.y); y < pos.y+rect1.height;y++){ for (int x(pos.x); x < pos.x+rect1.width;x++){ if (x >= 64 or y >= 36) { std::cout<<" hors limite\n"; construtible = false; break; }else if (map.getTile(x, y).haveTop()) { construtible = false; break; } } if(!construtible) break; } if (construtible){ for (int y(0); y < rect1.height;y++){ for (int x(0); x <rect1.width;x++){ map.getTile(x+pos.x,y+pos.y).paint(sf::Vector2i(ground_selection.x+x,ground_selection.y+y),0); } } map.addBuildings(EntityInfo(sf::Vector2f(rect1.left,rect1.top),mEntity, mTeam, EntityInfo::Building)); } } bool MapEditorState::supressBuildings(sf::Vector2i pos) { sf::Vector2f v2; sf::Vector2i size; auto b = map.getBuildingsIt(); for(; b.first != b.second; b.first++){ v2 = b.first->getPosition(); switch (b.first->getID()) { case EntityInfo::Castle : size.x = 3; size.y = 3; break; case EntityInfo::Village : size.x = 2; size.y = 2; break; default : size.x = 1; size.y = 1; break; } if (pos.x < v2.x + size.x && pos.x >= v2.x && pos.y < v2.y + size.y && pos.y >= v2.y) { for (int y(0); y < size.y ;y++){ for (int x(0); x < size.x ;x++){ map.getTile(x+v2.x,y+v2.y).paint(sf::Vector2i(0,0),0); } } map.supBuildings(b.first); return true; } } return false; } void MapEditorState::createSoldier(sf::Vector2i pos){ if(not map.getTile(pos).isCrossable()) return; auto posf = static_cast<sf::Vector2f>(pos); auto other = map.getEntitiesIt(); for(;other.first != other.second; other.first++) if(other.first->getPosition() == posf) return; map.addEntity(EntityInfo(posf,mEntity,mTeam,EntityInfo::Type::Soldier)); } bool MapEditorState::supressSoldier(sf::Vector2i pos){ bool ret = false; auto posf = static_cast<sf::Vector2f>(pos); auto other = map.getEntitiesIt(); for(;other.first != other.second; other.first++) if(other.first->getPosition() == posf){ map.supEntity(other.first); ret = true; break; } return ret; }
c0f430767b8c35d4e05e61b84579c2439038f9d7
beba204784698e2ebb174c63674815e8238e2fb5
/src/Modules/Interface/IModuleBuilder.hpp
c431093118059ac620713bcb36cf416c81693b5e
[ "MIT" ]
permissive
pawel-jarosz/nastya-lisp
599a04d0b6b37ff4230268641847df9efc92c3ec
813a58523b741e00c8c27980fe658b546e9ff38c
refs/heads/master
2023-05-12T06:18:12.810066
2021-06-08T09:37:18
2021-06-08T09:37:18
321,453,980
1
0
MIT
2021-06-08T09:35:31
2020-12-14T19:39:34
C++
UTF-8
C++
false
false
254
hpp
IModuleBuilder.hpp
// // Created by caedus on 04.02.2021. // #pragma once #include "Modules/Interface/IModule.hpp" namespace nastya::modules { class IModuleBuilder { public: virtual ~IModuleBuilder() = default; virtual std::unique_ptr<IModule> build() = 0; }; }
c2a89d63349e0b580ec414812a9d50b9249e78aa
fd27f79974cb261b67f87fa32f6abdc4fc6a2709
/medicalKG/genAtc.cpp
31af4cf91d53751d12af302a494dd0448a26a5c3
[]
no_license
king-yyf/filehandle
2beca86a9c024c4b899825117a13d06df2514315
2ac0da83afe1a9c813e5373f260f2f9318414b96
refs/heads/master
2021-09-24T06:38:31.698999
2018-10-04T14:58:32
2018-10-04T14:58:32
115,418,426
0
0
null
null
null
null
UTF-8
C++
false
false
3,664
cpp
genAtc.cpp
// // main.cpp // txt2owl // // Created by Yang Yunfei on 2018/7/16. // Copyright © 2018年 Yang Yunfei. All rights reserved. // #include <iostream> #include <set> #include <cstring> #include <string> #include <queue> #include <map> using namespace std; string get_fa(string key, map<string, string> actMap) { int len = (int)key.length(); string res; switch (len) { case 1: res = "D药物"; break; case 3: if(actMap.count(key.substr(0,1)) > 0) res = key.substr(0,1) + "-" +actMap[key.substr(0,1)]; else res = "D药物"; break; case 4: if(actMap.count(key.substr(0,3)) > 0) res = key.substr(0,3) + "-" + actMap[key.substr(0,3)]; else res = get_fa(key.substr(0,3), actMap); break; case 5: if(actMap.count(key.substr(0,4)) > 0) res = key.substr(0,4) + "-" + actMap[key.substr(0,4)]; else res = get_fa(key.substr(0,4), actMap); break; case 7: if(actMap.count(key.substr(0,5)) > 0) res = key.substr(0,5) + "-" + actMap[key.substr(0,5)]; else res = get_fa(key.substr(0,5), actMap); break; default: res = "error"; break; } return res; } int main(int argc, const char * argv[]) { // insert code here... // FILE * f1 = fopen("/Users/yangyf/Desktop/file1.txt", "r"); FILE * f2 = fopen("/Users/yangyf/Desktop/atc.txt", "r"); FILE * f3 = fopen("/Users/yangyf/Desktop/atc_class.properties", "w"); FILE * f4 = fopen("/Users/yangyf/Desktop/atc_ind.properties", "w"); char code[100], chname[200]; map<string, string> atcCode; set<string> nameSet; string name; string key,value; while (fscanf(f2, "%s %s", code, chname) == 2) { // name = chname; // if(nameSet.count(name) > 0) // continue; // else // nameSet.insert(name); key = code; atcCode.emplace(key.substr(2), chname); } map<string, string>::iterator it; string fa; for(it = atcCode.begin(); it != atcCode.end(); ++it) { fa = get_fa(it->first, atcCode); if (fa == "error") { cout << "error : " << it->first << endl; } key = "D." + it->first + "-" + it->second; fa = "D." + fa; if(it->first.length() == 7) { fprintf(f4, "%s = %s\n",key.data(), fa.data()); // fprintf(f3, "%s", tmp.c_str()); } else { fprintf(f3, "%s = %s\n",key.data(), fa.data()); } } printf("ok!\n"); return 0; } //int main(){ // FILE * f1 = fopen("/Users/yangyf/Desktop/atc1.txt", "r"); // FILE * f2 = fopen("/Users/yangyf/Desktop/temp.txt", "r"); // FILE * f3 = fopen("/Users/yangyf/Desktop/atc2.txt", "w"); // map<string, string> atcMap; // // char key[300], value[300]; // string code, str1,str2; // int n,pos; // while (fscanf(f1, "%s %s %d",key,value,&n) == 3) // { // code = key; // pos = code.find('-'); // code = code.substr(2,pos-2); // atcMap.emplace(code,value); // } // while (fscanf(f2, "%s %s",key,value) == 2) { // code = key; // pos = code.find('-'); // code = code.substr(2,pos-2); // if(atcMap.count(code) > 0) // { // fprintf(f3, "%s %s %d\n",key, atcMap[code].data(),0); // } // } // printf("ok\n"); // return 0; //}
2086f213cddf6e5bb08a1ac7de6b75ffcd7c3dcc
e523a3393be45b603b26f0b1f2e3bad876a9d48d
/CommWithPi_2.1_WriteByteToPi/CommWithPi_2.1_WriteByteToPi.ino
4afed08eb690ca5072dbccb254310c8ad56196fe
[]
no_license
BradROlbrey/I2C
9bddd64a6fcad196d9177f22e83f40eb0c4fbcfc
6c0f0482148c59fc35e3a31d98b6a9659eea620b
refs/heads/master
2020-08-06T18:31:14.869308
2019-10-06T04:10:12
2019-10-06T04:10:12
213,107,518
0
0
null
null
null
null
UTF-8
C++
false
false
806
ino
CommWithPi_2.1_WriteByteToPi.ino
// Wire Slave Sender // by Nicholas Zambetti <http://www.zambetti.com> // Demonstrates use of the Wire library // Sends data as an I2C/TWI slave device // Refer to the "Wire Master Reader" example for use with this // Created 29 March 2006 // This example code is in the public domain. byte to_send = 1; #include <Wire.h> void setup() { Wire.begin(0x7f); // join i2c bus with address Wire.onRequest(requestEvent); // register event } void loop() { delay(100); } // function that executes whenever data is requested by master // this function is registered as an event, see setup() void requestEvent() { delayMicroseconds(8); // With a frequency of 8us, an 8us delay seems to work pretty swell. Wire.write(to_send); to_send <<= 1; if (to_send == 0) to_send = 1; }
befc9139310bafa0e2e84896e20037bad7f6e427
6b68b51c3745d9c8de701dca4db403ba4a73ed54
/crosbot_ui/include/crosbot_ui/renders/robot/joystick.hpp
cf1754bd3a4f9b0f96be42959d6036ebcdf3e571
[]
no_license
Forrest-Z/rsa-crosbot
3b9fd1a8074b2bdc5dcdac08c2bac5d999599055
e539b418b850132d92a8369826961e7280d4f960
refs/heads/master
2020-06-06T21:58:17.428140
2016-10-30T00:55:53
2016-10-30T00:55:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,079
hpp
joystick.hpp
/* * image.h * * Created on: 22/03/2012 * Author: rescue */ #ifndef CROSBOT_RENDER_JOYSTICK_HPP_ #define CROSBOT_RENDER_JOYSTICK_HPP_ #include <crosbot_ui/panels/robot.hpp> #include <crosbot_ui/joystick.hpp> namespace crosbot { namespace gui { #define RENDER_JOYSTICK "joystick" class JoystickRender : public RobotRender { public: class RenderJoystick : public Joystick { public: JoystickRender& render; int buttonKeys[MAX_JOYSTICK_BUTTONS]; RenderJoystick(JoystickRender& render) : render(render) { for (int i = 0; i < MAX_JOYSTICK_BUTTONS; ++i) { buttonKeys[i] = Joystick::Undefined; } } void axisChanged(Axis, int); void buttonPressed(int); void buttonReleased(int); }; JoystickRender(RobotPanel& panel, ConfigElementPtr config); virtual void start(); virtual void stop(); virtual void render(); protected: RenderJoystick joystick; float stickSize, hatSize; Colour4f colour, hatColour, activeColour; friend class RenderJoystick; }; } // namespace gui } // namespace crosbot #endif /* CROSBOT_RENDER_JOYSTICK_HPP_ */
2d6db3303e7efb655ce5b65db771ee40014218dc
fb1ee9b9cb748599f75d8bafebdf78abebcf6002
/queso/key_handler.h
2caef3571393747b123472d76881cf36dc617eba
[]
no_license
russgayle/opengl4-lessons
fb64e604d876062685897c2e4917634ea64b427a
33d310443e41b822f4dc612ff6acc770f02e488e
refs/heads/master
2020-05-29T17:58:37.694304
2014-03-23T05:37:25
2014-03-23T05:37:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
237
h
key_handler.h
#ifndef _QUESO_KEY_HANDLER_H_ #define _QUESO_KEY_HANDLER_H_ #include "common.h" namespace queso { void keyHandler(GLFWwindow* window, int key, int scancode, int action, int mods); } // namespace queso #endif //_QUESO_KEY_HANDLER_H_
15c8c4306800895a71dc4d9dea379575bd1002d7
78f8badd914d95d82c9da8bc9961f2c7c6d92b9a
/ImageProcessing/vtkCudaImageAnalytics/vtkCudaDirectedAcyclicGraphMaxFlowSegmentation.h
45240c0b1ff8ba984bca8b0076cb5aaa4c930cd3
[ "MIT" ]
permissive
jcfr/RobartsVTK
140459de6a5f5a95c4d22255dcd00810a5b52939
d711c99b9c5b8a53afd23ee10d84f77a24565a3f
refs/heads/master
2021-01-25T13:24:01.221479
2018-03-01T18:28:20
2018-03-01T18:28:20
123,564,796
0
0
MIT
2018-03-02T10:18:50
2018-03-02T10:18:50
null
UTF-8
C++
false
false
4,970
h
vtkCudaDirectedAcyclicGraphMaxFlowSegmentation.h
/*========================================================================= Program: Robarts Visualization Toolkit Module: vtkCudaDirectedAcyclicGraphMaxFlowSegmentation.h Copyright (c) John SH Baxter, Robarts Research Institute This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** @file vtkHierarchicalMaxFlowSegmentation2.h * * @brief Header file with definitions of GPU-based solver for DAG-based max-flow * segmentation problems with greedy scheduling over multiple GPUs. See * vtkDirectedAcyclicGraphMaxFlowSegmentation.h for most of the interface documentation. * * @author John Stuart Haberl Baxter (Dr. Peters' Lab (VASST) at Robarts Research Institute) * * @note June 22nd 2014 - Documentation first compiled. * */ #ifndef __VTKCUDADIRECTEDACYCLICGRAPHMAXFLOWSEGMENTATION_H__ #define __VTKCUDADIRECTEDACYCLICGRAPHMAXFLOWSEGMENTATION_H__ #include "vtkCudaImageAnalyticsExport.h" #include "vtkDirectedAcyclicGraphMaxFlowSegmentation.h" #include <map> #include <set> class CudaObject; class vtkCudaMaxFlowSegmentationScheduler; class vtkCudaMaxFlowSegmentationTask; class vtkCudaMaxFlowSegmentationWorker; class vtkCudaImageAnalyticsExport vtkCudaDirectedAcyclicGraphMaxFlowSegmentation : public vtkDirectedAcyclicGraphMaxFlowSegmentation { public: vtkTypeMacro( vtkCudaDirectedAcyclicGraphMaxFlowSegmentation, vtkDirectedAcyclicGraphMaxFlowSegmentation ); static vtkCudaDirectedAcyclicGraphMaxFlowSegmentation *New(); // Description: // Insert, remove, and verify a given GPU into the set of GPUs usable by the algorithm. This // set defaults to {GPU0} and must be non-empty when the update is invoked. void AddDevice(int GPU); void RemoveDevice(int GPU); bool HasDevice(int GPU); // Description: // Clears the set of GPUs usable by the algorithm void ClearDevices(); // Description: // Set the class to use a single GPU, the one provided. void SetDevice(int GPU); // Description: // Get and Set the maximum percent of GPU memory usable by the algorithm. // Recommended to keep below 98% on compute-only cards, and 90% on cards // used for running the monitors. The number provided will act as a de // facto value for all cards. (Default is 90%.) vtkSetClampMacro(MaxGPUUsage,double,0.0,1.0); vtkGetMacro(MaxGPUUsage,double); // Description: // Get, Set, and Clear exceptions, allowing for a particular card to have its // memory consumption managed separately. void SetMaxGPUUsage(double usage, int device); double GetMaxGPUUsage(int device); void ClearMaxGPUUsage(); // Description: // Get and Set how often the algorithm should report if in Debug mode. If set // to 0, the algorithm doesn't report task completions. Default is 100 tasks. vtkSetClampMacro(ReportRate,int,0,INT_MAX); vtkGetMacro(ReportRate,int); protected: vtkCudaDirectedAcyclicGraphMaxFlowSegmentation(); virtual ~vtkCudaDirectedAcyclicGraphMaxFlowSegmentation(); vtkCudaMaxFlowSegmentationScheduler* Scheduler; std::set<int> GPUsUsed; double MaxGPUUsage; std::map<int,double> MaxGPUUsageNonDefault; int ReportRate; virtual int InitializeAlgorithm(); virtual int RunAlgorithm(); void FigureOutBufferPriorities( vtkIdType currNode ); void PropogateLabels( vtkIdType currNode ); void SolveMaxFlow( vtkIdType currNode, int* timeStep ); void UpdateLabel( vtkIdType node, int* timeStep ); std::map<vtkIdType,vtkCudaMaxFlowSegmentationTask*> UpdateSpatialFlowsTasks; void CreateUpdateSpatialFlowsTasks(); std::map<vtkIdType,vtkCudaMaxFlowSegmentationTask*> ResetSinkFlowTasks; void CreateResetSinkFlowRootTasks(); void CreateResetSinkFlowBranchTasks(); std::map<vtkIdType,vtkCudaMaxFlowSegmentationTask*> ApplySinkPotentialLeafTasks; void CreateApplySinkPotentialLeafTasks(); std::map<vtkIdType,vtkCudaMaxFlowSegmentationTask*> PushUpSourceFlowsTasks; void CreatePushUpSourceFlowsLeafTasks(); void CreatePushUpSourceFlowsBranchTasks(); std::map<vtkIdType,vtkCudaMaxFlowSegmentationTask*> PushDownSinkFlowsTasks; void CreatePushDownSinkFlowsRootTasks(); void CreatePushDownSinkFlowsBranchTasks(); std::map<vtkIdType,vtkCudaMaxFlowSegmentationTask*> UpdateLabelsTasks; void CreateUpdateLabelsTasks(); std::map<vtkIdType,vtkCudaMaxFlowSegmentationTask*> ClearSourceBufferTasks; void CreateClearSourceBufferTasks(); void AssociateFinishSignals(); void InitializeSpatialFlowsTasks(); void InitializeSinkFlowsTasks(); private: vtkCudaDirectedAcyclicGraphMaxFlowSegmentation operator=(const vtkCudaDirectedAcyclicGraphMaxFlowSegmentation&); vtkCudaDirectedAcyclicGraphMaxFlowSegmentation(const vtkCudaDirectedAcyclicGraphMaxFlowSegmentation&); }; #endif
44a7e83e033b3c6cc4cc7afd76d6f7758b8d3f99
69b7e41654886eb3382ae0312664c87c230c72b3
/src/include/common.hpp
4855878dc41f6a7160ae4abf401cd45a0655b12f
[ "MIT" ]
permissive
Axion243/FLattice
c6a5713128c59835785b242018f674add2334c27
ddc6479a2c6de12dcdedf96b8e19cc3875b7a3fd
refs/heads/master
2021-06-27T03:25:34.508651
2020-03-09T22:12:09
2020-03-09T22:12:09
164,052,181
0
1
MIT
2020-10-30T07:06:42
2019-01-04T03:18:17
C++
UTF-8
C++
false
false
188
hpp
common.hpp
#ifndef _COMMON_H_ #define _COMMON_H_ #include "allocator.hpp" #include "field.hpp" #include "calculation.hpp" #include "stopwatch.hpp" #include "write.hpp" #include "search.hpp" #endif