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
5eb2ffdb5a4dea1425a7d8593fee3646a33b2c3d
193f83a14d8df7812754692a8a1e849e5f24ac55
/3lr/2.cpp
4aec89dd30f0c85a693c29199edfdcfd5380170e
[]
no_license
denchik666s/c
c0d941a68a88a4fd02ccbd984904381622541672
a450777f2ba2f287d2664db166e2c29117f6426b
refs/heads/master
2021-05-22T15:59:42.298517
2020-04-16T08:40:43
2020-04-16T08:40:43
252,993,193
1
0
null
null
null
null
UTF-8
C++
false
false
150
cpp
2.cpp
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { int n = 10+ rand() %(91); cout<<n; return 0; }
7b7b0fdc90ad3a1a969fd8e457b4fc87cd1f5813
5975831759e2a4cb5e10c2423b0ebdffde9ffab9
/src/bucket_sampler.h
8970374ae14ba59f9ccd18a49a27e8794399635b
[]
no_license
cvtuge/vstab
5b7b82c57c468e88680e8872d1b76d4e030e730f
8fe6f3f23d51429f96d9e578091e648ae8e7f691
refs/heads/master
2022-01-10T22:38:24.142515
2019-04-20T09:47:43
2019-04-20T09:47:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
464
h
bucket_sampler.h
#pragma once #include <random> class BucketSampler { public: using Bucket = std::vector<int>; BucketSampler(const cv::Mat& m1, const cv::Mat& m2, const int num_buckets_x=8, const int num_buckets_y=5); bool getSubset(cv::Mat& out_ms1, cv::Math out_ms2, const int model_points, const int max_attempts); private: cv::Mat m1; cv::Mat m2; std::vector<Bucket> buckets; std::random_device rd; std::mt19937 gen; std::discrete_distribution<> dist; };
4950b89511272cd7c649dc15f9d8918e67526239
b9e9938343b60cb636923fa062b665794de2d16f
/log/inc/handle.h
8d89d20b8dafd6776ecd791603ebd1b7b28f61cc
[]
no_license
changyuezhou/commlib
d4d2a5feb45820b0ea65939924e3e2bda46bde7f
d1d2a87f84fc5a6f52e53fda612da9f23d85663a
refs/heads/master
2021-09-11T19:10:11.500357
2018-04-11T06:42:45
2018-04-11T06:42:45
109,566,856
0
0
null
null
null
null
UTF-8
C++
false
false
1,573
h
handle.h
// Copyright (c) 2013 zhou chang yue. All rights reserved. #ifndef COMMLIB_LOG_INC_HANDLE_H_ #define COMMLIB_LOG_INC_HANDLE_H_ #include <unistd.h> #include <string> #include <cstdio> #include <iostream> #include "commlib/public/inc/type.h" #include "commlib/log/inc/record.h" #include "commlib/log/inc/format.h" #include "commlib/magic/inc/mutex.h" #include "commlib/magic/inc/scopeLock.h" #include "commlib/log/inc/err.h" namespace lib { namespace log { using lib::magic::Mutex; using lib::magic::ScopeLock; class Handle { public: typedef Record::LEVEL LEVEL; public: static const INT32 kLOG_THREAD = 1; static const INT32 kLOG_CACHE = 2; static const INT32 kLOG_NET = 4; static const INT32 kLOG_NSF = 8; static const INT32 kLOG_PLUS = 16; public: Handle(Format * format, \ LEVEL level, BOOL exact, UINT64 mask): \ fd_(-1), format_(format), \ level_(level), exact_(exact), mask_(mask) {} virtual ~Handle() {} public: virtual INT32 Logging(const Record & record) = 0; virtual VOID DestroyHandle() { if (0 < fd_) { ::close(fd_); fd_ = -1; } if (NULL != format_) { delete format_; format_ = NULL; } } protected: INT32 fd_; Format * format_; LEVEL level_; BOOL exact_; UINT64 mask_; Mutex mutex_; }; } // namespace log } // namespace lib #endif // COMMLIB_LOG_INC_HANDLE_H_
5147ea1a3ee0fff593df3bfa4cf21ade4e82fc34
b2ab7d82c16746012a90530554718af5b58fc3bc
/class_practice/main.cpp
de635a5a3c883db11e30bc693af8317b842e04c1
[]
no_license
RVL224/EstimationTheory
08f8b01c4f2d11b1d83af0425dcc918444c83f29
c1d3ef19d63a82fe69bcf18c1219eee2986e7269
refs/heads/master
2022-08-31T11:10:30.168936
2020-05-30T09:10:26
2020-05-30T09:10:26
256,185,388
0
0
null
null
null
null
UTF-8
C++
false
false
889
cpp
main.cpp
#include "tool.h" #include<iostream> using namespace std; int main() { CComplex a(1,2); CComplex b(3,4); CComplex c = a+b; cout << c.GetReValue()<<","<< c.GetImValue() << endl; CComplex d = a+1; cout << d.GetReValue()<<","<< d.GetImValue() << endl; CComplex e = 1+a; cout << e.GetReValue()<<","<< e.GetImValue() << endl; // cout << a.GetReValue()<<","<< a.GetImValue() << endl; // a.SetValue(3,4); // cout << a.GetReValue()<<","<< a.GetImValue() << endl; // CComplex a(1,2); // CComplex b(3,4); // CComplex c = a+b; // CComplex c_ = a.Add(b); // cout << c.GetReValue()<<","<< c.GetImValue() << endl; // cout << c_.GetReValue()<<","<< c_.GetImValue() << endl; // cout <<"---------------------------------"<<endl; // CComplex d(a); // cout << d.GetReValue() <<"," << d.GetImValue() << endl; return 0; }
95a31ebc465f23f58e24c971533a4afc6c2023ff
f28a73354b449c690b4aaa712d3338fce3a91c79
/TreeFiller/src/FillerPhotons.cc
c0f518cb0a2f78dba45b862e0fc3bb852684874a
[]
no_license
GuillelmoGomezCeballos/MitProd
035c358598acc48eaa631e3f68102a24eec1be16
5de27f8a5b807623999ea829d677830d18772be5
refs/heads/master
2021-01-20T06:38:50.958185
2014-08-14T02:16:36
2014-08-14T02:16:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,746
cc
FillerPhotons.cc
// $Id: FillerPhotons.cc,v 1.33 2013/07/01 20:18:00 paus Exp $ #include "MitProd/TreeFiller/interface/FillerPhotons.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/EgammaCandidates/interface/Photon.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" #include "DataFormats/EgammaCandidates/interface/Conversion.h" #include "DataFormats/EgammaCandidates/interface/ConversionFwd.h" #include "MitAna/DataTree/interface/Names.h" #include "MitAna/DataTree/interface/PhotonCol.h" #include "MitProd/ObjectService/interface/ObjectService.h" #include "RecoEgamma/EgammaTools/interface/ggPFPhotons.h" #include "RecoEgamma/EgammaTools/interface/ggPFClusters.h" #include "Geometry/CaloGeometry/interface/CaloGeometry.h" #include "Geometry/CaloTopology/interface/CaloSubdetectorTopology.h" #include "DataFormats/EcalRecHit/interface/EcalRecHit.h" #include "Geometry/Records/interface/CaloGeometryRecord.h" #include "FWCore/Framework/interface/ESHandle.h" #include "DataFormats/EcalDetId/interface/EcalSubdetector.h" #include "TSystem.h" using namespace std; using namespace edm; using namespace mithep; //--------------------------------------------------------------------------------------------------- FillerPhotons::FillerPhotons(const edm::ParameterSet &cfg, const char *name, bool active) : BaseFiller (cfg,name,active), edmName_ (Conf().getUntrackedParameter<string>("edmName","photons")), mitName_ (Conf().getUntrackedParameter<string>("mitName",Names::gkPhotonBrn)), conversionMapName_ (Conf().getUntrackedParameter<string>("conversionMapName","")), oneLegConversionMapName_ (Conf().getUntrackedParameter<string>("oneLegConversionMapName","")), barrelSuperClusterMapName_(Conf().getUntrackedParameter<string>("barrelSuperClusterMapName","")), endcapSuperClusterMapName_(Conf().getUntrackedParameter<string>("endcapSuperClusterMapName","")), pfSuperClusterMapName_ (Conf().getUntrackedParameter<string>("pfSuperClusterMapName","")), pfClusterMapName_ (Conf().getUntrackedParameter<string>("pfClusterMapName","")), pfCandMapName_ (Conf().getUntrackedParameter<string>("pfCandMapName","")), photonMapName_ (Conf().getUntrackedParameter<string>("photonMapName","")), phIDCutBasedTightName_ (Conf().getUntrackedParameter<string>("phIDCutBasedTightName", "PhotonIDProd:PhotonCutBasedIDTight")), phIDCutBasedLooseName_ (Conf().getUntrackedParameter<string>("phIDCutBasedLooseName", "PhotonIDProd:PhotonCutBasedIDLoose")), EBRecHitsEdmName_ (Conf().getUntrackedParameter<string>("EBRecHitsEdmName_", "reducedEcalRecHitsEB")), EERecHitsEdmName_ (Conf().getUntrackedParameter<string>("EERecHitsEdmName_", "reducedEcalRecHitsEE")), PFCandsEdmName_ (Conf().getUntrackedParameter<string>("PFCandsEdmName","particleFlow")), HBHERecHitsEdmName_ (Conf().getUntrackedParameter<edm::InputTag>("HBHERecHitsEdmName", edm::InputTag("reducedHcalRecHits:hbhereco"))), photonMap_ (new mithep::PhotonMap), photons_ (new mithep::PhotonArr(16)), conversionMap_ (0), oneLegConversionMap_ (0), barrelSuperClusterMap_ (0), endcapSuperClusterMap_ (0), pfSuperClusterMap_ (0), pfClusterMap_ (0), pfCandMap_ (0) { // Constructor. } //-------------------------------------------------------------------------------------------------- FillerPhotons::~FillerPhotons() { // Destructor. delete photons_; } //-------------------------------------------------------------------------------------------------- void FillerPhotons::BookDataBlock(TreeWriter &tws) { // Add photon branch to tree and get the map. tws.AddBranch(mitName_,&photons_); OS()->add<mithep::PhotonArr>(photons_,mitName_); if (!conversionMapName_.empty()) { conversionMap_ = OS()->get<ConversionDecayMap>(conversionMapName_); if (conversionMap_) AddBranchDep(mitName_,conversionMap_->GetBrName()); } if (!barrelSuperClusterMapName_.empty()) { barrelSuperClusterMap_ = OS()->get<SuperClusterMap>(barrelSuperClusterMapName_); if (barrelSuperClusterMap_) AddBranchDep(mitName_,barrelSuperClusterMap_->GetBrName()); } if (!endcapSuperClusterMapName_.empty()) { endcapSuperClusterMap_ = OS()->get<SuperClusterMap>(endcapSuperClusterMapName_); if (endcapSuperClusterMap_) AddBranchDep(mitName_,endcapSuperClusterMap_->GetBrName()); } if (!pfSuperClusterMapName_.empty()) { pfSuperClusterMap_ = OS()->get<SuperClusterMap>(pfSuperClusterMapName_); if (pfSuperClusterMap_) AddBranchDep(mitName_,pfSuperClusterMap_->GetBrName()); } if (!pfClusterMapName_.empty()) { pfClusterMap_ = OS()->get<BasicClusterMap>(pfClusterMapName_); if (pfClusterMap_) AddBranchDep(mitName_,pfClusterMap_->GetBrName()); } if (!pfCandMapName_.empty()) { pfCandMap_ = OS()->get<PFCandidateMap>(pfCandMapName_); if (pfCandMap_) AddBranchDep(mitName_,pfCandMap_->GetBrName()); } if (!photonMapName_.empty()) { photonMap_->SetBrName(mitName_); OS()->add<PhotonMap>(photonMap_,photonMapName_); } } //-------------------------------------------------------------------------------------------------- void FillerPhotons::FillDataBlock(const edm::Event &event, const edm::EventSetup &setup) { // Fill photon array. //if (!ecorr_.IsInitialized()) // ecorr_.Initialize(setup,std::string(TString("gbrph.root"))); photons_->Delete(); photonMap_->Reset(); // get photon collection Handle<reco::PhotonCollection> hPhotonProduct; GetProduct(edmName_, hPhotonProduct, event); const reco::PhotonCollection inPhotons = *(hPhotonProduct.product()); //pf photon stuff edm::Handle<EcalRecHitCollection> pEBRecHits; event.getByLabel(EBRecHitsEdmName_, pEBRecHits); edm::Handle<EcalRecHitCollection> pEERecHits; event.getByLabel(EERecHitsEdmName_, pEERecHits); edm::ESHandle<CaloGeometry> pGeometry; setup.get<CaloGeometryRecord>().get(pGeometry); const CaloSubdetectorGeometry *geometryEB = pGeometry->getSubdetectorGeometry(DetId::Ecal, EcalBarrel); const CaloSubdetectorGeometry *geometryEE = pGeometry->getSubdetectorGeometry(DetId::Ecal, EcalEndcap); ggPFClusters pfclusters(pEBRecHits, pEERecHits, geometryEB, geometryEE); Handle<reco::PFCandidateCollection> pPFCands; event.getByLabel(PFCandsEdmName_, pPFCands); // handles to the the pho-HErecHit matching edm::Handle<HBHERecHitCollection> hcalRecHitHandle; event.getByLabel(HBHERecHitsEdmName_, hcalRecHitHandle); const HBHERecHitCollection* hbheRecHitCol = hcalRecHitHandle.product(); const CaloGeometry* caloGeom = pGeometry.product(); // handles to get the photon ID information Handle<edm::ValueMap<bool> > phidLooseMap; if (!phIDCutBasedLooseName_.empty()) GetProduct(phIDCutBasedLooseName_, phidLooseMap, event); Handle<edm::ValueMap<bool> > phidTightMap; if (!phIDCutBasedTightName_.empty()) GetProduct(phIDCutBasedTightName_, phidTightMap, event); for (reco::PhotonCollection::const_iterator iP = inPhotons.begin(); iP != inPhotons.end(); ++iP) { int photonIndex = iP - inPhotons.begin(); reco::PhotonRef phRef(hPhotonProduct, photonIndex); mithep::Photon *outPhoton = photons_->Allocate(); new (outPhoton) mithep::Photon(iP->px(),iP->py(),iP->pz(),iP->energy()); outPhoton->SetIsConverted(iP->hasConversionTracks()); outPhoton->SetR9(iP->r9()); outPhoton->SetHadOverEm(iP->hadronicOverEm()); outPhoton->SetHasPixelSeed(iP->hasPixelSeed()); // shower shape variables outPhoton->SetHcalDepth1OverEcal(iP->hadronicDepth1OverEm()); outPhoton->SetHcalDepth2OverEcal(iP->hadronicDepth2OverEm()); outPhoton->SetMaxEnergyXtal(iP->maxEnergyXtal()); outPhoton->SetE15(iP->e1x5()); outPhoton->SetE25(iP->e2x5()); outPhoton->SetE33(iP->e3x3()); outPhoton->SetE55(iP->e5x5()); outPhoton->SetCovEtaEta(iP->sigmaEtaEta()); outPhoton->SetCoviEtaiEta(iP->sigmaIetaIeta()); outPhoton->SetHadOverEmTow(iP->hadTowOverEm()); //isolation variables for dR=0.3 outPhoton->SetEcalRecHitIsoDr03(iP->ecalRecHitSumEtConeDR03()); outPhoton->SetHcalTowerSumEtDr03(iP->hcalTowerSumEtConeDR03()); outPhoton->SetHcalDepth1TowerSumEtDr03(iP->hcalDepth1TowerSumEtConeDR03()); outPhoton->SetHcalDepth2TowerSumEtDr03(iP->hcalDepth2TowerSumEtConeDR03()); outPhoton->SetSolidConeTrkIsoDr03(iP->trkSumPtSolidConeDR03()); outPhoton->SetHollowConeTrkIsoDr03(iP->trkSumPtHollowConeDR03()); outPhoton->SetSolidConeNTrkDr03(iP->nTrkSolidConeDR03()); outPhoton->SetHollowConeNTrkDr03(iP->nTrkHollowConeDR03()); outPhoton->SetHCalIsoTowDr03(iP->hcalTowerSumEtConeDR03() + (iP->hadronicOverEm() - iP->hadTowOverEm())*iP->superCluster()->energy()/cosh(iP->superCluster()->eta())); //isolation variables for dR=0.4 outPhoton->SetEcalRecHitIsoDr04(iP->ecalRecHitSumEtConeDR04()); outPhoton->SetHcalTowerSumEtDr04(iP->hcalTowerSumEtConeDR04()); outPhoton->SetHcalDepth1TowerSumEtDr04(iP->hcalDepth1TowerSumEtConeDR04()); outPhoton->SetHcalDepth2TowerSumEtDr04(iP->hcalDepth2TowerSumEtConeDR04()); outPhoton->SetSolidConeTrkIsoDr04(iP->trkSumPtSolidConeDR04()); outPhoton->SetHollowConeTrkIsoDr04(iP->trkSumPtHollowConeDR04()); outPhoton->SetSolidConeNTrkDr04(iP->nTrkSolidConeDR04()); outPhoton->SetHollowConeNTrkDr04(iP->nTrkHollowConeDR04()); outPhoton->SetHCalIsoTowDr04(iP->hcalTowerSumEtConeDR04() + (iP->hadronicOverEm() - iP->hadTowOverEm())*iP->superCluster()->energy()/cosh(iP->superCluster()->eta())); //pflow isolation outPhoton->SetPFChargedHadronIso(iP->chargedHadronIso()); outPhoton->SetPFChargedHadronIso(iP->neutralHadronIso()); outPhoton->SetPFChargedHadronIso(iP->photonIso()); //fiducial and quality flags outPhoton->SetIsEB(iP->isEB()); outPhoton->SetIsEE(iP->isEE()); outPhoton->SetIsEBGap(iP->isEBGap()); outPhoton->SetIsEEGap(iP->isEEGap()); outPhoton->SetIsEBEEGap(iP->isEBEEGap()); //deprecated, identical to supercluster preselection in 3_1_X, so set to true outPhoton->SetIsLooseEM(true); //deprecated if (!phIDCutBasedLooseName_.empty()) outPhoton->SetIsLoosePhoton((*phidLooseMap)[phRef]); if (!phIDCutBasedTightName_.empty()) outPhoton->SetIsTightPhoton((*phidTightMap)[phRef]); //calo position outPhoton->SetCaloPosXYZ(iP->caloPosition().x(),iP->caloPosition().y(),iP->caloPosition().z()); //MIP tagger information outPhoton->SetMipChi2(iP->mipChi2()); outPhoton->SetMipTotEnergy(iP->mipTotEnergy()); outPhoton->SetMipSlope(iP->mipSlope()); outPhoton->SetMipIntercept(iP->mipIntercept()); outPhoton->SetMipNhitCone(iP->mipNhitCone()); outPhoton->SetMipIsHalo(iP->mipIsHalo()); //make the pho-HErecHit matching ThreeVector matchRhPos(0,0,0); double deltaPhiMin = 0.2; double rhoMin = 110.; double rhoMax = 140.; double rhEnMin = 1.; double matchedRhEnergy = -1.; double matchedRhTime = -1000.; //first do the std 2012 matching (wide DR window) - Plus side HERecHitMatcher(&(*iP), +1, deltaPhiMin, rhoMin, rhoMax, rhEnMin, matchRhPos, matchedRhEnergy, matchedRhTime, hbheRecHitCol, caloGeom); outPhoton->SetMatchHePlusPos(matchRhPos.X(),matchRhPos.Y(),matchRhPos.Z()); outPhoton->SetMatchHePlusEn(matchedRhEnergy); outPhoton->SetMatchHePlusTime(matchedRhTime); //then do the std 2012 matching (wide DR window) - Minus side matchRhPos.SetXYZ(0,0,0); matchedRhEnergy = -1.; matchedRhTime = -1000.; HERecHitMatcher(&(*iP), -1, deltaPhiMin, rhoMin, rhoMax, rhEnMin, matchRhPos, matchedRhEnergy, matchedRhTime, hbheRecHitCol, caloGeom); outPhoton->SetMatchHeMinusPos(matchRhPos.X(),matchRhPos.Y(),matchRhPos.Z()); outPhoton->SetMatchHeMinusEn(matchedRhEnergy); outPhoton->SetMatchHeMinusTime(matchedRhTime); //thirdly do the std 2011 matching (narrow DR window) - Plus side matchRhPos.SetXYZ(0,0,0); deltaPhiMin = 0.2; rhoMin = 115.; rhoMax = 130.; rhEnMin = 1.; matchedRhEnergy = -1.; matchedRhTime = -1000.; HERecHitMatcher(&(*iP), +1, deltaPhiMin, rhoMin, rhoMax, rhEnMin, matchRhPos, matchedRhEnergy, matchedRhTime, hbheRecHitCol, caloGeom); outPhoton->SetMatchHePlusPosDR15(matchRhPos.X(),matchRhPos.Y(),matchRhPos.Z()); outPhoton->SetMatchHePlusEnDR15(matchedRhEnergy); outPhoton->SetMatchHePlusTimeDR15(matchedRhTime); //finally do the std 2011 matching (narrow DR window) - Minus side matchRhPos.SetXYZ(0,0,0); matchedRhEnergy = -1.; matchedRhTime = -1000.; HERecHitMatcher(&(*iP), -1, deltaPhiMin, rhoMin, rhoMax, rhEnMin, matchRhPos, matchedRhEnergy, matchedRhTime, hbheRecHitCol, caloGeom); outPhoton->SetMatchHeMinusPosDR15(matchRhPos.X(),matchRhPos.Y(),matchRhPos.Z()); outPhoton->SetMatchHeMinusEnDR15(matchedRhEnergy); outPhoton->SetMatchHeMinusTimeDR15(matchedRhTime); // make links to conversions if (conversionMap_) { const reco::ConversionRefVector &conversionRefs = iP->conversions(); for (reco::ConversionRefVector::const_iterator conversionRef = conversionRefs.begin(); conversionRef != conversionRefs.end(); ++conversionRef) { outPhoton->AddConversionD(conversionMap_->GetMit(*conversionRef)); } } // make links to conversions (single leg) if (oneLegConversionMap_) { const reco::ConversionRefVector &conversionRefs = iP->conversionsOneLeg(); for (reco::ConversionRefVector::const_iterator conversionRef = conversionRefs.begin(); conversionRef != conversionRefs.end(); ++conversionRef) { outPhoton->AddConversionS(oneLegConversionMap_->GetMit(*conversionRef)); } } // make link to supercluster if (barrelSuperClusterMap_ && endcapSuperClusterMap_ && iP->superCluster().isNonnull()) { if (barrelSuperClusterMap_->HasMit(iP->superCluster())) outPhoton->SetSuperCluster(barrelSuperClusterMap_->GetMit(iP->superCluster())); else if(endcapSuperClusterMap_->HasMit(iP->superCluster())) outPhoton->SetSuperCluster(endcapSuperClusterMap_->GetMit(iP->superCluster())); } // make link to pf supercluster if (pfSuperClusterMap_ && iP->pfSuperCluster().isNonnull()) { if(pfSuperClusterMap_->HasMit(iP->pfSuperCluster())) outPhoton->SetPFSuperCluster(pfSuperClusterMap_->GetMit(iP->pfSuperCluster())); //horrible stuff: mark PF superclusters with fraction of energy that overlaps with egamma supercluster if (pfClusterMap_ && iP->superCluster().isNonnull()) { for (reco::CaloCluster_iterator pfcit = iP->pfSuperCluster()->clustersBegin(); pfcit!=iP->pfSuperCluster()->clustersEnd(); ++pfcit) { float eoverlap = pfclusters.getPFSuperclusterOverlap(**pfcit,*iP->superCluster()); if(pfClusterMap_->GetMit(*pfcit)) const_cast<mithep::BasicCluster*>(pfClusterMap_->GetMit(*pfcit))->SetMatchedEnergy(eoverlap); } } } //horrible stuff: make links to PFCandidates to try and recover pflow clustering when pflow id failed... if (pfCandMap_ && iP->superCluster().isNonnull()) { std::vector<PFCandidatePtr> inmust; std::vector<PFCandidatePtr> outmust; std::pair<double,double> scsize = ggPFPhotons::SuperClusterSize(*iP->superCluster(), pEBRecHits, pEERecHits, geometryEB, geometryEE); ggPFPhotons::recoPhotonClusterLink(*iP->superCluster(), inmust, outmust, pPFCands, scsize.first, scsize.second); for (std::vector<PFCandidatePtr>::const_iterator pfit = inmust.begin(); pfit!=inmust.end(); ++pfit) outPhoton->AddPFPhotonInMustache(pfCandMap_->GetMit(*pfit)); for (std::vector<PFCandidatePtr>::const_iterator pfit = outmust.begin(); pfit!=outmust.end(); ++pfit) outPhoton->AddPFPhotonOutOfMustache(pfCandMap_->GetMit(*pfit)); } ////regression energy corrections //std::pair<double,double> cor = ecorr_.CorrectedEnergyWithError(*iP); //outPhoton->SetEnergyRegr(cor.first); //outPhoton->SetEnergyErrRegr(cor.second); // add electron to map edm::Ptr<reco::Photon> thePtr(hPhotonProduct, iP - inPhotons.begin()); photonMap_->Add(thePtr, outPhoton); } photons_->Trim(); } //-------------------------------------------------------------------------------------------------- void FillerPhotons::HERecHitMatcher(const reco::Photon* pho, int zSide, double deltaPhiMin, double rhoMin, double rhoMax, double rhEnMin, ThreeVector& matchRhPos, double& matchedRhEnergy, double& matchedRhTime, const HBHERecHitCollection* hbheRecHitCol, const CaloGeometry* caloGeom) { // This function provides information on the HBHE recHits aligned to the photon ECAL cluster. A // phi window around the photon is scanned, within the rho strip covering the ECAL EB, and the // location, energy, timing of the most energetic recHits. One in HE+ and one in HE- are kept as // photon attributes. The goal is to find beam halo candidates. // re-initialize the input variables to be safe matchRhPos.SetXYZ(0,0,0); matchedRhEnergy = -1.; matchedRhTime = -1000.; // check if the photon is in EB if (!pho->isEB()) return; // loop on the HE rechits for (HBHERecHitCollection::const_iterator hh = hbheRecHitCol->begin(); hh != hbheRecHitCol->end(); hh++) { HcalDetId id(hh->detid()); // discard the rh if not in HBHE if (id.subdet()!=HcalEndcap) continue; const CaloCellGeometry *hbhe_cell = caloGeom->getGeometry(hh->id()); Global3DPoint hbhe_position = hbhe_cell->getPosition(); // discard the rh if not in right side if (hbhe_position.z() * zSide < 0) continue; // discard the rh if not enough energetic if (hh->energy() < rhEnMin) continue; // discard the rh if not in the rho window aruond ECAL EB double thisX = hbhe_position.x(); double thisY = hbhe_position.y(); double thisZ = hbhe_position.z(); double rho = sqrt(thisX*thisX + thisY*thisY); if ((rho < rhoMin) || (rho > rhoMax)) continue; // discard the rh if not in the phi window around the photon double corrDeltaPhi = TMath::Abs(pho->phi()-hbhe_position.phi()); if (corrDeltaPhi > TMath::Pi()) corrDeltaPhi = TMath::TwoPi() - corrDeltaPhi; if (corrDeltaPhi > deltaPhiMin) continue; // update the selected rechit if (hh->energy() > matchedRhEnergy) { matchedRhEnergy = hh->energy(); matchedRhTime = hh->time(); matchRhPos.SetXYZ(thisX,thisY,thisZ); } } // End loop over RecHits return; }
e376e7d60dd911bdf0519ec8c42f2babb96f932a
fd7ed208359ad08fa6bb716e1b008aa4e39e7efe
/labs/J70_State/cpp/complete/src/OrderStatus.hpp
a6a19cb5de499bb70c201508310b854179804a48
[ "MIT" ]
permissive
Meera94/design_patterns
54ca8f2796d5c878487c82f5d758b5811d3bcef2
bf9f599149359921c8171b82d102a2f2904f915e
refs/heads/main
2023-07-02T04:02:11.116457
2021-08-09T14:49:44
2021-08-09T14:49:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,716
hpp
OrderStatus.hpp
#pragma once #include <memory> using namespace std; class OrderStatus { public: virtual shared_ptr<OrderStatus> next(shared_ptr<OrderStatus> newStatus) = 0; virtual string toString() =0; }; namespace OrderStatuses { extern shared_ptr<OrderStatus> created; extern shared_ptr<OrderStatus> filled; extern shared_ptr<OrderStatus> shipped; extern shared_ptr<OrderStatus> billed; } class CreatedStatus : public OrderStatus { public: string toString(){return "Created";} shared_ptr<OrderStatus> next(shared_ptr<OrderStatus> newStatus) { if(newStatus != OrderStatuses::filled) { throw "Bogus state transition!"; } return newStatus; } }; class FilledStatus :public OrderStatus { public: string toString(){return "Filled";} shared_ptr<OrderStatus> next(shared_ptr<OrderStatus> newStatus) { if(newStatus != OrderStatuses::shipped) { throw "Bogus state transition!"; } return newStatus; } }; class ShippedStatus : public OrderStatus { public: string toString(){return "Shipped";} shared_ptr<OrderStatus> next(shared_ptr<OrderStatus> newStatus) { if(newStatus != OrderStatuses::billed) { throw "Bogus state transition!"; } return newStatus; } }; class BilledStatus : public OrderStatus { public: string toString(){return "Billed";} shared_ptr<OrderStatus> next(shared_ptr<OrderStatus> newStatus) { throw "Bogus state transition!"; } }; shared_ptr<OrderStatus> OrderStatuses::created = make_shared<CreatedStatus>(); shared_ptr<OrderStatus> OrderStatuses::filled = make_shared<FilledStatus>(); shared_ptr<OrderStatus> OrderStatuses::shipped = make_shared<ShippedStatus>(); shared_ptr<OrderStatus> OrderStatuses::billed = make_shared<BilledStatus>();
aef0eb16dc258b5e6ce4b3047b00d770f1a6b2cc
085036d7cca1839f4296a6ed55639ba326bf3f75
/APT 1020B/Area of a rectangle using a function.cpp
3fcf577877c2715a51ef8dc69826a30d63134dee
[]
no_license
IanMwiti/C-projects
436d003f57f3831fa2fff89eb36838c58b5635a7
3b08e773138cac51394f416f245ac657aa773e44
refs/heads/master
2020-06-24T05:03:17.743590
2019-07-25T16:05:15
2019-07-25T16:05:15
198,856,077
0
0
null
null
null
null
UTF-8
C++
false
false
195
cpp
Area of a rectangle using a function.cpp
#include <iostream> using namespace std; int area(int x,int y) { int area; area=x*y; return (area); } int main() { int x, y, p; x=9; y=8; p=area (x,y); cout<<"The area is \n"<<p<<endl; }
a52056c7b633093b494ee81b924a331023b16095
9e84d7a0a22eb94722cbef7bd819afb06b28d49a
/pgwriter.cpp
41bea955b27af4699e467d2d7ddbeef5bcdb7d9d
[ "MIT", "OLDAP-2.8" ]
permissive
commandus/wacs
606e4830d1b5d9d9edac112f9d98bf93bd640972
e00740fc856edbf1bf1b0fa13a7f51533145be80
refs/heads/master
2020-09-22T10:06:28.160547
2019-07-02T01:57:28
2019-07-02T01:57:28
225,149,885
0
0
null
null
null
null
UTF-8
C++
false
false
3,820
cpp
pgwriter.cpp
/** * Write to the PostgreSQL database */ #include <algorithm> #include <iostream> #include <cstring> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <arpa/inet.h> #include <nanomsg/nn.h> #include <nanomsg/bus.h> #include "errorcodes.h" #include "pgwriter.h" #include "pglog.h" #include "log.h" #define USE_SNMP 1 #ifdef USE_SNMP #include "utilsnmp.h" #include "snmp-params.h" #include "snmpagent-wacs.h" #include "snmp-params.h" #endif #define BUF_SIZE 128 #define snmp_name "wacs" static void snmpInitialize ( WacsPgConfig *config ) { #ifdef USE_SNMP #define DEF_FILE_NAME "/mdbx.dat" if (config) { config->counter = getInstance(); config->counter->clear(); config->counter->databasefilename = config->path + DEF_FILE_NAME; if (config->snmp_agent) snmpInit(snmp_name, config->snmp_agent, config->verbosity, &config->stop_request, init_mibs); } #endif } static void snmpDone ( WacsPgConfig *config ) { #ifdef USE_SNMP if (config->snmp_agent > 0) snmpDone(snmp_name); #endif } /** * @brief Write LMDB loop * @param config * @return 0- success * >0- error (see errorcodes.h) */ int run ( WacsPgConfig *config ) { START: snmpInitialize(config); config->stop_request = 0; int accept_socket = nn_socket(AF_SP, NN_BUS); int eid = nn_bind(accept_socket, config->message_url.c_str()); if (eid < 0) { LOG(ERROR) << ERR_NN_BIND << config->message_url << std::endl; return ERRCODE_NN_BIND; } if (config->verbosity > 2) LOG(INFO) << MSG_BIND_SUCCESSFULLY << config->message_url << std::endl; int recv_timeout = 1000; // 1s if (nn_setsockopt(accept_socket, NN_SOL_SOCKET, NN_RCVTIMEO, &recv_timeout, sizeof (recv_timeout)) < 0) { LOG(ERROR) << ERR_NN_SET_SOCKET_OPTION << config->message_url << " timeout " << recv_timeout << std::endl; return ERRCODE_NN_BIND; } struct dbenv env; env.dbconn = config->dbconn; env.dboptionsfile = config->dboptionsfile; env.dbname = config->dbname; env.dbuser = config->dbuser; env.dbpassword = config->dbpassword; env.dbhost = config->dbhost; env.dbport = config->dbport; env.dbsocket = config->dbsocket; env.dbcharset = config->dbcharset; env.dbclientflags = config->dbclientflags; if (!openDb(&env)) { LOG(ERROR) << ERR_DATABASE_NO_CONNECTION << std::endl; return ERRCODE_DATABASE_NO_CONNECTION; } while (!config->stop_request) { LogEntry e; int bytes = nn_recv(accept_socket, &e, sizeof(LogEntry), 0); if (bytes < 0) { switch (errno) { case EINTR: LOG(ERROR) << ERR_INTERRUPTED << std::endl; config->stop_request = true; break; case ETIMEDOUT: break; default: LOG(ERROR) << ERR_NN_RECV << errno << " " << strerror(errno) << std::endl; break; } } else { if (config->verbosity > 2) LOG(INFO) << MSG_RECEIVED << bytes << std::endl; putLog(&env, &e, bytes, config->verbosity); #ifdef USE_SNMP if ((config->counter != NULL) && config->snmp_agent) config->counter->put(&e); #endif } } int r = 0; if (!closeDb(&env)) { LOG(ERROR) << ERR_LMDB_CLOSE << config->path << std::endl; r = ERRCODE_LMDB_CLOSE; } r = nn_shutdown(accept_socket, eid); if (r) { LOG(ERROR) << ERR_NN_SHUTDOWN << config->message_url << std::endl; r = ERRCODE_NN_SHUTDOWN; } nn_close(accept_socket); accept_socket = 0; snmpDone(config); return r; } /** * @brief Stop writer * @param config * @return 0- success * >0- config is not initialized yet */ int stop ( WacsPgConfig *config ) { if (!config) return ERRCODE_NO_CONFIG; config->stop_request = 1; return ERR_OK; } int reload(WacsPgConfig *config) { if (!config) return ERRCODE_NO_CONFIG; LOG(ERROR) << MSG_RELOAD_BEGIN << std::endl; config->stop_request = 2; return ERR_OK; }
8e789da2ba14d107f1dde09ceae4a854da38091b
ea02017f2a5bd6ac68791993083b249da60b2602
/include/PlayerModelInventory.h
f8cd0aafa62b3f17c526f6262b1f7478834430ab
[]
no_license
aarribas/WizardsAndOrcs
fc7fbdb888f17f1f677ea0ddbd650eeff9ba0aff
c8e7e1c9ae0f6f1f852ac5f7f80fe8ccc902fdba
refs/heads/master
2020-05-19T07:38:34.978921
2013-09-20T18:41:33
2013-09-20T18:41:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
971
h
PlayerModelInventory.h
#pragma once class PlayerModelInventory { friend class PlayerModel; public: PlayerModelInventory(); ~PlayerModelInventory(); public: static const int INVENTORY_MORE_COINS; static const int INVENTORY_MORE_PROTECTION; static const int INVENTORY_MORE_GEMS; static const int INVENTORY_MORE_BOOTS; static const int INVENTORY_MORE_LIFE_POTIONS; public: void addCoins(){if(m_coins<101)m_coins+=INVENTORY_MORE_COINS;} void addProtection(){if(m_protection<101)m_protection+=INVENTORY_MORE_PROTECTION;} void addGems(){if(m_gems<101)m_gems+=INVENTORY_MORE_GEMS;} void addBoots(){if(m_boots<101)m_boots+=INVENTORY_MORE_BOOTS;} void addPotions(){if(m_boots<101)m_potions+=INVENTORY_MORE_LIFE_POTIONS;} int getCoins(){return m_coins;} int getProtection(){return m_protection;} int getGems(){return m_gems;} int getBoots(){return m_boots;} int getPotions(){return m_potions;} public: int m_coins; int m_protection; int m_gems; int m_boots; int m_potions; };
68226da4bd6b4c9a2640df73cd6361b3224848a0
908f7c9be9f879c914ed2298d62e5fb5bd13ecb2
/data-struct-and-algorithms-III/List.h
7e3100dd1b2296121e88e6a3e262f5caea5523ba
[]
no_license
bartoszpogoda/data-struct-and-algorithms-III
a864d2d3d2ff5f6abb025f1094af5370b65a62e6
b93f1f90baae9463bb1bb47183a3b7f9c84d3f87
refs/heads/master
2021-03-30T18:17:07.938467
2017-06-08T05:18:52
2017-06-08T05:18:52
92,441,857
0
0
null
null
null
null
UTF-8
C++
false
false
1,497
h
List.h
#pragma once #include "ListNode.h" #include <iostream> template <class Element> class List { ListNode<Element>* head; ListNode<Element>* tail; int currentSize; public: List() : currentSize(0), head(nullptr), tail(nullptr) {} ~List(); int size() { return currentSize; } void addFront(Element element); void addEnd(Element element); Element get(int position); }; template<class Element> inline List<Element>::~List() { if (head == nullptr) return; ListNode<Element>* iterator = head; ListNode<Element>* preIterator = head; while (iterator->next != nullptr) { preIterator = iterator; iterator = iterator->next; delete preIterator; } delete iterator; } template<class Element> inline void List<Element>::addFront(Element element) { ListNode<Element>* newNode = new ListNode<Element>(element); if (head == nullptr) { head = newNode; tail = newNode; } else { newNode->next = head; head = newNode; } currentSize++; } template<class Element> inline void List<Element>::addEnd(Element element) { ListNode<Element>* newNode = new ListNode<Element>(element); if (head == nullptr) { head = newNode; tail = newNode; } else { tail->next = newNode; tail = newNode; } currentSize++; } template<class Element> inline Element List<Element>::get(int position) { if (currentSize == 0 || position >= currentSize) return Element(); ListNode<Element>* iterator = head; while (position--) iterator = iterator->next; return iterator->element; }
42be97430ecf6c0826022c8c535656ff2ae63cc9
a02ccb5dff094fad8bcd691dda234d50ff768299
/plugin/multilevelProposeROI/multilevelProposeROIPlugin.cpp
d9ad8adddf8fd21a8430b64b6e2c7bd9252c66c4
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "BSD-3-Clause", "MIT", "ISC", "BSD-2-Clause" ]
permissive
NVIDIA/TensorRT
5520d5a6a5926a2b30dbdd2c5b2e4dfe6d1b429b
a167852705d74bcc619d8fad0af4b9e4d84472fc
refs/heads/release/8.6
2023-07-29T05:39:45.688091
2023-06-09T22:29:09
2023-06-09T23:04:18
184,657,328
8,026
2,096
Apache-2.0
2023-09-13T17:30:16
2019-05-02T22:02:08
C++
UTF-8
C++
false
false
18,962
cpp
multilevelProposeROIPlugin.cpp
/* * SPDX-FileCopyrightText: Copyright (c) 1993-2023 NVIDIA CORPORATION & AFFILIATES. All rights reserved. * SPDX-License-Identifier: Apache-2.0 * * 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 "multilevelProposeROIPlugin.h" #include "common/plugin.h" #include "multilevelProposeROI/tlt_mrcnn_config.h" #include <algorithm> #include <cuda_runtime_api.h> #include <iostream> #include <math.h> #include <fstream> using namespace nvinfer1; using namespace plugin; using nvinfer1::plugin::MultilevelProposeROI; using nvinfer1::plugin::MultilevelProposeROIPluginCreator; namespace { char const* const kMULTILEVELPROPOSEROI_PLUGIN_VERSION{"1"}; char const* const kMULTILEVELPROPOSEROI_PLUGIN_NAME{"MultilevelProposeROI_TRT"}; } // namespace PluginFieldCollection MultilevelProposeROIPluginCreator::mFC{}; std::vector<PluginField> MultilevelProposeROIPluginCreator::mPluginAttributes; MultilevelProposeROIPluginCreator::MultilevelProposeROIPluginCreator() noexcept { mPluginAttributes.clear(); mPluginAttributes.emplace_back(PluginField("prenms_topk", nullptr, PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back(PluginField("keep_topk", nullptr, PluginFieldType::kINT32, 1)); mPluginAttributes.emplace_back(PluginField("fg_threshold", nullptr, PluginFieldType::kFLOAT32, 1)); mPluginAttributes.emplace_back(PluginField("iou_threshold", nullptr, PluginFieldType::kFLOAT32, 1)); mPluginAttributes.emplace_back(PluginField("image_size", nullptr, PluginFieldType::kINT32, 3)); mFC.nbFields = mPluginAttributes.size(); mFC.fields = mPluginAttributes.data(); } char const* MultilevelProposeROIPluginCreator::getPluginName() const noexcept { return kMULTILEVELPROPOSEROI_PLUGIN_NAME; } char const* MultilevelProposeROIPluginCreator::getPluginVersion() const noexcept { return kMULTILEVELPROPOSEROI_PLUGIN_VERSION; } PluginFieldCollection const* MultilevelProposeROIPluginCreator::getFieldNames() noexcept { return &mFC; } IPluginV2Ext* MultilevelProposeROIPluginCreator::createPlugin( char const* name, PluginFieldCollection const* fc) noexcept { try { plugin::validateRequiredAttributesExist({"prenms_topk", "keep_topk", "fg_threshold", "iou_threshold"}, fc); auto imageSize = TLTMaskRCNNConfig::IMAGE_SHAPE; PluginField const* fields = fc->fields; for (int32_t i = 0; i < fc->nbFields; ++i) { char const* attrName = fields[i].name; if (!strcmp(attrName, "prenms_topk")) { PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32); mPreNMSTopK = *(static_cast<int32_t const*>(fields[i].data)); } if (!strcmp(attrName, "keep_topk")) { PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32); mKeepTopK = *(static_cast<int32_t const*>(fields[i].data)); } if (!strcmp(attrName, "fg_threshold")) { PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kFLOAT32); mFGThreshold = *(static_cast<float const*>(fields[i].data)); } if (!strcmp(attrName, "iou_threshold")) { PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kFLOAT32); mIOUThreshold = *(static_cast<float const*>(fields[i].data)); } if (!strcmp(attrName, "image_size")) { PLUGIN_VALIDATE(fields[i].type == PluginFieldType::kINT32); auto const dims = static_cast<int32_t const*>(fields[i].data); std::copy_n(dims, 3, imageSize.d); } } return new MultilevelProposeROI(mPreNMSTopK, mKeepTopK, mFGThreshold, mIOUThreshold, imageSize); } catch (std::exception const& e) { caughtError(e); } return nullptr; } IPluginV2Ext* MultilevelProposeROIPluginCreator::deserializePlugin( char const* name, void const* data, size_t length) noexcept { try { return new MultilevelProposeROI(data, length); } catch (std::exception const& e) { caughtError(e); } return nullptr; } MultilevelProposeROI::MultilevelProposeROI( int32_t prenms_topk, int32_t keep_topk, float fg_threshold, float iou_threshold, const nvinfer1::Dims imageSize) : mPreNMSTopK(prenms_topk) , mKeepTopK(keep_topk) , mFGThreshold(fg_threshold) , mIOUThreshold(iou_threshold) , mImageSize(imageSize) { mBackgroundLabel = -1; PLUGIN_VALIDATE(mPreNMSTopK > 0); PLUGIN_VALIDATE(mPreNMSTopK <= 4096); PLUGIN_VALIDATE(mKeepTopK > 0); PLUGIN_VALIDATE(mIOUThreshold >= 0.0F); PLUGIN_VALIDATE(mFGThreshold >= 0.0F); PLUGIN_VALIDATE(mImageSize.nbDims == 3); PLUGIN_VALIDATE(mImageSize.d[0] > 0 && mImageSize.d[1] > 0 && mImageSize.d[2] > 0); mParam.backgroundLabelId = -1; mParam.numClasses = 1; mParam.keepTopK = mKeepTopK; mParam.scoreThreshold = mFGThreshold; mParam.iouThreshold = mIOUThreshold; mType = DataType::kFLOAT; mFeatureCnt = TLTMaskRCNNConfig::MAX_LEVEL - TLTMaskRCNNConfig::MIN_LEVEL + 1; generate_pyramid_anchors(mImageSize); } int32_t MultilevelProposeROI::getNbOutputs() const noexcept { return 1; } int32_t MultilevelProposeROI::initialize() noexcept { // Init the regWeight [1, 1, 1, 1] mRegWeightDevice = std::make_shared<CudaBind<float>>(4); std::vector<float> reg_weight(4, 1); PLUGIN_CUASSERT(cudaMemcpy(static_cast<void*>(mRegWeightDevice->mPtr), static_cast<void*>(reg_weight.data()), sizeof(float) * 4, cudaMemcpyHostToDevice)); // Init the mValidCnt of max batch size std::vector<int32_t> tempValidCnt(mMaxBatchSize, mPreNMSTopK); mValidCnt = std::make_shared<CudaBind<int32_t>>(mMaxBatchSize); PLUGIN_CUASSERT(cudaMemcpy(mValidCnt->mPtr, static_cast<void*>(tempValidCnt.data()), sizeof(int32_t) * mMaxBatchSize, cudaMemcpyHostToDevice)); // Init the anchors for batch size: for (int32_t i = 0; i < mFeatureCnt; i++) { int32_t i_anchors_cnt = mAnchorsCnt[i]; auto i_anchors_host = mAnchorBoxesHost[i].data(); auto i_anchors_device = std::make_shared<CudaBind<float>>(i_anchors_cnt * 4 * mMaxBatchSize); int32_t batch_offset = sizeof(float) * i_anchors_cnt * 4; uint8_t* device_ptr = static_cast<uint8_t*>(i_anchors_device->mPtr); for (int32_t i = 0; i < mMaxBatchSize; i++) { PLUGIN_CUASSERT(cudaMemcpy(static_cast<void*>(device_ptr + i * batch_offset), static_cast<void*>(i_anchors_host), batch_offset, cudaMemcpyHostToDevice)); } mAnchorBoxesDevice.push_back(i_anchors_device); } // Init the temp storage for proposals from feature maps before concat std::vector<void*> score_tp; std::vector<void*> box_tp; for (int32_t i = 0; i < mFeatureCnt; i++) { if (mType == DataType::kFLOAT) { auto i_scores_device = std::make_shared<CudaBind<float>>(mKeepTopK * mMaxBatchSize); auto i_bboxes_device = std::make_shared<CudaBind<float>>(mKeepTopK * 4 * mMaxBatchSize); mTempScores_float.push_back(i_scores_device); score_tp.push_back(static_cast<void*>(i_scores_device->mPtr)); mTempBboxes_float.push_back(i_bboxes_device); box_tp.push_back(static_cast<void*>(i_bboxes_device->mPtr)); } else if (mType == DataType::kHALF) { auto i_scores_device = std::make_shared<CudaBind<uint16_t>>(mKeepTopK * mMaxBatchSize); auto i_bboxes_device = std::make_shared<CudaBind<uint16_t>>(mKeepTopK * 4 * mMaxBatchSize); mTempScores_half.push_back(i_scores_device); score_tp.push_back(static_cast<void*>(i_scores_device->mPtr)); mTempBboxes_half.push_back(i_bboxes_device); box_tp.push_back(static_cast<void*>(i_bboxes_device->mPtr)); } } // Init the temp storage for pointer arrays of score and box: PLUGIN_CUASSERT(cudaMalloc(&mDeviceScores, sizeof(void*) * mFeatureCnt)); PLUGIN_CUASSERT(cudaMalloc(&mDeviceBboxes, sizeof(void*) * mFeatureCnt)); PLUGIN_CUASSERT(cudaMemcpy(mDeviceScores, score_tp.data(), sizeof(void*) * mFeatureCnt, cudaMemcpyHostToDevice)); PLUGIN_CUASSERT(cudaMemcpy(mDeviceBboxes, box_tp.data(), sizeof(void*) * mFeatureCnt, cudaMemcpyHostToDevice)); return 0; } void MultilevelProposeROI::terminate() noexcept {} void MultilevelProposeROI::destroy() noexcept { delete this; } bool MultilevelProposeROI::supportsFormat(DataType type, PluginFormat format) const noexcept { return ((type == DataType::kFLOAT || type == DataType::kHALF) && format == PluginFormat::kLINEAR); } char const* MultilevelProposeROI::getPluginType() const noexcept { return "MultilevelProposeROI_TRT"; } char const* MultilevelProposeROI::getPluginVersion() const noexcept { return "1"; } IPluginV2Ext* MultilevelProposeROI::clone() const noexcept { try { return new MultilevelProposeROI(*this); } catch (std::exception const& e) { caughtError(e); } return nullptr; } void MultilevelProposeROI::setPluginNamespace(char const* libNamespace) noexcept { mNameSpace = libNamespace; } char const* MultilevelProposeROI::getPluginNamespace() const noexcept { return mNameSpace.c_str(); } size_t MultilevelProposeROI::getSerializationSize() const noexcept { return sizeof(int32_t) * 2 + sizeof(float) * 2 + sizeof(int32_t) * (mFeatureCnt + 1) + sizeof(nvinfer1::Dims) + sizeof(DataType); } void MultilevelProposeROI::serialize(void* buffer) const noexcept { char *d = reinterpret_cast<char*>(buffer), *a = d; write(d, mPreNMSTopK); write(d, mKeepTopK); write(d, mFGThreshold); write(d, mIOUThreshold); write(d, mMaxBatchSize); for (int32_t i = 0; i < mFeatureCnt; i++) { write(d, mAnchorsCnt[i]); } write(d, mImageSize); write(d, mType); PLUGIN_ASSERT(d == a + getSerializationSize()); } MultilevelProposeROI::MultilevelProposeROI(void const* data, size_t length) { mFeatureCnt = TLTMaskRCNNConfig::MAX_LEVEL - TLTMaskRCNNConfig::MIN_LEVEL + 1; char const *d = reinterpret_cast<char const*>(data), *a = d; int32_t prenms_topk = read<int32_t>(d); int32_t keep_topk = read<int32_t>(d); float fg_threshold = read<float>(d); float iou_threshold = read<float>(d); mMaxBatchSize = read<int32_t>(d); PLUGIN_VALIDATE(mAnchorsCnt.size() == 0); for (int32_t i = 0; i < mFeatureCnt; i++) { mAnchorsCnt.push_back(read<int32_t>(d)); } mImageSize = read<nvinfer1::Dims3>(d); mType = read<DataType>(d); PLUGIN_VALIDATE(d == a + length); mBackgroundLabel = -1; mPreNMSTopK = prenms_topk; mKeepTopK = keep_topk; mFGThreshold = fg_threshold; mIOUThreshold = iou_threshold; mParam.backgroundLabelId = -1; mParam.numClasses = 1; mParam.keepTopK = mKeepTopK; mParam.scoreThreshold = mFGThreshold; mParam.iouThreshold = mIOUThreshold; generate_pyramid_anchors(mImageSize); } void MultilevelProposeROI::check_valid_inputs(nvinfer1::Dims const* inputs, int32_t nbInputDims) noexcept { // x=2,3,4,5,6 // foreground_delta_px [N, h_x * w_x * anchors_per_location, 4, 1], // foreground_score_px [N, h_x * w_x * anchors_per_location, 1, 1], // anchors should be generated inside PLUGIN_ASSERT(nbInputDims == 2 * mFeatureCnt); for (int32_t i = 0; i < 2 * mFeatureCnt; i += 2) { // foreground_delta PLUGIN_ASSERT(inputs[i].nbDims == 3 && inputs[i].d[1] == 4); // foreground_score PLUGIN_ASSERT(inputs[i + 1].nbDims == 3 && inputs[i + 1].d[1] == 1); } } size_t MultilevelProposeROI::getWorkspaceSize(int32_t batch_size) const noexcept { size_t total_size = 0; PLUGIN_ASSERT(mAnchorsCnt.size() == static_cast<size_t>(mFeatureCnt)); // workspace for propose on each feature map for (int32_t i = 0; i < mFeatureCnt; i++) { MultilevelProposeROIWorkSpace proposal(batch_size, mAnchorsCnt[i], mPreNMSTopK, mParam, mType); total_size += proposal.totalSize; } // workspace for Concat and TopK ConcatTopKWorkSpace ct(batch_size, mFeatureCnt, mKeepTopK, mType); total_size += ct.totalSize; return total_size; } Dims MultilevelProposeROI::getOutputDimensions(int32_t index, Dims const* inputs, int32_t nbInputDims) noexcept { check_valid_inputs(inputs, nbInputDims); PLUGIN_ASSERT(index == 0); return {2, {mKeepTopK, 4}}; } void MultilevelProposeROI::generate_pyramid_anchors(nvinfer1::Dims const& imageSize) { auto const image_dims = imageSize; auto const& anchor_scale = TLTMaskRCNNConfig::RPN_ANCHOR_SCALE; auto const& min_level = TLTMaskRCNNConfig::MIN_LEVEL; auto const& max_level = TLTMaskRCNNConfig::MAX_LEVEL; auto const& aspect_ratios = TLTMaskRCNNConfig::ANCHOR_RATIOS; // Generate anchors strides and scales std::vector<float> anchor_scales; std::vector<int32_t> anchor_strides; for (int32_t i = min_level; i < max_level + 1; i++) { int32_t stride = static_cast<int32_t>(pow(2.0, i)); anchor_strides.push_back(stride); anchor_scales.push_back(stride * anchor_scale); } auto& anchors = mAnchorBoxesHost; PLUGIN_VALIDATE(anchors.size() == 0); PLUGIN_VALIDATE(anchor_scales.size() == anchor_strides.size()); for (size_t s = 0; s < anchor_scales.size(); ++s) { float scale = anchor_scales[s]; int32_t stride = anchor_strides[s]; std::vector<float> s_anchors; for (int32_t y = stride / 2; y < image_dims.d[1]; y += stride) for (int32_t x = stride / 2; x < image_dims.d[2]; x += stride) for (auto r : aspect_ratios) { float h = scale * r.second; float w = scale * r.first; // Using y+h/2 instead of y+h/2-1 for alignment with TLT implementation s_anchors.insert(s_anchors.end(), {(y - h / 2), (x - w / 2), (y + h / 2), (x + w / 2)}); } anchors.push_back(s_anchors); } PLUGIN_VALIDATE(anchors.size() == static_cast<size_t>(max_level - min_level + 1)); } int32_t MultilevelProposeROI::enqueue( int32_t batch_size, void const* const* inputs, void* const* outputs, void* workspace, cudaStream_t stream) noexcept { void* final_proposals = outputs[0]; size_t kernel_workspace_offset = 0; cudaError_t status; std::vector<void*> mTempScores; std::vector<void*> mTempBboxes; for (int32_t i = 0; i < mFeatureCnt; i++) { if (mType == DataType::kFLOAT) { mTempScores.push_back(mTempScores_float[i]->mPtr); mTempBboxes.push_back(mTempBboxes_float[i]->mPtr); } else if (mType == DataType::kHALF) { mTempScores.push_back(mTempScores_half[i]->mPtr); mTempBboxes.push_back(mTempBboxes_half[i]->mPtr); } } for (int32_t i = 0; i < mFeatureCnt; i++) { MultilevelProposeROIWorkSpace proposal_ws(batch_size, mAnchorsCnt[i], mPreNMSTopK, mParam, mType); status = MultilevelPropose(stream, batch_size, mAnchorsCnt[i], mPreNMSTopK, static_cast<float*>(mRegWeightDevice->mPtr), static_cast<float>(mImageSize.d[1]), // Input Height static_cast<float>(mImageSize.d[2]), mType, // mType, mParam, proposal_ws, static_cast<uint8_t*>(workspace) + kernel_workspace_offset, inputs[2 * i + 1], // inputs[object_score], inputs[2 * i], // inputs[bbox_delta] mValidCnt->mPtr, mAnchorBoxesDevice[i]->mPtr, // inputs[anchors] mTempScores[i], // temp scores [batch_size, topk, 1] mTempBboxes[i]); // temp PLUGIN_ASSERT(status == cudaSuccess); kernel_workspace_offset += proposal_ws.totalSize; } ConcatTopKWorkSpace ctopk_ws(batch_size, mFeatureCnt, mKeepTopK, mType); status = ConcatTopK(stream, batch_size, mFeatureCnt, mKeepTopK, mType, static_cast<uint8_t*>(workspace) + kernel_workspace_offset, ctopk_ws, reinterpret_cast<void**>(mDeviceScores), reinterpret_cast<void**>(mDeviceBboxes), final_proposals); PLUGIN_ASSERT(status == cudaSuccess); return status; } // Return the DataType of the plugin output at the requested index DataType MultilevelProposeROI::getOutputDataType( int32_t index, nvinfer1::DataType const* inputTypes, int32_t nbInputs) const noexcept { // Only DataType::kFLOAT is acceptable by the plugin layer if ((inputTypes[0] == DataType::kFLOAT) || (inputTypes[0] == DataType::kHALF)) return inputTypes[0]; return DataType::kFLOAT; } // Return true if output tensor is broadcast across a batch. bool MultilevelProposeROI::isOutputBroadcastAcrossBatch( int32_t outputIndex, bool const* inputIsBroadcasted, int32_t nbInputs) const noexcept { return false; } // Return true if plugin can use input that is broadcast across batch without replication. bool MultilevelProposeROI::canBroadcastInputAcrossBatch(int32_t inputIndex) const noexcept { return false; } // Configure the layer with input and output data types. void MultilevelProposeROI::configurePlugin(Dims const* inputDims, int32_t nbInputs, Dims const* outputDims, int32_t nbOutputs, DataType const* inputTypes, DataType const* outputTypes, bool const* inputIsBroadcast, bool const* outputIsBroadcast, PluginFormat floatFormat, int32_t maxBatchSize) noexcept { check_valid_inputs(inputDims, nbInputs); mAnchorsCnt.clear(); for (int32_t i = 0; i < mFeatureCnt; i++) { mAnchorsCnt.push_back(inputDims[2 * i].d[0]); PLUGIN_ASSERT(mAnchorsCnt[i] == (int32_t) (mAnchorBoxesHost[i].size() / 4)); } mMaxBatchSize = maxBatchSize; mType = inputTypes[0]; } // Attach the plugin object to an execution context and grant the plugin the access to some context resource. void MultilevelProposeROI::attachToContext( cudnnContext* cudnnContext, cublasContext* cublasContext, IGpuAllocator* gpuAllocator) noexcept { } // Detach the plugin object from its execution context. void MultilevelProposeROI::detachFromContext() noexcept {}
6239714233b098940bb061d43d1be0bd13e06d0b
9209a62997622a50e1520048381ac6651b32030a
/hprof/test/types/test_instance.h
bd9797a57d91b867c0336ded0472c4ed14413514
[ "Apache-2.0" ]
permissive
pvoid/android-hprof-browser
c88529591e97c10c98a10ad90a6f8b9107ce1288
548d5429becde0bbb746ecf71f505dd1b70d8547
refs/heads/master
2021-09-25T17:03:36.456763
2017-11-23T09:27:02
2017-11-23T09:27:02
103,631,792
1
0
Apache-2.0
2018-10-24T11:15:19
2017-09-15T08:09:52
C++
UTF-8
C++
false
false
2,699
h
test_instance.h
/// /// Copyright 2017 Dmitry "PVOID" Petukhov /// /// 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. /// #pragma once #include <gtest/gtest.h> #include "types/class.h" #include "types/instance.h" #include "mocks.h" using namespace hprof; using testing::Return; using testing::ReturnRef; using testing::_; TEST(instance_info_impl_t, When_ClassIdIsNotSet_Expect_Return0) { auto instance = instance_info_impl_t::create(4, 0xc0f060, 0); ASSERT_EQ(0, instance->class_id()); } TEST(instance_info_impl_t, When_SetClassId300_Expect_ReturnSameClassId300) { auto instance = instance_info_impl_t::create(4, 0xc0f060, 0); instance->set_class_id(300); ASSERT_EQ(300, instance->class_id()); } TEST(instance_info_impl_t, When_ClassIsNotSet_Expect_ReturnNull) { auto instance = instance_info_impl_t::create(4, 0xc0f060, 0); ASSERT_EQ(nullptr, instance->get_class()); } TEST(instance_info_impl_t, When_ClassSuper_Expect_ReturnSameinstance) { mock_fields_iterator_t iterator; mock_fields_iterator_helper_t helper { &iterator }; EXPECT_CALL(iterator, not_equals(_)).Times(1).WillOnce(Return(false)); mock_fields_spec_t fields; EXPECT_CALL(fields, begin()).Times(1).WillOnce(Return(helper)); EXPECT_CALL(fields, end()).Times(1).WillOnce(Return(helper)); mock_class_info_t cls; EXPECT_CALL(cls, fields()).Times(2).WillRepeatedly(ReturnRef(fields)); EXPECT_CALL(cls, super()).Times(1).WillOnce(Return(nullptr)); auto item = std::make_shared<mock_heap_item_t>(); EXPECT_CALL(*item, as_class()).Times(2).WillRepeatedly(Return(&cls)); auto instance = instance_info_impl_t::create(4, 0xc0f060, 0); instance->set_class(item); ASSERT_EQ(&cls, instance->get_class()); } TEST(instance_info_impl_t, When_StackTraceIdDefaultValue_Expect_Return0) { auto instance = instance_info_impl_t::create(4, 0xc0f060, 0); ASSERT_EQ(0, instance->stack_trace_id()); } TEST(instance_info_impl_t, When_StackTraceIdIsSetted_Expect_ReturnSameValue) { auto instance = instance_info_impl_t::create(4, 0xc0f060, 0); instance->set_stack_trace_id(2000); ASSERT_EQ(2000, instance->stack_trace_id()); }
8c66d0bafaf1816506886bf3d9dd28eba32c56b9
e3e8b7056b8c5a604cc1a576da0d6d5134870f93
/src/lc153/lc153.cpp
38b99f6cf162a5c76bfe74451b4fd7637614902d
[]
no_license
zou-song/leetcode
a2acc8d01538f8bc84dbb83f11c24fe876cd071b
5172da312cba7e185d155386bc5527432c40c2f8
refs/heads/master
2020-04-25T14:57:22.251872
2019-05-20T11:59:18
2019-05-20T11:59:18
172,860,827
0
0
null
2019-05-20T11:59:19
2019-02-27T06:55:26
C++
UTF-8
C++
false
false
950
cpp
lc153.cpp
#include "lc.h" class Solution { public: int findMin(vector<int>& nums) { int len = nums.size(); int beg = 0, end = len - 1; while (beg < end) { int mid = (beg + end) / 2; if (nums[beg] <= nums[mid] && nums[mid] <= nums[end]) return nums[beg]; if (nums[mid] >= nums[beg]) { if (mid + 1 < len && nums[mid + 1] < nums[mid]) return nums[mid + 1]; beg = mid + 1; } else { if (mid - 1 >= 0 && nums[mid - 1] > nums[mid]) return nums[mid]; end = mid - 1; } } return nums[beg]; } }; int main(int argc, char const *argv[]) { string line; while (getline(cin, line)) { vector<int> nums; walkString(nums, line); cout << toString(Solution().findMin(nums)) << endl; } return 0; }
f497549bcba75e84ad8c1c9d302c6dd52f7fa555
17ea9e26a0aefd6ebc5f0ac5bec4918c92d8415c
/src/CliOptions.cpp
c24cf53a5c0d2cc28e87de6df640670b2cc1ef4c
[ "MIT" ]
permissive
jieziww/JoSIM
5232d780b32f48786a132b078d31cd34ac014595
a5a055b8aedb4e5966ae7c83257489e2be28ed16
refs/heads/master
2023-01-08T04:56:23.212464
2020-08-18T08:44:38
2020-08-18T08:44:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,737
cpp
CliOptions.cpp
// Copyright (c) 2019 Johannes Delport // This code is licensed under MIT license (see LICENSE for details) #include "JoSIM/CliOptions.hpp" #include "JoSIM/Errors.hpp" #include <iostream> #include <iomanip> #include <cstring> using namespace JoSIM; CliOptions CliOptions::parse(int argc, const char **argv) { CliOptions out; int pos = 0; std::string argument; // If zero arguments are specified: complain if (argc <= 1) { Errors::cli_errors(CLIErrors::TOO_FEW_ARGUMENTS); // If arguments are specified } else { // Loop through the arguments for (int i = 1; i < argc; ++i) { // If the argument is a switch if (argv[i][0] == '-') { char swChar; bool specArg; // If specific argument set tested char to 3rd char if (argv[i][1] == '-') { swChar = argv[i][2]; specArg = true; } // If not set tested char to 2nd char else { swChar = argv[i][1]; specArg = false; } switch (swChar) { // Analysis switch case 'a': if (specArg) { argument = argv[i]; argument = argument.substr(argument.find('=') + 1); if (argument == "0") out.analysis_type = AnalysisType::Voltage; else if (argument == "1") out.analysis_type = AnalysisType::Phase; else Errors::cli_errors(CLIErrors::INVALID_ANALYSIS); } else { if (i != argc - 1) { if (argv[i + 1][0] != '-') { if (std::strcmp(argv[i + 1], "0") == 0) out.analysis_type = AnalysisType::Voltage; else if (std::strcmp(argv[i + 1], "1") == 0) out.analysis_type = AnalysisType::Phase; else Errors::cli_errors(CLIErrors::INVALID_ANALYSIS); i++; } else Errors::cli_errors(CLIErrors::NO_ANALYSIS); } else Errors::cli_errors(CLIErrors::NO_ANALYSIS); } break; // Convention switch case 'c': // If specific argument, extract argument if (specArg) { argument = argv[i]; argument = argument.substr(argument.find('=') + 1); if (argument == "0") out.input_type = InputType::Jsim; else if (argument == "1") out.input_type = InputType::WrSpice; else Errors::cli_errors(CLIErrors::INVALID_CONVENTION); } else { if (i != argc - 1) { if (argv[i + 1][0] != '-') { if (std::strcmp(argv[i + 1], "0") == 0) out.input_type = InputType::Jsim; else if (std::strcmp(argv[i + 1], "1") == 0) out.input_type = InputType::WrSpice; else Errors::cli_errors(CLIErrors::INVALID_CONVENTION); i++; } else Errors::cli_errors(CLIErrors::NO_CONVENTION); } else Errors::cli_errors(CLIErrors::NO_CONVENTION); } break; // Help switch case 'h': display_help(); exit(0); // Standard Input Switch case 'i': out.standardin = true; out.cir_file_name = "standard_input"; break; // Output file switch case 'o': if (specArg) { argument = argv[i]; if (argument.find('=') != std::string::npos) { argument = argument.substr(argument.find('=') + 1); out.output_file_name = argument; } else { out.output_file_name = "output.csv"; } if (out.output_file_name.value().find('.') != std::string::npos) { std::string outExt = out.output_file_name.value().substr( out.output_file_name.value().find_last_of('.'), out.output_file_name.value().size() - 1); std::transform(outExt.begin(), outExt.end(), outExt.begin(), toupper); if (outExt == ".CSV") out.output_file_type = FileOutputType::Csv; else if (outExt == ".DAT") out.output_file_type = FileOutputType::Dat; else out.output_file_type = FileOutputType::WrSpice; } else out.output_file_type = FileOutputType::WrSpice; } else { if (i != argc - 1) { if (argv[i + 1][0] != '-') { out.output_file_name = argv[i + 1]; if (out.output_file_name.value().find('.') != std::string::npos) { std::string outExt = out.output_file_name.value().substr( out.output_file_name.value().find_last_of('.'), out.output_file_name.value().size() - 1); std::transform(outExt.begin(), outExt.end(), outExt.begin(), toupper); if (outExt == ".CSV") out.output_file_type = FileOutputType::Csv; else if (outExt == ".DAT") out.output_file_type = FileOutputType::Dat; else out.output_file_type = FileOutputType::WrSpice; } else out.output_file_type = FileOutputType::WrSpice; i++; } else { out.output_file_type = FileOutputType::Csv; out.output_file_name = "output.csv"; Errors::cli_errors(CLIErrors::NO_OUTPUT); } } else { out.output_file_type = FileOutputType::Csv; out.output_file_name = "output.csv"; Errors::cli_errors(CLIErrors::NO_OUTPUT); } } break; // Parallelization switch case 'p': #ifdef _OPENMP std::cout << "Parallelization is ENABLED" << std::endl; #else std::cout << "Parallelization is DISABLED" << std::endl; #endif break; // Verbose switch case 'V': out.verbose = true; break; // Version switch case 'v': if (specArg) { argument = argv[i]; if (argument.find("version") != std::string::npos) exit(0); else if (argument.find("verbose") != std::string::npos) out.verbose = true; else Errors::cli_errors(CLIErrors::UNKNOWN_SWITCH, argument); break; } else exit(0); // Specific option specifier case '-': break; } // If the argument is not a switch it is the input file } else { if(!out.standardin) { out.cir_file_name = argv[i]; } else { out.cir_file_name = "standard_input"; } } } } if (out.cir_file_name.empty()) { Errors::cli_errors(CLIErrors::NO_INPUT); } if (out.output_file_name) { if(out.output_file_name.value() == out.cir_file_name) { Errors::cli_errors(CLIErrors::INPUT_SAME_OUTPUT); } } std::cout << "Input file: " << out.cir_file_name << std::endl; std::cout << std::endl; if(out.output_file_name) { std::cout << "Output file: " << out.output_file_name.value() << std::endl; std::cout << std::endl; } return out; } void CliOptions::display_help() { std::cout << "JoSIM help interface\n"; std::cout << "====================\n"; std::cout << std::setw(13) << std::left << "-a" << std::setw(3) << std::left << "|" << "Specifies the analysis type." << std::endl; std::cout << std::setw(13) << std::left << "--analysis=" << std::setw(3) << std::left << "|" << "0 for Voltage analysis (Default)." << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << "1 for Phase analysis." << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << std::endl; std::cout << std::setw(13) << std::left << "-c" << std::setw(3) << std::left << "|" << "Sets the subcircuit convention to left(0) or right(1)." << std::endl; std::cout << std::setw(13) << std::left << "--convention=" << std::setw(3) << std::left << "|" << "Default is left. WRSpice (normal SPICE) use right." << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << "Eg. X01 SUBCKT 1 2 3 vs. X01 1 2 3 SUBCKT" << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << std::endl; std::cout << std::setw(13) << std::left << "-h" << std::setw(3) << std::left << "|" << "Displays this help menu" << std::endl; std::cout << std::setw(13) << std::left << "--help" << std::setw(3) << std::left << "|" << " " << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << std::endl; std::cout << std::setw(13) << std::left << "-i" << std::setw(3) << std::left << "|" << "Input circuit netlist from standard input." << std::endl; std::cout << std::setw(13) << std::left << "--input" << std::setw(3) << std::left << "|" << "This command ignores any additional input file specified." << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << "Reads from standard input until the .end command or EOF character is specified." << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << std::endl; std::cout << std::setw(13) << std::left << "-o" << std::setw(3) << std::left << "|" << "Specify output file for simulation results (.csv)." << std::endl; std::cout << std::setw(13) << std::left << "--output=" << std::setw(3) << std::left << "|" << "Default will be output.csv if no file is specified." << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << std::endl; std::cout << std::setw(13) << std::left << "-p" << std::setw(3) << std::left << "|" << "(EXPERIMENTAL) Enables parallelization of certain functions." << std::endl; std::cout << std::setw(13) << std::left << "--parallel" << std::setw(3) << std::left << "|" << "Requires compilation with OPENMP switch enabled." << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << "Threshold applies, overhead on small circuits negates performance." << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << std::endl; std::cout << std::setw(13) << std::left << "-V" << std::setw(3) << std::left << "|" << "Runs JoSIM in verbose mode." << std::endl; std::cout << std::setw(13) << std::left << "--verbose" << std::setw(3) << std::left << "|" << " " << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << std::endl; std::cout << std::setw(13) << std::left << "-v" << std::setw(3) << std::left << "|" << "Displays the JoSIM version info only." << std::endl; std::cout << std::setw(13) << std::left << "--version" << std::setw(3) << std::left << "|" << " " << std::endl; std::cout << std::setw(13) << std::left << " " << std::setw(3) << std::left << "|" << std::endl; std::cout << std::endl; std::cout << "Example command: josim -o ./output.csv test.cir" << std::endl; std::cout << std::endl; exit(0); } void CliOptions::version_info() { std::cout << std::endl; std::cout << "JoSIM: Josephson Junction Superconductive SPICE Circuit Simulator" << std::endl; std::cout << "Copyright (C) 2019 by Johannes Delport (jdelport@sun.ac.za)" << std::endl; std::cout << "v" << VERSION << "." << GIT_COMMIT_HASH << " compiled on " << __DATE__ << " at " << __TIME__ << std::endl; #ifndef NDEBUG std::cout << "(Debug)" << std::endl; #endif std::cout << std::endl; }
9ef6e76199ae6530b202784ed04f5328b2a3b756
2f2c2a0bf9d77c0a5ee10fbc6390a7aaca637c4b
/algorithms/calc_force.cpp
23458e7b16f37ab1c3acfb5e90c7672c10a1ad07
[]
no_license
carisamuelson/StepRite
143d622113fe726331c43e5d16d7897b56ae27d5
bd2f9cc21cd885af7c62985dca2c313b2756451e
refs/heads/master
2016-09-15T20:41:21.925429
2014-01-08T14:51:34
2014-01-08T14:51:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,074
cpp
calc_force.cpp
#include <iostream> #include <cstdio> #include <cstdlib> #include "lib.cpp" double * ForceCalculations(double ** lcsv, double ** rcsv, int num_elements, int weight, int target); double * ForcePerSensor(double ** lcsv, double ** rcsv, int num_elements); using namespace std; int main(int argc, char *argv[]) { if (argc != 3) { cout << "usage: ./wrapper leftFileName rightFileName" << endl; return 0; } char * leftFile = argv[1]; char * rightFile = argv[2]; int target = 0; int weight = 100; int num_elements = 0; const char * sfile1 = leftFile; const char * sfile2 = rightFile; string leftData = "", rightData = ""; readFile(sfile1, leftData); readFile(sfile2, rightData); int left_elements = 0, right_elements = 0; double ** lcsv = SplitFile(leftData, &left_elements); double ** rcsv = SplitFile(rightData, &right_elements); num_elements = left_elements < right_elements ? left_elements : right_elements; ForceCalculations(lcsv, rcsv, num_elements, weight, target); ForcePerSensor(lcsv, rcsv, num_elements); return 0; } /* Copyright 2012, MedHab LLC */ /* Calculates information for the force dashboard. the calculation returns the average, minimum, maximum, # of times over max, # of times under min for each leg and the total number of elements. remember to free the returned structure when finished */ double * ForceCalculations(double ** lcsv, double ** rcsv, int num_elements, int weight, int target) { double minimum_weight = (target-5) * weight / 100; double maximum_weight = (target+5) * weight / 100; double left_total = 0, right_total = 0, total = 0, left_actual = 0, right_actual = 0; int left_over_max = 0, left_under_min = 0; int right_over_max = 0, right_under_min = 0; bool left_still_over = false, left_still_under = false; bool right_still_over = false, right_still_under = false; double left_average = 0, left_minimum = weight, left_maximum = 0; double right_average = 0, right_minimum = weight, right_maximum = 0; int data_start = 2; for(int i = data_start; i < num_elements; i++) { //compute totals for each leg and the overall total left_total = lcsv[i][1] + lcsv[i][2] + lcsv[i][3] + lcsv[i][4]; right_total = rcsv[i][1] + rcsv[i][2] + rcsv[i][3] + rcsv[i][4]; total = left_total + right_total; //compute actual on each leg left_actual = left_total/total; right_actual = right_total/total; left_average += left_actual; right_average += right_actual; if(left_actual < left_minimum) left_minimum = left_actual; if(right_actual < right_minimum) right_minimum = right_actual; if(left_actual > left_maximum) left_maximum = left_actual; if(right_actual > right_maximum) right_maximum = right_actual; //add over/under MAX/MIN here if(left_actual > maximum_weight && !left_still_over) { left_over_max++; left_still_over = true; }else if(left_still_over) left_still_over = false; if(left_actual < minimum_weight && !left_still_under) { left_under_min++; left_still_under = true; }else if(left_still_under) left_still_under = false; if(right_actual > maximum_weight && !right_still_over) { right_over_max++; right_still_over = true; }else if(right_still_over) right_still_over = false; if(right_actual < minimum_weight && !right_still_under) { right_under_min++; right_still_under = true; }else if(right_still_under) right_still_under = false; } left_average /= num_elements; right_average /= num_elements; //create a dynamic array to return to the calling function double * ret = (double *)malloc(sizeof(double) * 11); ret[0] = left_average; ret[1] = left_minimum; ret[2] = left_maximum; ret[3] = left_over_max; ret[4] = left_under_min; ret[5] = right_average; ret[6] = right_minimum; ret[7] = right_maximum; ret[8] = right_over_max; ret[9] = right_under_min; ret[10] = num_elements; cout << left_average << endl; cout << left_maximum << endl; cout << right_average << endl; cout << right_maximum << endl; cout << num_elements << endl; return ret; }
5ab2447ccf3e6391d9d8f2191ab2da8cfb4374f9
1b57a5c1d0a85b6d9092a354fd5bbc9e950d4446
/Include/Tubo.h
10cb54ccc2ff40aaf1eb80ab9ebd7b2c083efca2
[]
no_license
martinscairo/tubos
3e157025440692e17e0d28bffe363ff6d300f18a
e189ff5fc40c8a763baf338483931c06dd1118d6
refs/heads/master
2021-01-01T04:26:46.575616
2016-04-26T02:12:43
2016-04-26T02:12:43
56,858,475
0
0
null
null
null
null
UTF-8
C++
false
false
3,316
h
Tubo.h
#ifndef TUBO_H #define TUBO_H //============================================================================== // INCLUDE C++ //============================================================================== #include <Ponto2D.h> #include <Geometria.h> #include <iostream> //============================================================================== // typedef //============================================================================== typedef double Real; class Tubo{ //============================================================================== // função friend //============================================================================== friend std :: ostream& operator << (std:: ostream&, const Tubo&); friend std :: istream& operator >> (std:: istream&, Tubo&); friend Tubo concentrico (const Geometria&, const Tubo&); friend Tubo continuidade (const Tubo&, const Tubo&); friend Tubo PrimeiroTubo (const Tubo&, const Real&); public: //============================================================================== // CONSTRUTORES E DESTRUTORA //============================================================================== Tubo() : esp (0), diametro (0), comprimento (0), ptr () {}; Tubo(const Tubo& _orig): esp (_orig.esp), diametro (_orig.diametro), comprimento(_orig.comprimento), ptr (_orig.ptr) {}; Tubo (const Real _esp, const Real _dia, const Real _alt) : esp (_esp), diametro (_dia), comprimento (_alt), ptr () {}; Tubo (const Real _esp, const Real _dia, const Real _alt, const Ponto2D _centro): esp (_esp), diametro (_dia), comprimento (_alt), ptr (_centro) {}; Tubo (const Real _esp, const Real _dia, const Real _alt, const Real _x, const Real _y) : esp (_esp), diametro (_dia), comprimento (_alt), ptr (_x,_y) {}; virtual ~Tubo() {}; //============================================================================== // FUNÇÕES INLINE //============================================================================== inline const Real ESP() const {return esp;}; //exibir apenas espessura inline Ponto2D PTR() const {return ptr;}; //exibir apenas centro inline const Real CMP() const {return comprimento;}; //exibir apenas altura inline const Real DMT() const {return diametro;}; //exibir apenas diâmetro //============================================================================== // SOBRECARGA DE OPERADORES //============================================================================== const Tubo& operator= (const Tubo&); //============================================================================== // VARIÁVEIS PRIVADAS //============================================================================== private: Real esp, comprimento, diametro; //DIAMETRO INTERNO Ponto2D ptr; }; #endif /* TUBO_H */
b7b8ca2be8cd331cdf403ef4747c4680e9793619
8ebc3dcfd7d046672d1847b9308b8c57accb564b
/src/obj/camera.hpp
f274150737beb3f852b8d021eb05d7449c22fb07
[]
no_license
tcmug/gpm
9a4e4baef45523a78939b4e8cb20576f709045a6
11e9d266fa4387be422271f4d921689a732aea76
refs/heads/master
2021-01-23T13:09:50.971655
2018-01-11T19:35:05
2018-01-11T19:35:05
93,231,838
0
0
null
null
null
null
UTF-8
C++
false
false
1,722
hpp
camera.hpp
#ifndef CORE_CAMERA_HPP #define CORE_CAMERA_HPP #include "common.hpp" class pipeline; class object; void gl_uniform(const char *name, const glm::vec3 &p); void gl_uniform(const char *name, const glm::mat4x4 &p); /* Class: camera_base Base camera class */ class camera_base { protected: /* Variable: world_position The position of the camera in the world. */ glm::vec3 world_position; public: /* Function: set_position Set the position of the camera Parameters: &new_position - The new position */ void set_position(const glm::vec3 &new_position); /* Function: get_position Get position of the camera Returns: glm::vec3 The world position of the camera */ const glm::vec3 &get_position() const; virtual void activate(); virtual void gl_bind(); virtual glm::vec3 ray(const glm::vec3 &localray) const; }; /* Class: camera A generic camera implementation. */ class generic_camera: public camera_base { protected: glm::vec3 up_vector, camera_target; glm::mat4 camera_matrix; glm::mat4 projection_matrix; float field_of_view, width, height, near, far; public: generic_camera( const glm::vec3 &from, const glm::vec3 &to, const glm::vec3 &up, float w, float h ); void set_target(const glm::vec3 &new_target); virtual void activate(); virtual glm::vec3 ray(const glm::vec3 &localray) const; void gl_bind(); }; /* Class: camera A generic camera implementation. */ class orto_camera: public generic_camera { public: orto_camera( const glm::vec3 &from, const glm::vec3 &to, const glm::vec3 &up, float w, float h ); virtual void activate(); }; class effect_base { }; #endif
bc76e115a04b2bc0a3cc370afce4e257f1e1235a
6e05f42e0f12960277ef1c71a6f9dc4bcbe89729
/Solution/pangda/1_D.cc
f960302dd5015dcfacfffcec13567340ff85edbb
[]
no_license
Linfanty/TeamA
946cdb8890be7c19ef0a51e60751755c39378b19
a95109c4e22701f8f421d9c0e1a806838cc15197
refs/heads/master
2020-03-28T10:57:05.984215
2018-10-18T16:39:28
2018-10-18T16:39:28
148,162,759
1
0
null
2018-09-10T13:51:02
2018-09-10T13:51:01
null
UTF-8
C++
false
false
242
cc
1_D.cc
#include <iostream> int gcd(int a, int b) { return (b > 0) ? gcd(b, a % b) : a; } int main(int argc, char *argv[]) { for (int a, b; std::cin >> a >> b; ) { std::cout << a * b / gcd(a, b) << std::endl; } return 0; }
2f836ced22de04b1d32a6a71617fd8912ca6298c
fb81d60eaea26c8feed34cdf8bcb302e6246caad
/examples_theory/teacher/4_struct_class/opera/opfun/Vector2D.cc
7e90cec7b2fffb38478a2ae87ee27c1f812de28e
[]
no_license
auroraleso/Cpp-course
e03ff719c7b6dc8ee56f1dde9b5a0521231edc94
dce1cd39da03c22e595f513379aa0b7e14228c1e
refs/heads/main
2023-03-27T07:14:24.730861
2021-03-25T17:41:00
2021-03-25T17:41:00
345,602,280
0
0
null
null
null
null
UTF-8
C++
false
false
593
cc
Vector2D.cc
#include "Vector2D.h" #include <cmath> Vector2D& operator*=( Vector2D& v, float f ) { v = Vector2D( v.getX() * f, v.getY() * f ); return v; } Vector2D operator+( const Vector2D& vl, const Vector2D& vr ) { return Vector2D( vl.getX() + vr.getX(), vl.getY() + vr.getY() ); } Vector2D::Vector2D(): xv( 0.0 ), yv( 0.0 ) { } Vector2D::Vector2D( float x, float y ): xv( x ), yv( y ) { } Vector2D::~Vector2D() { } float Vector2D::getX() const { return xv; } float Vector2D::getY() const { return yv; } float Vector2D::mod() const { return sqrt( ( xv * xv ) + ( yv * yv ) ); }
097d91ddaf819fa171b9b29e390e3eae72c93b20
ee6caf788762d7e297aed4c291b20012ed681410
/90. 언어 연습/2. C연습/11021.cpp
5d4f6e59e97f451266990feb3619871c702d1cf0
[]
no_license
dmlimgo/Problem-Solving
61ea51f1737f572714bc5030470a73a6e0339336
c265ccac046b3e87c34d014876fde11f33a15ed9
refs/heads/master
2020-08-30T15:45:08.895947
2020-02-02T14:45:28
2020-02-02T14:45:28
218,424,679
0
0
null
null
null
null
UTF-8
C++
false
false
179
cpp
11021.cpp
#include <stdio.h> int main() { int t, i = 0; scanf("%d", &t); while (i < t) { i++; int n, m; scanf("%d %d", &n, &m); printf("Case #%d: %d\n", i, n+m); } return 0; }
b1b3b5165de736693e09d774b19fe7a12fb29c58
23ce9939fddf910c090bda03618023f74a7337de
/FlockingBoids/MultiThreaded_OpenCL/Source/BaseBehavior.h
09b9c9206400355a9bba35faa175d9e9cb5e30ea
[]
no_license
schwittlick/ParallelOptimization
4f21d88ab9d703b8f179e661488257a3fa3eb59a
b2160c4781aec83103eab249f361a5462501e2ae
refs/heads/master
2021-05-27T19:26:08.065894
2013-09-27T10:22:38
2013-09-27T10:22:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
712
h
BaseBehavior.h
/** * FlockingBoids - Base Behavior Module. * * @author Andy Liebke<coding@andysmiles4games.com> * @file Source/BaseBehavior.h * @version 1.0.0 30-Jun-13 * @version 1.1.0 11-Jul-13 * @copyright Copyright (c) 2013 by Andy Liebke. All rights reserved. (http://andysmiles4games.com) */ #ifndef __BASE_BEHAVIOR_H__ #define __BASE_BEHAVIOR_H__ #include <BoidGroup.h> class BaseBehavior { public: BaseBehavior(void); BaseBehavior(const BaseBehavior &src); virtual ~BaseBehavior(void); BaseBehavior& operator = (const BaseBehavior &src); virtual void update(void) = 0; void setBoidGroup(BoidGroup* group) { this->_group = group; } protected: BoidGroup* _group; }; #endif
def77ee13ecc0d6d5c290bd9868a3fce9e1ccaf7
feb941d499e01917ed1065624813ece36ee3753c
/src/game/game_listener.cc
6beb358103bff2a4a479dba7bd203a354bdcb62d
[ "BSD-3-Clause" ]
permissive
cpatrasciuc/nine-men-morris
5212252733c5104e0149983d904a86259f381fc3
acf6ba0aec0230faf617cda1c4ce6718ee3a825e
refs/heads/master
2016-09-09T18:54:40.089624
2013-12-30T20:14:52
2013-12-30T20:14:52
5,828,379
2
1
null
null
null
null
UTF-8
C++
false
false
603
cc
game_listener.cc
// Copyright (c) 2013 Cristian Patrasciuc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "game/game_listener.h" #include "game/piece_color.h" #include "game/player_action.h" namespace game { GameListener::GameListener() {} GameListener::~GameListener() {} void GameListener::OnGameInitialized() {} void GameListener::OnPlayerAction(const PlayerAction& action) {} void GameListener::OnUndoPlayerAction(const PlayerAction& action) {} void GameListener::OnGameOver(PieceColor winner) {} } // namespace game
2bba001205d0fd012a04e8541745034ac47bf62a
9011166b29eefb4d0fabfa087bfa97402272c5f7
/Problem Solving Paradigms/10487 - Closest Sums/10487 - Closest Sums.cpp
a74dfece8cbfbff16c96a3e934c0cfe901934e35
[ "MIT" ]
permissive
matheuscr30/UVA
b6ad38e92dc75dba9c19b6c3ae335bbec5f85d96
2623f15de4a3948146fe4148a236d932750633b3
refs/heads/master
2021-03-27T18:56:08.551238
2019-06-07T01:14:08
2019-06-07T01:14:08
71,507,615
2
0
null
null
null
null
UTF-8
C++
false
false
696
cpp
10487 - Closest Sums.cpp
#include <bits/stdc++.h> using namespace std; main() { vector<int>vet; int n, m, cases=1,num; while(cin >> n && n != 0) { vet.clear(); for (int i = 0; i < n; i++) { cin >> num; vet.push_back(num); } cin >> m; cout << "Case " << cases++ << ":" << endl; while(m--) { int menor = INT_MAX, res; cin >> num; for (int i = 0; i < vet.size(); i++) { for(int j = i+1; j < vet.size(); j++) { int sum = vet[i] + vet[j]; if (abs(sum-num) < menor) menor = abs(sum-num), res = sum; } } cout << "Closest sum to " << num << " is " << res << ".\n"; } } }
b1ebdaa22551df9f6338e998f5fca4348d75a9d3
d299c3dff77b8ec5cfa0313b60d78f02010fd425
/openfpga/src/base/openfpga_context.h
c85bf8607ffe8d49f0558132757d45af7210808a
[ "MIT" ]
permissive
AyaseErii/OpenFPGA
547eebefa2419a5a3e59c60d6fd711cc0759f140
1603c9b40413a4256c7718b72d0cb40183bfb88b
refs/heads/master
2023-08-15T08:18:50.615270
2021-09-22T02:02:29
2021-09-22T02:02:29
414,767,999
1
0
null
null
null
null
UTF-8
C++
false
false
7,893
h
openfpga_context.h
#ifndef OPENFPGA_CONTEXT_H #define OPENFPGA_CONTEXT_H #include <vector> #include "vpr_context.h" #include "openfpga_arch.h" #include "simulation_setting.h" #include "bitstream_setting.h" #include "vpr_netlist_annotation.h" #include "vpr_device_annotation.h" #include "vpr_clustering_annotation.h" #include "vpr_placement_annotation.h" #include "vpr_routing_annotation.h" #include "vpr_bitstream_annotation.h" #include "mux_library.h" #include "decoder_library.h" #include "tile_direct.h" #include "module_manager.h" #include "netlist_manager.h" #include "openfpga_flow_manager.h" #include "bitstream_manager.h" #include "fabric_bitstream.h" #include "device_rr_gsb.h" #include "io_location_map.h" #include "fabric_global_port_info.h" /******************************************************************** * This file includes the declaration of the date structure * OpenfpgaContext, which is used for data exchange between * different modules in OpenFPGA shell environment * * If a command of OpenFPGA needs to exchange data with other commands, * it must use this data structure to access/mutate. * In such case, you must add data structures to OpenfpgaContext * * Note: * Please respect to the following rules when using the OpenfpgaContext * 1. This data structure will be created only once in the main() function * The data structure is design to be large and contain all the * data structure required by each module of OpenFPGA core engine. * Do NOT create or duplicate in your own module! * 2. Be clear in your mind if you want to access/mutate the data inside OpenfpgaContext * Read-only data should be accessed by * const OpenfpgaContext& * Mutate should use reference * OpenfpgaContext& * 3. Please keep the definition of OpenfpgaContext short * Do put ONLY well-modularized data structure under this root. * 4. We build this data structure based on the Context from VPR * which does NOT allow users to copy the internal members * This is due to that the data structures in the OpenFPGA context * are typically big in terms of memory *******************************************************************/ class OpenfpgaContext : public Context { public: /* Public accessors */ const openfpga::Arch& arch() const { return arch_; } const openfpga::SimulationSetting& simulation_setting() const { return sim_setting_; } const openfpga::BitstreamSetting& bitstream_setting() const { return bitstream_setting_; } const openfpga::VprDeviceAnnotation& vpr_device_annotation() const { return vpr_device_annotation_; } const openfpga::VprNetlistAnnotation& vpr_netlist_annotation() const { return vpr_netlist_annotation_; } const openfpga::VprClusteringAnnotation& vpr_clustering_annotation() const { return vpr_clustering_annotation_; } const openfpga::VprPlacementAnnotation& vpr_placement_annotation() const { return vpr_placement_annotation_; } const openfpga::VprRoutingAnnotation& vpr_routing_annotation() const { return vpr_routing_annotation_; } const openfpga::VprBitstreamAnnotation& vpr_bitstream_annotation() const { return vpr_bitstream_annotation_; } const openfpga::DeviceRRGSB& device_rr_gsb() const { return device_rr_gsb_; } const openfpga::MuxLibrary& mux_lib() const { return mux_lib_; } const openfpga::DecoderLibrary& decoder_lib() const { return decoder_lib_; } const openfpga::TileDirect& tile_direct() const { return tile_direct_; } const openfpga::ModuleManager& module_graph() const { return module_graph_; } const openfpga::FlowManager& flow_manager() const { return flow_manager_; } const openfpga::BitstreamManager& bitstream_manager() const { return bitstream_manager_; } const openfpga::FabricBitstream& fabric_bitstream() const { return fabric_bitstream_; } const openfpga::IoLocationMap& io_location_map() const { return io_location_map_; } const openfpga::FabricGlobalPortInfo& fabric_global_port_info() const { return fabric_global_port_info_; } const openfpga::NetlistManager& verilog_netlists() const { return verilog_netlists_; } const openfpga::NetlistManager& spice_netlists() const { return spice_netlists_; } public: /* Public mutators */ openfpga::Arch& mutable_arch() { return arch_; } openfpga::SimulationSetting& mutable_simulation_setting() { return sim_setting_; } openfpga::BitstreamSetting& mutable_bitstream_setting() { return bitstream_setting_; } openfpga::VprDeviceAnnotation& mutable_vpr_device_annotation() { return vpr_device_annotation_; } openfpga::VprNetlistAnnotation& mutable_vpr_netlist_annotation() { return vpr_netlist_annotation_; } openfpga::VprClusteringAnnotation& mutable_vpr_clustering_annotation() { return vpr_clustering_annotation_; } openfpga::VprPlacementAnnotation& mutable_vpr_placement_annotation() { return vpr_placement_annotation_; } openfpga::VprRoutingAnnotation& mutable_vpr_routing_annotation() { return vpr_routing_annotation_; } openfpga::VprBitstreamAnnotation& mutable_vpr_bitstream_annotation() { return vpr_bitstream_annotation_; } openfpga::DeviceRRGSB& mutable_device_rr_gsb() { return device_rr_gsb_; } openfpga::MuxLibrary& mutable_mux_lib() { return mux_lib_; } openfpga::DecoderLibrary& mutable_decoder_lib() { return decoder_lib_; } openfpga::TileDirect& mutable_tile_direct() { return tile_direct_; } openfpga::ModuleManager& mutable_module_graph() { return module_graph_; } openfpga::FlowManager& mutable_flow_manager() { return flow_manager_; } openfpga::BitstreamManager& mutable_bitstream_manager() { return bitstream_manager_; } openfpga::FabricBitstream& mutable_fabric_bitstream() { return fabric_bitstream_; } openfpga::IoLocationMap& mutable_io_location_map() { return io_location_map_; } openfpga::FabricGlobalPortInfo& mutable_fabric_global_port_info() { return fabric_global_port_info_; } openfpga::NetlistManager& mutable_verilog_netlists() { return verilog_netlists_; } openfpga::NetlistManager& mutable_spice_netlists() { return spice_netlists_; } private: /* Internal data */ /* Data structure to store information from read_openfpga_arch library */ openfpga::Arch arch_; openfpga::SimulationSetting sim_setting_; openfpga::BitstreamSetting bitstream_setting_; /* Annotation to pb_type of VPR */ openfpga::VprDeviceAnnotation vpr_device_annotation_; /* Naming fix to netlist */ openfpga::VprNetlistAnnotation vpr_netlist_annotation_; /* Pin net fix to cluster results */ openfpga::VprClusteringAnnotation vpr_clustering_annotation_; /* Placement results */ openfpga::VprPlacementAnnotation vpr_placement_annotation_; /* Routing results annotation */ openfpga::VprRoutingAnnotation vpr_routing_annotation_; /* Annotation to pb_type of VPR */ openfpga::VprBitstreamAnnotation vpr_bitstream_annotation_; /* Device-level annotation */ openfpga::DeviceRRGSB device_rr_gsb_; /* Library of physical implmentation of routing multiplexers */ openfpga::MuxLibrary mux_lib_; /* Library of physical implmentation of decoders */ openfpga::DecoderLibrary decoder_lib_; /* Inner/inter-column/row tile direct connections */ openfpga::TileDirect tile_direct_; /* Fabric module graph */ openfpga::ModuleManager module_graph_; openfpga::IoLocationMap io_location_map_; openfpga::FabricGlobalPortInfo fabric_global_port_info_; /* Bitstream database */ openfpga::BitstreamManager bitstream_manager_; openfpga::FabricBitstream fabric_bitstream_; /* Netlist database * TODO: Each format should have an independent entry */ openfpga::NetlistManager verilog_netlists_; openfpga::NetlistManager spice_netlists_; /* Flow status */ openfpga::FlowManager flow_manager_; }; #endif
911210fe7b8dadf9ca5964b9782ffc0278f7ef0e
9426ad6e612863451ad7aac2ad8c8dd100a37a98
/ULLib/include/ULFrameWnd.h
aeaf149ed51fd7de27e34078b9f7b5028584a70f
[]
no_license
piroxiljin/ullib
61f7bd176c6088d42fd5aa38a4ba5d4825becd35
7072af667b6d91a3afd2f64310c6e1f3f6a055b1
refs/heads/master
2020-12-28T19:46:57.920199
2010-02-17T01:43:44
2010-02-17T01:43:44
57,068,293
0
0
null
2016-04-25T19:05:41
2016-04-25T19:05:41
null
WINDOWS-1251
C++
false
false
1,786
h
ULFrameWnd.h
///\file ULFrameWnd.h ///\brief Заголовочный файл класса главного окна(2006) #pragma once #ifndef __UL_ULFRAMEWND_H__ #define __UL_ULFRAMEWND_H__ #include "ULWnd.h" namespace ULWnds { namespace ULFrames { ///\class CULFrameWnd ///\brief Класс главного окна(2006) class CULFrameWnd: public CULWnd { public: ///\brief Конструктор CULFrameWnd(void); ///\brief Конструктор копирования CULFrameWnd(CULFrameWnd& FrameWnd); ///\brief Деструктор virtual ~CULFrameWnd(void); ///\brief Оператор копирования virtual void operator = (CULFrameWnd&); ///\brief Функция создания главного окна ///\param szWindowName - заголовок окна ///\param MenuID - ID меню из ресурсов ///\param IconID - ID иконки из ресурсов ///\param IconSmID - ID маленькой иконки из ресурсов ///\param BGColor - цвет клиентской области ///\param dwStyle - стиль окна ///\param dwStyleEx - расширенный стиль окна ///\return TRUE в случае успеха BOOL Create(LPCTSTR szWindowName, short MenuID, short IconID, short IconSmID, short BGColor, DWORD dwStyle=WS_OVERLAPPEDWINDOW, DWORD dwStyleEx=WS_EX_APPWINDOW); protected: ///\brief Обработчик WM_DESTROY virtual LRESULT OnDestroy(WPARAM /*wParam*/,LPARAM /*lParam*/); ///\brief Обработчик WM_CREATE virtual LRESULT OnCreate(WPARAM /*wParam*/,LPARAM); }; } } #endif//__UL_ULFRAMEWND_H__
a2de2a9208078ef541085ded33f6afc09cdde095
8c7a3e006411447223a7e68f9d0c8f3f997104a7
/src/net/socket.cpp
14d8995975eecc1ead3589335af8eeda08d4f259
[ "MIT" ]
permissive
ruoka/net4cpp
0075dd29f9194ef4a468975ce1088476da8934be
a4874be5a50a050b54f0898e588d1077d8695b6b
refs/heads/master
2023-06-27T22:46:26.547047
2023-06-20T22:32:31
2023-06-20T22:32:31
36,616,987
12
4
MIT
2021-03-25T14:34:12
2015-05-31T18:50:03
C++
UTF-8
C++
false
false
1,118
cpp
socket.cpp
#include "net/socket.hpp" #include "net/network.hpp" namespace net { socket::socket(int domain, int type, int protocol) : m_fd{native_handle_npos} { m_fd = ::socket(domain, type, protocol); } socket::socket(int fd) : m_fd{fd} {} socket::socket(socket&& s) : m_fd{native_handle_npos} { m_fd = s.m_fd; s.m_fd = native_handle_npos; } socket::~socket() { if(m_fd != native_handle_npos) net::close(m_fd); } bool socket::wait_for(const std::chrono::milliseconds& timeout) const { auto fds = net::fd_set{}; FD_ZERO(&fds); FD_SET(m_fd, &fds); net::timeval tv{ static_cast<decltype(tv.tv_sec)>(timeout.count() / 1000), static_cast<decltype(tv.tv_usec)>(timeout.count() % 1000 * 1000) }; // checks ready for read const auto result = net::select(m_fd+1, &fds, nullptr, nullptr, &tv); return result > 0; } bool socket::wait() const { auto fds = net::fd_set{}; FD_ZERO(&fds); FD_SET(m_fd, &fds); // checks ready for send const auto result = net::select(m_fd+1, nullptr, &fds, nullptr, nullptr); return result > 0; } } // namespace net
77f5b8784713e415fa9f67c9539a2056c4a0b7db
11a76a55f1cbf8a7ef3d894f14a65a72ff96fb84
/src/server/math/geometry/SimplifyCurve.h
c16b1b9d51529a5947a59600527840f6d8cc88b2
[ "MIT" ]
permissive
florent-engineering/anemomind
61db624de0df0354275da27d271108ab7ef33215
86a5833d670331c9ce113d194651138a35dcfac5
refs/heads/master
2023-02-10T02:09:37.817653
2021-01-04T08:35:46
2021-01-04T08:35:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,641
h
SimplifyCurve.h
// Julien Pilet, 2014 #ifndef MATH_GEOMETRY_SIMPLIFY_CURVE_H #define MATH_GEOMETRY_SIMPLIFY_CURVE_H #include <cmath> #include <vector> // A curve is an ordered collection of connected 2D points. // The point might be closed or open. // // The "priorities" method returns one priority value for each point. // The lower the value, the higher the priority. // The idea is that drawing a curve with only points of priority lower than a // threshold limits the number of points but preserves the curve quality as // much as possible. class CurveSimplifier { public: CurveSimplifier(bool closed) : _closed(closed) { } void addPoint(double x, double y) { _points.push_back(Vertex(x, y)); } std::vector<int> priorities(); bool closed() const { return _closed; } private: struct Vertex; struct Triangle { Vertex* _points[3]; Triangle() { set(0, 0, 0); } Triangle(const Triangle& other); void set(Vertex* a, Vertex* b, Vertex* c) { _points[0] = a; _points[1] = b; _points[2] = c; } double area() const { double x[3] = { _points[0]->_x, _points[1]->_x, _points[2]->_x }; double y[3] = { _points[0]->_y, _points[1]->_y, _points[2]->_y }; return fabs((x[0] - x[2]) * (y[1] - y[0]) - (x[0] - x[1]) * (y[2] - y[0])); } double oppositeSquaredEdgeLength() const { double x[2] = {_points[0]->_x, _points[2]->_x}; double y[2] = {_points[0]->_y, _points[2]->_y}; double xdif = x[0] - x[1]; double ydif = y[0] - y[1]; return xdif*xdif + ydif*ydif; } }; struct SortingTrianglePointer { Triangle *triangle; SortingTrianglePointer(Triangle* ptr) : triangle(ptr) { } Triangle* operator->() { return triangle; } bool operator < (const SortingTrianglePointer& other) const { // Firstly, eliminate points with small triangle area. // If area is the same, eliminate points that have a long opposite edge first. return std::make_pair(triangle->area(), -triangle->oppositeSquaredEdgeLength()) < std::make_pair(other.triangle->area(), -other.triangle->oppositeSquaredEdgeLength()); } bool operator == (const SortingTrianglePointer& other) const { return triangle == other.triangle; } }; struct Vertex { double _x, _y; Triangle* _triangle; Vertex(double x, double y) : _x(x), _y(y), _triangle(0) { } }; void computeTriangles(std::vector<Triangle>* triangles); int numTriangles() const { return (_closed ? _points.size() : _points.size() - 2); } std::vector<Vertex> _points; bool _closed; }; #endif // MATH_GEOMETRY_SIMPLIFY_CURVE_H
c3a1e68a2d9696562b084c97a7bc8cb0bbaa104a
bcf922683a3db8bc41afff404c392c5c85efceb8
/Data_struture/SeqList.cpp
eef865235ab9e456ceff550d5a6ac6e18b3c9910
[]
no_license
hezeqiang/Data_struture
3c5ca24e3fc4928024a88400b2e9e4684ee2f5f5
b2332aeaac4e1cd2d042785a20403620a849c876
refs/heads/master
2022-05-28T16:31:17.989792
2022-05-24T05:59:34
2022-05-24T05:59:34
230,293,189
0
0
null
null
null
null
UTF-8
C++
false
false
1,605
cpp
SeqList.cpp
#include <stdio.h> #include <stdlib.h> #define ElementType int SeqList* L; int i,j,k; typedef struct{ ElementType *array; int length; int capacity; }SeqList; SeqList* creatList(int capacity) { L = ( SeqList * )malloc(sizeof(SeqList)); L->length = 0; L->capacity = capacity; L->array = (ElementType * )malloc(capacity * sizeof(ElementType)); return L; } int get(SeqList*L, int i, ElementType *x)//x is used to store the value { if (i<1 || i>L->length) { return 0; } *x = L->array[i - 1]; return 1; } int find(SeqList* L, ElementType x) { i = L->length - 1; while (i >= 0 && L->array[i] != x) { i--; } return i; } int insertList(SeqList* L, int i, ElementType x) { if (L->length >= L->capacity) {return 0;} if (i<1 || i>L->length + 1) { return 0; } for (k = L->length - 1; k >= i - 1; k--) { L->array[k + 1] = L->array[k]; } L->array[i - 1] = x; L->length++; return 1; } int deleteList(SeqList*L, int i, ElementType *x) //*x is used to restore the deleted value in case { if (i<1 || i>L->length) { return 0; } *x = L->array[i - 1]; for (k = i; k < L->length; k++) { L->array[k - 1] = L->array[k]; } L->length--; return 1; } void mergeList(SeqList*LA, SeqList*LB, SeqList*LC) { i = i = k = 0; while (i < LA->length&&j < LB->length) { if (LA->array[i] < LB->array[j]) { LC->array[k] = LA->array[i]; k++; i++; } else { LC->array[k] = LB->array[j]; k++; j++; } } while (i < LA->length) { LC->array[k++] = LA->array[i++]; } while (j < LB->length) { LC->array[k++] = LB->array[j++]; } LC->length = k; }
5f70a63a2568d3f7cba656e8188ae8e3a222121f
34bb46af0e2363229048227ff10faf88c12b4f02
/BasicFramework_DX/CustomMesh.h
c204769beef752c67b459460590c505aeeac6210
[]
no_license
KidCozy/BasicDX11Framework
2521d5849aa48a2dc78f75205cc233102dd5ef91
4c1e5edb39964fd57d6400e1cdac36da63e5273c
refs/heads/master
2020-08-08T18:05:27.922546
2019-10-17T16:01:13
2019-10-17T16:01:13
213,884,338
0
0
null
null
null
null
UTF-8
C++
false
false
146
h
CustomMesh.h
#pragma once #include "Model.h" class CustomMesh : public Model { private: std::string Name; public: CustomMesh(); virtual ~CustomMesh(); };
afeb9e761948094fe6c7174610cb093d82b5804a
f2dfc26d73b10dafa88a9aec856461292b4e7904
/dice-roll/Test.cpp
6cf32afb61fdfee6a988531e887ef57d4058dab0
[]
no_license
fellicienta/pr
daaa9b8e076ebef78b11dd0a2e62f95882933a5f
85199f50e1d50acf4095698c9a4cff7b73a94cfb
refs/heads/main
2023-06-05T02:59:40.274578
2021-06-29T14:30:25
2021-06-29T14:30:25
350,853,536
0
0
null
null
null
null
UTF-8
C++
false
false
130
cpp
Test.cpp
#include "lib.h" #include <gtest/gtest.h> TEST(RollDice, main) { EXPECT_EQ(7, get_most_frequent_dice_roll(2, 6, 100000)); }
654da65735b92522c1a34200b13d6d7cce203f43
2fe370454d774a0247a3bcb473ba48f57914b7ff
/ir_send/ir_send.ino
c5019411e9c6734cb0f9ecd5471aa1a2f0055bf1
[]
no_license
snt/rpi_arduino_ir_remote
222be63c4b89151bf32b0ec790cdf48b7ee94cb6
47aef1ed9cd607aaac00d73169329a90adbd4dc2
refs/heads/master
2021-01-20T05:31:33.611769
2014-09-08T07:09:44
2014-09-08T07:09:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,126
ino
ir_send.ino
#define IR_RECV_PIN 2 #define IR_SEND_PIN 4 #define IR_TIMEOUT_USEC 1000000 #define BUFFER_SIZE 256 void setup() { Serial.begin(115200); pinMode(IR_RECV_PIN, INPUT); pinMode(IR_SEND_PIN, OUTPUT); } void loop() { int irdata[BUFFER_SIZE]; int i = 0; Serial.println("ready"); while(true) { int c = Serial.read(); if(c == -1 || c == 13 || c == 10 || c == 32) continue; irdata[i++] = c; Serial.print(c); Serial.print(", "); if(c=='Z') break; } Serial.println(); long t = 425; char format = 'A'; for(int i=0; i<BUFFER_SIZE; i++) { int c = irdata[i]; switch(c) { case -1: break; case 'L': Serial.println("leader"); send_leader(format, t); break; case 'T': send_trailer(format, t); Serial.println("trailer"); return; break; case 'X': //config Xtnnn; t = [NAS] NEC, AEHA, SONY; nnn = pulse width [us] format = irdata[i+1]; switch(format) { case 'N': t = 562; break; case 'A': t = 100 * (irdata[i+2] - '0') + 10 * (irdata[i+3] - '0') + (irdata[i+4] - '0'); break; case 'S': t = 600; break; default: Serial.println("Not in the format: Xtnnn; t = [NAS] NEC, AEHA, SONY; nnn = pulse width [us]"); break; } Serial.print("format="); Serial.println(format); Serial.print("T="); Serial.println(t); i+=4; break; default: send_4bits(format, t, c); break; } } } void on(long us) { long init = micros(); while(micros()-init <= us) { digitalWrite(IR_SEND_PIN, HIGH); delayMicroseconds(9); digitalWrite(IR_SEND_PIN, LOW); delayMicroseconds(17); } //Serial.print(" "); //Serial.print(us); } void off(long us) { delayMicroseconds(us); //Serial.print("-"); //Serial.print(us); } void send_leader(char format, long t) { switch(format) { case 'N': on(16 * t); off(8 * t); break; case 'A': on(8 * t); off(4 * t); break; case 'S': on(4 * t); break; default: Serial.println("fail on send leader"); } } void send_trailer(char format, long t) { on(t); } void send_4bits(char format, long t, int c) { int x = 0; if( '0' <= c && c <= '9') { x = c - '0'; } else if ('A' <= c && 'F' <= 46) { x = c - 'A' + 10; } else if ('a' <= c && c <= 'f') { x = c - 'a' + 10; } else { Serial.print("unknown char:"); Serial.println(c); return; } switch(format) { case 'N': case 'A': for(int i = 0; i<4; i++) { if(x & 1) { on(t); off(3*t); } else { on(t); off(t); } x = x >> 1; } break; case 'S': for(int i = 0; i<4; i++) { if(x & 1) { off(2*t); on(t); } else { off(t); on(t); } x = x >> 1; } break; default: Serial.println("invalid format"); } //Serial.println(); }
003614bcdb0ab70889501ede10daa5e551d87b59
def16c78851f1f6f214d26a69c5ff7f066266671
/ReversiGame/src/Client.cpp
6e0a3dc092891a425a282edde6a558f6e8405589
[]
no_license
Mazgana/Reversi
ae7e110c9f243c64124feb2b4e64825169a00b25
9a4ed749886b642b6c03db7817383455d85c60eb
refs/heads/master
2021-09-05T07:40:54.548720
2018-01-25T09:52:58
2018-01-25T09:52:58
111,842,261
0
1
null
null
null
null
UTF-8
C++
false
false
4,811
cpp
Client.cpp
#include "Client.h" Client::Client(const char *serverIP, int serverPort): serverIP(serverIP), serverPort(serverPort), clientSocket(0){ displayer = new ConsoleDisplay(); } Client :: ~Client() { } void Client::connectToServer() { //create a socket point this->clientSocket = socket(AF_INET, SOCK_STREAM, 0); if (clientSocket == -1) { throw "Error opening socket"; } //Convert the ip string to a network address struct in_addr address; if (!inet_aton(serverIP, &address)) { throw "Can't parse IP address"; } // Get a hostest structure for the given host address struct hostent *server; server = gethostbyaddr((const void *)&address, sizeof address, AF_INET); if (server == NULL) { throw "Host is unreachable"; } //Create a structure for the server address struct sockaddr_in serverAddress; bzero((char *)&address, sizeof(address)); serverAddress.sin_family = AF_INET; memcpy((char *)&serverAddress.sin_addr.s_addr, (char *)server->h_addr, server->h_length); //htons converts values between host and network byte orders serverAddress.sin_port = htons(serverPort); //Establish a connection with the TCP server if (connect(this->clientSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == -1) { throw "Error connecting to server"; } //displayer->printMessageWitheNewLine("Connected to server"); } char Client::getOpeningPlayer() { try { //reading first integer sent from server indicates the player's cheap type. int playersPlace = readInt(); if(playersPlace == 1) { displayer->printNewLine(); displayer->printMessageWitheNewLine("You are the black player X, you go first"); return 'X'; } else if (playersPlace == 2) { displayer->printNewLine(); displayer->printMessageWitheNewLine("You are the white player O, you go second"); return 'O'; } else { displayer->printNewLine(); displayer->printMessageWitheNewLine("got unreadable starting player from server"); return ' '; } } catch (const char *msg) { return 'F'; } } int Client::receiveCoordinate() { //reading an integer from server to be coordinate int cor = readInt(); return cor; } void Client::sendMove(int x, int y) { //writing to server 2 integers that will be read as coordinates. writeInt(x); writeInt(y); } int Client :: sendCommandMessage(string message) { //Sending the server the user's command int n = (int) send(this->clientSocket, message.c_str(), message.length(), 0); if (n == -1) { throw "Error writing message to socket."; } else if (n == 0) { displayer->printMessageWitheNewLine("The server disconnected."); throw "Lost server connection"; } // reading the server's response if the command succeeded or failed. int serverResponse = readInt(); return serverResponse; } void Client::attending() { int mes = 1; writeInt(mes); } vector<string> Client :: receiveStringList(string messageToServer) { vector<string> list; char line[MAX_STR] = ""; string gameName; int len = 0; //Sending the server the user's command int n = (int) send(clientSocket, messageToServer.c_str(), messageToServer.length(), 0); if (n == -1) { throw "Error writing message to socket."; } else if (n == 0) { displayer->printMessageWitheNewLine("The server disconnected."); throw "The server disconnected"; } // reading the list one name at a time and add them to the games vector while (len != -1) { // the list has names len = readInt(); if (len == -1) //The end of the list break; int n = recv((int)clientSocket, line, len, 0); if (n == -1) { throw "Error reading string"; } else if (n == 0) { displayer->printMessageWitheNewLine("The server disconnected."); throw "The server disconnected"; } gameName = line; list.push_back(gameName); } return list; } int Client::readInt() { int val; int w = (int) read(clientSocket, &val, sizeof(int)); if (w == -1) { displayer->printMessageWitheNewLine("A connection problem occured."); throw "Error reading int"; } else if (w == 0) { displayer->printMessageWitheNewLine("The server disconnected."); exit(-1); } return val; } void Client::writeInt(int val) { int n = (int) write(clientSocket, &val, sizeof(val)); if (n == -1) { displayer->printMessageWitheNewLine("A connection problem occured."); throw "Error writing int"; } else if (n == 0) { displayer->printMessageWitheNewLine("The server disconnected."); exit(-1); } }
c78c8a7c93f636e75baf16d93954c6487018deab
8aad0674a89e5b5785e3b28acd5c2a0d453bb92a
/EPSILON/core/common/inc/common/basics/shapes.h
007bff3d38f33d88d9be5b8c8683820b36d82e4e
[ "MIT" ]
permissive
Mesywang/EPSILON_Noted
d047b9434a563d991d66f415bac48e52734cb91a
099ce4e74bd3245e89c50379bb93270b7fba99e0
refs/heads/main
2023-01-09T19:29:18.380687
2020-11-12T08:30:32
2020-11-12T08:30:32
312,210,761
3
2
null
null
null
null
UTF-8
C++
false
false
11,942
h
shapes.h
/** * @file shapes.h * @author HKUST Aerial Robotics Group * @brief * @version 0.1 * @date 2019-03-17 * * @copyright Copyright (c) 2019 */ #ifndef _COMMON_INC_COMMON_BASICS_SHAPES_H__ #define _COMMON_INC_COMMON_BASICS_SHAPES_H__ #include <map> #include <opencv2/core/core.hpp> #include "common/basics/basics.h" #include "common/basics/colormap.h" #include "common/math/calculations.h" namespace common { struct Point { decimal_t x = 0.0; decimal_t y = 0.0; decimal_t z = 0.0; /** * @brief Default constructor */ Point(); /** * @brief Construct a new Point object * * @param _x * @param _y */ Point(decimal_t _x, decimal_t _y); /** * @brief Construct a new Point object * * @param _x * @param _y * @param _z */ Point(decimal_t _x, decimal_t _y, decimal_t _z); /** * @brief Print info */ void print() const; }; struct Point2i { int x = 0; int y = 0; /** * @brief Default constructor */ Point2i(); /** * @brief Construct a new Point 2i object * * @param _x * @param _y */ Point2i(int _x, int _y); /** * @brief Print info */ void print() const; }; template <typename T> struct PointWithValue { Point pt; std::vector<T> values; }; struct OrientedBoundingBox2D { decimal_t x; decimal_t y; decimal_t angle; decimal_t width; decimal_t length; /** * @brief Default constructor */ OrientedBoundingBox2D(); /** * @brief Construct a new Oriented Bounding Box 2D object * * @param x_ x of center of obb * @param y_ y of center of obb * @param angle_ angle between x-positive and longitudinal axis of obb * @param width_ width of obb * @param length_ length of obb */ OrientedBoundingBox2D(const decimal_t x_, const decimal_t y_, const decimal_t angle_, const decimal_t width_, const decimal_t length_); }; template <int N> struct AxisAlignedBoundingBoxND { std::array<decimal_t, N> coord; std::array<decimal_t, N> len; /** * @brief Default constructor */ AxisAlignedBoundingBoxND() {} /** * @brief Construct a new AxisAlignedBoundingBoxND object * * @param coord_ Center of AABB * @param len_ Length of AABB */ AxisAlignedBoundingBoxND(const std::array<decimal_t, N> coord_, const std::array<decimal_t, N> len_) : coord(coord_), len(len_) {} }; template <typename T, int N_DIM> struct AxisAlignedCubeNd { std::array<T, N_DIM> upper_bound; std::array<T, N_DIM> lower_bound; AxisAlignedCubeNd() = default; AxisAlignedCubeNd(const std::array<T, N_DIM> ub, const std::array<T, N_DIM> lb) : upper_bound(ub), lower_bound(lb) {} }; struct Circle { Point center; decimal_t radius; /** * @brief Print info */ void print() const; }; struct PolyLine { int dir; std::vector<Point> points; /** * @brief Print info */ void print() const; }; struct Polygon { std::vector<Point> points; /** * @brief Print info */ void print() const; }; class ShapeUtils { public: /** * @brief Check if 2 OBBs intersect * * @param obb_a OBB A * @param obb_b OBB B * @return true Intersect * @return false No intersect */ static bool CheckIfOrientedBoundingBoxIntersect(const OrientedBoundingBox2D& obb_a, const OrientedBoundingBox2D& obb_b); /** * @brief Get the Vertices Of OrientedBoundingBox object * * @param obb Input OBB * @param vertices Output vertice vector * @return ErrorType */ static ErrorType GetVerticesOfOrientedBoundingBox(const OrientedBoundingBox2D& obb, vec_E<Vecf<2>>* vertices); /** * @brief Get the Perpendicular Axes Of Oriented Bounding Box * * @param vertices * @param axes * @return ErrorType */ static ErrorType GetPerpendicularAxesOfOrientedBoundingBox(const vec_E<Vecf<2>>& vertices, vec_E<Vecf<2>>* axes); /** * @brief Get the Projection On Axis object * * @param vertices * @param axis * @param proj * @return ErrorType */ static ErrorType GetProjectionOnAxis(const vec_E<Vecf<2>>& vertices, const Vecf<2>& axis, Vecf<2>* proj); /** * @brief Get the Perpendicular Axis Of Oriented Bounding Box object * * @param vertices * @param index * @param axis * @return ErrorType */ static ErrorType GetPerpendicularAxisOfOrientedBoundingBox(const vec_E<Vecf<2>>& vertices, const int index, Vecf<2>* axis); /** * @brief Get the Overlap Length * * @param a * @param b * @param len * @return ErrorType */ static ErrorType GetOverlapLength(const Vecf<2> a, const Vecf<2> b, decimal_t* len); /** * @brief Get the cv::Point2i Vector Using Common::Point2i Vector * * @param pts_in Input common::Point2i vector * @param pts_out Output cv::Point2i vector * @return ErrorType */ static ErrorType GetCvPoint2iVecUsingCommonPoint2iVec(const std::vector<Point2i>& pts_in, std::vector<cv::Point2i>* pts_out); /** * @brief Get the cv::Point2i Using Common::Point2i * * @param pt_in Input Common::Point2i * @param pt_out Output cv::Point2i * @return ErrorType */ static ErrorType GetCvPoint2iUsingCommonPoint2i(const Point2i& pt_in, cv::Point2i* pt_out); /** * @brief * * @tparam T * @tparam N_DIM * @param cube_a * @param cube_b * @return true * @return false */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeAContainsAxisAlignedCubeB(const common::AxisAlignedCubeNd<T, N_DIM>& cube_a, const common::AxisAlignedCubeNd<T, N_DIM>& cube_b) { for (int i = 0; i < N_DIM; ++i) { if (cube_a.lower_bound[i] > cube_b.lower_bound[i] || cube_a.upper_bound[i] < cube_b.upper_bound[i]) { return false; } } return true; } /** * @brief * * @tparam T * @tparam N_DIM * @param aabb_a * @param aabb_b * @return true * @return false */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeCollide(const common::AxisAlignedCubeNd<T, N_DIM>& aabb_a, const common::AxisAlignedCubeNd<T, N_DIM>& aabb_b) { for (int i = 0; i < N_DIM; ++i) { decimal_t half_len_a = fabs(static_cast<double>(aabb_a.upper_bound[i] - aabb_a.lower_bound[i]) / 2.0); decimal_t half_len_b = fabs(static_cast<double>(aabb_b.upper_bound[i] - aabb_b.lower_bound[i]) / 2.0); decimal_t center_a = static_cast<double>(aabb_a.upper_bound[i] + aabb_a.lower_bound[i]) / 2.0; decimal_t center_b = static_cast<double>(aabb_b.upper_bound[i] + aabb_b.lower_bound[i]) / 2.0; decimal_t len_c = fabs(center_a - center_b); // ~ Seperated if (fabs(half_len_a + half_len_b) <= len_c) { return false; } } return true; } /** * @brief * * @tparam T * @tparam N_DIM * @param aabb_a * @param aabb_b * @param inter_dim_a * @param inter_dim_b * @return true If two AABBs intersect * @return false If two AABBs is seperated or one AABB contains another */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeNdIntersect(const AxisAlignedCubeNd<T, N_DIM>& aabb_a, const AxisAlignedCubeNd<T, N_DIM>& aabb_b, std::array<bool, N_DIM * 2>* inter_dim_a, std::array<bool, N_DIM * 2>* inter_dim_b) { inter_dim_a->fill(false); inter_dim_b->fill(false); // ~ A contains B or B contains A if (CheckIfAxisAlignedCubeAContainsAxisAlignedCubeB(aabb_a, aabb_b) || CheckIfAxisAlignedCubeAContainsAxisAlignedCubeB(aabb_b, aabb_a)) { return false; } // ~ Check if collide if (!CheckIfAxisAlignedCubeCollide(aabb_a, aabb_b)) { return false; } // ~ Calculate on which A's surface collision happened for (int i = 0; i < N_DIM; ++i) { if (CheckIfAxisAlignedCubeNdCollideOnOneDim(aabb_a, aabb_b, i)) { if (aabb_a.upper_bound[i] < aabb_b.upper_bound[i] && aabb_a.upper_bound[i] > aabb_b.lower_bound[i]) { (*inter_dim_a)[2 * i] = true; } if (aabb_a.lower_bound[i] < aabb_b.upper_bound[i] && aabb_a.lower_bound[i] > aabb_b.lower_bound[i]) { (*inter_dim_a)[2 * i + 1] = true; } } } // ~ Calculate on which B's surface collision happened for (int i = 0; i < N_DIM; ++i) { if (CheckIfAxisAlignedCubeNdCollideOnOneDim(aabb_a, aabb_b, i)) { if (aabb_b.upper_bound[i] > aabb_a.lower_bound[i] && aabb_b.upper_bound[i] < aabb_a.upper_bound[i]) { (*inter_dim_b)[2 * i] = true; } if (aabb_b.lower_bound[i] > aabb_a.lower_bound[i] && aabb_b.lower_bound[i] < aabb_a.upper_bound[i]) { (*inter_dim_b)[2 * i + 1] = true; } } } return true; } /** * @brief * @notice This function only check on dim intersection */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeNdIntersectionOnOneDim(const AxisAlignedCubeNd<T, N_DIM>& aabb_a, const AxisAlignedCubeNd<T, N_DIM>& aabb_b, const int& i) { decimal_t half_len_a = fabs(static_cast<double>(aabb_a.upper_bound[i] - aabb_a.lower_bound[i]) / 2.0); decimal_t half_len_b = fabs(static_cast<double>(aabb_b.upper_bound[i] - aabb_b.lower_bound[i]) / 2.0); decimal_t center_a = aabb_a.lower_bound[i] + half_len_a; decimal_t center_b = aabb_b.lower_bound[i] + half_len_b; decimal_t len_c = fabs(center_a - center_b); // ~ Seperated or Contained if (fabs(half_len_a + half_len_b) <= len_c || fabs(half_len_a - half_len_b) >= len_c) { return false; } return true; }; /** * @brief * @notice This function only check on dim collision * * @tparam T * @tparam N_DIM * @param aabb_a * @param aabb_b * @param i * @return true * @return false */ template <typename T, int N_DIM> static bool CheckIfAxisAlignedCubeNdCollideOnOneDim(const AxisAlignedCubeNd<T, N_DIM>& aabb_a, const AxisAlignedCubeNd<T, N_DIM>& aabb_b, const int& i) { decimal_t half_len_a = fabs(static_cast<double>(aabb_a.upper_bound[i] - aabb_a.lower_bound[i]) / 2.0); decimal_t half_len_b = fabs(static_cast<double>(aabb_b.upper_bound[i] - aabb_b.lower_bound[i]) / 2.0); decimal_t center_a = aabb_a.lower_bound[i] + half_len_a; decimal_t center_b = aabb_b.lower_bound[i] + half_len_b; decimal_t len_c = fabs(center_a - center_b); // ~ Seperated or Contained if (fabs(half_len_a + half_len_b) <= len_c) { return false; } return true; }; }; // class ShapeUtils } // namespace common #endif //_COMMON_INC_COMMON_BASICS_SHAPES_H__
84b07881e1abc87f93b43fe56ba7990a88771f97
996ff94e796804be7edc7c76720e9c6f44234e5f
/src/Interface/Application/GuiCommands.h
0b1ebcb41e3567ff12a1aa905c78dc2f7e93866a
[ "MIT" ]
permissive
manual123/SCIRun
aad3e304dcb329baad71fd5f38db9402cca0f0d6
053ec3dd005c43d5850460e2a0ea482dc172b108
refs/heads/master
2023-07-06T22:19:23.764845
2023-02-06T20:49:32
2023-02-06T20:49:32
178,338,084
1
0
MIT
2019-03-29T05:26:35
2019-03-29T05:26:35
null
UTF-8
C++
false
false
4,226
h
GuiCommands.h
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. 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 INTERFACE_APPLICATION_GUICOMMANDS_H #define INTERFACE_APPLICATION_GUICOMMANDS_H #include <Dataflow/Network/NetworkFwd.h> #include <Core/Command/Command.h> #include <Core/Application/Application.h> #include <QString> class QSplashScreen; class QTimer; namespace SCIRun { namespace Gui { class NetworkEditor; class SCIRunMainWindow; class LoadFileCommandGui : public Core::Commands::FileCommand<Core::Commands::GuiCommand> { public: LoadFileCommandGui(); bool execute() override; }; class RunPythonScriptCommandGui : public Core::Commands::GuiCommand { public: bool execute() override; }; class ExecuteCurrentNetworkCommandGui : public Core::Commands::GuiCommand { public: bool execute() override; }; class QuitAfterExecuteCommandGui : public Core::Commands::GuiCommand { public: QuitAfterExecuteCommandGui(); bool execute() override; }; class QuitCommandGui : public Core::Commands::GuiCommand { public: QuitCommandGui(); bool execute() override; }; class ShowMainWindowGui : public Core::Commands::GuiCommand { public: bool execute() override; }; class SetupDataDirectoryCommandGui : public Core::Commands::GuiCommand { public: bool execute() override; }; class ShowSplashScreenGui : public Core::Commands::GuiCommand { public: ShowSplashScreenGui(); bool execute() override; private: static void initSplashScreen(); static QSplashScreen* splash_; static QTimer* splashTimer_; }; class NetworkFileProcessCommand : public Core::Commands::FileCommand<Core::Commands::GuiCommand> { public: NetworkFileProcessCommand(); bool execute() override; Dataflow::Networks::NetworkFileHandle file_; protected: virtual Dataflow::Networks::NetworkFileHandle processXmlFile(const std::string& filename) = 0; int guiProcess(const Dataflow::Networks::NetworkFileHandle& file); NetworkEditor* networkEditor_; }; class FileOpenCommand : public NetworkFileProcessCommand { public: FileOpenCommand(); protected: Dataflow::Networks::NetworkFileHandle processXmlFile(const std::string& filename) override; }; class FileImportCommand : public NetworkFileProcessCommand { public: FileImportCommand(); std::string logContents() const { return logContents_.str(); } protected: Dataflow::Networks::NetworkFileHandle processXmlFile(const std::string& filename) override; std::ostringstream logContents_; }; class NetworkSaveCommand : public Core::Commands::FileCommand<Core::Commands::GuiCommand>, public Core::Commands::SaveFileCommandHelper { public: bool execute() override; }; class DisableViewScenesCommandGui : public Core::Commands::GuiCommand { public: bool execute() override; }; class ToolkitUnpackerCommand : public Core::Commands::FileCommand<Core::Commands::GuiCommand> { public: bool execute() override; }; } } #endif
942eb6637477a51ff7c1081598ade6460aabd803
465df8cc43f0fed03e36c06897fe29ee59b49c5b
/frameworks/runtime-src/Classes/sunmap/MapPrivoder/GoogleSatelliteMapStrategy.h
53e6ab0766039d2e261b66d545e65e5d3258f744
[ "MIT" ]
permissive
wish-wish/skyheroes
781ed41a707eacaadc3d618036bf96c8b1d71b47
6411a3834f0ef152371d732ef76321793e5a3955
refs/heads/master
2023-04-16T21:00:23.253065
2021-05-01T07:05:16
2021-05-01T07:05:16
339,356,308
0
1
null
null
null
null
UTF-8
C++
false
false
353
h
GoogleSatelliteMapStrategy.h
#ifndef __COCOS2D_GoogleSatelliteMapStrategy_H__ #define __COCOS2D_GoogleSatelliteMapStrategy_H__ #include "cocos2d.h" #include "MapStrategy.h" USING_NS_CC; class GoogleSatelliteMapStrategy : public MapStrategy { public: std::string getUrl(int x, int y, int z); std::string getDescription(); std::string getImageType(){ return "png"; }; }; #endif
345d76aa75693edf305d15538da91b214a8d04fd
e9481553419aa5956f6f94a68eceadafadb95ab5
/db_proxy/src/tb/kai_fu_act_log.cpp
c8ab16e84c65e713d2ea0cb88e1c5abe6fa35144
[]
no_license
OrAlien/gserver
4b5ed7cde428062361413495b290b0c6b0a96bed
463471cf62a155bc695119c84f5d67f5a36ce376
refs/heads/master
2021-05-10T17:56:05.324201
2015-03-27T12:32:36
2015-03-27T12:32:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,290
cpp
kai_fu_act_log.cpp
#include "db_async_store.h" #include "mblock_pool.h" #include "tb_msg_map.h" #include "proxy_obj.h" #include "kai_fu_act_log.h" #include "sys_log.h" #include "istream.h" #include "message.h" static ilog_obj *s_log = sys_log::instance()->get_ilog("base"); static ilog_obj *e_log = err_log::instance()->get_ilog("base"); namespace { class sql : public sql_opt { public: virtual int id() { return this->data_.char_id_; } kai_fu_act_log data_; }; class tb_msg_get : public tb_msg_handler { class sql_get : public sql { virtual int opt_type() { return sql_opt::SQL_SELECT; } virtual int build_sql(char *bf, const int bf_len) { return this->data_.select_sql(bf, bf_len); } virtual void read_sql_result(MYSQL_RES *res, async_result *ar) { MYSQL_ROW row = NULL; while((row = mysql_fetch_row(res)) != NULL) { mblock *mb = mblock_pool::instance()->alloc(sizeof(kai_fu_act_log)); kai_fu_act_log *si = (kai_fu_act_log *)mb->data(); si->reset(); this->read_sql_row(si, row); mb->wr_ptr(sizeof(kai_fu_act_log)); ar->push_back(mb); } } void read_sql_row(kai_fu_act_log *data, MYSQL_ROW &row) { data->char_id_ = ::atoi(row[kai_fu_act_log::IDX_CHAR_ID]); data->act_type_ = ::atoi(row[kai_fu_act_log::IDX_ACT_TYPE]); data->value_ = ::atoi(row[kai_fu_act_log::IDX_VALUE]); } }; public: tb_msg_get(const int res) : resp_id_(res) { } virtual int handle_msg(proxy_obj *po, const char *msg, const int len) { int db_sid = -1; sql_get *sql = new sql_get(); in_stream is(msg, len); is >> db_sid >> sql->data_.char_id_; db_async_store::instance()->do_sql(po->proxy_id(), db_sid, 0, this->resp_id_, sql); return 0; } int resp_id_; }; static tb_msg_maper tm_get(REQ_GET_KAI_FU_ACT_LOG, new tb_msg_get(RES_GET_KAI_FU_ACT_LOG)); class tb_msg_insert : public tb_msg_handler { class sql_insert : public sql { virtual int opt_type() { return sql_opt::SQL_INSERT; } virtual int build_sql(char *bf, const int bf_len) { return this->data_.insert_sql(bf, bf_len); } }; public: tb_msg_insert(const int res) : resp_id_(res) { } virtual int handle_msg(proxy_obj *po, const char *msg, const int len) { int db_sid = -1; char bf[sizeof(kai_fu_act_log) + 4]; stream_istr si(bf, sizeof(bf)); in_stream is(msg, len); is >> db_sid >> si; assert(si.str_len() == sizeof(kai_fu_act_log)); sql_insert *sql = new sql_insert(); ::memcpy((char *)&sql->data_, si.str(), sizeof(kai_fu_act_log)); db_async_store::instance()->do_sql(po->proxy_id(), db_sid, 0, this->resp_id_, sql); return 0; } int resp_id_; }; static tb_msg_maper tm_insert(REQ_INSERT_KAI_FU_ACT_LOG, new tb_msg_insert(RES_INSERT_KAI_FU_ACT_LOG)); }
2744f9f7e1c64ee31b7a27a8f3c190eaeba45394
d8f1d71fcd714a16b805f94b318a91641d53bb68
/src/libgraphic/src/message/entity/MoveGraphicEntityMessage.cpp
497d88ba81ee117eb88828aad0d5802347c2a6fb
[ "Apache-2.0" ]
permissive
SimonPiCarter/GameEngine
0b72a3bed7054af5df7ffb8134f19ceb58fbd564
10d366bd37d202a5a22eb504b2a2dd9a49669dc8
refs/heads/main
2023-05-29T11:53:22.338760
2021-06-19T12:28:04
2021-06-19T12:28:04
365,501,044
0
0
Apache-2.0
2021-05-18T20:40:32
2021-05-08T11:49:07
C++
UTF-8
C++
false
false
384
cpp
MoveGraphicEntityMessage.cpp
#include "MoveGraphicEntityMessage.h" #include "message/GraphicMessageHandler.h" MoveGraphicEntityMessage::MoveGraphicEntityMessage(GraphicEntity * entity_p, std::array<double, 3> const &vector_p) : GraphicMessage("") , _entity(entity_p) , _vector(vector_p) {} void MoveGraphicEntityMessage::visit(GraphicMessageHandler &handler_p) { handler_p.visitMoveGraphicEntity(*this); }
fa8733407674cb4c95c748ba87cb1050bc9a0e37
500b22f28ebce4c398c8af837e657adf83eff27f
/clientservice.h
bef1406c4609e767b049549ff97f08a201210db2
[]
no_license
MarcSky/localDB
8c91e183f0e62d12b312858c71af56e2003d5824
66e7a7e5ff2dd261245123a49570c0e1034c85d4
refs/heads/master
2016-09-06T12:55:21.401090
2015-06-09T04:44:32
2015-06-09T04:44:32
37,110,717
0
0
null
null
null
null
UTF-8
C++
false
false
950
h
clientservice.h
#ifndef __localDB__clientservice__ #define __localDB__clientservice__ #include <stdio.h> #include <string> #include <vector> #include "file.h" #include <iostream> #include <ctime> const char events[] = "/Users/Levan/xcode/localDB/localDB/files/events.txt"; enum EVENTS_TYPE{EVENT_SECONDS=0, EVENT_SMS}; typedef struct ClientService{ //список услуг для клиента long long phone; int id_service; std::string dateStart; int time; ClientService * next; ClientService * prev; } ClientService; struct ClientServiceList { public: ClientServiceList(); ~ClientServiceList(); std::vector<long long> getSmsPhones(int minSms); int getCurrentUnixtime(void); int getUnixtime(std::string date); void debug(void); private: ClientService * head; ClientService * tail; FileReader * fr; int client_size; int _id; }; #endif /* defined(__localDB__clientservice__) */
b3997f55681dcf1b8389431ba24f3ed6318b4bdb
13b92b899893f5337a3ce13e033dc18bfd40dcd9
/tests/main.cc
954e8f640743de422fb8f8883f3bc06887fa36a5
[ "MIT" ]
permissive
mbetten89/CppProjectTemplate
d57869368fba79e41a9ea626907beda760ed043b
d8214722da773d722d4caa77f5a6b924ee5475a1
refs/heads/master
2023-08-27T02:01:29.573912
2021-11-03T13:34:31
2021-11-03T13:34:31
424,193,178
0
0
null
null
null
null
UTF-8
C++
false
false
451
cc
main.cc
#define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" #include "my_lib.h" TEST_CASE("Test my cout function", "TestCout") { cout_hello_world(); } TEST_CASE("Test my vector function", "TestVector") { linalg::aliases::float3 v = print_linalg_vector(); REQUIRE(1 == v[0]); REQUIRE(2 == v[1]); REQUIRE(3 == v[2]); } TEST_CASE("Test my boost function", "TestBoost") { bool b = print_boost_version(); REQUIRE(true == b); }
943c985a4bce4def471cc0bcfd1533392ce70422
29eb3d1bd7a8d2905faf1eef532f20baddfcb259
/Public/FbxBuilderTextureImportData.h
aa6a87708627659bde92ef49b6959f7bec01c836
[]
no_license
alexanderyyg/load
836b811b5fde30bb6163483ee936fb7714dd3c12
94b3a2d38b89c36ac8ee66ac63c8f7535436c6c7
refs/heads/master
2020-04-17T21:43:06.320042
2019-01-25T07:58:27
2019-01-25T07:58:27
166,963,024
3
2
null
null
null
null
UTF-8
C++
false
false
1,935
h
FbxBuilderTextureImportData.h
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "UObject/ObjectMacros.h" #include "UObject/SoftObjectPath.h" #include "FbxBuilderAssetImportData.h" //#include "MaterialImportHelpers.h" #include "Engine.h" #include "FbxBuilderTextureImportData.generated.h" /** * Import data and options used when importing any mesh from FBX */ UCLASS(AutoExpandCategories=(Texture)) class LOAD_API UFbxBuilderTextureImportData : public UFbxBuilderAssetImportData { //GENERATED_BODY() public: GENERATED_UCLASS_BODY() //UFbxBuilderTextureImportData(const FObjectInitializer& ObjectInitializer); /** If importing textures is enabled, this option will cause normal map Y (Green) values to be inverted */ UPROPERTY(EditAnywhere, AdvancedDisplay, config, Category=ImportSettings, meta=(OBJRestrict="true")) uint32 bInvertNormalMaps:1; /** Specify where we should search for matching materials when importing */ UPROPERTY(EditAnywhere, config, Category = ImportSettings, meta = (DisplayName="Search Location", OBJRestrict = "true", ImportType = "Mesh")) EMaterialSearchLocation MaterialSearchLocation; /** Base material to instance from when importing materials. */ UPROPERTY(EditAnywhere, config, Category = Material, meta = (ImportType = "Mesh", AllowedClasses = "MaterialInterface")) FSoftObjectPath BaseMaterialName; UPROPERTY(config, meta = (ImportType = "Mesh")) FString BaseColorName; UPROPERTY(config, meta = (ImportType = "Mesh")) FString BaseDiffuseTextureName; UPROPERTY(config, meta = (ImportType = "Mesh")) FString BaseNormalTextureName; UPROPERTY(config, meta = (ImportType = "Mesh")) FString BaseEmissiveColorName; UPROPERTY(config, meta = (ImportType = "Mesh")) FString BaseEmmisiveTextureName; UPROPERTY(config, meta = (ImportType = "Mesh")) FString BaseSpecularTextureName; bool CanEditChange( const UProperty* InProperty ) const override; };
e99c87f3ce4fbf04f46714fa0009d3fbe3929b12
a6b09b1f27e0aae2753dc68600eaaad8ca3e9c1a
/Monopoly/Player/Player.h
082c9f7bf1c1544e4304c71114ed42d9f4ac1bc1
[]
no_license
Berlisia/Monopoly
7d1c44660ffcec5ecb5b818a91ccbe2a814cb51b
4fe0d1b0b91045a69a5ea369e99ec0a7193ee594
refs/heads/master
2021-07-10T06:20:04.908004
2020-11-22T21:34:25
2020-11-22T21:34:25
215,247,323
1
0
null
null
null
null
UTF-8
C++
false
false
1,211
h
Player.h
#pragma once #include "Contestant.h" #include "PlayerFsm.h" #include "PlayerPropertis.h" namespace { const unsigned int moneyOnStartGame = 1500; } class Estate; class Dice; using Fsm = std::unique_ptr<FsmBase<PlayerState, PlayerEvent>>; class Player : public Contestant { public: Player(std::string p_name, const Dice& p_dice, const SubjectBuildingProperty& p_buildingProperty); void turn() override; const PlayerStatus status() override; void lockInPrison() override; bool withdrawMoney(unsigned int money) override; bool haveEnoughtMoney(unsigned int money) override; void addMoney(unsigned int money) override; bool buyProperty(unsigned int price, const Estate* property, const District& district) override; void sellProperty(unsigned int price, const Estate* property, const District& district) override; unsigned int checkPropertisInDistrict(const std::vector<const Estate*>& propertisInDistrict) override; unsigned int rollDice() override; const std::string& myName() override; void printStatus(); private: std::string name; PlayerPropertis propertis; Fsm fsm; unsigned int money = moneyOnStartGame; const Dice& dice; };
31edf18a8f66c9979e9e3e0e207e4422d8a24c2f
7a8153e3fde0807462b6b6696b796d772639fa74
/src/system/graphic/DynamicObject.h
ce4fa2b2e80b26ce58cf22ed52f1b72f81f1f996
[]
no_license
qaze/violetland
7183f9670676d05da3970cd2fbd8cf7e5f5197c2
9f0fc9aff4ca1a4111b45fb105fc33fd9ae97dad
refs/heads/master
2021-01-02T22:38:01.687080
2011-10-10T12:35:36
2011-10-10T12:35:36
32,754,552
2
0
null
null
null
null
UTF-8
C++
false
false
693
h
DynamicObject.h
#ifndef DYNAMICOBJECT_H_ #define DYNAMICOBJECT_H_ #ifdef _WIN32 #define _USE_MATH_DEFINES #endif //_WIN32W #include "../Object.h" #include "Sprite.h" class DynamicObject: public Object { private: int m_lastFrameRollTime; public: DynamicObject(float x, float y, Sprite *sprite); void rollFrame(bool forward); void draw(); void draw(float x, float y, float angle, float scale, float rMask, float gMask, float bMask, float aMask); Texture* getFrame() const { return AnimSprite->getFrame(Frame); } void process(int deltaTime) { Object::move(deltaTime); } virtual ~DynamicObject(); int Frame; Sprite* AnimSprite; }; #endif /* DYNAMICOBJECT_H_ */
92c04bd53b353369438e658ccdbd8271a10930b8
dd629803899abbb8b6d8b4503b3591bb7eae6e73
/include/forge/base/gf/line.h
8fb88e9817481bcf1dead7636bc6a4c791cebf23
[]
no_license
furby-tm/Winggverse
8d78bb691d2e5eecc5197845e9cbfb98f45c58bd
0dc9db7057f52fca3e52e73491e24f298d108106
refs/heads/main
2023-04-21T17:32:20.350636
2021-04-30T04:24:30
2021-04-30T04:24:30
362,732,238
1
0
null
null
null
null
UTF-8
C++
false
false
3,788
h
line.h
#line 1 "C:/Users/tyler/dev/WINGG/forge/base/gf/line.h" /* * Copyright 2021 Forge. All Rights Reserved. * * The use of this software is subject to the terms of the * Forge license agreement provided at the time of installation * or download, or which otherwise accompanies this software in * either electronic or hard copy form. * * Portions of this file are derived from original work by Pixar * distributed with Universal Scene Description, a project of the * Academy Software Foundation (ASWF). https://www.aswf.io/ * * Original Copyright (C) 2016-2021 Pixar. * Modifications copyright (C) 2020-2021 ForgeXYZ LLC. * * Forge. The Animation Software & Motion Picture Co. */ #ifndef FORGE_BASE_GF_LINE_H #define FORGE_BASE_GF_LINE_H /// \file gf/line.h /// \ingroup group_gf_BasicGeometry #include "forge/forge.h" #include "forge/base/gf/vec3d.h" #include <float.h> #include <iosfwd> FORGE_NAMESPACE_BEGIN /// \class GfLine /// \ingroup group_gf_BasicGeometry /// /// Basic type: 3D line /// /// This class represents a three-dimensional line in space. Lines are /// constructed from a point, \p p0, and a direction, dir. The direction is /// normalized in the constructor. /// /// The line is kept in a parametric represention, p = p0 + t * dir. /// class GfLine { public: /// The default constructor leaves line parameters undefined. GfLine() { } /// Construct a line from a point and a direction. GfLine(const GfVec3d &p0, const GfVec3d &dir ) { Set( p0, dir ); } double Set(const GfVec3d &p0, const GfVec3d &dir ) { _p0 = p0; _dir = dir; return _dir.Normalize(); } /// Return the point on the line at \p ( p0 + t * dir ). /// Remember dir has been normalized so t represents a unit distance. GfVec3d GetPoint( double t ) const { return _p0 + _dir * t; } /// Return the normalized direction of the line. const GfVec3d &GetDirection() const { return _dir; } /// Returns the point on the line that is closest to \p point. If \p t is /// not \c NULL, it will be set to the parametric distance along the line /// of the returned point. GF_API GfVec3d FindClosestPoint(const GfVec3d &point, double *t = NULL) const; /// Component-wise equality test. The starting points and directions, /// must match exactly for lines to be considered equal. bool operator ==(const GfLine &l) const { return _p0 == l._p0 && _dir == l._dir; } /// Component-wise inequality test. The starting points, and directions /// must match exactly for lines to be considered equal. bool operator !=(const GfLine &r) const { return ! (*this == r); } private: GF_API friend bool GfFindClosestPoints( const GfLine &, const GfLine &, GfVec3d *, GfVec3d *, double *, double * ); // Parametric description: // l(t) = _p0 + t * _length * _dir; GfVec3d _p0; GfVec3d _dir; }; /// Computes the closets points between two lines. /// /// The two points are returned in \p p1 and \p p2. The parametric distance /// of each point on the lines is returned in \p t1 and \p t2. /// /// This returns \c false if the lines were close enough to parallel that no /// points could be computed; in this case, the other return values are /// undefined. GF_API bool GfFindClosestPoints(const GfLine &l1, const GfLine &l2, GfVec3d *p1 = nullptr, GfVec3d *p2 = nullptr, double *t1 = nullptr, double *t2 = nullptr); /// Output a GfLine. /// \ingroup group_gf_DebuggingOutput GF_API std::ostream &operator<<(std::ostream&, const GfLine&); FORGE_NAMESPACE_END #endif // FORGE_BASE_GF_LINE_H
98192934c88ebb5ce8bff740720e09afa7d7eba3
eab8d3252193ed1e66732e042443d5cb88eb3c02
/Lista Circular/List.cpp
302deb61534b92989e6aeba2f3bc61d56e30e0c6
[ "MIT" ]
permissive
lunebakami/projeto-ed
acc000d42826b42e701fdb5c6f4ee24961da9a54
09a58bf5624c5cfc0d6fbce5f3b2f6f82670ce29
refs/heads/main
2023-03-16T16:40:35.203942
2021-02-28T23:22:33
2021-02-28T23:22:33
340,897,237
2
0
null
null
null
null
UTF-8
C++
false
false
6,981
cpp
List.cpp
// José Luis dos Santos Araujo - 472435 // Joyce Kelly Chaves Barros da Silva - 472032 #include <iostream> #include <sstream> #include "List.h" using namespace std; struct Node { int value; Node* next; Node* prev; }; // José Luis List::List() { // Definindo head e tail head = new Node; tail = new Node; head->value = -77777777; head->next = tail; head->prev = tail; tail->value = -77777777; tail->next = head; tail->prev = head; } // Joyce Kelly List::~List() { // Limpando a lista e liberando head e tail clear(); delete head; delete tail; cout << "lista liberada" << endl; } // José Luis Node* List::search(int key) { // Verificamos se a lista está vazia if (empty()) { return nullptr; } Node* aux = head; // Procuramos qual elemento tem o mesmo valor que a key passada while (aux->next != tail) { if (aux->next->value == key) { return aux; } aux = aux->next; } return nullptr; } // José Luis void List::push_back(int key) { // Criamos o novo nó e definimos seus valores Node* new_node = new Node(); new_node->value = key; // Liga novo nó ao tail new_node->next = tail; new_node->prev = tail->prev; // Liga o novo nó ao anterior ao tail tail->prev->next = new_node; tail->prev = new_node; } // Joyce Kelly int List::pop_back() { // Verifica se a lista está vazia if (empty()) { cout << "Lista vazia "; return 0; } // Pegamos o primeiro elemento antes do tail Node* aux = tail->prev; // Reorganizamos os relacionamentos tail->prev = aux->prev; aux->prev->next = tail; // Pegamos o valor para retornar int i = aux->value; // Deleta o elemento delete aux; return i; } // José Luis void List::insertAfter(int key, int k) { Node* aux = head; int count = 0; // definimos um novo nó Node* new_node = new Node(); new_node->value = key; // Percorremos até o local escolhido while (count < k) { aux = aux->next; count++; } // Reorganizamos os relacionamentos e inserimos o novo nó no local new_node->prev = aux; new_node->next = aux->next; aux->next->prev = new_node; aux->next = new_node; } // Joyce Kelly void List::remove(int key) { // Verifica se a lista está vazia if (empty()) { cout << "Lista vazia"; } // Recebemos o elemento com o valor especificado Node* aux = search(key); Node* temp; // Se não for nulo reorganizamos os relacionamentos if (aux != nullptr) { temp = aux->next; aux->next = aux->next->next; aux->next->prev = aux; delete temp; } } // José Luis void List::removeAll(int key) { // Verifica se a lista é vazia if (empty()) { cout << "Lista vazia"; } Node* aux = head->next; Node* temp; // Percorre a lista e remove todas as ocorrencias do valor while (aux != tail) { temp = aux; aux = aux->next; if (temp->value == key) { temp->prev->next = temp->next; temp->next->prev = temp->prev; delete temp; } } } // Joyce Kelly void List::print() { // Verifica se a lista está vazia if (empty()) { cout << "Lista vazia" << endl; return; } // Cria uma stringstream para mostrar os valores no final stringstream ss; ss << "["; Node* aux = head->next; // Percorre a lista enquanto o auxiliar não for o tail while (aux != tail) { // Armazena o valor na stringstream ss << aux->value; // se o próximo não for o tail, adiciona uma virgula if (aux->next != tail) { ss << ","; } // passa para o próximo elemento aux = aux->next; } ss << "]"; cout << ss.str() << endl;; } // José Luis void List::printReverse() { if (empty()) { cout << "Lista vazia" << endl; return; } // Cria uma stringstream para mostrar os valores no final stringstream ss; ss << "["; Node* aux = tail->prev; // Percorre a lista enquanto o auxiliar não for o tail while (aux != head) { ss << aux->value; // se o próximo não for o head, adiciona uma virgula if (aux->prev != head) { ss << ","; } // passa para o elemento anterior aux = aux->prev; } ss << "]"; cout << ss.str() << endl;; } // José Luis bool List::empty() { // Se o head aponta pro next, significa que não há nenhum nó na Lista if (head->next == tail) { return true; } return false; } // Joyce Kelly int List::size() { Node* aux = head; int count = 0; // Percorre a Lista utilizando uma variável contadora while (aux->next != tail) { count++; aux = aux->next; } return count; } // José Luis void List::clear() { Node* aux = head; Node* temp; // Percorremos enquanto o próximo do aux(head) não é o tail while (aux->next != tail) { // Reorganiza os relacionamentos para apagar o próximo do aux(head) temp = aux->next; aux->next = aux->next->next; delete temp; } // Reorganiza o head e o tail head->next = tail; tail->prev = head; } // Joyce Kelly void List::concat(List* lst) { /** * Se a lista passada não for vazia * reorganiza os heads e tails de ambas as listas * para concatenar o inicio de uma ao final da outra */ if (!lst->empty()) { this->tail->prev->next = lst->head->next; lst->head->next->prev = this->tail->prev; this->tail->prev = lst->tail->prev; lst->tail->prev->next = this->tail; lst->head->next = lst->tail; } } // Joyce Kelly List* List::copy() { // Cria nova lista List* lst = new List(); // Verifica se a lista está vazia if (this->empty()) { return lst; } Node* aux = this->head->next; // Percorre a lista adicionando cada valor ao final da nova lista while (aux != tail) { lst->push_back(aux->value); aux = aux->next; } return lst; } // José Luis void List::copyArray(int n, int arr[]) { // Percorre o array inserindo os valores no final da lista for (int i = 0; i < n; i++) { this->push_back(arr[i]); } } // José Luis bool List::equal(List* lst) { // Verifica se ambas tem o mesmo tamanho if (lst->size() != this->size()) { return false; } Node* aux1 = this->head->next; Node* aux2 = lst->head->next; // Percorre uma das listas e se encontrar uma divergencia retorna falso while (aux1 != tail) { if (aux1->value != aux2->value) { return false; } aux1 = aux1->next; aux2 = aux2->next; } return true; }
0927dea1f00d379d2d04f0c3e97d9c3dffdd331d
7b5e6b1c54fc8729b5f1a3c595f3d409e8868840
/CGWork/Scene.cpp
375448405aaa627e4c53803049ad182856cdec34
[]
no_license
asafanter/Graphics_Hw3
f2f35face4ad6fbd540e30f922b1b5f78d102c7c
4ca1d08eee08a2bcf66efd54d7dd0474a7548fd7
refs/heads/master
2020-12-13T21:37:12.010070
2020-03-04T20:14:40
2020-03-04T20:14:40
234,537,440
0
0
null
null
null
null
UTF-8
C++
false
false
9,277
cpp
Scene.cpp
#include "Scene.h" #include "Line.h" #include "Draw.h" #define DEF_BOUNDING_BOX_SCREEN_RATION 3 Scene::Scene() : _objs(), _view(), _projection(), _is_initialized(false), _background_color(RGB(0, 0, 0)), _camera({}), _look_at(), _drawing_mode(DrawingMode::SOLID), _lights(), _ambient(), _is_normals_fliped(false), _shading(Shading::PHONG), _back_face_culling(false), _is_foggy(false), _fog_color(RGB(127, 127, 127)), _filter(Filter::NONE), _is_recording_history(false), _need_save_history(false), _background_image_type(ZBuffer::BackgroundImageType::NONE), _background_image_file_name(), _spot_light_theta(7.0), _min_fog(1.0), _max_fog(1.0), _phong_factor(1) { _projection = TransformationMatrix<double>::ortho(-10.0, 10.0, -5.0, 5.0, -5.0, 5.0); _camera.pos = Vec3d(0.0, 0.0, 3.0); _camera.front = Vec3d(0.0, 0.0, -1.0); _camera.up = Vec3d(0.0, 1.0, 0.0); _look_at = lookAt(_camera.pos, _camera.pos + _camera.front, _camera.up); } void Scene::flipNormals() { _is_normals_fliped = !_is_normals_fliped; for (auto &object : _objs) { object.flipNormals(); } } Scene &Scene::reset() { _objs.clear(); _view = Tmatd(); _projection = TransformationMatrix<double>::ortho(-10.0, 10.0, -5.0, 5.0, -5.0, 5.0); _is_initialized = false; _background_color = RGB(0, 0, 0); _camera.pos = Vec3d(0.0, 0.0, 3.0); _camera.front = Vec3d(0.0, 0.0, -1.0); _camera.up = Vec3d(0.0, 1.0, 0.0); _look_at = lookAt(_camera.pos, _camera.pos + _camera.front, _camera.up); return *this; } void Scene::addObject(const Object &object) { _objs.push_back(object); } Tmatd Scene::lookAt(const Vec3d &eye, const Vec3d &at, const Vec3d &up) { Vec3d n = (eye - at).normalize(); Vec3d u = up.cross(n).normalize(); Vec3d v = n.cross(u).normalize(); return Tmatd(u(0), v(0), n(0), eye(0), u(1), v(1), n(1), eye(1), u(2), v(2), n(2), eye(2), 0, 0, 0, 1); } void Scene::draw(ZBuffer &zbuffer, bool showFaceNormals, bool showVerNormals, bool givenFaceNormals, bool givenVertexNormals, bool showBoundingBox) { initHistory(zbuffer); Attr attr = { showFaceNormals ,showVerNormals, givenFaceNormals, givenVertexNormals, showBoundingBox, Tmatd(), NEAR_PLANE , _shading, _drawing_mode, _camera.pos, _back_face_culling}; zbuffer.setLights(_lights); zbuffer.setAmbient(_ambient); zbuffer.setEnableFog(_is_foggy); zbuffer.setFogColor(_fog_color); zbuffer.setSpotLightTheta(_spot_light_theta); zbuffer.setMinFog(_min_fog); zbuffer.setMaxFog(_max_fog); zbuffer.setPhongFactor(_phong_factor); for (auto &obj : _objs) { attr.T = _projection * _look_at * _view * obj.getModel(); zbuffer.setAttributes(attr); zbuffer.draw(obj); } if (_is_recording_history) { updateHistory(zbuffer); } if (_need_save_history) { zbuffer.saveImageAsPng("blur.png", _history); _need_save_history = false; } if (_filter != Filter::NONE) { auto kernel = createKernel(); zbuffer.applyFilter(kernel); } if (_background_image_type != ZBuffer::BackgroundImageType::NONE) { zbuffer.setBackgroundImage(_background_image_file_name.c_str(), _background_image_type); } if (!_is_initialized) { _is_initialized = true; } } void Scene::saveHistory() { _need_save_history = true; } void Scene::updateHistory(const ZBuffer &zbuffer) { float factor = 0.9; int *bits = zbuffer.getBits(); for (int i = 0; i < zbuffer.getWidth() * zbuffer.getHeight(); i++) { if (bits[i] != 0) { _history[i] = bits[i]; } else { if (_history[i] != 0) { int r = GetBValue(_history[i]); int g = GetGValue(_history[i]); int b = GetRValue(_history[i]); Color color = RGB(b * factor, g * factor, r * factor); _history[i] = color; } } } } void Scene::initHistory(const ZBuffer &zbuffer) { if (_history == nullptr) { int size = zbuffer.getWidth() * zbuffer.getHeight(); _history = new int[size]; for (int i = 0; i < size; i++) { _history[i] = 0; } } } Scene::~Scene() { if (_history != nullptr) { delete[] _history; } } std::vector<int> Scene::createKernel() { if (_filter == Filter::BOX3) { return createKernelBox3(); } else if (_filter == Filter::BOX5) { return createKernelBox5(); } else if (_filter == Filter::TRAINGLE3) { return createKernelTriangle3(); } else if (_filter == Filter::TRAINGLE5) { return createKernelTriangle5(); } else if (_filter == Filter::GAUSSIAN3) { return createKernelGaussian3(); } else if (_filter == Filter::GAUSSIAN5) { return createKernelGaussian5(); } else if (_filter == Filter::SINC3) { return createKernelSinc3(); } else if (_filter == Filter::SINC5) { return createKernelSinc5(); } } std::vector<int> Scene::createKernelBox3() { std::vector<int> kernel; for (int i = 0; i < 9; i++) { kernel.push_back(1); } return kernel; } std::vector<int> Scene::createKernelBox5() { std::vector<int> kernel; for (int i = 0; i < 25; i++) { kernel.push_back(1); } return kernel; } std::vector<int> Scene::createKernelTriangle3() { std::vector<int> kernel; kernel.push_back(1); kernel.push_back(2); kernel.push_back(1); kernel.push_back(2); kernel.push_back(4); kernel.push_back(2); kernel.push_back(1); kernel.push_back(2); kernel.push_back(1); return kernel; } std::vector<int> Scene::createKernelTriangle5() { std::vector<int> kernel; kernel.push_back(1); kernel.push_back(2); kernel.push_back(3); kernel.push_back(2); kernel.push_back(1); kernel.push_back(2); kernel.push_back(4); kernel.push_back(6); kernel.push_back(4); kernel.push_back(2); kernel.push_back(3); kernel.push_back(6); kernel.push_back(9); kernel.push_back(6); kernel.push_back(3); kernel.push_back(2); kernel.push_back(4); kernel.push_back(6); kernel.push_back(4); kernel.push_back(2); kernel.push_back(1); kernel.push_back(2); kernel.push_back(3); kernel.push_back(2); kernel.push_back(1); return kernel; } std::vector<int> Scene::createKernelGaussian3() { std::vector<int> kernel; kernel.push_back(1); kernel.push_back(2); kernel.push_back(1); kernel.push_back(2); kernel.push_back(5); kernel.push_back(2); kernel.push_back(1); kernel.push_back(2); kernel.push_back(1); return kernel; } std::vector<int> Scene::createKernelGaussian5() { std::vector<int> kernel; kernel.push_back(1); kernel.push_back(1); kernel.push_back(1); kernel.push_back(1); kernel.push_back(1); kernel.push_back(1); kernel.push_back(2); kernel.push_back(4); kernel.push_back(2); kernel.push_back(1); kernel.push_back(1); kernel.push_back(4); kernel.push_back(10); kernel.push_back(4); kernel.push_back(1); kernel.push_back(1); kernel.push_back(2); kernel.push_back(4); kernel.push_back(2); kernel.push_back(1); kernel.push_back(1); kernel.push_back(1); kernel.push_back(1); kernel.push_back(1); kernel.push_back(1); return kernel; } std::vector<int> Scene::createKernelSinc3() { std::vector<int> kernel; kernel.push_back(2); kernel.push_back(3); kernel.push_back(2); kernel.push_back(3); kernel.push_back(4); kernel.push_back(3); kernel.push_back(2); kernel.push_back(3); kernel.push_back(2); return kernel; } std::vector<int> Scene::createKernelSinc5() { std::vector<int> kernel; kernel.push_back(-2); kernel.push_back(-1); kernel.push_back(0); kernel.push_back(-1); kernel.push_back(-2); kernel.push_back(-1); kernel.push_back(4); kernel.push_back(6); kernel.push_back(4); kernel.push_back(-1); kernel.push_back(0); kernel.push_back(6); kernel.push_back(9); kernel.push_back(6); kernel.push_back(0); kernel.push_back(-1); kernel.push_back(4); kernel.push_back(6); kernel.push_back(4); kernel.push_back(-1); kernel.push_back(-2); kernel.push_back(-1); kernel.push_back(0); kernel.push_back(-1); kernel.push_back(-2); return kernel; } Scene & Scene::setWireFrameColor(const COLORREF & color, int Id) { if (Id == -1) for (auto& ob : _objs) for(auto& mesh : ob.getMeshes()) mesh.setColor(color); else if (Id < _objs.size()) for (auto& mesh : _objs[Id].getMeshes()) mesh.setColor(color); return *this; } Scene & Scene::setFaceNormalsColor(const COLORREF & color, int Id) { if (Id == -1) for (auto& ob : _objs) ob.setFNColor(color); else if (Id < _objs.size()) _objs[Id].setFNColor(color); return *this; } Scene & Scene::setVerticesNormalsColor(const COLORREF & color, int Id) { if (Id == -1) for (auto& ob : _objs) ob.setVNColor(color); else if (Id < _objs.size()) _objs[Id].setVNColor(color); return *this; } Scene & Scene::setBoundingBoxColor(const COLORREF & color, int Id) { if (Id == -1) for (auto& ob : _objs) ob.setBBColor(color); else if (Id < _objs.size()) _objs[Id].setBBColor(color); return *this; } void Scene::setBackgroundImage(const std::string &file_name) { _background_image_file_name = file_name; }
77bb46f52b9889a56b61824708507f3f93c39e61
f20e965e19b749e84281cb35baea6787f815f777
/Online/Online/DataSvcTests/src/EvtDataSvc_Test.cpp
2c9591947264b04899fd604d75943c271b6a7fa7
[]
no_license
marromlam/lhcb-software
f677abc9c6a27aa82a9b68c062eab587e6883906
f3a80ecab090d9ec1b33e12b987d3d743884dc24
refs/heads/master
2020-12-23T15:26:01.606128
2016-04-08T15:48:59
2016-04-08T15:48:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,210
cpp
EvtDataSvc_Test.cpp
#include "GaudiKernel/System.h" #include "GaudiKernel/IService.h" #include "GaudiKernel/IDataProviderSvc.h" #include "GaudiKernel/IDataManagerSvc.h" #include "GaudiKernel/IEventDataSvc.h" #include "DataSvcTests/UnitTest.h" #include "DataSvcTests/EventDataSvcSetup.h" // C/C++ header files #include <stdexcept> using namespace Tests; using namespace Gaudi; using namespace std; namespace Tests { template <class T> class EvtDataSvcTest : public UnitTest, public EventDataSvcSetup { /// Pointer to data provider interface T* m_pIDP; public: EvtDataSvcTest(const std::string& name) : UnitTest("EvtDataSvcTest",true), EventDataSvcSetup() { StatusCode status = getService(name,IService::interfaceID(), (void**)&m_pIS); if ( !status.isSuccess() ) { m_nerr++; cout << "Service:" << name << " not found. " << endl; throw runtime_error("Fatal exception. cannot continue to run."); } // Data provider interface status = m_pIS->queryInterface(T::interfaceID(), (void**)&m_pIDP); if ( !status.isSuccess() ) { m_nerr++; cout << "Service:" << m_pIS->name() << " has NO DataProviderSvc. " << endl; throw runtime_error("Fatal exception. NO DataProviderSvc. cannot continue to run."); } // IID_IDataManager status = m_pIS->queryInterface(IDataManagerSvc::interfaceID(), (void**)&m_pIDM); if ( !status.isSuccess() ) { m_nerr++; cout << "Service:" << m_pIS->name() << " has NO IID_IDataManagerSvc. " << endl; throw runtime_error("Fatal exception. NO DataManagerSvc. cannot continue to run."); } setup(m_pIDP); } virtual ~EvtDataSvcTest() { shutdown(); } void populate(const std::string& file_name) { size_t num_events = 10000, num_actions=0; Timer tim; load_tags(file_name); create_objects(); tim.start(); for(size_t loop=0; loop<num_events;++loop) { num_actions += insert_leaves(m_pIDP); } tim.stop(); delete_objects(); cout << "Inserted " << tags.size() << " tags [" << num_actions << " actions] in tes:" << tim.seconds() << endl; } void execute(const std::string& file_name) { Timer tim; size_t num_events = 10000, num_actions=0; load_commands(file_name); create_objects(); tim.start(); for(size_t loop=0; loop<num_events;++loop) { num_actions += excute_commands(m_pIDP); } tim.stop(); delete_objects(); cout << "Processed " << num_events << " events [ " << num_actions << " actions] from " << file_name << " in:" << tim.seconds() << " seconds. " << tim.seconds()/num_events << " sec/event" << endl; cout << "With a nominal Brunel processing time of ~ 600 msec, this corresponds to " << 100.0*tim.seconds()/0.6/num_events << " %" << endl; } }; } extern "C" int gaudi_evtdatasvc_test(int, char**) { { EvtDataSvcTest<IDataProviderSvc> test("EvtDataSvc/DataSvc"); test.populate("REG.data"); test.execute("CMDS.data"); } { EvtDataSvcTest<IEventDataSvc> test("Gaudi::EventDataSvc/DataSvc"); test.populate("REG.data"); test.execute("CMDS.data"); } return 1; }
8a6a2cfd6a3da9309a08d6591edacab934090a1d
c51febc209233a9160f41913d895415704d2391f
/library/ATF/UnloadInfo.hpp
7be209b3d6c37be7396cb6b65464492d9aa0b95f
[ "MIT" ]
permissive
roussukke/Yorozuya
81f81e5e759ecae02c793e65d6c3acc504091bc3
d9a44592b0714da1aebf492b64fdcb3fa072afe5
refs/heads/master
2023-07-08T03:23:00.584855
2023-06-29T08:20:25
2023-06-29T08:20:25
463,330,454
0
0
MIT
2022-02-24T23:15:01
2022-02-24T23:15:00
null
UTF-8
C++
false
false
312
hpp
UnloadInfo.hpp
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <ImgDelayDescr.hpp> START_ATF_NAMESPACE struct UnloadInfo { UnloadInfo *puiNext; ImgDelayDescr *pidd; }; END_ATF_NAMESPACE
6bc82a600a314ea01b89a7586d0a7dba971766e5
bf5ed404acf947792f3755847d9b9168ffae6e20
/config/config.h
0ebddf706309732cb0c3ea2d3638492f60c6e08b
[]
no_license
1071496910/c-redis-cli
85d46d55c37883c5828dbf06456abb35e88a4f7e
5c2165c924a337d4d4082b3af3f163951628c86c
refs/heads/master
2021-01-01T17:12:29.767818
2017-09-26T12:33:10
2017-09-26T12:33:10
98,023,650
0
0
null
null
null
null
UTF-8
C++
false
false
517
h
config.h
#ifndef C_REDIS_CLI_CONFIG_CONFIG_H_ #define C_REDIS_CLI_CONFIG_CONFIG_H_ #include <map> #include <string> const int kDefaultLineSize = 1024; class Config { std::map<std::string,std::string> config_storage_; std::string config_file_; char line_buffer[kDefaultLineSize]; bool is_inited_; public: Config(); ~Config(); public: int Init(const char* config_file); const char* GetByKey(const char* section,const char* key); void Dump(); }; #endif //C_REDIS_CLI_CONFIG_CONFIG_H_
d92bf7a20321f5aff5beb281488ac2eb299f2faf
f5dd10b51cdd86a2461ada5c81b87ed933094440
/project/red_black_tree.cpp
4e6153b274ce15787bfb7e85bf3e1485967ef417
[]
no_license
ElRomanenkova/4_sem
faa0195b6cec0112893ac8f7019953bba66d5d5c
a7e555390f48f8a2788039120413fc28e16c9456
refs/heads/master
2022-07-18T00:36:34.245129
2020-05-23T10:55:51
2020-05-23T10:55:51
255,391,317
0
0
null
null
null
null
UTF-8
C++
false
false
14,788
cpp
red_black_tree.cpp
#include "red_black_tree.h" RB_Node::RB_Node() { this->parent = nullptr; this->left_ch = nullptr; this->right_ch = nullptr; this->color = Poison_color; this->key = Poison_key; } RB_Node::RB_Node(int node_key) { this->parent = nullptr; this->left_ch = nullptr; this->right_ch = nullptr; this->color = Poison_color; this->key = node_key; } RB_Node::~RB_Node() { this->parent = nullptr; this->left_ch = nullptr; this->right_ch = nullptr; this->color = Poison_color; this->key = Poison_key; delete this; } void RB_Node::setColor(RB_Node * node, Colors new_color) { node->color = new_color; } ////////////////////////////////////////////////// RB_Tree::RB_Tree() { this->num_nodes = 0; this->nil = new RB_Node; this->nil->setColor(this->nil, Black); this->root = this->nil; } RB_Tree::~RB_Tree() { size_t counter = this->num_nodes; int ret = subtree_distruct(this->root, this->nil, &counter); if (counter != 0) { this->num_nodes = counter; } this->nil->~RB_Node(); this->root = nullptr; this->nil = nullptr; this->num_nodes = 0; delete this; } ///////////////////////////////////////////////////// int RB_Tree::RB_insert(RB_Node * new_node) { //int RB_Tree::RB_insert(int new_value) { // RB_Node * new_node = new RB_Node(new_value); // if (this == nullptr || new_node == nullptr) // return BAD_ARGS; RB_Node * Nil = this->nil; int new_key = new_node->key; RB_Node * cur_node = this->root; RB_Node * new_parent = Nil; while(cur_node != Nil) { new_parent = cur_node; if (new_key > cur_node->key) cur_node = cur_node->right_ch; else cur_node = cur_node->left_ch; } if (new_parent == Nil) this->root = new_node; else if(new_key > new_parent->key) new_parent->right_ch = new_node; else new_parent->left_ch = new_node; new_node->parent = new_parent; new_node->color = Red; new_node->left_ch = Nil; new_node->right_ch = Nil; (this->num_nodes)++; int ret_val = insert_fixup(new_node); if (ret_val != 0) return BAD_TREE_CONDITION; return 0; } int RB_Tree::RB_delete(RB_Node *node) { if (this == nullptr || node == nullptr) return BAD_ARGS; RB_Node * new_nil = this->nil; RB_Node * old = node; int old_orig_color = old->color; RB_Node * replaced = nullptr; if (node->right_ch == new_nil) { replaced = node->left_ch; int ret = node_transplant(node, replaced); if (ret < 0) return ret; } else if (node->left_ch == new_nil) { replaced = node->right_ch; int ret = node_transplant(node, replaced); if (ret < 0) return ret; } else { old = min_node(node->right_ch); if (old == nullptr) return ERROR; old_orig_color = old->color; replaced = old->right_ch; if (old->parent == node) replaced->parent = old; // it heps us if replaced == nil else { int ret = node_transplant(old, old->right_ch); if (ret < 0) return ret; old->right_ch = node->right_ch; old->right_ch->parent = old; } node_transplant(node, old); old->left_ch = node->left_ch; old->left_ch->parent = old; old->color = node->color; } node->~RB_Node(); (this->num_nodes)--; int ret = 0; if (old_orig_color == Black) ret = delete_fixup(replaced); return ret; } RB_Node * RB_Tree::RB_search(int key) { if (this == nullptr) return nullptr; RB_Node * cur_node = this->root; size_t counter = this->num_nodes; for(; counter > 0; counter--) { if (cur_node == this->nil) return nullptr; if (key > cur_node->key) cur_node = cur_node->right_ch; else if (key < cur_node->key) cur_node = cur_node->left_ch; else return cur_node; } return nullptr; } int RB_Tree::tree_dump(std::ofstream& out) { // if (out == nullptr || this == nullptr) // return BAD_ARGS; out << "digraph dump\n{\n"; out << "\tnode [color = \"#000000\", shape = \"box\", fontsize = 20];\n" "\tedge [color = \"#000000\", fontsize = 20];\n\n"; out << "\t\troot_nil [label = \"root_nil\", shape = \"diamond\"," " color = \"#FFFFFF\", fontcolor = \"#000000\"];\n"; if (this->num_nodes == 0) { out << "}\n"; return 0; } size_t counter = this->num_nodes; int ret = node_dump(out, this->root, &counter); out << "\t\tkey_nil [label = \"nil\", shape = \"diamond\"," " color = \"#FFFFFF\", fontcolor = \"#000000\"];\n"; out << "}\n"; if (ret != 0) return BAD_TREE_CONDITION; return 0; } int RB_Tree::node_dump(std::ofstream& out, RB_Node * node, size_t * counter) { if (node == nullptr || this == nullptr || counter == nullptr) return BAD_ARGS; if (*counter == 0) return ERROR; (*counter)--; out << "\t\tkey_" << node->key << " [label = \"" << node->key << "\", "; if (node->color == Red) out << "color = \"#FF0000\", style = \"filled\", " "fillcolor = \"#FF0000\", fontcolor = \"#FFFFFF\""; else out << "color = \"#000000\", style = \"filled\", " "fillcolor = \"#000000\", fontcolor = \"#FFFFFF\""; out << "];\n"; if (node->parent == nullptr) return ERROR; if (node->parent == this->nil) out << "\t\tkey_" << node->key << " -> root_nil"; else out << "\t\tkey_" << node->key << " -> key_" << node->parent->key; out << "[label = \"parent\"];\n"; if (node->left_ch == nullptr) return ERROR; if (node->left_ch == this->nil) out << "\t\tkey_" << node->key << " -> key_nil [label = \"left\"];\n"; else { out << "\t\tkey_" << node->key << " -> key_" << node->left_ch->key << " [label = \"left\"];\n"; int ret = node_dump(out, node->left_ch, counter); if (ret < 0) return ret; } if (node->right_ch == nullptr) return ERROR; if (node->right_ch == this->nil) out << "\t\tkey_" << node-> key << " -> key_nil [label = \"right\"];\n"; else { out << "\t\tkey_" << node->key << " -> key_" << node->right_ch->key << " [label = \"right\"];\n"; int ret = node_dump(out, node->right_ch, counter); if (ret < 0) return ret; } return 0; } int RB_Tree::insert_fixup(RB_Node * new_node) { // NOT_NULL(tree); // NOT_NULL(new_node); RB_Node * cur_node = new_node; int ret_val = 0; while (cur_node->parent->color == Red) { if (cur_node->parent->parent->left_ch == cur_node->parent) { // left branch RB_Node * uncle = cur_node->parent->parent->right_ch; if (uncle->color == Red) { cur_node->parent->color = Black; uncle->color = Black; cur_node = cur_node->parent->parent; cur_node->color = Red; } else { if(cur_node->parent->right_ch == cur_node) { cur_node = cur_node->parent; left_rotate(cur_node); } cur_node->parent->color = Black; cur_node->parent->parent->color = Red; right_rotate(cur_node->parent->parent); } } else {// right branch RB_Node * uncle = cur_node->parent->parent->left_ch; if (uncle->color == Red) { cur_node->parent->color = Black; uncle->color = Black; cur_node = cur_node->parent->parent; cur_node->color = Red; } else { if (cur_node->parent->left_ch == cur_node) { cur_node = cur_node->parent; right_rotate(cur_node); } cur_node->parent->parent->color = Red; cur_node->parent->color = Black; left_rotate(cur_node->parent->parent); } } } this->root->color = Black; return 0; } void RB_Tree::left_rotate(RB_Node * node) { RB_Node * child = node->right_ch; child->parent = node->parent; if (child->parent->left_ch == node) child->parent->left_ch = child; else if (child->parent->right_ch == node) child->parent->right_ch = child; node->parent = child; if (child->parent == this->nil) this->root = child; node->right_ch = child->left_ch; if (node->right_ch != this->nil) node->right_ch->parent = node; child->left_ch = node; } void RB_Tree::right_rotate(RB_Node* node) { RB_Node * child = node->left_ch; child->parent = node->parent; if (child->parent->left_ch == node) child->parent->left_ch = child; else if (child->parent->right_ch == node) child->parent->right_ch = child; node->parent = child; if (child->parent == this->nil) this->root = child; node->left_ch = child->right_ch; if (node->left_ch != this->nil) node->left_ch->parent = node; child->right_ch = node; } RB_Node * RB_Tree::min_node(RB_Node * node) { if (this == nullptr || node == nullptr) return nullptr; size_t counter = this->num_nodes; RB_Node * new_nil = this->nil; RB_Node * min = node; for(; counter > 0; counter--) { if (min->left_ch == new_nil) return min; min = min->left_ch; } return nullptr; } RB_Node * RB_Tree::max_node(RB_Node * node) { if (this == nullptr || node == nullptr) return nullptr; size_t counter = this->num_nodes; RB_Node * new_nil = this->nil; RB_Node * max = this->root; for (; counter > 0; counter--) { if (max->right_ch == new_nil) return max; max = max->right_ch; } return nullptr; } int RB_Tree::delete_fixup(RB_Node * extra_black) { if (this == nullptr || extra_black == nullptr) return BAD_ARGS; RB_Node * new_root = this->root; while(extra_black->color == Black && extra_black != new_root) { if (extra_black->parent->left_ch == extra_black) { RB_Node * bro = extra_black->parent->right_ch; if (bro->color == Red) { extra_black->parent->color = Red; bro->color = Black; left_rotate(extra_black->parent); bro = extra_black->parent->right_ch; } if (bro->left_ch->color == Black && bro->right_ch->color == Black) { bro->color = Red; extra_black = extra_black->parent; } else { if (bro->right_ch->color == Black) { bro->color = Red; bro->left_ch->color = Black; right_rotate(bro); bro = extra_black->parent->right_ch; } bro->color = extra_black->parent->color; extra_black->parent->color = Black; bro->right_ch->color = Black; left_rotate(extra_black->parent); extra_black = new_root; } } else { RB_Node * bro = extra_black->parent->left_ch; if (bro->color == Red) { bro->color = Black; extra_black->parent->color = Red; right_rotate(extra_black->parent); bro = extra_black->parent->left_ch; } if (bro->left_ch->color == Black && bro->right_ch->color == Black) { bro->color = Red; extra_black = extra_black->parent; } else { if (bro->left_ch->color == Black) { bro->right_ch->color = Black; bro->color = Red; left_rotate(bro); bro = extra_black->parent->left_ch; } bro->color = extra_black->parent->color; extra_black->parent->color = Black; bro->left_ch->color = Black; right_rotate(extra_black->parent); extra_black = new_root; } } } extra_black->color = Black; return 0; } int RB_Tree::node_transplant(RB_Node * to, RB_Node * who) { if (this == nullptr || to == nullptr || who == nullptr) return BAD_ARGS; RB_Node * new_nil = this->nil; if (to->parent == new_nil) this->root = who; else if (to == to->parent->left_ch) to->parent->left_ch = who; else to->parent->right_ch = who; who->parent = to->parent; return 0; } int RB_Tree::subtree_distruct(RB_Node * cur_root, RB_Node * cur_nil, size_t * counter) { if (cur_root == nullptr || cur_nil == nullptr || counter == nullptr) return BAD_ARGS; if (cur_root == cur_nil) return 0; int ret = 0; if (cur_root->left_ch != cur_nil || cur_root->left_ch != nullptr) { ret = subtree_distruct(cur_root->left_ch, cur_nil, counter); if (ret != 0) return ret; } if (cur_root->right_ch != cur_nil || cur_root->right_ch != nullptr) { ret = subtree_distruct(cur_root->right_ch, cur_nil, counter); if (ret != 0) return ret; } if (*counter == 0) return E_TOO_MUCH_ELEM; (*counter)--; cur_root->~RB_Node(); return ret; } int RB_Tree::foreach(int (*func)(RB_Tree *, RB_Node*, void*), void* data) { if (this == nullptr || func == nullptr) return BAD_ARGS; int ret = call(this->root, func, data, this->num_nodes); return ret; } int RB_Tree::call(RB_Node * node, int (*func)(RB_Tree *, RB_Node *, void *), void * data, size_t counter) { if (node == nullptr || this == nullptr || func == nullptr) return BAD_ARGS; RB_Node * new_nil = this->nil; if (node == new_nil) return EMPTY_TREE; int ret = 0; if (counter <= 0) return E_TOO_MUCH_ELEM; if (node->left_ch != new_nil) { ret = call(node->left_ch, func, data, counter - 1); if (ret < 0) return ret; } ret = func(this, node, data); if (ret < 0) return ret; if (node->right_ch != new_nil) { ret = call(node->right_ch, func, data, counter - 1); if (ret < 0) return ret; } return 0; }
da78d755a86db94dff1e02f34224268111017e0f
33526483a755fa5e1dca9f42759cd2f2db765aa1
/MouseRun/species.cpp
37852924a26a8a8234d35b67db40df1da6bf6420
[]
no_license
jovanovic16942/MouseRun
76c9dd123a342d51b63b1789692a0c585d1464ea
268248df7754011711706ba7ce6bf47631fba736
refs/heads/master
2020-04-25T01:32:59.563484
2019-05-28T19:50:29
2019-05-28T19:50:29
172,411,533
0
2
null
null
null
null
UTF-8
C++
false
false
5,267
cpp
species.cpp
#include "species.h" #include <random> #include <QDebug> Species::Species(Genome *p) : bestFitness{0}, averageFitness{0}, stagnantCoeff{0}, allowedReproduction{true}, excessCoeff{1}, weightDiffCoeff{0.4}, compatibilityThreshold{3} { genomes.push_back(p); bestFitness = p->fitness; // Best fitness, because it is the only Genome representGenome = p; } bool Species::isSameSpecies(const Genome &genome) { // We need to calculate the number of excess and disjoint genes between two input genomes // Plainly, we calculate the number of genes which don't match unsigned matchingExcessDisjoint = 0; // These are used a lot, move to variable size_t genomeConnSize = genome.connections.size(); size_t representGenomeConnSize = representGenome->connections.size(); for (size_t i = 0; i < genomeConnSize; i++) { for (size_t j = 0; j < representGenomeConnSize; j++) { if (genome.connections[i]->innovationNumber == representGenome->connections[j]->innovationNumber) { matchingExcessDisjoint++; break; } } } double excessAndDisjoint = genomeConnSize + representGenomeConnSize - 2*matchingExcessDisjoint; // Now we need to get the average weight difference between matching genes in the input genomes double averageWeightDiff = 0; if (genomeConnSize == 0 || representGenomeConnSize == 0) averageWeightDiff = 0; unsigned matchingWeightDiff = 0; double totalDiff = 0; for (size_t i = 0; i < genomeConnSize; i++) { for (size_t j = 0; j < representGenomeConnSize; j++) { if (genome.connections[i]->innovationNumber == representGenome->connections[j]->innovationNumber) { matchingWeightDiff++; totalDiff += abs(genome.connections[i]->weight - representGenome->connections[j]->weight); break; } } } if (matchingWeightDiff == 0) // division by 0 averageWeightDiff = 1; else averageWeightDiff = totalDiff / matchingWeightDiff; // Calculate N - number of genes in the larger genome double largeGenomeNormalizer = genome.connections.size(); if (largeGenomeNormalizer < 20) { // Small genomes, both have less than 20 genes largeGenomeNormalizer = 1; } // Now calculate the compatibility function double tmp1 = excessCoeff * excessAndDisjoint / largeGenomeNormalizer; double compatibilityDistance = tmp1 + (weightDiffCoeff * averageWeightDiff); return (compatibilityThreshold > compatibilityDistance); } void Species::sortGenomesByFitness() { std::sort(genomes.begin(), genomes.end(), [] (const auto &lhs, const auto &rhs) { return lhs->fitness > rhs->fitness; }); // Checking if we should penalize the species if the fittest is not so fit if (genomes[0]->fitness > bestFitness) { // OK - generation improved stagnantCoeff = 0; bestFitness = genomes[0]->fitness; representGenome = genomes[0]; } else { if (++stagnantCoeff > 15) { // Too stale, don't reproduce allowedReproduction = false; } } } void Species::addToSpecies(Genome *genome) { genomes.push_back(genome); } Genome* Species::createOffspring() { std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dist(0, 1); double r = dist(gen); Genome* offspring = nullptr; if (r < 0.25) { offspring = selectParent()->clone(); } else { Genome *p1 = selectParent(); Genome *p2 = selectParent(); if (p1->fitness > p2->fitness) { offspring = p1->crossover(p2); } else { offspring = p2->crossover(p1); } } return offspring; } Genome* Species::selectParent() { // Finding a Genome using roulette selection double totalSpeciesFitness = std::accumulate(genomes.cbegin(), genomes.cend(), 0, [](double acc, Genome *p) { return p->fitness + acc; }); std::random_device rd; std::mt19937 gen(rd()); std::uniform_real_distribution<> dist(0, totalSpeciesFitness); double selectedValue = dist(gen); double fitnessSum = 0; for (unsigned i=0; i < genomes.size(); i++) { fitnessSum += genomes[i]->fitness; if (fitnessSum >= selectedValue) return genomes[i]; } // This will never execute, but return value must exist. Pick a random Genome std::uniform_real_distribution<> dist1(0, genomes.size()-1); return genomes[static_cast<size_t>(dist1(gen))]; } void Species::explicitFitnessSharing() { for (unsigned i=0; i < genomes.size(); i++) { genomes[i]->fitness /= genomes.size(); } } void Species::decimateSpecies() { if (genomes.size() <= 20) return; // Remove the second (worse) half of the species genomes.resize(genomes.size() / 2); } // Calculate average fitness in the species (setter, not getter) void Species::calcAverageFitness() { double sum = std::accumulate(genomes.cbegin(), genomes.cend(), 0, [](double acc, Genome *p){ return p->fitness + acc; }); averageFitness = sum/genomes.size(); }
c3b81246b05883968fac92e1b146b375add00a28
d19bc21a959615c232354c87c916edba2be9aa17
/Tree/0226_InvertBinaryTree/main.cpp
f3532eebe3c8ba3a251fcc8dda56d74b98ba0186
[]
no_license
Aierhaimian/LeetCode
47a48bded9cb790c21f73c6ff2abff1e9eaec3aa
67a54618efbb37437412ee7d471688c5770eedd6
refs/heads/master
2020-04-25T20:57:13.066885
2019-09-19T10:57:47
2019-09-19T10:57:47
173,065,705
1
0
null
null
null
null
UTF-8
C++
false
false
681
cpp
main.cpp
#include <iostream> #include <vector> #include <algorithm> #include <cmath> #include <cassert> using namespace std; // Definition for a binary tree node. struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: TreeNode* invertTree(TreeNode* root) { if (!root) return NULL; generateInvert(root); return root; } private: void generateInvert(TreeNode* root) { if (!root) return; swap(root->left, root->right); generateInvert(root->left); generateInvert(root->right); } }; int main() { return 0; }
e3ad5194784c1e9945deae90d566f77d85fede9e
3ddea841d0d2b067c7a339d44a290c854abbd9ec
/Rasterizer/includes/Rendering/SDL_Manager.h
387f7708d6e5fa9d217efbf1deb327dc803c34d9
[]
no_license
gnoailles/softwareRasterizer
6ddd2e44fddddce868ef9636b9dd416d0a8d2d8f
23245593ce1844d5ce844e3b7931d8b71d954266
refs/heads/master
2021-04-09T16:18:27.864460
2019-05-07T00:06:01
2019-05-07T00:06:01
125,764,492
1
1
null
null
null
null
UTF-8
C++
false
false
441
h
SDL_Manager.h
#pragma once #include <SDL.h> #include "Graphics/Texture.h" using namespace Graphics; namespace Rendering { class SDL_Manager { protected: SDL_Window * m_window; SDL_Renderer* m_renderer; Texture* m_activeBuffer; public: SDL_Manager(); ~SDL_Manager(); bool Init(int p_w, int p_h); void Close(); Texture* GetBuffer() const; void ClearBuffer(const Color& c = Color(0,0,0)) const; void UpdateWindow() const; }; }
ec4f7b288919578c850f4fb16d59cb1a67bca341
b53bdc4576f948e6066bbead8a93451fa1598726
/templates/centroid.cpp
f3fef5677a5cc2f523ad6bcf5afd2f551d4941b7
[]
no_license
Clouder0/AlgorithmPractice
da2e28cb60d19fe7a99e9f3d1ba99810897244a4
42faedfd9eb49d6df3d8031d883784c3514a7e8b
refs/heads/main
2023-07-08T11:07:17.631345
2023-07-06T12:15:33
2023-07-06T12:15:33
236,957,049
0
0
null
null
null
null
UTF-8
C++
false
false
755
cpp
centroid.cpp
#include <algorithm> #include <cstdio> const int maxm = 1e5 + 100; const int maxn = 1e5 + 100; struct node { int to, next; } E[maxm]; int head[maxn], tot; inline void add(const int &u, const int &v) { E[++tot].next = head[u], E[tot].to = v, head[u] = tot; } int n, root, maxsiz; int fa[maxn], siz[maxn]; void init() { root = 0; for (int i = 1; i <= n; ++i) siz[i] = 1; maxsiz = 1 << 30; } void dfs(int u) { int maxs = 0; for (int p = head[u]; p; p = E[p].next) { int v = E[p].to; if (v == fa[u]) continue; fa[v] = u, dfs(v), siz[u] += siz[v]; maxs = std::max(maxs, siz[v]); } maxs = std::max(maxs, n - siz[u]); if (maxs < maxsiz) maxsiz = maxs, root = u; } int main() { scanf("%d", &n); return 0; }
5da15df3393031262269fe2cb4da0871ae731813
82c1a68d8e133baaa5f2fb7aa15300a49a34b8db
/HomeWork1/HWLauncher/main.cpp
446f2db222aebaccf5c42486ff59fcf3c1e86db4
[]
no_license
MizraelAnael/homework1
299cd6fa1c7170f9894859a17a871f9926aa400e
0131b010c1d5db1bbace15bde162aa5193d03c44
refs/heads/master
2020-05-20T12:35:45.921633
2014-09-08T18:55:46
2014-09-08T18:55:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
181
cpp
main.cpp
#include <iostream> #include "Task 1.h" #include "Task 2.h" #include "Task 3.h" using namespace std; int main() { task1 (); task2 (); task3 (); system ( "pause" ); }
81aa8bea754ebc1037a38ded5eeb7a485c84ab98
757c6647ebd75909785b3a730cd123f2065f1b70
/pat1041.cpp
be6df7b42b73e93de3710243942cefe0856e5bd1
[ "Apache-2.0" ]
permissive
iceco1a/PAT-Advanced-Level-
c67a3cc26bac7b7b51c5ffd29af5e47708fb1ad7
1896890df32ed162601b96bbbb3c56ce904a6122
refs/heads/master
2021-06-05T19:50:34.179569
2016-09-21T05:33:28
2016-09-21T05:33:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
415
cpp
pat1041.cpp
#include<stdio.h> #include<string.h> using namespace std; int n; int ary[100002]; int ary1[100002]; int main(void){ int i,temp; while(scanf("%d",&n)!=EOF){ memset(ary,0,sizeof(ary)); for(i=0;i<n;i++){ scanf("%d",&temp); ary1[i] = temp; ary[temp]++; } for(i=0;i<n;i++){ if(ary[ary1[i]]==1){ printf("%d\n",ary1[i]); break; } } if(i==n){ printf("None\n"); } } return 0; }
2337a2197ce32704e96d01103e5ad81e7daf4302
f70366f4a01a50e627b52f2f67496ae7e2e8c0a4
/DatabaseHandling/databaseConnection.h
03cf7f8a915009cec7daaa043f3298007619d460
[]
no_license
hammadar/ECE656ProjectHRTScpp
e14ad96f2f09bf14309359c7da2f45b536b1bb33
0416abec5b1a45dd3f5791d21c4547a92b7176ab
refs/heads/master
2023-01-27T13:47:33.022953
2020-12-13T13:03:33
2020-12-13T13:03:33
312,749,283
0
0
null
2020-12-10T21:13:36
2020-11-14T05:01:43
C++
UTF-8
C++
false
false
874
h
databaseConnection.h
// // Created by Hammad Rehman on 2020-11-13. // #ifndef ECE656PROJECTHRTS_DATABASECONNECTION_H #define ECE656PROJECTHRTS_DATABASECONNECTION_H #endif //ECE656PROJECTHRTS_DATABASECONNECTION_H #include <cstdlib> #include <iostream> #include <mysql_driver.h> #include <mysql_error.h> #include <mysql_connection.h> #include <cppconn/driver.h> #include <cppconn/exception.h> #include <cppconn/resultset.h> #include <cppconn/statement.h> #include <cppconn/prepared_statement.h> class dataBaseConnection { private: ::sql::mysql::MySQL_Driver *driver; ::sql::Connection *con; public: dataBaseConnection(const std::string& host, const std::string& user, const std::string& password); void disconnect(); void createUser(const std::string& user, const std::string& password); ::sql::Connection* getSQLConnection(); };
f03339ec222158b2bcf3dc6cbe86ad7eb37165b3
6911d7ba9eb53bd885917e6fbed8eec694f00488
/2013TGS07班/TGS_Team7_Projects_Ver1.17/TGS_Team7_Projects/Souse/Scene/GamePlay.h
59ee636599fa350cb9e4513fd5aeffe92666aa83
[]
no_license
KORYUOH/koryuohproject-svn-server
86fc2128546bb6000af65f65e210775004cd03fc
eea045863cab70fc8534917b6a1356690e6fc10e
refs/heads/master
2021-01-19T13:25:33.993255
2015-04-04T08:10:21
2015-04-04T08:10:21
32,276,044
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
1,897
h
GamePlay.h
/****************************************************************************** * File Name : GamePlay.h Ver : 1.00 Date : 2012-12-14 * * Description : * * ゲームプレイクラス. * ******************************************************************************/ #ifndef _GAMEPLAY_H_ #define _GAMEPLAY_H_ /*---- ヘッダファイルの読み込み ---------------------------------------------*/ #include"../Scene\IScene.h" #include"../World/World.h" #include"../Flag/FlagManager.h" /*---- 先行宣言 -------------------------------------------------------------*/ class World; class FlagManager; enum Scene; /// <summary> /// ゲームプレイシーンクラス. /// </summary> class GamePlay : public IScene { public: /// <summary> /// コンストラクタ. /// </summary> GamePlay(); /// <summary> /// 初期化. /// </summary> virtual void Initialize(); /// <summary> /// 更新. /// </summary> /// <param name="frameTimer">フレームタイマー</param> virtual void Update(float frameTimer); /// <summary> /// 描画. /// </summary> virtual void Draw(); /// <summary> /// シーンの終了判定. /// </summary> /// <returns>シーンが終了していれば真、していなければ偽を返す</returns> virtual bool IsEnd() const; /// <summary> /// 次のシーンに移行. /// </summary> /// <returns>次のシーン列挙型を返す</returns> virtual Scene Next() const; /// <summary> /// 終了. /// </summary> virtual void Shutdown(); private: /// <summary> /// ワールド. /// </summary> World mWorld; /// <summary> /// フラグ管理者. /// </summary> FlagManager mFlagManager; }; // class GamePlay end #endif // !_GAMEPLAY_H_ /********** End of File ******************************************************/
66ea65d68d9a8fd2d9cc48043874c2dbeb0440ff
570d07d53f01a27215c796a0aeaba6c4324de536
/basicGameEngine/Player.cpp
f14b9d1cc48d0fa89750e010c6f2bcc95a5f2467
[]
no_license
RicardoGonzalezJ/basicgameengine
e5206a1626a5230baef0cc40fbd7e76df46145a4
b6fd9e931b8e4e302f5a6d4502a9642b41ec11d3
refs/heads/master
2020-03-20T11:24:29.404962
2018-07-17T20:21:22
2018-07-17T20:21:22
137,401,765
0
0
null
null
null
null
UTF-8
C++
false
false
2,488
cpp
Player.cpp
#include "Player.h" // Player class implementation using game object /*void Player::load(int x, int y, int width, int height, std::string textureID) { GameObject::load(x, y, width, height, textureID); } void Player::draw(SDL_Renderer* pRenderer) { GameObject::draw(pRenderer); } void Player::update() { m_x -= 1; m_currentFrame = int(((SDL_GetTicks() / 100) % 6)); } void Player::clean() { }*/ // Player class implementation using SDLGameObject Player::Player(const LoaderParams* pParams) : SDLGameObject(pParams) { } void Player::draw() { SDLGameObject::draw(); } void Player::handleInput() { /*if (TheInputHandler::Instance()->joysticksInitialized()) { if (TheInputHandler::Instance()->xvalue(0, 1) > 0 || TheInputHandler::Instance()->xvalue(0, 1) < 0) { m_velocity.setX(1 * TheInputHandler::Instance()->xvalue(0, 1)); } if (TheInputHandler::Instance()->yvalue(0, 1) > 0 || TheInputHandler::Instance()->yvalue(0, 1) < 0) { m_velocity.setY(1 * TheInputHandler::Instance()->yvalue(0, 1)); } if (TheInputHandler::Instance()->xvalue(0, 2) > 0 || TheInputHandler::Instance()->xvalue(0, 2) < 0) { m_velocity.setX(1 * TheInputHandler::Instance()->xvalue(0, 2)); } if (TheInputHandler::Instance()->yvalue(0, 2) > 0 || TheInputHandler::Instance()->yvalue(0, 2) < 0) { m_velocity.setY(1 * TheInputHandler::Instance()->yvalue(0, 2)); } if (TheInputHandler::Instance()->getButtonState(0, 3)) { m_velocity.setX(1); } }*/ // using mouse /*if (TheInputHandler::Instance()->getMouseButtonState(LEFT)) { m_velocity.setX(-1); } Vector2D* vec = TheInputHandler::Instance()->getMousePosition(); m_velocity = (*vec - m_position) / 100;*/ // using keyboard if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_RIGHT)) { m_velocity.setX(2); } if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_LEFT)) { m_velocity.setX(-2); } if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_UP)) { m_velocity.setY(-2); } if (TheInputHandler::Instance()->isKeyDown(SDL_SCANCODE_DOWN)) { m_velocity.setY(2); } } void Player::update() { // m_x -= 1; // m_position.setX(m_position.getX() - 1); // m_position.setY(m_position.getY() + 1); m_velocity.setX(0); m_velocity.setY(0); handleInput(); // add our function m_currentFrame = int(((SDL_GetTicks() / 100) % 6)); // m_velocity.setX(-1); // m_acceleration.setX(-1); SDLGameObject::update(); } void Player::clean() { }
961145e16ee5ac55d01ea7c8d302af4de0df405c
049f41a76f64320dc64fba091ae3f215fd9fcf6e
/include/types/filters/GRADIENTBEVELFILTER.hpp
6c3a98570c404fb5be684013fedef58f71b2fc76
[]
no_license
piepie62/NSWF
f8c8e47864d39b2d439f99007551795ace625b3e
cec15e9c33f8a4810315895bb3e04f9b718dbe57
refs/heads/master
2023-05-25T23:54:29.084716
2021-05-29T20:53:55
2021-05-29T20:53:55
370,969,031
1
0
null
null
null
null
UTF-8
C++
false
false
537
hpp
GRADIENTBEVELFILTER.hpp
#pragma once #include "types/RGBA.hpp" #include "types/basic/fixed16.hpp" #include "types/basic/fixed32.hpp" #include <cstdint> #include <vector> namespace NSWF { struct GRADIENTBEVELFILTER { std::vector<RGBA> gradientColors; std::vector<uint8_t> gradientRatio; fixed32 blurX; fixed32 blurY; fixed32 angle; fixed32 distance; fixed16 strength; bool innerShadow; bool knockout; bool compositeSource; bool onTop; int passes; }; }
4870f33c3da66d60e84489bb24b4cc7f29077597
07e6fc323f657d1fbfc24f861a278ab57338b80a
/cpp/sketches_OCL/Grids/convolve2D.h
bbf55c57fb91a3c6bddf7bd971b33377d58b9b19
[ "MIT" ]
permissive
ProkopHapala/SimpleSimulationEngine
99cf2532501698ee8a03b2e40d1e4bedd9a12609
47543f24f106419697e82771289172d7773c7810
refs/heads/master
2022-09-05T01:02:42.820199
2022-08-28T10:22:41
2022-08-28T10:22:41
40,007,027
35
4
null
null
null
null
UTF-8
C++
false
false
2,178
h
convolve2D.h
#ifndef convolve2D_h #define convolve2D_h //============== Globals constexpr int nx = 256+2; constexpr int ny = 256+2; //constexpr int nx = 1024+2; //constexpr int ny = 1024+2; constexpr int ntot = nx*ny; float buff [nx*ny]; float buff_[nx*ny]; void genXOR2D(int nx, int ny, float * data){ float scale_val = 1.0/256.0; for(int iy=0;iy<ny;iy++){ for(int ix=0;ix<nx;ix++){ buff[iy*nx+ix] = ((ix^iy)&0xFF)*scale_val; //data[iy*nx+ix] = 0.5; } } } void genZero(int nx, int ny, float * data){ float scale_val = 1.0/256.0; for(int iy=0;iy<ny;iy++){ for(int ix=0;ix<nx;ix++){ buff[iy*nx+ix] = 0; } } } void blur(int nx, int ny, float * I, float * O ){ float renorm = 1.0/9.0; for(int iy=1;iy<ny-1;iy++){ for(int ix=1;ix<nx-1;ix++){ int i = iy*nx+ix; O[i] =( I[i-nx-1] + I[i-nx] + I[i-nx+1] + I[i -1] + I[i ] + I[i +1] + I[i+nx-1] + I[i+nx] + I[i+nx+1] ) * renorm; } } } void blur_scanline(int nx, int ny, float * I, float * O ){ float renorm = 1.0/9.0; for(int ix=1;ix<nx-1;ix++){ Vec3f Lm; Lm.set(I[ix -1], I[ix ], I[ix +1]); Vec3f L0; L0.set(I[ix+nx-1], I[ix+nx], I[ix+nx+1]); for(int iy=1;iy<ny-1;iy++){ int i = iy*nx+ix; int ip = i+nx; Vec3f Lp; Lp.set(I[ip-1], I[ip], I[ip+1]); O[i] =( Lm.x + Lm.y + Lm.z + L0.x + L0.y + L0.z + Lp.x + Lp.y + Lp.z ) * renorm; Lm=L0; L0=Lp; } } } void blur_Gauss(int nx, int ny, float * I, float * O ){ for(int iy=1;iy<ny-1;iy++){ for(int ix=1;ix<nx-1;ix++){ int i = iy*nx+ix; //O[i] =( 0.0625*I[i-nx-1] + 0.125*I[i-nx] + 0.0625*I[i-nx+1] + // 0.125 *I[i -1] + 0.25 *I[i ] + 0.125 *I[i +1] + // 0.0625*I[i+nx-1] + 0.125*I[i+nx] + 0.0625*I[i+nx+1] ); O[i] = 0.25 * I[i] + 0.0625*( I[i-nx-1] + I[i+nx-1] + I[i+nx+1] + I[i-nx+1] ) + 0.125 *( I[i-nx] + I[i-1] + I[i+1] + I[i+nx] ); } } } //============== Functions #endif
1048d9258f91c484f79b236e6e2dc1858716c223
16df3cdc7e6373b2888a125fbea6ae805e0aa6a1
/battle/SpecialAttackHandler.cpp
6a3eb8b3f99e01c68cb3d99a518cb3c8d9bdd7cd
[]
no_license
functionoliveira/darkness-age
df52656b0f6fb0754efd2a998e5cf7ef3c3f0061
2aff60df94d5590beda259176050efe4eb1273d6
refs/heads/master
2023-03-31T20:49:35.006734
2021-04-03T16:41:27
2021-04-03T16:41:27
352,785,932
0
0
null
null
null
null
UTF-8
C++
false
false
465
cpp
SpecialAttackHandler.cpp
class SpecialAttackHandler { public: enum class SpecialAttackType { // magic attacks MAGIC_MISSEL = 1 // psychic attacks // physical attacks } SpecialAttack handle(int type) { switch (type) { case 1: return MagicMissel(); break; default: break; } } };
e418670526c322acec0f8507c899e3ccd7d7c474
e2cf0b5db389ebc82565c4ceb1d664a29dcbf79a
/csrc/cpu/scatter_cpu.cpp
b7dc82d2d9981a6ab16630c656f4a945c0513d5d
[ "MIT" ]
permissive
rusty1s/pytorch_scatter
d1a78c5fabbb64f270769e83bd374cb4798e2084
a2a2afb9e946094e7e89b3a35568ac793fe7e70b
refs/heads/master
2023-08-29T02:08:00.131102
2023-06-04T07:48:29
2023-06-04T07:48:29
114,475,042
1,350
186
MIT
2023-08-17T01:03:08
2017-12-16T16:34:23
Python
UTF-8
C++
false
false
2,757
cpp
scatter_cpu.cpp
#include "scatter_cpu.h" #include "index_info.h" #include "reducer.h" #include "utils.h" std::tuple<torch::Tensor, torch::optional<torch::Tensor>> scatter_cpu(torch::Tensor src, torch::Tensor index, int64_t dim, torch::optional<torch::Tensor> optional_out, torch::optional<int64_t> dim_size, std::string reduce) { CHECK_CPU(src); CHECK_CPU(index); if (optional_out.has_value()) CHECK_CPU(optional_out.value()); CHECK_INPUT(src.dim() == index.dim()); for (auto i = 0; i < index.dim() - 1; i++) CHECK_INPUT(src.size(i) >= index.size(i)); src = src.contiguous(); torch::Tensor out; if (optional_out.has_value()) { out = optional_out.value().contiguous(); for (auto i = 0; i < out.dim(); i++) if (i != dim) CHECK_INPUT(src.size(i) == out.size(i)); } else { auto sizes = src.sizes().vec(); if (dim_size.has_value()) sizes[dim] = dim_size.value(); else if (index.numel() == 0) sizes[dim] = 0; else sizes[dim] = 1 + *index.max().data_ptr<int64_t>(); out = torch::empty(sizes, src.options()); } torch::optional<torch::Tensor> arg_out = torch::nullopt; int64_t *arg_out_data = nullptr; if (reduce2REDUCE.at(reduce) == MIN || reduce2REDUCE.at(reduce) == MAX) { arg_out = torch::full_like(out, src.size(dim), index.options()); arg_out_data = arg_out.value().data_ptr<int64_t>(); } if (src.numel() == 0) { if (!optional_out.has_value()) out.fill_(0); return std::make_tuple(out, arg_out); } auto B = 1; for (auto i = 0; i < dim; i++) B *= src.size(i); auto E = src.size(dim); auto K = src.numel() / (B * E); auto N = out.size(dim); auto index_info = getTensorInfo<int64_t>(index); AT_DISPATCH_ALL_TYPES_AND2(at::ScalarType::Half, at::ScalarType::BFloat16, src.scalar_type(), "scatter_cpu", [&] { auto src_data = src.data_ptr<scalar_t>(); auto out_data = out.data_ptr<scalar_t>(); int64_t i, idx; AT_DISPATCH_REDUCTION_TYPES(reduce, [&] { if (!optional_out.has_value()) out.fill_(Reducer<scalar_t, REDUCE>::init()); for (auto b = 0; b < B; b++) { for (auto e = 0; e < E; e++) { for (auto k = 0; k < K; k++) { i = b * E * K + e * K + k; idx = index_info.data[IndexToOffset<int64_t>::get(i, index_info)]; Reducer<scalar_t, REDUCE>::update( out_data + b * N * K + idx * K + k, src_data[i], arg_out_data + b * N * K + idx * K + k, e); } } } if (!optional_out.has_value() && (REDUCE == MIN || REDUCE == MAX)) out.masked_fill_(out == Reducer<scalar_t, REDUCE>::init(), (scalar_t)0); }); }); return std::make_tuple(out, arg_out); }
2ca202ea851cd9202f000586e443a939218e804f
351899b0585d68190c20d84b91324a16a7e863ed
/source/mainDoubleSolution.cpp
3cb17c0ced8d5303f90cb26fcaa03c918047508b
[]
no_license
casfeq/Geomec2D
9cf2d6cc2663f4b1ec68647a9fcf2028f5cf9b0b
0e9faeb647583922a1d52c5640638c4366ad9628
refs/heads/master
2022-10-20T11:28:19.001334
2020-06-11T08:54:25
2020-06-11T08:54:25
225,952,799
2
0
null
null
null
null
UTF-8
C++
false
false
3,903
cpp
mainDoubleSolution.cpp
/* This source code implements a Finite Volume Method for discretization and solution of the consolidation problems with double porosity. The governing equations are discretized within the FVM and the resulting linear system of equations is solved with a LU Factorization found in PETSc [1]. Written by FERREIRA, C. A. S. Florianópolis, 2020. [1] BALAY et al. PETSc User Manual. Technical Report, Argonne National Laboratory, 2017. */ #include "customPrinter.hpp" #include "exportRunInfo.hpp" #include "benchmarking.hpp" int main(int argc, char** args) { string myGridType=args[1]; string myInterpScheme=args[2]; string myMedium=args[3]; vector<int> problemsSolved; problemsSolved.push_back(atoi(args[4])/100%10); problemsSolved.push_back(atoi(args[4])/10%10); problemsSolved.push_back(atoi(args[4])%10); double pore=stod(args[5]); double frac=stod(args[6]); /* PROPERTIES IMPORT ----------------------------------------------------------------*/ poroelasticProperties myProperties; ifstream inFile; inFile.open("../input/"+myMedium+".txt"); if(!inFile) { cout << "Unable to open properties file."; exit(1); } getline(inFile,myProperties.pairName); myProperties.pairName=myMedium; inFile >> myProperties.shearModulus; inFile >> myProperties.bulkModulus; inFile >> myProperties.solidBulkModulus; inFile >> myProperties.solidDensity; inFile >> myProperties.fluidBulkModulus; double porosity; inFile >> porosity; inFile >> myProperties.permeability; inFile >> myProperties.fluidViscosity; inFile >> myProperties.fluidDensity; inFile.close(); myProperties.macroPorosity=frac*porosity; myProperties.porosity=pore*porosity; myProperties.macroPermeability=myProperties.permeability*1e1; /* GRID DEFINITION ----------------------------------------------------------------*/ // Consolidation coefficient double storativity,fluidViscosity,permeability,fluidCompressibility,solidCompressibility, bulkCompressibility,longitudinalModulus,alpha; porosity=myProperties.porosity+myProperties.macroPorosity; fluidViscosity=myProperties.fluidViscosity; permeability=(myProperties.macroPermeability+myProperties.permeability)/2; fluidCompressibility=1/myProperties.fluidBulkModulus; solidCompressibility=1/myProperties.solidBulkModulus; bulkCompressibility=1/myProperties.bulkModulus; longitudinalModulus=myProperties.bulkModulus+4*myProperties.shearModulus/3; alpha=1-solidCompressibility/bulkCompressibility; storativity=porosity*fluidCompressibility+(alpha-porosity)*solidCompressibility; double consolidationCoefficient=(permeability/fluidViscosity)/(storativity+ alpha*alpha/longitudinalModulus); int Nt=501; int mesh=5; double h=1./mesh; double consolidationTime=h*h/consolidationCoefficient; double dt=consolidationTime/5; double Lt=(Nt-1)*dt; /* OTHER PARAMETERS ----------------------------------------------------------------*/ double columnLoad=-10e3; // Pa /* PETSC INITIALIZE ----------------------------------------------------------------*/ PetscErrorCode ierr; ierr=PetscInitialize(&argc,&args,(char*)0,NULL);CHKERRQ(ierr); /* SOLVE BENCHMARKING PROBLEMS ----------------------------------------------------------------*/ cout << "Grid type: " << myGridType << "\n"; cout << "Interpolation scheme: " << myInterpScheme << "\n"; cout << "Minimum time-step: " << consolidationTime/6 << "\n"; cout << "Medium:" << myProperties.pairName << "\n"; for(int i=0; i<3; i++) { if(problemsSolved[i]==2) { cout << "Solved Terzaghi for: \n"; createSolveRunInfo(myGridType,myInterpScheme,"Terzaghi"); exportSolveRunInfo(dt,"Terzaghi_"+myMedium); ierr=terzaghiDouble(myGridType,myInterpScheme,Nt,mesh,Lt,0,columnLoad,myProperties); CHKERRQ(ierr); } /* PETSC FINALIZE ----------------------------------------------------------------*/ ierr=PetscFinalize();CHKERRQ(ierr); return ierr; };
7907ac55532ac83c8f86fc2c398a4b16264a9ae2
060067983bb02e1046743da5af92f9aa9fe85f04
/enumerator/testpp.cpp
62e37fa09ec6b49ccf137f9fde5cbc27e500bd0c
[ "MIT" ]
permissive
MichaelBrim/tedium
ef0de9398cae2b2f6bc280c79ffb790cf7200a9c
79ae6533d87217b6f61d6ae12df0c2f46a119441
refs/heads/master
2020-03-08T00:01:07.217280
2018-06-15T18:12:39
2018-06-15T18:12:39
127,795,915
1
0
null
null
null
null
UTF-8
C++
false
false
965
cpp
testpp.cpp
/* Copyright (c) 2018 - Michael J. Brim * * See https://github.com/MichaelBrim/tedium/blob/master/LICENSE for licensing */ #include <cstring> #include <cstdio> #include "enumerator.h" int main(int argc, char* argv[]) { int checkval; prefix_e testval; const char* estr; for( checkval = (int)PREFIX_ENUM_INVALID+1; checkval < (int)PREFIX_ENUM_MAX; checkval++ ) { printf("checking value %d - ", checkval); if( check_valid_prefix_enum((prefix_e)checkval) ) { estr = prefix_enum_str((prefix_e)checkval); printf("VALID\n\tname = %s\n\tdescription = %s\n", estr, prefix_enum_description((prefix_e)checkval)); testval = prefix_enum_from_str(estr); if( checkval != testval ) { printf("\tERROR on reverse lookup from string '%s'\n", estr); } } else { printf("NOT DEFINED\n"); } } return 0; }
2d6d418305a95d32f0e00256c3bd40e13e510808
a3d6556180e74af7b555f8d47d3fea55b94bcbda
/chrome/third_party/mozilla_security_manager/nsNSSCertHelper.cpp
81eae702f8d78c335c05d37285859c02d6084c22
[ "LGPL-2.1-or-later", "MPL-1.1", "GPL-2.0-or-later", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-only", "LGPL-2.1-only", "BSD-3-Clause" ]
permissive
chromium/chromium
aaa9eda10115b50b0616d2f1aed5ef35d1d779d6
a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c
refs/heads/main
2023-08-24T00:35:12.585945
2023-08-23T22:01:11
2023-08-23T22:01:11
120,360,765
17,408
7,102
BSD-3-Clause
2023-09-10T23:44:27
2018-02-05T20:55:32
null
UTF-8
C++
false
false
2,592
cpp
nsNSSCertHelper.cpp
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Netscape security libraries. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2000 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Ian McGreer <mcgreer@netscape.com> * Javier Delgadillo <javi@netscape.com> * John Gardiner Myers <jgmyers@speakeasy.net> * Martin v. Loewis <martin@v.loewis.de> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ #include "chrome/third_party/mozilla_security_manager/nsNSSCertHelper.h" #include <certdb.h> namespace mozilla_security_manager { net::CertType GetCertType(CERTCertificate *cert) { CERTCertTrust trust = {0}; CERT_GetCertTrust(cert, &trust); unsigned all_flags = trust.sslFlags | trust.emailFlags | trust.objectSigningFlags; if (cert->nickname && (all_flags & CERTDB_USER)) return net::USER_CERT; if ((all_flags & CERTDB_VALID_CA) || CERT_IsCACert(cert, nullptr)) return net::CA_CERT; // TODO(mattm): http://crbug.com/128633. if (trust.sslFlags & CERTDB_TERMINAL_RECORD) return net::SERVER_CERT; return net::OTHER_CERT; } } // namespace mozilla_security_manager
f95dda501206a33720037ecdca6cefdcda50bb72
6b8325aedb956175071e93f005a98057095dbb3d
/UGen/core/ugen_Bits.h
6dd37d1262a8221a16667a11efa5972db925eebe
[]
no_license
0x4d52/ugen
73bdf090d8328e469977991cb9b662c8031cf467
590c03ba6e1e9caa20992327189dfcd74438ac86
refs/heads/master
2021-07-13T16:55:20.969401
2016-09-27T10:53:32
2016-09-27T10:53:32
34,687,605
22
3
null
null
null
null
UTF-8
C++
false
false
3,294
h
ugen_Bits.h
// $Id$ // $HeadURL$ /* ============================================================================== This file is part of the UGEN++ library Copyright 2008-11 The University of the West of England. by Martin Robinson ------------------------------------------------------------------------------ UGEN++ can be redistributed and/or modified under the terms of the GNU General Public License, as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. UGEN++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with UGEN++; if not, visit www.gnu.org/licenses or write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA The idea for this project and code in the UGen implementations is derived from SuperCollider which is also released under the GNU General Public License: SuperCollider real time audio synthesis system Copyright (c) 2002 James McCartney. All rights reserved. http://www.audiosynth.com ============================================================================== */ // check gpl // most of this appears to be "common knowledge"? #ifndef _UGEN_ugen_Bits_H_ #define _UGEN_ugen_Bits_H_ /** For bit pattern conversion between a few types. */ typedef union { unsigned long u; long i; float f; } Element; /** Various bitwise utilities. All functions are statics at present but this may develop into a bits class (perhaps similar to the juce::BitArray) */ class Bits { public: static inline long countLeadingZeros(long x) { x |= (x >> 1); x |= (x >> 2); x |= (x >> 4); x |= (x >> 8); x |= (x >> 16); return(32 - countOnes(x)); } static inline long countTrailingZeros(long x) { return 32 - countLeadingZeros(~x & (x-1)); } static inline long countLeadingOnes(long x) { return countLeadingZeros(~x); } static inline long countTrailingOnes(long x) { return 32 - countLeadingZeros(x & (~x-1)); } static inline long numBitsRequired(long x) { return 32 - countLeadingZeros(x); } static inline long log2Ceil(long x) { return 32 - countLeadingZeros(x - 1); } static inline long nextPowerOf2(long x) { return 1L << log2Ceil(x); } static inline bool isPowerOf2(long x) { return (x & (x-1)) == 0; } static inline unsigned long countOnes(unsigned long x) { x -= ((x >> 1) & 0x55555555); x = (((x >> 2) & 0x33333333) + (x & 0x33333333)); x = (((x >> 4) + x) & 0x0f0f0f0f); x += (x >> 8); x += (x >> 16); return(x & 0x0000003f); } static inline void endianSwap(unsigned short& x) { x = (x >> 8) | (x << 8); } static inline void endianSwap(short& x) { return endianSwap((unsigned short&)x); } static inline void endianSwap(unsigned int& x) { x = (x >> 24) | ((x << 8) & 0x00FF0000) | ((x >> 8) & 0x0000FF00) | (x << 24); } static inline void endianSwap(int& x) { return endianSwap((unsigned int&)x); } }; #endif // _UGEN_ugen_Bits_H_
7ce03022c5849673cc0b8ccaddc39ad69a27e9a7
88b130d5ff52d96248d8b946cfb0faaadb731769
/searchlib/src/vespa/searchlib/util/dirtraverse.h
c26246e2596ed0c2e304d42309328b7ebd7f142d
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
vespa-engine/vespa
b8cfe266de7f9a9be6f2557c55bef52c3a9d7cdb
1f8213997718c25942c38402202ae9e51572d89f
refs/heads/master
2023-08-16T21:01:12.296208
2023-08-16T17:03:08
2023-08-16T17:03:08
60,377,070
4,889
619
Apache-2.0
2023-09-14T21:02:11
2016-06-03T20:54:20
Java
UTF-8
C++
false
false
487
h
dirtraverse.h
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <cstdint> #include <string> namespace search { /* * Class used to get size of directory tree on disk. */ class DirectoryTraverse { private: std::string _base_dir; public: uint64_t GetTreeSize(); // Returns size of directory in bytes explicit DirectoryTraverse(const std::string& base_dir); ~DirectoryTraverse(); }; } // namespace search
36e384bd899409e350d4ce2865443497a281f22d
7fea47e6aee75e90e39c09020bb66ae3d18355d0
/leetcode/leetcode_cpp/path-sum-iii.cpp
a3c399ca9e2fdf2e019f1142c25da00cc36def78
[]
no_license
doum1004/code_assessment
52facd8b361702ef7d342896921ec328eb80ad4a
4b930bb9596adc5153e897a7f95625e78aebcd8a
refs/heads/master
2020-12-04T20:06:04.993844
2020-08-19T00:23:56
2020-08-19T00:23:56
231,888,307
0
1
null
null
null
null
UTF-8
C++
false
false
3,072
cpp
path-sum-iii.cpp
#include <iostream> #include <cassert> #include <vector> #include <stack> #include <unordered_map> #include "../tree.h" using namespace std; /** https://leetcode.com/problems/path-sum-iii/ // Solution1. Recursion DSF (preorder) // time: o(n^2) // space: o(n) 10 15 5 18 8 3 (o) 21 11 6 3 16 9 4 -2 17 7 18 8 1 (o) int ans = 0; r (node, sum, vector<int> sums) if (node == nullptr) return; sums.push_back(0); for (int i=0; i<sums.size(); ++i) sums[i] += node->val if (sums[i] == sum) ans++; r(node->left, sum, sums); r(node->right, sum, sums); r(root, sum, vector<int>()) // Solution2: recursion DSF preorder with dp(hash). store sum of all path of parent. And find parent sum equal to cursum - target // time: o(n) // space: o(n) 10 (target 8) 5 -3 3 2 11 3 -2 1 10 -> [10: 1] 0-8 5 -> [10: 1, 15: 1] 10-5=5 3 -> [10: 1, 15: 1, 18: 1] 18-8 = 10. cnt = 1, rcnt = 1. total 2 3 -> [10, 1, 15: 1, 18: 1, 21: 1] -2 -> [10, 1, 15: 1, 18: 1, 21: 0, 16: 1] 2 -> [10, 1, 15: 1, 18: 1, 21: 0, 16: 0, 19: 1] 1 -> [10, 1, 15: 1, 18: 1, 21: 0, 16: 0, 19: 1, 18: 1] 18-8 = 10. cnt = 1 */ class Solution { public: int pathSum(TreeNode* node, int sum, vector<int> sums) { if (node == nullptr) return 0; auto cnt = 0; sums.push_back(0); for (auto &n : sums) { n += node->val; if (n == sum) cnt++; } int lcnt = pathSum(node->left, sum, sums); int rcnt = pathSum(node->right, sum, sums); return cnt + lcnt + rcnt; } int pathSum_recursion1(TreeNode* root, int sum) { return pathSum(root, sum, vector<int>()); } int pathSum_recursion2(TreeNode *root, int sum) { unordered_map<int, int> hash; return path(root, 0, sum, hash); } int path(TreeNode *node, int pre, int target, unordered_map<int, int>& hash) { if (node == nullptr) return 0; auto cursum = pre + node->val; auto curcnt = hash.count(cursum-target) ? hash[cursum-target] : 0; if (cursum == target) curcnt++; hash[cursum]++; auto lcnt = path(node->left, cursum, target, hash); auto rcnt = path(node->right, cursum, target, hash); hash[cursum]--; return curcnt + lcnt + rcnt; } int pathSum(TreeNode* root, int sum) { //return pathSum_recursion1(root, sum); return pathSum_recursion2(root, sum); } }; int main() { auto input1 = new TreeNode(10); input1->left = new TreeNode(5); input1->left->left = new TreeNode(3); input1->left->left->left = new TreeNode(3); input1->left->left->right = new TreeNode(-2); input1->left->right = new TreeNode(2); input1->left->right->right = new TreeNode(1); input1->right = new TreeNode(-3); input1->right->right = new TreeNode(11); assert(Solution().pathSum(input1, 8) == (3)); return 0; }
cbc171de0b2bf48b63fab8d1da4b1b7c4d22e6e9
45874c847c5a2fc4e89e05a7fc8ad9b63d8c4860
/sycl/test-e2e/DeviceCodeSplit/Inputs/split-per-source-second-file.cpp
d5ee857ec4df3b91342870bcd83f9dcc69ce154a
[ "NCSA", "LLVM-exception", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
intel/llvm
2f023cefec793a248d8a237267410f5e288116c5
a3d10cf63ddbdcc23712c45afd1b6b0a2ff5b190
refs/heads/sycl
2023-08-24T18:53:49.800759
2023-08-24T17:38:35
2023-08-24T17:38:35
166,008,577
1,050
735
NOASSERTION
2023-09-14T20:35:07
2019-01-16T09:05:33
null
UTF-8
C++
false
false
727
cpp
split-per-source-second-file.cpp
#include "split-per-source.h" void runKernelsFromFile2() { sycl::queue Q; int Data = 0; { sycl::buffer<int, 1> Buf(&Data, sycl::range<1>(1)); auto KernelID1 = sycl::get_kernel_id<File2Kern1>(); auto KB = sycl::get_kernel_bundle<sycl::bundle_state::executable>( Q.get_context(), {KernelID1}); auto Krn = KB.get_kernel(KernelID1); std::vector<sycl::kernel_id> KernelIDStorage = KB.get_kernel_ids(); assert(KernelIDStorage.size() == 1); assert(KernelIDStorage[0] == KernelID1); Q.submit([&](sycl::handler &Cgh) { auto Acc = Buf.get_access<sycl::access::mode::read_write>(Cgh); Cgh.single_task<File2Kern1>(Krn, [=]() { Acc[0] = 3; }); }); } assert(Data == 3); }
9f2533f0d3cbc2c1d359f2462b72a14792e7e5d0
e024ddd3c3bf037c08187d7ac9c7fec37b06c0b1
/Builder/main.cpp
2ea31cff4f9ce12560cab0a1cba6d2f5fcb3013d
[]
no_license
Andrew22674/ExamenVanguardia
ffa90294525000c4d04db22168664af09eb90b76
c98221ce243c72e7baedb4181ca8513bdf0fdd13
refs/heads/master
2021-01-15T00:39:48.649267
2020-02-24T19:38:59
2020-02-24T19:38:59
242,815,695
0
0
null
null
null
null
UTF-8
C++
false
false
335
cpp
main.cpp
#include <iostream> #include "Director.cpp" using namespace std; int main(){ Director dir; Note10Builder nb; GalaxyA10Builder gb; Phone *note = dir.createPhone(&nb); Phone *galaxy = dir.createPhone(&gb); note-> showPhone(); galaxy -> showPhone(); delete note; delete galaxy; return 0; };
b8ff5cfbcf37a29f9182cb9ad9b3703e9560259f
b04fc6477319e8deb95a2e98332190cfc744f758
/Consensus.cpp
0058b1e34f4b51d9a24ada2aac3780b3930696b5
[]
no_license
mattheww95/MSA_Con
d59e85e571c3414b3eb653c197a1184864097806
450609d9d6de15d6b60b4fbda1619ee21d0ae48f
refs/heads/main
2023-07-16T04:20:20.011407
2021-09-07T15:14:21
2021-09-07T15:14:21
404,025,044
0
0
null
null
null
null
UTF-8
C++
false
false
7,310
cpp
Consensus.cpp
#include <iostream> #include <fstream> #include <vector> #include <string> typedef unsigned long long int __uint64; struct nucleotides { /// From MSAIndex as well :^) __uint64 A = 0; __uint64 T = 0; __uint64 C = 0; __uint64 G = 0; __uint64 N = 0; __uint64 other = 0; __uint64 del = 0; }; void switch_chars(std::string fasta, std::vector<nucleotides> &tracer) { // My own code from MSAIndex :^) // maybe proper to inline this later will see // Leaving as switch statements, as probably faster than applying upper first, need to check this though for (__uint64 i = 0; i < fasta.length(); i++) { switch (fasta[i]) { case 'A': tracer[i].A += 1; break; case 'T': tracer[i].T += 1; break; case 'C': tracer[i].C += 1; break; case 'G': tracer[i].G += 1; break; case 'N': tracer[i].G += 1; break; case '-': tracer[i].del += 1; break; case 'a': tracer[i].A += 1; break; case 't': tracer[i].T += 1; break; case 'c': tracer[i].C += 1; break; case 'g': tracer[i].G += 1; break; case 'n': tracer[i].N += 1; break; default: tracer[i].other += 1; break; } } } void IUPAC_call(struct nucleotides cur_base){ // Identify the IUPAC nucleotide for the mixture // Break the struct, probably smarter way to do this... // TODO clean this dumb logic up // TODO Make sure to use a plurality for when things are below 50% you know what i mean matthew //__uint64 A, T, C, G, N = cur_base.A, cur_base.T, cur_base.C, cur_base.G, cur_base.N; __uint64 base_freq[4] = {cur_base.A, cur_base.T, cur_base.C, cur_base.G}; if(cur_base.A > 0 && cur_base.T > 0 && cur_base.C > 0 && cur_base.G > 0){ std::cout << 'N'; }else if(cur_base.A > 0 && cur_base.T == 0 && cur_base.C > 0 && cur_base.G > 0){ std::cout << 'V'; }else if(cur_base.A == 0 && cur_base.T > 0 && cur_base.C > 0 && cur_base.G > 0){ std::cout << 'B'; }else if (cur_base.A > 0 && cur_base.T > 0 && cur_base.C > 0 && cur_base.G == 0) { std::cout << 'H'; }else if (cur_base.A > 0 && cur_base.T > 0 && cur_base.C == 0 && cur_base.G > 0) { std::cout << 'D'; }else if (cur_base.A > 0 && cur_base.T == 0 && cur_base.C > 0 && cur_base.G == 0) { std::cout << 'M'; }else if (cur_base.A == 0 && cur_base.T > 0 && cur_base.C == 0 && cur_base.G > 0) { std::cout << 'K'; }else if (cur_base.A > 0 && cur_base.T > 0 && cur_base.C == 0 && cur_base.G == 0) { std::cout << 'W'; }else if(cur_base.A == 0 && cur_base.T == 0 && cur_base.C > 0 && cur_base.G > 0) { std::cout << 'S'; }else if(cur_base.A == 0 && cur_base.T > 0 && cur_base.C > 0 && cur_base.G == 0 ) { std::cout << 'Y'; }else if (cur_base.A > 0 && cur_base.T == 0 && cur_base.C == 0 && cur_base.G > 0){ std::cout << 'R'; }else{ for(__uint64 i = 0; i < 4; i++){ if(base_freq[i] != 0){ switch (i) { case 0: std::cout << 'A'; break; case 1: std::cout << 'T'; break; case 2: std::cout << 'C'; break; case 3: std::cout << 'G'; break; } } } } } int main( int argc, char **argv ){ /// Code to get a single line fasta from -> http://www.rosettacode.org/wiki/FASTA_format#C.2B.2B /// Default output threshold is 0.5 make this a command line arg later if( argc <= 1 ){ std::cerr << "Usage: "<<argv[0]<<" [infile]" << std::endl; std::cerr << "Default threshold for creating a consensus seqeunce is 0.5, this is set in the source code and will be a cmd option at another time" << std::endl; std::cerr << "Consensus sequence is output to stdout so capture it." << std::endl; return -1; } std::ifstream input(argv[1]); if(!input.good()){ std::cerr << "Error opening '"<<argv[1]<<"'. Bailing out." << std::endl; return -1; } std::string line, name, content; // Initialize the vector! std::vector<nucleotides> nucs; bool is_vector_set = false; while( std::getline( input, line ).good() ){ if( line.empty() || line[0] == '>' ){ // Identifier marker if( !name.empty() ){ // Print out what we read from the last entry //std::cout << name << " : " << content << std::endl; if(!is_vector_set){ for(__uint64 i = 0; i < content.length(); i++){ nucleotides nucs_; nucs.push_back(nucs_); } is_vector_set = true; }else{ // Should probably make this the default if statement in the future switch_chars(content, nucs); } name.clear(); } if( !line.empty() ){ name = line.substr(1); } content.clear(); } else if( !name.empty() ){ if( line.find(' ') != std::string::npos ){ // Invalid sequence--no spaces allowed name.clear(); content.clear(); } else { content += line; } } } if( !name.empty() ){ // Print out what we read from the last entry //std::cout << name << " : " << content << std::endl; // the last entry probably do not need to check if last entry is set.... probably switch_chars(content, nucs); } input.close(); // finally send out the consensus sequences // Need to cout the header std::cout << '>' << argv[1] << "_consenses\n"; for(nucleotides cur_base: nucs){ // Need to output the larges element of the struct __uint64 nuc_struct_sum = cur_base.A + cur_base.T + cur_base.C + cur_base.G + cur_base.N + cur_base.other + cur_base.del; // set default threshold to 0.5 make cmd arg when nessecary __uint64 consensus_threshold = nuc_struct_sum / 2; if(cur_base.A > consensus_threshold){ std::cout << 'A'; }else if(cur_base.T > consensus_threshold){ std::cout << 'T'; }else if (cur_base.G > consensus_threshold) { std::cout << 'G'; }else if (cur_base.C > consensus_threshold) { std::cout << 'C'; }else if(cur_base.N > consensus_threshold){ std::cout << 'N'; }else if (cur_base.del > consensus_threshold) { std::cout << 'N'; // changed the del to a N as it behaves in programs better }else{ // Need to make this a plurality call IUPAC_call(cur_base); } } std::cout << std::endl; return 0; }
d9218e2239bf8dc603aff42737abd27b39059c0c
23d7dc823f9e50f326c08b716362ab46e26fb5a8
/ophidian/placement/PlacementMapping.cpp
7b63a2231cff9b6f0dfe645043368db5b2212425
[ "Apache-2.0" ]
permissive
joaovicentesouto/ophidian
f15251c1f19ab379cb37efb0b4fb0110cab7d981
6871c18e7be0674fd0363f4f10a2b9d04027516b
refs/heads/development
2021-09-19T11:47:22.034011
2017-10-30T13:23:34
2017-10-30T13:23:34
101,916,908
0
0
null
2017-08-30T18:41:58
2017-08-30T18:41:58
null
UTF-8
C++
false
false
1,126
cpp
PlacementMapping.cpp
#include "PlacementMapping.h" namespace ophidian { namespace placement { PlacementMapping::PlacementMapping(const Placement &placement, const Library &library, const circuit::Netlist &netlist, const circuit::LibraryMapping &libraryMapping) : mPlacement(placement), mLibrary(library), mNetlist(netlist), mLibraryMapping(libraryMapping) { } geometry::MultiBox PlacementMapping::geometry(const circuit::Cell &cell) const { auto stdCell = mLibraryMapping.cellStdCell(cell); auto stdCellGeometry = mLibrary.geometry(stdCell); auto cellLocation = mPlacement.cellLocation(cell); geometry::MultiBox cellGeometry = stdCellGeometry.translate(cellLocation.toPoint()); return cellGeometry; } util::LocationDbu PlacementMapping::location(const circuit::Pin &pin) const { auto stdCellPin = mLibraryMapping.pinStdCell(pin); auto pinOwner = mNetlist.cell(pin); auto cellLocation = mPlacement.cellLocation(pinOwner); auto pinOffset = mLibrary.pinOffset(stdCellPin); util::LocationDbu pinLocation(cellLocation.x() + pinOffset.x(), cellLocation.y() + pinOffset.y()); return pinLocation; } } }
a0fa5f146f069b56bbc6c31ff989bac899e357b9
054454a3033bd65763dbe1f81535138712c47952
/w6/d3_templates/templates_06.cpp
ef9bfaad13ab487c5ec5e80f6b7809a3dc11dc7c
[]
no_license
greenfox-zerda-sparta/szaboattus
8e6cec0bdde81f7942ce5d451ed20826d7994a4d
7eee9c38361895b96eb3612fa5242f821c50526e
refs/heads/master
2021-01-17T18:18:13.841031
2017-02-17T09:19:32
2017-02-17T09:19:32
71,350,874
0
0
null
null
null
null
UTF-8
C++
false
false
770
cpp
templates_06.cpp
#include <iostream> #include <string> using namespace std; template <class ATTUS> double sumofElements ( ATTUS* array, int x) { double sum = 0; for (int i = 0; i < x; i ++) { sum += array [i]; } return sum; } template <> double sumofElements<char>(char* array, int x) { int sum = 0; for (int i = 0; i < x; i ++) { sum += int(array[i] - 96); } return sum; } int main() { // Create a function template that takes an array, and its length and return the sum of it elements // Create a template specialization for char types, that it returns the sum of the characters integer position in the alphabet int x = 4; int array[x] = {1, 2, 3, 4}; char array2[x] = {'a', 'b', 'c', 'd'}; cout << sumofElements (array2, x); return 0; }
3cc0820b4569e3d7450394db01ee831f7d46b487
4cc3b4aa2b7d9f5467d88785bb42653e98bc302a
/belanja.cpp
741c143a6ba99f341613a8ff3236a6d084a0ae82
[]
no_license
khafid-gionino/C-
275a3938ea8a2625a47c30604ff3c3bbac804b8c
544da8afa581783f729c79beb688dcb22c82151b
refs/heads/master
2021-08-23T17:25:32.441057
2017-12-05T21:47:34
2017-12-05T21:47:34
113,182,443
0
1
null
null
null
null
UTF-8
C++
false
false
654
cpp
belanja.cpp
#include <iostream> using namespace std; main(){ int h_gula, h_beras, h_minyak, h_telor, diskon, total; int b_gula, b_beras, b_minyak, b_telor; cout<<"masukan jumlah Gula :"; cin>>b_gula; cout<<"masukkan jumlah beras :"; cin>>b_beras; cout<<"masukkan jumlah minyak :"; cin>>b_minyak; cout<<"msukkan numlah telor :"; cin>>b_telor; h_gula=50000, h_beras=7000, h_minyak=3000, h_telor=4000; diskon=0.2; total=((h_gula*b_gula) + (h_minyak*b_minyak) + (h_telor*b_telor)); diskon=total * diskon; cout<<"totalnya adalah ="<<total<<endl; cout<<"diskonnya ="<<diskon; }
0fcb2ae03d4cbf02756d8cd9a90e7e682ae6ff6a
9f3f1c141054113c0c72f187a016550d4c403e5d
/D04/ex00/Sorcerer.hpp
7cec01805f764ef7f138245564575592c0e5b83e
[]
no_license
MarineBaron/Piscine_CPP
a0526710c77036ff93c21cfcc5413e17e7311253
8675320fb373e0bbf2965b152db47cbdfd964585
refs/heads/master
2021-09-11T01:01:54.524302
2018-04-05T08:54:59
2018-04-05T08:54:59
123,882,935
0
0
null
null
null
null
UTF-8
C++
false
false
1,448
hpp
Sorcerer.hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Sorcerer.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbaron <mbaron@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/09 08:55:11 by mbaron #+# #+# */ /* Updated: 2018/03/09 11:37:26 by mbaron ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef SORCERER_HPP # define SORCERER_HPP # include <iostream> # include "Victim.hpp" class Sorcerer { public: Sorcerer(std::string const name, std::string const title); Sorcerer(Sorcerer const & src); virtual ~Sorcerer(void); Sorcerer &operator=(Sorcerer const & rhs); std::string const &getName(void) const; std::string const &getTitle(void) const; void polymorph(Victim const & victim) const; private: std::string _name; std::string _title; }; std::ostream &operator<<(std::ostream &os, Sorcerer const & rhs); #endif
2ed032817f4153e5b8b9c40a18cea9ce62ed0506
6cb6a875e9a42f91674c2cc5a9901c6af9daf456
/src/lib/wombat/body/BodyConfiguration.h
aec91d6320e9c5b8a672f280e21e59143566c5f7
[]
no_license
benknopp/wombat
9f6d2a03ddfd8b51fbf4585e0a248adfb3e10086
7d45bcc8e7557c49a5d019efe12e584caa9d7084
refs/heads/master
2021-01-15T18:04:08.098240
2010-06-21T17:48:17
2010-06-21T17:48:17
732,328
1
0
null
null
null
null
UTF-8
C++
false
false
849
h
BodyConfiguration.h
/* * BodyConfiguration.h * * Created on: 10.12.2009 * Author: bknopp */ #ifndef BODYCONFIGURATION_H_ #define BODYCONFIGURATION_H_ #include <Eigen/Core> USING_PART_OF_NAMESPACE_EIGEN #include <vector> #include "BodyStructures.h" namespace wombat { /*! * \brief contains all time-variing information about a body model. */ struct BodyConfiguration { BodyConfiguration(){} /*! * _size must be equal to the number of ridgid parts of * the modell, R[t] for every part is requierd. * coordinates are in world coordinate system */ BodyConfiguration(unsigned _size) { translations.resize(_size); rotations.resize(_size); } std::vector<Vector3d> translations; std::vector<Matrix3d> rotations; Identifier identifier; }; } #endif /* BODYCONFIGURATION_H_ */
ba492210ab3fb69df44f116d7b860d01dec89b07
5e3a5af3473ead6c3ebbd617464e4d09ee26ad25
/Ai For Games Lab1/Ai For Games Lab1/Math.h
ec42fe026b538ef829b0a791985c207e24433f4f
[]
no_license
David-Whiteford/Games-Ai-1
a09cc8fbdf07535af15c57efb8db94d4885c0524
98fc3d797e23d083ab1a6a949bb120ccf4f7f6c0
refs/heads/master
2022-12-31T10:08:00.649698
2020-10-19T22:16:11
2020-10-19T22:16:11
305,525,487
0
0
null
null
null
null
UTF-8
C++
false
false
340
h
Math.h
#ifndef MATH_H #define MATH_H #include <SFML/Graphics.hpp> #include <cmath> class Math { public: Math(); sf::Vector2f normalise(sf::Vector2f t_vec); float magnitude(sf::Vector2f t_vec); float magnitudeSquared(float t_vecX, float t_vecY); float length(sf::Vector2f& vec); float dot(sf::Vector2f& vec, sf::Vector2f& vec2); }; #endif
f9bd6fcabf36314a9b009a848cb8d881a65c5cb8
17ee514db94b7a1932e37073491e59c67114e4aa
/CJ60/CJ60Lib/CJTabctrlBar.cpp
1ea0924431337c6d4ae0695eb24e1e886e62d1b0
[ "MIT" ]
permissive
joeriedel/Tread3.0A2
024ab01fbce9b33fb39d5987483dd740ed34aad7
9ce31695bd02f30f07464d18dbbfbf5d4d7fccf9
refs/heads/master
2023-03-15T15:30:05.499251
2023-03-04T04:01:11
2023-03-04T04:01:11
196,284,234
6
0
null
null
null
null
WINDOWS-1252
C++
false
false
9,689
cpp
CJTabctrlBar.cpp
// CJTabCtrlBar.cpp : implementation file // // DevStudio Style Resizable Docking Tab Control Bar. // // Copyright © 1998 Written by Kirk Stowell // mailto:kstowel@sprynet.com // http://www.geocities.com/SiliconValley/Haven/8230 // // The code contained in this file is based on the original // CSizingTabCtrlBar class written by Dirk Clemens, // mailto:dirk_clemens@hotmail.com // http://www.codeguru.com/docking/sizing_tabctrl_bar.shtml // // This code may be used in compiled form in any way you desire. This // file may be redistributed unmodified by any means PROVIDING it is // not sold for profit without the authors written consent, and // providing that this notice and the authors name and all copyright // notices remains intact. If the source code in this file is used in // any commercial application then a statement along the lines of // "Portions Copyright © 1998 Kirk Stowell" must be included in // the startup banner, "About" box or printed documentation. An email // letting me know that you are using it would be nice as well. That's // not much to ask considering the amount of work that went into this. // // This file is provided "as is" with no expressed or implied warranty. // The author accepts no liability for any damage/loss of business that // this product may cause. // // ========================================================================== // HISTORY: // ========================================================================== // 1.00 17 Oct 1998 - Initial re-write and release. // ========================================================================== // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "CJTabCtrlBar.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CCJTabCtrlBar CCJTabCtrlBar::CCJTabCtrlBar() { m_nActiveTab = 0; } CCJTabCtrlBar::~CCJTabCtrlBar() { while(!m_views.IsEmpty()) { TCB_ITEM *pMember=m_views.RemoveHead(); delete pMember; } } #define IDC_TABCTRLBAR 1000 BEGIN_MESSAGE_MAP(CCJTabCtrlBar, CCJControlBar) //{{AFX_MSG_MAP(CCJTabCtrlBar) ON_WM_CREATE() ON_NOTIFY(TCN_SELCHANGE, IDC_TABCTRLBAR, OnTabSelChange) ON_WM_WINDOWPOSCHANGED() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CCJTabCtrlBar message handlers // *** K.Stowell void CCJTabCtrlBar::OnWindowPosChanged(WINDOWPOS FAR* lpwndpos) { CWnd *pWnd; if (IsFloating()) { m_tabctrl.MoveWindow( 5, 5, lpwndpos->cx-10, lpwndpos->cy-7 ); for (POSITION pos=m_views.GetHeadPosition(); pos; m_views.GetNext(pos)) { pWnd=m_views.GetAt(pos)->pWnd; pWnd->MoveWindow(8, 8, lpwndpos->cx-16, lpwndpos->cy-34); } } else if (IsHorzDocked()) { m_tabctrl.MoveWindow( 17, 5, lpwndpos->cx-25, lpwndpos->cy-17 ); for (POSITION pos=m_views.GetHeadPosition(); pos; m_views.GetNext(pos)) { pWnd=m_views.GetAt(pos)->pWnd; pWnd->MoveWindow(20, 8, lpwndpos->cx-31, lpwndpos->cy-44); } } else { m_tabctrl.MoveWindow( 5, 20, lpwndpos->cx-17, lpwndpos->cy-31 ); for (POSITION pos=m_views.GetHeadPosition(); pos; m_views.GetNext(pos)) { pWnd=m_views.GetAt(pos)->pWnd; pWnd->MoveWindow(8, 23, lpwndpos->cx-23, lpwndpos->cy-58); } } CCJControlBar::OnWindowPosChanged(lpwndpos); } // *** K.Stowell CImageList* CCJTabCtrlBar::SetTabImageList(CImageList *pImageList) { return m_tabctrl.SetImageList (pImageList); } // *** K.Stowell BOOL CCJTabCtrlBar::ModifyTabStyle(DWORD dwRemove, DWORD dwAdd, UINT nFlags) { return m_tabctrl.ModifyStyle(dwRemove, dwAdd); } // *** K.Stowell int CCJTabCtrlBar::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CCJControlBar::OnCreate(lpCreateStruct) == -1) return -1; //Create the Tab Control if (!m_tabctrl.Create(WS_VISIBLE|WS_CHILD|TCS_BOTTOM|TCS_TOOLTIPS, CRect(0,0,0,0), this, IDC_TABCTRLBAR)) { TRACE0("Unable to create tab control bar\n"); return -1; } // set "normal" GUI-font CFont *font = CFont::FromHandle((HFONT)::GetStockObject(DEFAULT_GUI_FONT)); m_tabctrl.SetFont(font); // VC5 Support. #if _MSC_VER >= 1200 m_ToolTip = m_tabctrl.GetToolTips(); m_tabctrl.SetToolTips(m_ToolTip); #else m_ToolTip = m_tabctrl.GetTooltips(); m_tabctrl.SetTooltips(m_ToolTip); #endif return 0; } // *** KStowell void CCJTabCtrlBar::OnTabSelChange(NMHDR* pNMHDR, LRESULT* pResult) { SetActiveView(m_tabctrl.GetCurSel()); Invalidate(); } ////////////////////////////////////////////////// // The remainder of this class was written by Dirk Clemens... BOOL CCJTabCtrlBar::AddView(LPCTSTR lpszLabel, CRuntimeClass *pViewClass, CCreateContext *pContext) { #ifdef _DEBUG ASSERT_VALID(this); ASSERT(pViewClass != NULL); ASSERT(pViewClass->IsDerivedFrom(RUNTIME_CLASS(CWnd))); ASSERT(AfxIsValidAddress(pViewClass, sizeof(CRuntimeClass), FALSE)); #endif CCreateContext context; if (pContext == NULL) { // if no context specified, generate one from the currently selected // client if possible CView* pOldView = NULL; if (pOldView != NULL && pOldView->IsKindOf(RUNTIME_CLASS(CView))) { // set info about last pane ASSERT(context.m_pCurrentFrame == NULL); context.m_pLastView = pOldView; context.m_pCurrentDoc = pOldView->GetDocument(); if (context.m_pCurrentDoc != NULL) context.m_pNewDocTemplate = context.m_pCurrentDoc->GetDocTemplate(); } pContext = &context; } CWnd* pWnd; TRY { pWnd = (CWnd*)pViewClass->CreateObject(); if (pWnd == NULL) AfxThrowMemoryException(); } CATCH_ALL(e) { TRACE0("Out of memory creating a view.\n"); // Note: DELETE_EXCEPTION(e) not required return FALSE; } END_CATCH_ALL ASSERT_KINDOF(CWnd, pWnd); ASSERT(pWnd->m_hWnd == NULL); // not yet created DWORD dwStyle = AFX_WS_DEFAULT_VIEW; CRect rect; // Create with the right size and position if (!pWnd->Create(NULL, NULL, dwStyle, rect, this, 0, pContext)) { TRACE0("Warning: couldn't create client pane for view.\n"); // pWnd will be cleaned up by PostNcDestroy return FALSE; } m_pActiveView = (CView*) pWnd; TCB_ITEM *pMember=new TCB_ITEM; pMember->pWnd=pWnd; strcpy(pMember->szLabel, lpszLabel); m_views.AddTail(pMember); // ToolTip support for tabs. if((m_views.GetCount()-1)==0) { m_ToolTip->AddTool( &m_tabctrl, lpszLabel, NULL, m_views.GetCount()-1 ); } else { m_ToolTip->AddTool( &m_tabctrl, lpszLabel, CRect(0,0,0,0), m_views.GetCount()-1 ); } int nViews = m_views.GetCount(); if (nViews!=1) { pWnd->EnableWindow(FALSE); pWnd->ShowWindow(SW_HIDE); } else { ((CFrameWnd *)GetParent())->SetActiveView((CView *)m_pActiveView); } TC_ITEM tci; tci.mask = TCIF_TEXT | TCIF_IMAGE; tci.pszText = (LPTSTR)(LPCTSTR)lpszLabel; tci.iImage = nViews-1; m_tabctrl.InsertItem(nViews, &tci); return TRUE; } void CCJTabCtrlBar::RemoveView(int nView) { ASSERT_VALID(this); ASSERT(nView >= 0); // remove the page from internal list m_views.RemoveAt(m_views.FindIndex(nView)); } void CCJTabCtrlBar::SetActiveView(int nNewTab) { ASSERT_VALID(this); ASSERT(nNewTab >= 0); if (nNewTab!=-1 && nNewTab!=m_nActiveTab) { TCB_ITEM *newMember=m_views.GetAt(m_views.FindIndex(nNewTab)); TCB_ITEM *oldMember=NULL; if (m_nActiveTab!=-1) { oldMember=m_views.GetAt(m_views.FindIndex(m_nActiveTab)); oldMember->pWnd->EnableWindow(FALSE); oldMember->pWnd->ShowWindow(SW_HIDE); } newMember->pWnd->EnableWindow(TRUE); newMember->pWnd->ShowWindow(SW_SHOW); newMember->pWnd->SetFocus(); m_pActiveView = (CView *)newMember->pWnd; ((CFrameWnd *)GetParent())->SetActiveView(m_pActiveView); m_nActiveTab = nNewTab; // select the tab (if tab programmatically changed) m_tabctrl.SetCurSel(m_nActiveTab); } } void CCJTabCtrlBar::SetActiveView(CRuntimeClass *pViewClass) { ASSERT_VALID(this); ASSERT(pViewClass != NULL); ASSERT(pViewClass->IsDerivedFrom(RUNTIME_CLASS(CWnd))); ASSERT(AfxIsValidAddress(pViewClass, sizeof(CRuntimeClass), FALSE)); int nNewTab = 0; for (POSITION pos=m_views.GetHeadPosition(); pos; m_views.GetNext(pos)) { TCB_ITEM *pMember=m_views.GetAt(pos); if (pMember->pWnd->IsKindOf(pViewClass)) { //first hide old first view m_pActiveView->EnableWindow(FALSE); m_pActiveView->ShowWindow(SW_HIDE); // set new active view m_pActiveView = (CView*)pMember->pWnd; // enable, show, set focus to new view m_pActiveView->EnableWindow(TRUE); m_pActiveView->ShowWindow(SW_SHOW); m_pActiveView->SetFocus(); ((CFrameWnd *)GetParent())->SetActiveView(m_pActiveView); m_nActiveTab = nNewTab; // select the tab m_tabctrl.SetCurSel(m_nActiveTab); break; } nNewTab++; } } CView* CCJTabCtrlBar::GetActiveView() { return m_pActiveView; } CView* CCJTabCtrlBar::GetView(int nView) { ASSERT_VALID(this); ASSERT(nView >= 0); if (nView!=-1) { TCB_ITEM *pMember=m_views.GetAt(m_views.FindIndex(nView)); return (CView*)pMember->pWnd; } else return NULL; } CView* CCJTabCtrlBar::GetView(CRuntimeClass *pViewClass) { ASSERT_VALID(this); ASSERT(pViewClass != NULL); ASSERT(pViewClass->IsDerivedFrom(RUNTIME_CLASS(CWnd))); ASSERT(AfxIsValidAddress(pViewClass, sizeof(CRuntimeClass), FALSE)); for (POSITION pos=m_views.GetHeadPosition(); pos; m_views.GetNext(pos)) { TCB_ITEM *pMember=m_views.GetAt(pos); if (pMember->pWnd->IsKindOf(pViewClass)) { return (CView*)pMember->pWnd; } } return NULL; }
c11e78ecd7b49fd4dacef1e3359855103f4f51d3
30706a797475e914835288113abd5f1ccd83a12e
/DuilibTeachBox0324/DuilibTeachBox0324/KeyPadWnd.h
812b89ac76b6d966e2f0e8be0ed9c249b1300015
[]
no_license
TenYearsADream/TeachBox
79435af280b16328246a56113c5860b9d6d3f946
6b8a3203eab128ac495e8128ca0fffc9a66a1b9d
refs/heads/master
2020-04-22T20:24:44.579794
2015-12-06T07:55:26
2015-12-06T07:55:26
null
0
0
null
null
null
null
GB18030
C++
false
false
2,205
h
KeyPadWnd.h
/** *@file *文件名称:KeyPadWnd.h * *摘要:软键盘窗口 * *@author fly1992@163.com * **/ #pragma once #include "GlobalVar.h" #include "KeyBoard.h" #include "KeyTable.h" #define WM_INPUTEDIT (WM_USER+103)///<发送字符的窗口消息 ///软键盘窗口类 class KeyPadWnd : public CWindowWnd, public INotifyUI { public: KeyPadWnd(); LPCTSTR GetWindowClassName() const; UINT GetClassStyle() const ; void OnFinalMessage(HWND /*hWnd*/); void Init(); void OnPrepare() ; void Notify(TNotifyUI& msg); LRESULT OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled); LRESULT HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam); void KeyLetterInit(); void KeyNumberInit(); void KeyFunctionInit(); void SetCapsLock(CAPSLOCK cap); void SelectKeyNumber(CStdString KeyStr); void SelectKeyLetter(CStdString KeyStr); void SelectkeyFunction(CStdString KeyStr); static KeyPadWnd* GetHandle(HWND hwnd); HWND m_KeyPadHandle;///<设置键盘中的字符要发送的窗口的句柄 static KeyPadWnd* keyPadWnd; public: CPaintManagerUI m_pm; private: CEditUI *m_pInputEdit; private: CButtonUI* m_pKey1; CButtonUI* m_pKey2; CButtonUI* m_pKey3; CButtonUI* m_pKey4; CButtonUI* m_pKey5; CButtonUI* m_pKey6; CButtonUI* m_pKey7; CButtonUI* m_pKey8; CButtonUI* m_pKey9; CButtonUI* m_pKey0; CButtonUI* m_pKeyA; CButtonUI* m_pKeyB; CButtonUI* m_pKeyC; CButtonUI* m_pKeyD; CButtonUI* m_pKeyE; CButtonUI* m_pKeyF; CButtonUI* m_pKeyG; CButtonUI* m_pKeyH; CButtonUI* m_pKeyI; CButtonUI* m_pKeyJ; CButtonUI* m_pKeyK; CButtonUI* m_pKeyL; CButtonUI* m_pKeyM; CButtonUI* m_pKeyN; CButtonUI* m_pKeyO; CButtonUI* m_pKeyP; CButtonUI* m_pKeyQ; CButtonUI* m_pKeyR; CButtonUI* m_pKeyS; CButtonUI* m_pKeyT; CButtonUI* m_pKeyU; CButtonUI* m_pKeyV; CButtonUI* m_pKeyW; CButtonUI* m_pKeyX; CButtonUI* m_pKeyY; CButtonUI* m_pKeyZ; CButtonUI* m_pKeyEnter; CButtonUI* m_pKeySpace; CButtonUI* m_pKeyBackSpace; CButtonUI* m_pKeyCancle; CButtonUI* m_pKeyCapsLock; CAPSLOCK m_pCapsLock; CStdString m_pEditStr; };
6e1fd3671d50c8cda86803b8fc35a79fad99abea
da66cb126f71cf777366a0f4eea8b0254c785e87
/include/itkMGHImageIO.h
4f087b9eafce04ee8da8697e358f4a15ad0a6adf
[]
no_license
PubFork/itkMGHImageIO
2bd4074ccf93de8f67e4faee10ee0f2405dce62a
9519c2c38d7ba0a6bf93182000224a7698fc1ca7
refs/heads/master
2020-04-18T07:34:16.593245
2018-05-06T03:33:37
2018-05-06T03:33:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,733
h
itkMGHImageIO.h
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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 itkMGHImageIO_h #define itkMGHImageIO_h #include "itkMatrix.h" #include "itkImageIOBase.h" #include <fstream> #include "itk_zlib.h" #include "MGHIOExport.h" namespace itk { /** \class MGHImageIO * * \author Hans J. Johnson * \brief Class that defines how to read MGH file format. * Originally developed as part of the Slicer software * package under grants XXXX * * \ingroup IOFilters * \ingroup MGHIO */ class MGHIO_EXPORT MGHImageIO:public ImageIOBase { public: /** Standard class type alias. */ using Self = MGHImageIO; using Superclass = ImageIOBase; using Pointer = SmartPointer<Self>; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(MGHImageIO, Superclass); /*-------- This part of the interfaces deals with reading data. ----- */ /** Determine if the file can be read with this ImageIO implementation. * \param FileNameToRead The name of the file to test for reading. * \post Sets classes ImageIOBase::m_FileName variable to be FileNameToWrite * \return Returns true if this ImageIO can read the file specified. */ bool CanReadFile(const char *FileNameToRead) override; /** Set the spacing and dimension information for the set filename. */ void ReadImageInformation() override; /** Reads the data from disk into the memory buffer provided. */ void Read(void *buffer) override; /*-------- This part of the interfaces deals with writing data. ----- */ /** Determine if the file can be written with this ImageIO implementation. * \param FileNameToWrite The name of the file to test for writing. * \post Sets classes ImageIOBase::m_FileName variable to be FileNameToWrite * \return Returns true if this ImageIO can write the file specified. */ bool CanWriteFile(const char *FileNameToWrite) override; /** Set the spacing and dimension information for the set filename. */ void WriteImageInformation() override; /** Writes the data to disk from the memory buffer provided. Make sure * that the IORegions has been set properly. */ void Write(const void *buffer) override; protected: MGHImageIO(); ~MGHImageIO() override; void PrintSelf(std::ostream& os, Indent indent) const override; void ReadVolumeHeader(); private: static const int MRI_UCHAR = 0; static const int MRI_INT = 1; static const int MRI_FLOAT = 3; static const int MRI_SHORT = 4; static const int MRI_TENSOR = 6; static const unsigned int FS_DIMENSION_HEADER_SIZE = sizeof(int) * 7; static const unsigned int FS_RAS_HEADER_SIZE = (sizeof(float) * 15) + sizeof(short); static const unsigned int FS_UNUSED_HEADER_SIZE = 256 - FS_RAS_HEADER_SIZE; static const unsigned int FS_WHOLE_HEADER_SIZE = FS_RAS_HEADER_SIZE + FS_DIMENSION_HEADER_SIZE + FS_UNUSED_HEADER_SIZE; /** check if a filename is for a compressed file */ bool IsCompressedFilename(const std::string fname); /// processes the actual data buffer void SwapBytesIfNecessary(void * const buffer, const unsigned long numberOfPixels); /// examines the direction cosines and creates encapsulation data // void MriDirCos(); void WriteHeader(); void WriteData(const void* buffer); void PermuteFrameValues(const void* buffer, char* tempmemory); unsigned int GetComponentSize() const override; std::string GetOrientation( itk::Matrix<double> directions ); bool m_IsCompressed; gzFile m_GZFile; std::ofstream m_Output; // Utility function to assist with writing to disk in the // proper format. TInType is static_cast<TDiskType> type. template <typename TInType, typename TDiskType> int TWrite(const TInType inValue); template <typename TDiskType, typename TOutType> int TRead(TOutType &outValue); int TWrite(const char *buf,const unsigned long count); void OpenFile(); void CloseFile(); }; } // end namespace itk #endif // itkMGHImageIO_h
e3dc77376a5ed28d428761373251e2fab6d570c9
ea89955e343ced5e705b4a338039e658a4ba67cb
/Source/Cancelable.h
8634a8a11ddd3e971284df641a95d3f4c0eb2709
[]
no_license
kennethdmiller3/videoventure
775ce24ee4aebe3dfc65876a3fc9abb93f29b51d
7182b78fde61421c48abc679ef6f2992e740d678
refs/heads/master
2021-06-03T19:26:26.704306
2020-07-25T05:37:02
2020-07-25T05:37:02
32,195,803
2
0
null
null
null
null
UTF-8
C++
false
false
921
h
Cancelable.h
#pragma once class CancelableTemplate { public: unsigned int mSpawn; unsigned int mSwitch; bool mTethered; float mBacklash; public: CancelableTemplate(void); ~CancelableTemplate(void); // configure bool Configure(const tinyxml2::XMLElement *element); }; class Cancelable { protected: unsigned int mId; public: #ifdef USE_POOL_ALLOCATOR // allocation void *operator new(size_t aSize); void operator delete(void *aPtr); #endif // constructor Cancelable(void); Cancelable(const CancelableTemplate &aTemplate, unsigned int aId); // destructor virtual ~Cancelable(void); // cancel void Cancel(unsigned int aId, unsigned int aSourceId); protected: // creator death void CreatorDeath(unsigned int aId, unsigned int aSourceId); }; namespace Database { extern Typed<CancelableTemplate> cancelabletemplate; extern Typed<Cancelable *> cancelable; }
bb2184bd94a312a5ffdbe2b3bc9cebbda5b4b91e
6e528660a364d395174aed25dea77a336f5754d7
/goodnessofstring.cpp
316a43ae9d003f6aee6e6da0adbebb327fdfa7a9
[]
no_license
RaperTon-Lab/Kickstart
56b6294192daa252cfd2c5da589387a9b829a154
ff9787033f647cb30a862e48beea6f7eb6836865
refs/heads/main
2023-07-01T00:08:29.327480
2021-07-24T07:58:29
2021-07-24T07:58:29
388,757,336
0
0
null
null
null
null
UTF-8
C++
false
false
3,284
cpp
goodnessofstring.cpp
/*Charles defines the goodness score of a string as the number of indices i such that Si≠SN−i+1 where 1≤i≤N/2 (1-indexed). For example, the string CABABC has a goodness score of 2 since S2≠S5 and S3≠S4. Charles gave Ada a string S of length N, consisting of uppercase letters and asked her to convert it into a string with a goodness score of K. In one operation, Ada can change any character in the string to any uppercase letter. Could you help Ada find the minimum number of operations required to transform the given string into a string with goodness score equal to K? Input The first line of the input gives the number of test cases, T. T test cases follow. The first line of each test case contains two integers N and K. The second line of each test case contains a string S of length N, consisting of uppercase letters. Output For each test case, output one line containing Case #x: y, where x is the test case number (starting from 1) and y is the minimum number of operations required to transform the given string S into a string with goodness score equal to K. Limits Memory limit: 1 GB. 1≤T≤100. 0≤K≤N/2. Test Set 1 Time limit: 20 seconds. 1≤N≤100. Test Set 2 Time limit: 40 seconds. 1≤N≤2×105 for at most 10 test cases. For the remaining cases, 1≤N≤100.*/ //Commented lines are not neccesary for the competition. They are to reduce time complexity #include <bits/stdc++.h> using namespace std; int stringGoodnessScore(string str, int len); /*string stringManipulationLesser(string str, int len); string stringManipulationLarger(string str, int len); int o;*/ int main() { std::ios_base::sync_with_stdio(0); std::cin.tie(NULL); int n, len, k, score, realGoodScore = 0; string str; cin >> n; for (int i = 1; i <= n; ++i) { len = k = 0; str.clear(); cin >> len >> k; cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); getline(cin, str); //cout << str << endl; //realGoodScore = 0; score = stringGoodnessScore(str, len); //o = 0; //cout << stringGoodnessScore(str, len) << endl; if (score < k) { //str = stringManipulationLesser(str, len); //++realGoodScore; score = k - score; } else { //str = stringManipulationLarger(str, len); //++realGoodScore; score = score - k; } cout << "Case #" << i << ": " << score << endl; } return 0; } int stringGoodnessScore(string str, int len) { char *c = const_cast<char *>(str.c_str()); int k = 0; for (int i = 0; i < len / 2; ++i) { if (c[i] != c[len - i - 1]) ++k; } return k; } /*string stringManipulationLesser(string str, int len) { char *c = const_cast<char *>(str.c_str()); while (c[o] != c[len - o - 1]) ++o; c[o] = c[o] + 1; str = c; return str; } string stringManipulationLarger(string str, int len) { char *c = const_cast<char *>(str.c_str()); while (o <= len / 2) { if (c[o] != c[len - o - 1]) { c[o] = c[len - o - 1]; str = c; return str; } ++o; } return str; }*/
6be336d937e22bdb69f945a5ee3f0cffca15a1ac
b7d170f1f013d8802a0474ed0fe7735d6f32f7ba
/main.cc
a37204a63d4fe5ec057c19a6f6e5651ade06e419
[ "BSD-2-Clause" ]
permissive
jaxonwang/suffixtree
433e918e82ccb81d8ab885bb5fde88f35ec8cfad
cf92de365a244deb0cdd0917d8a622da1276bfd8
refs/heads/master
2022-11-29T15:53:43.708816
2020-08-20T08:10:27
2020-08-20T08:10:27
288,432,085
2
1
null
null
null
null
UTF-8
C++
false
false
13,874
cc
main.cc
#include <array> #include <charconv> #include <chrono> #include <iostream> #include <memory> #include <sstream> #include <unordered_map> #include <vector> using namespace std; using namespace std::chrono; class SuffixTree; class Node; class NonLeaf; class InternalNode; class Leaf; class Edge; class InternalEdge; class LeafEdge; using CharT = char; class Node { public: using edge_ptr = std::unique_ptr<Edge>; using node_ptr = Node *; Node() = default; virtual ~Node() = default; // virtual node_ptr next_node(const CharT c) = 0; // virtual edge_ptr &next_edge(const CharT c) = 0; }; class NonLeaf : public Node { public: using edge_ptr = std::unique_ptr<Edge>; using node_ptr = Node *; std::unordered_map<CharT, node_ptr> children; std::unordered_map<CharT, edge_ptr> adj_edges; node_ptr next_node(const CharT c) { if (children.count(c)) return children[c]; return nullptr; } edge_ptr &next_edge(const CharT c) { static edge_ptr empty_edge{}; if (adj_edges.count(c)) return adj_edges[c]; return empty_edge; } }; class InternalNode : public NonLeaf { friend class SuffixTree; using internal_node_ptr = InternalNode *; using node_ptr = Node *; using suffix_link_t = InternalNode *; suffix_link_t suffix_link; public: InternalNode() = default; void set_suffix_link(const internal_node_ptr &p) { suffix_link = p; } suffix_link_t get_suffix_link() { return suffix_link; } }; class Leaf : public Node { using size_type = size_t; public: size_type length; Leaf() : length(0) {} }; class Edge { public: using edge_ptr = std::unique_ptr<Edge>; using size_type = size_t; Edge() = default; virtual ~Edge() = default; virtual size_type start_position() = 0; virtual size_type end_position() = 0; virtual size_type length() { return end_position() - start_position() + 1; } virtual std::pair<edge_ptr, edge_ptr> break_edge(const size_type pos) const = 0; }; class InternalEdge : public Edge { using size_type = typename Edge::size_type; using edge_ptr = typename Edge::edge_ptr; const size_type start_pos; const size_type end_pos; public: InternalEdge(const size_type start_pos, const size_type end_pos) : start_pos(start_pos), end_pos(end_pos) {} size_type start_position() override { return start_pos; } size_type end_position() override { return end_pos; } virtual std::pair<edge_ptr, edge_ptr> break_edge(const size_type pos) const override { if (pos < start_pos || pos >= end_pos) throw std::logic_error("bad pos"); auto new_first = edge_ptr{new InternalEdge(start_pos, pos)}; auto new_second = edge_ptr{new InternalEdge(pos + 1, end_pos)}; return make_pair(move(new_first), move(new_second)); } }; class LeafEdge : public Edge { using size_type = typename Edge::size_type; using edge_ptr = typename Edge::edge_ptr; const size_type start_pos; const size_type &end_pos; public: LeafEdge(const size_type start_pos, const size_type &end_pos) : start_pos(start_pos), end_pos(end_pos) {} virtual size_type start_position() override { return start_pos; } virtual size_type end_position() override { return end_pos; } virtual std::pair<edge_ptr, edge_ptr> break_edge(const size_type pos) const override { if (pos < start_pos || pos >= end_pos) throw std::logic_error("bad pos"); auto new_first = edge_ptr{new InternalEdge(start_pos, pos)}; auto new_second = edge_ptr{new LeafEdge(pos + 1, end_pos)}; return make_pair(move(new_first), move(new_second)); } }; class SuffixTreeBase { public: using edge_ptr = std::unique_ptr<Edge>; using node_ptr = Node *; using internal_node_ptr = InternalNode *; using size_type = size_t; protected: using StringT = std::string; const StringT text; const size_type textlen; static const CharT term_symbol = '\0'; internal_node_ptr root; vector<unique_ptr<Node>> node_holder; public: SuffixTreeBase() = delete; SuffixTreeBase(const StringT &text) : text(text), textlen(text.size()) { std::unique_ptr<InternalNode> root_ptr{new InternalNode}; root = root_ptr.get(); node_holder.push_back(move(root_ptr)); root->set_suffix_link(root); } internal_node_ptr break_edge(internal_node_ptr &edge_owner, const CharT c, const size_type pos) { // break edge[start, end] into [start, pos] [post+1, end] auto real_node = edge_owner; auto &e = real_node->adj_edges[c]; auto edge_pair = e->break_edge(pos); auto first_edge = move(edge_pair.first); auto second_edge = move(edge_pair.second); std::unique_ptr<InternalNode> new_internal_ptr{new InternalNode()}; internal_node_ptr new_internal = new_internal_ptr.get(); node_holder.push_back(move(new_internal_ptr)); const CharT breakpoint_c = text[pos + 1]; new_internal->children[breakpoint_c] = real_node->children[c]; new_internal->adj_edges[breakpoint_c] = move(second_edge); real_node->children[c] = new_internal; real_node->adj_edges[c] = move(first_edge); return new_internal; } void new_leaf(internal_node_ptr &current_node, const size_type start_pos, const size_type &end_pos) { const CharT c = text[start_pos]; current_node->adj_edges[c] = std::unique_ptr<Edge>{new LeafEdge{start_pos, end_pos}}; std::unique_ptr<Leaf> newleaf_ptr{new Leaf{}}; current_node->children[c] = newleaf_ptr.get(); node_holder.push_back(move(newleaf_ptr)); } void _print(const internal_node_ptr &node) const { for (auto &kv : node->children) { CharT c = kv.first; std::cout << node << " "; auto &edge = node->adj_edges[c]; size_type end_pos = edge->end_position(); for (size_type i = edge->start_position(); i <= end_pos; i++) { if (text[i] == term_symbol) std::cout << '$'; else std::cout << text[i]; } std::cout << " " << kv.second << std::endl; } internal_node_ptr suffix_node = node->get_suffix_link(); if (suffix_node) { std::cout << node << " -> " << suffix_node << endl; } for (auto &kv : node->children) { auto next = dynamic_cast<internal_node_ptr>(kv.second); if (next) _print(next); } } bool static _same_tree(const internal_node_ptr &root1, const internal_node_ptr &root2) { if (root1->adj_edges.size() != root2->adj_edges.size()) { std::cout << "size different" << std::endl; return false; } for (auto &c : root1->adj_edges) { if (root2->adj_edges.count(c.first) == 0) { std::cout << c.first << " not in the second" << std::endl; return false; } auto &edge1 = c.second; auto &edge2 = root2->adj_edges[c.first]; if (edge1->start_position() != edge2->start_position()) { std::cout << "Different start position" << std::endl; return false; } if (edge1->end_position() != edge2->end_position()) { std::cout << "Different end position" << std::endl; return false; } } for (auto &c : root1->children) { if (root2->children.count(c.first) == 0) { std::cout << "children size different" << std::endl; return false; } auto child1 = dynamic_cast<internal_node_ptr>(c.second); auto child2 = dynamic_cast<internal_node_ptr>(root2->children[c.first]); // if child is leaf then the cooresponding child should be leaf if ((!child1 && child2) || (child1 && !child2)) { std::cout << "different child type" << std::endl; return false; } if (!child1) continue; if (!_same_tree(child1, child2)) return false; } return true; } bool operator==(const SuffixTreeBase &other) const { return _same_tree(root, other.root); } void print() const { _print(root); } }; class SuffixTreeNaive : public SuffixTreeBase { public: SuffixTreeNaive(const StringT &s) : SuffixTreeBase(s) {} void build() { for (size_t i = 0; i <= textlen; i++) { int j = i; internal_node_ptr current_node = root; while (true) { // will eventually create a leaf CharT current_char = text[j]; auto &nextedge_ptr = current_node->next_edge(current_char); if (!nextedge_ptr) { new_leaf(current_node, j, textlen); goto end_insert_i; } size_t start = nextedge_ptr->start_position(); size_t end = nextedge_ptr->end_position(); for (; start <= end; start++, j++) { if (text[start] != text[j]) { auto new_node = break_edge(current_node, current_char, start - 1); new_leaf(new_node, j, textlen); // include the term symbol goto end_insert_i; } } current_node = dynamic_cast<internal_node_ptr>( current_node->next_node(current_char)); if (!current_node) throw std::logic_error("Goes to Leaf!"); } end_insert_i:; } } }; class SuffixTreeImpl : public SuffixTreeBase { private: enum class ExtensionType : int { newleaf, newnode, extendleaf, // extend the end point of leaf or just do nothing for implicit // suffix tree }; size_type leaf_end_pos; public: SuffixTreeImpl(const StringT &s) : SuffixTreeBase(s), leaf_end_pos(0) {} // try travel down to the point S[j, i)(could be empty) is matchd, and append // S(i), create node if necessary ExtensionType travel_down_and_extend(internal_node_ptr &node, const size_type _j, const size_type i, internal_node_ptr &stop_node, internal_node_ptr &suffix_link_node, size_type &travel_depth) { size_type j = _j; auto current_node = node; ExtensionType ret = ExtensionType::extendleaf; suffix_link_node = nullptr; travel_depth = 0; for (;;) { const CharT c = text[j]; auto &edge = current_node->next_edge(c); if (!edge) { // node has no edge with label start with c new_leaf(current_node, j, leaf_end_pos); ret = ExtensionType::newleaf; break; } size_type remain_length = i - j + 1; size_type start_pos = edge->start_position(); size_type edge_length = edge->length(); if (remain_length <= edge_length) { // travel will end in this edge size_type possible_diverge_point = start_pos + remain_length - 1; if (text[possible_diverge_point] == text[i]) { break; // nothing to do, break and will return extendleaf } else { auto new_node = break_edge(current_node, c, possible_diverge_point - 1); new_leaf(new_node, i, leaf_end_pos); ret = ExtensionType::newnode; suffix_link_node = new_node; break; } } // skip this node and travel to next node j += edge_length; travel_depth += edge_length; auto maybe_internal = dynamic_cast<internal_node_ptr>(current_node->next_node(c)); if (!maybe_internal) { // extend on leaf edge if (i - j + 1 != 1) throw("remain error"); break; } else { current_node = maybe_internal; // go to next node } } stop_node = current_node; if (!suffix_link_node) suffix_link_node = stop_node; return ret; } void build() { // S[j,i) internal_node_ptr longest_node = root; internal_node_ptr node_to_start = longest_node; size_type j_start_with = 0; size_type start_depth = 0; for (size_type i = 0; i <= textlen; i++) { leaf_end_pos = i; internal_node_ptr node_to_update_suffix_link = nullptr; // find the depth of the longest_node for (size_type j = j_start_with; j <= i; j++) { internal_node_ptr stop_node; internal_node_ptr suffix_link_node; size_type travel_depth; auto ret = travel_down_and_extend(node_to_start, j + start_depth, i, stop_node, suffix_link_node, travel_depth); if (node_to_update_suffix_link) { // set suffix link node_to_update_suffix_link->set_suffix_link(suffix_link_node); } if (ret == ExtensionType::newnode) { // need to specify suffix link must // be updated node_to_update_suffix_link = suffix_link_node; } else { node_to_update_suffix_link = nullptr; } if (ret != ExtensionType::extendleaf) { // new leaf is created j_start_with = j + 1; node_to_start = stop_node->get_suffix_link(); // next to start start_depth += (stop_node == root) ? 0 : travel_depth - 1; } else { // no need for the future extend , since they must be extesion // type 3 break; } } } } }; string rand_str(size_t length) { stringstream ss; for (size_t i = 0; i < length; i++) { ss << static_cast<char>('a' + rand() % 26); } return ss.str(); } int main(int argc, char *argv[]) { if (argc != 2) { std::cout << "Usage: a.out str" << std::endl; return -1; } std::string s1 = rand_str(stoi(argv[1])); auto t_start = steady_clock::now(); SuffixTreeNaive st2{s1}; st2.build(); auto t_end = steady_clock::now(); auto dur = duration<double>(t_end - t_start).count(); cout << "Test: naive Execution time: " << dur << endl; t_start = steady_clock::now(); SuffixTreeImpl st1{s1}; st1.build(); t_end = steady_clock::now(); dur = duration<double>(t_end - t_start).count(); cout << "Test: impl Execution time: " << dur << endl; std::cout << (st2 == st1) << std::endl; return 0; }
dbbddd830da29c276f48729c6feb4e178efdeeb2
0d3495b21a9ca6f9a0375a508a38b98ad73b01b5
/Before Clinet Started/Client/simple client.cpp
47bdd9cb2a0e7c6aa493f28c57f1cf4d5db1af41
[]
no_license
Iiqra/High5
04fd6d0d41c4d6d87def6d8373567952c96da64a
cd79340c01f871fb8fee1dc63b59868ce275a093
refs/heads/master
2020-06-28T03:07:55.703860
2017-08-16T11:34:51
2017-08-16T11:34:51
97,085,679
0
0
null
null
null
null
UTF-8
C++
false
false
846
cpp
simple client.cpp
#include "ace/INET_Addr.h" #include "ace/SOCK_Stream.h" #include "ace/SOCK_Connector.h" #include "ace/Log_Msg.h" #include "ace/OS.h" #include <iostream> #include <string> #include "User.h" #include "MessageProtocol.h" using namespace std; int ACE_TMAIN(int, ACE_TCHAR *[]) { printf("Inside main"); ACE_INET_Addr srvr(50009, ACE_LOCALHOST); ACE_SOCK_Connector connector; ACE_SOCK_Stream peer; //Try connecting if (-1 == connector.connect(peer, srvr)) ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("%p\r\n"), ACE_TEXT("connect")), 100); while (true) { printf("\nEnter something to send\n"); char buff[21]; char buff1[21]; // send ACE_OS::read(ACE_STDIN, buff, sizeof(buff)); int bs= peer.send_n(buff, sizeof(buff)); int br = peer.recv_n(buff1, sizeof(buff1)); _write(1, buff1, bs); } peer.close(); return (0); }
0be511cad77869c620d41982b73f8bbdfb5c10c2
72cc66c2026335ddb7b99e4a23c09d83df81226d
/Lab5/Lab.cpp
d957efa51d4e2dc375ae00d65dec7c9bc14f6916
[]
no_license
Jurden/417lab
bc5f8335021f9e0917028c1e3eb9d6641f30b7e6
67b45c986702bec70cebbf6956b9d172d3ca8db2
refs/heads/master
2021-01-10T16:39:51.580531
2015-12-10T18:41:39
2015-12-10T18:41:39
46,306,361
0
0
null
null
null
null
UTF-8
C++
false
false
1,243
cpp
Lab.cpp
// Lab 1 Jordan Millett // Compile using: // g++ filename.c -o filename -L "/usr/linux/public/labvolt" -l labvolt -l usb // Make sure output file permissions are set to include x (execute) #include "/home/jurden/Desktop/417Lab/labvolt/inc/labvolt.h" #include <unistd.h> #include <iostream> #include <cstdlib> #include <iomanip> #include <cmath> using namespace std; void Degrees(int Base, int Shoulder, int Elbow, int M4, int M5) { moverel(Base*(6500/360), Shoulder*(8600/360), Elbow*(8600/360), M4*(6500/360), M5*(6500/360)); } int main(void) { int x=1,p,r,t; int a,b,c,d,e; int A=0,B=0,C=0,D=0,E=0; init(); zero(); // Remember the home position Degrees(0,-132,-3,0,0); while(x){ cout << "Enter 0 to quit, 1 to enter angles" << endl; cin >> x; if(x!=0){ cout << endl << "Input 5 joint angles" << endl; cin >> a >> b >> c >> p >> r; //b-=132; //c-=135; c-=b; d=-r; e=-r; d+=p; e-=p; d+=c; e-=c; // d+=p; // d+=r; // e+=p; // e-=r; Degrees(a-A,b-B,c-C,d-D,e-E); A=a; B=b; C=c; D=d; E=e; } } //gripperClose(); // Close the gripper nest(); // Return arm to home position shutdown(); return 0; }
b4bfa88d3f1e853839e45c9b6abef89af947d40a
e82b2f4eddbbfe7b9196f9dcbf9698f6726674c9
/RemoteDesktop_Library/Firewall.cpp
ed285b64ed8e75be9d6021e574652e591b712b48
[]
no_license
wendysuly/RemoteDesktop-1
b937ce3be7036f489d285f987fcf9f87331dd3ab
a12fb71c66db252daa93328f63486e2123705798
refs/heads/master
2021-01-15T22:51:38.420579
2015-01-30T06:06:49
2015-01-30T06:06:49
41,962,507
1
0
null
2015-09-05T13:46:28
2015-09-05T13:46:27
null
UTF-8
C++
false
false
9,906
cpp
Firewall.cpp
#include "stdafx.h" #include "Firewall.h" #include <crtdbg.h> #include <netfw.h> #include <objbase.h> #include <oleauto.h> #include <stdio.h> HRESULT WindowsFirewallIsOn(IN INetFwProfile* fwProfile, OUT BOOL* fwOn) { HRESULT hr = S_OK; VARIANT_BOOL fwEnabled; _ASSERT(fwProfile != NULL); _ASSERT(fwOn != NULL); *fwOn = FALSE; // Get the current state of the firewall. hr = fwProfile->get_FirewallEnabled(&fwEnabled); if (FAILED(hr)) { printf("get_FirewallEnabled failed: 0x%08lx\n", hr); goto error; } // Check to see if the firewall is on. if (fwEnabled != VARIANT_FALSE) { *fwOn = TRUE; printf("The firewall is on.\n"); } else { printf("The firewall is off.\n"); } error: return hr; } HRESULT WindowsFirewallTurnOn(IN INetFwProfile* fwProfile) { HRESULT hr = S_OK; BOOL fwOn; _ASSERT(fwProfile != NULL); // Check to see if the firewall is off. hr = WindowsFirewallIsOn(fwProfile, &fwOn); if (FAILED(hr)) { printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr); goto error; } // If it is, turn it on. if (!fwOn) { // Turn the firewall on. hr = fwProfile->put_FirewallEnabled(VARIANT_TRUE); if (FAILED(hr)) { printf("put_FirewallEnabled failed: 0x%08lx\n", hr); goto error; } printf("The firewall is now on.\n"); } error: return hr; } HRESULT WindowsFirewallTurnOff(IN INetFwProfile* fwProfile) { HRESULT hr = S_OK; BOOL fwOn; _ASSERT(fwProfile != NULL); // Check to see if the firewall is on. hr = WindowsFirewallIsOn(fwProfile, &fwOn); if (FAILED(hr)) { printf("WindowsFirewallIsOn failed: 0x%08lx\n", hr); goto error; } // If it is, turn it off. if (fwOn) { // Turn the firewall off. hr = fwProfile->put_FirewallEnabled(VARIANT_FALSE); if (FAILED(hr)) { printf("put_FirewallEnabled failed: 0x%08lx\n", hr); goto error; } printf("The firewall is now off.\n"); } error: return hr; } HRESULT WindowsFirewallInitialize(OUT INetFwProfile** fwProfile) { HRESULT hr = S_OK; INetFwMgr* fwMgr = NULL; INetFwPolicy* fwPolicy = NULL; assert(fwProfile != nullptr); *fwProfile = NULL; // Create an instance of the firewall settings manager. hr = CoCreateInstance( __uuidof(NetFwMgr), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwMgr), (void**)&fwMgr ); if (FAILED(hr)) { DEBUG_MSG("CoCreateInstance failed: %", hr); goto error; } // Retrieve the local firewall policy. hr = fwMgr->get_LocalPolicy(&fwPolicy); if (FAILED(hr)) { DEBUG_MSG("get_LocalPolicy failed: %", hr); goto error; } // Retrieve the firewall profile currently in effect. hr = fwPolicy->get_CurrentProfile(fwProfile); if (FAILED(hr)) { DEBUG_MSG("get_CurrentProfile failed: %", hr); goto error; } error: // Release the local firewall policy. if (fwPolicy != NULL) { fwPolicy->Release(); } // Release the firewall settings manager. if (fwMgr != NULL) { fwMgr->Release(); } return hr; } HRESULT WindowsFirewallAppIsEnabled( IN INetFwProfile* fwProfile, IN const wchar_t* fwProcessImageFileName, OUT BOOL* fwAppEnabled ) { HRESULT hr = S_OK; BSTR fwBstrProcessImageFileName = NULL; VARIANT_BOOL fwEnabled; INetFwAuthorizedApplication* fwApp = NULL; INetFwAuthorizedApplications* fwApps = NULL; _ASSERT(fwProfile != NULL); _ASSERT(fwProcessImageFileName != NULL); _ASSERT(fwAppEnabled != NULL); *fwAppEnabled = FALSE; // Retrieve the authorized application collection. hr = fwProfile->get_AuthorizedApplications(&fwApps); if (FAILED(hr)) { DEBUG_MSG("get_AuthorizedApplications failed: %", hr); goto error; } // Allocate a BSTR for the process image file name. fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName); if (fwBstrProcessImageFileName == NULL) { hr = E_OUTOFMEMORY; DEBUG_MSG("SysAllocString failed: %", hr); goto error; } // Attempt to retrieve the authorized application. hr = fwApps->Item(fwBstrProcessImageFileName, &fwApp); if (SUCCEEDED(hr)) { // Find out if the authorized application is enabled. hr = fwApp->get_Enabled(&fwEnabled); if (FAILED(hr)) { DEBUG_MSG("get_Enabled failed: %", hr); goto error; } if (fwEnabled != VARIANT_FALSE) { // The authorized application is enabled. *fwAppEnabled = TRUE; DEBUG_MSG( "Authorized application % is enabled in the firewall.\n", fwProcessImageFileName ); } else { DEBUG_MSG( "Authorized application % is disabled in the firewall.\n", fwProcessImageFileName ); } } else { // The authorized application was not in the collection. hr = S_OK; DEBUG_MSG( "Authorized application % is disabled in the firewall.\n", fwProcessImageFileName ); } error: // Free the BSTR. SysFreeString(fwBstrProcessImageFileName); // Release the authorized application instance. if (fwApp != NULL) { fwApp->Release(); } // Release the authorized application collection. if (fwApps != NULL) { fwApps->Release(); } return hr; } HRESULT WindowsFirewallAddApp( IN INetFwProfile* fwProfile, IN const wchar_t* fwProcessImageFileName, IN const wchar_t* fwName ) { HRESULT hr = S_OK; BOOL fwAppEnabled; BSTR fwBstrName = NULL; BSTR fwBstrProcessImageFileName = NULL; INetFwAuthorizedApplication* fwApp = NULL; INetFwAuthorizedApplications* fwApps = NULL; _ASSERT(fwProfile != NULL); _ASSERT(fwProcessImageFileName != NULL); _ASSERT(fwName != NULL); // First check to see if the application is already authorized. hr = WindowsFirewallAppIsEnabled( fwProfile, fwProcessImageFileName, &fwAppEnabled ); if (FAILED(hr)) { DEBUG_MSG("WindowsFirewallAppIsEnabled failed: %", hr); goto error; } // Only add the application if it isn't already authorized. if (!fwAppEnabled) { // Retrieve the authorized application collection. hr = fwProfile->get_AuthorizedApplications(&fwApps); if (FAILED(hr)) { DEBUG_MSG("get_AuthorizedApplications failed: %", hr); goto error; } // Create an instance of an authorized application. hr = CoCreateInstance( __uuidof(NetFwAuthorizedApplication), NULL, CLSCTX_INPROC_SERVER, __uuidof(INetFwAuthorizedApplication), (void**)&fwApp ); if (FAILED(hr)) { DEBUG_MSG("CoCreateInstance failed: %", hr); goto error; } // Allocate a BSTR for the process image file name. fwBstrProcessImageFileName = SysAllocString(fwProcessImageFileName); if (fwBstrProcessImageFileName == NULL) { hr = E_OUTOFMEMORY; DEBUG_MSG("SysAllocString failed: %", hr); goto error; } // Set the process image file name. hr = fwApp->put_ProcessImageFileName(fwBstrProcessImageFileName); if (FAILED(hr)) { DEBUG_MSG("put_ProcessImageFileName failed: %", hr); goto error; } // Allocate a BSTR for the application friendly name. fwBstrName = SysAllocString(fwName); if (SysStringLen(fwBstrName) == 0) { hr = E_OUTOFMEMORY; DEBUG_MSG("SysAllocString failed: %", hr); goto error; } // Set the application friendly name. hr = fwApp->put_Name(fwBstrName); if (FAILED(hr)) { DEBUG_MSG("put_Name failed: %", hr); goto error; } // Add the application to the collection. hr = fwApps->Add(fwApp); if (FAILED(hr)) { DEBUG_MSG("Add failed: %", hr); goto error; } DEBUG_MSG( "Authorized application %lS is now enabled in the firewall.\n", fwProcessImageFileName ); } error: // Free the BSTRs. SysFreeString(fwBstrName); SysFreeString(fwBstrProcessImageFileName); // Release the authorized application instance. if (fwApp != NULL) { fwApp->Release(); } // Release the authorized application collection. if (fwApps != NULL) { fwApps->Release(); } return hr; } RemoteDesktop::WindowsFirewall::WindowsFirewall(){ HRESULT hr = S_OK; // Initialize COM. comInit = CoInitializeEx( 0, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE); // Ignore RPC_E_CHANGED_MODE; this just means that COM has already been // initialized with a different mode. Since we don't care what the mode is, // we'll just use the existing mode. if (comInit != RPC_E_CHANGED_MODE) { hr = comInit; if (FAILED(hr)) { DEBUG_MSG("CoInitializeEx failed: %", hr); return; } } // Retrieve the firewall profile currently in effect. hr = WindowsFirewallInitialize(&FirewallProfile); if (FAILED(hr)) { DEBUG_MSG("WindowsFirewallInitialize failed: %", hr); } } RemoteDesktop::WindowsFirewall::~WindowsFirewall(){ if (FirewallProfile != nullptr) FirewallProfile->Release(); // Uninitialize COM. if (SUCCEEDED(comInit)) { CoUninitialize(); } } bool RemoteDesktop::WindowsFirewall::AddProgramException(std::wstring exefullpath, std::wstring name){ if (FirewallProfile == nullptr) return false; return SUCCEEDED(WindowsFirewallAddApp(FirewallProfile, exefullpath.c_str(), name.c_str())); } void RemoteDesktop::WindowsFirewall::RemoveProgramException(std::wstring exefullpath, std::wstring name){ STARTUPINFO si = { 0 }; PROCESS_INFORMATION pi = { 0 }; TCHAR szCmd[2 * MAX_PATH]; std::wstring command = L"cmd.exe /C netsh advfirewall firewall delete rule name=\""; command += name; command += L"\""; command += L" program=\""; command += exefullpath; command += L"\""; wcscpy_s(szCmd, command.c_str()); CreateProcess(NULL, szCmd, NULL, NULL, FALSE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); } bool RemoteDesktop::WindowsFirewall::IsOn(){ if (FirewallProfile == nullptr) return false; BOOL onstat = FALSE; if (SUCCEEDED(WindowsFirewallIsOn(FirewallProfile, &onstat))) return onstat == TRUE; return false; } bool RemoteDesktop::WindowsFirewall::TurnOn(){ if (FirewallProfile == nullptr) return false; return SUCCEEDED(WindowsFirewallTurnOn(FirewallProfile)); } bool RemoteDesktop::WindowsFirewall::TurnOff(){ if (FirewallProfile == nullptr) return false; return SUCCEEDED(WindowsFirewallTurnOff(FirewallProfile)); }
f9e7ed4ce3ef550ab926f999888e56f2d27dffc3
0b0f2f74d98794d712effeb69124f884334772d2
/[6]분할정복/2447_별 찍기 - 10.cpp
a544c7a2b83392a7fd00bb313a8558290ff38e4d
[]
no_license
wjh51333/Problem-Solving
dff6a26df379bec8b7018b46b9d219db16d336a9
f36f0d9bdfd47b68b07e5410918a296080fad68a
refs/heads/main
2023-03-21T21:19:58.935457
2021-03-15T12:16:18
2021-03-15T12:16:18
330,971,229
0
0
null
null
null
null
UTF-8
C++
false
false
1,021
cpp
2447_별 찍기 - 10.cpp
/* 분할정복 * 2447 별 찍기 - 10 */ #include <iostream> #define MAX 3000 using namespace std; int n; char map[MAX][MAX]; void stars(int x, int y) { int cnt = 0; for (int i = x; i < x + 3; i++) { for (int j = y; j < y + 3; j++) { cnt++; if (cnt == 5) map[i][j] = ' '; else map[i][j] = '*'; } } } void space(int x, int y, int size) { for (int i = x; i < x + size; i++) { for (int j = y; j < y + size; j++) { map[i][j] = ' '; } } } // Divide & Conquer void divConq(int x, int y, int size) { if (size > 3) { int cnt = 0; for (int i = x; i < x + size; i += size / 3) { for (int j = y; j < y + size; j += size / 3) { cnt++; if (cnt == 5) space(i, j, size / 3); else divConq(i, j, size / 3); } } } else stars(x, y); } int main() { ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n; divConq(0, 0, n); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) cout << map[i][j]; cout << "\n"; } return 0; }
a0bbb863998c26f976ed521a503800b3e8b8f0a9
16ebc8f962c0473e6185b1416116761d7daaacad
/src/simplex/window/win32/window_win32.hpp
b5e9da5db134261bd58b296d8428e3da9ff3d09d
[]
no_license
dutow/simplex
4b1bf38545107761ec817a835dc8f49891ea6d64
0774c6da2a8365015002c6f17eabaa7c53b399ff
refs/heads/master
2021-01-10T18:38:56.134116
2015-05-27T05:26:47
2015-05-27T05:26:47
1,534,157
0
0
null
null
null
null
UTF-8
C++
false
false
848
hpp
window_win32.hpp
#pragma once #include <Windows.h> #include "simplex/window/window.hpp" #ifdef WIN32 namespace simplex { /** A win32 window. */ class win32_window : public window { public: /** * Creates a new window. * * @param [in,out] owner_application Reference to the running application. * @param title The window's title. * @param width The window's width. * @param height The window's height. */ win32_window(application& owner_application, std::wstring title, unsigned int width, unsigned int height); /** Destructor. */ virtual ~win32_window(); virtual bool is_running(); virtual void show(); virtual void swap_buffers(); virtual void move_cursor_to(glm::ivec2 coord); protected: HWND handle; }; } #endif
c4124a62e24096fa83887c3fc09bb9297c8563fb
b728c792b5171f6be6ad91919b4a76a6f198b3e9
/src/lib/datasrc/tests/logger_unittest.cc
9d419436a1adbb8976109dbba7b18a8fbe372ed0
[ "LicenseRef-scancode-unknown-license-reference", "ISC", "BSL-1.0" ]
permissive
bundy-dns/bundy
c8beeca2c051924590794c92a3a58d1980a86024
3d41934996b82b0cd2fe22dd74d2abc1daba835d
refs/heads/master
2021-09-28T16:24:39.037808
2021-09-22T06:04:17
2021-09-22T06:04:17
19,160,469
110
33
NOASSERTION
2021-09-22T06:04:18
2014-04-25T20:54:37
C++
UTF-8
C++
false
false
1,178
cc
logger_unittest.cc
// Copyright (C) 2010 Internet Systems Consortium, Inc. ("ISC") // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM // LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #include <gtest/gtest.h> #include <datasrc/logger.h> using namespace bundy::datasrc; namespace { TEST(CacheLogger, name) { // This does not check the name only, but the fact the logger is created // The dot is because of empty root logger std::string name(logger.getName()); EXPECT_EQ(name.size() - 8, name.rfind(".datasrc")) << "Wrong logger name: " << name; } }
b1261dab472bdec4e188d8292483926e43fc359a
1b9a32ea5f2492fd3512965f92e0f057b0528d33
/Alert_Using_Same_Key-Card_Three_or_More_Times _in_a_One_Hour_Period.cpp
389511f220190e06e0edd95ce756c19a6b5e688c
[]
no_license
shivangigoel1302/leetcode_solutions
a459a4279ffcfa889cf1fe0e8eb681e4e79186b6
3373f9710bd797bcda5cbd86958e8914ba9e2a15
refs/heads/master
2023-08-23T04:18:26.678630
2021-11-01T14:57:21
2021-11-01T14:57:21
274,206,300
1
1
null
null
null
null
UTF-8
C++
false
false
1,310
cpp
Alert_Using_Same_Key-Card_Three_or_More_Times _in_a_One_Hour_Period.cpp
class Solution { public: bool isAlert(string name, set<string>time){ auto it = time.begin(); while(it!=time.end()){ auto j = it; string t = *it; string hour = t.substr(0,2); int range = stoi(hour) +1; string newTime =""; if(range <= 9){ newTime = "0"+ to_string(range)+t.substr(2); } else{ newTime = to_string(range)+t.substr(2); } int count = 0; while(j != time.end()){ string present = *j; if(newTime < present){ break; } count++; j++; } if(count >=3){ return true; } it++; } return false; } vector<string> alertNames(vector<string>& keyName, vector<string>& keyTime) { map<string,set<string>>m; for(int i = 0 ; i < keyName.size(); i++){ m[keyName[i]].insert(keyTime[i]); } vector<string>v; for(auto it : m){ if(isAlert(it.first,it.second)){ v.push_back(it.first); } } return v; } };
7f3e94d14e2c7273bc46b64351c009288111e3d2
f7d9171e36daf02bc720cc139366505ef6ccd44d
/aliroot/vsaliroot/test_ForEachPadInArea.cxx
36273392b956718bca9de360cddb2c87ff290c3c
[]
no_license
mrrtf/alo
4e0689c99a2bda365f6852ed8ad430eb21b8f137
76898ba66e07cf4cc613f7086b277c66bcc97098
refs/heads/master
2022-06-20T20:09:06.344681
2022-05-30T16:50:13
2022-05-30T16:50:13
86,624,953
0
6
null
2020-04-08T20:46:23
2017-03-29T20:10:55
C++
UTF-8
C++
false
false
8,146
cxx
test_ForEachPadInArea.cxx
// // Copyright CERN and copyright holders of ALICE O2. This software is // distributed under the terms of the GNU General Public License v3 (GPL // Version 3), copied verbatim in the file "COPYING". // // See https://alice-o2.web.cern.ch/ for full licensing information. // // In applying this license CERN does not waive the privileges and immunities // granted to it by virtue of its status as an Intergovernmental Organization // or submit itself to any jurisdiction. /// /// @author Laurent Aphecetche #define BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #include "AliMpPad.h" #include "AliMpVPadIterator.h" #include "AliMpVSegmentation.h" #include "MappingFixture.h" #include "MCHContour/SVGWriter.h" #include "MCHMappingInterface/Segmentation.h" #include "MCHMappingSegContour/SegmentationContours.h" #include "MCHMappingSegContour/SegmentationSVGWriter.h" #include <AliMpArea.h> #include <TArrayD.h> #include <algorithm> #include <boost/format.hpp> #include <boost/mpl/bool.hpp> #include <boost/test/data/monomorphic.hpp> #include <boost/test/data/monomorphic/generators/xrange.hpp> #include <boost/test/data/test_case.hpp> #include <chrono> #include <cmath> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <utility> #include <vector> using namespace o2::mch::mapping; using namespace o2::mch::contour; using Area=std::pair<bool, AliMpArea>; std::ostream &operator<<(ostream &os, const Area &a) { os << a.first << " | " << a.second; return os; } class area_dataset { public: enum { arity = 1 }; area_dataset(std::vector<AliMpArea> areas) : mAreas{areas} {} std::vector<AliMpArea> mAreas; boost::unit_test::data::size_t size() const { return mAreas.size(); } using iterator=std::vector<AliMpArea>::const_iterator; // iterator iterator begin() const { return std::begin(mAreas); } }; namespace boost { namespace unit_test { namespace data { namespace monomorphic { // registering area_dataset as a proper dataset template<> struct is_dataset<area_dataset> : ::boost::mpl::true_ { }; } } } } SVGWriter writeSegmentation(const Segmentation &o2Seg, const BBox<double> &box, const BBox<double> &area) { SVGWriter w(box); w.addStyle(svgSegmentationDefaultStyle()); w.addStyle(R"( .area { fill:yellow; stroke-width:0.075px; stroke: red; opacity: 0.4; } } )"); svgSegmentation(o2Seg, w, true, true, true, false); w.svgGroupStart("area"); w.box(area.xmin(), area.ymin(), area.width(), area.height()); w.svgGroupEnd(); return w; } BOOST_AUTO_TEST_SUITE(o2_mch_mapping) BOOST_FIXTURE_TEST_SUITE(segmentationvsaliroot, MAPPING) AliMpArea shrink(const AliMpArea &area, double offset = 1E-5) { return { area.GetPositionX(), area.GetPositionY(), area.GetDimensionX() - offset, area.GetDimensionY() - offset, }; } void dumpToFile(const std::string &fileName, const Segmentation &o2Seg, const AliMpArea &area) { std::ofstream out(fileName); auto bbox = getBBox(o2Seg); BBox<double> barea{ area.GetPositionX() - area.GetDimensionX(), area.GetPositionY() - area.GetDimensionY(), area.GetPositionX() + area.GetDimensionX(), area.GetPositionY() + area.GetDimensionY() }; SVGWriter w = writeSegmentation(o2Seg, bbox, barea); std::vector<std::pair<double, double>> pads; o2Seg.forEachPadInArea(barea.xmin(), barea.ymin(), barea.xmax(), barea.ymax(), [&o2Seg, &pads](int paduid) { pads.push_back(std::make_pair(o2Seg.padPositionX(paduid), o2Seg.padPositionY(paduid))); }); w.svgGroupStart("testpoints"); w.points(pads); w.svgGroupEnd(); w.writeHTML(out); } /// Compare pads within a given area /// /// area is given relative to center for all detection elements /// bool comparePadsInArea(AliMpSegmentation *mseg, int detElemId, bool isBendingPlane, AliMpArea area) { const AliMpVSegmentation *alSeg = alirootSegmentation(mseg, detElemId, isBendingPlane); if (!area.IsValid()) { if (detElemId < 500) { area = AliMpArea(alSeg->GetPositionX() + alSeg->GetDimensionX(), alSeg->GetPositionY() + alSeg->GetDimensionY(), alSeg->GetDimensionX(), alSeg->GetDimensionY()); } else { area = AliMpArea(alSeg->GetPositionX() - alSeg->GetDimensionX(), alSeg->GetPositionY() - alSeg->GetDimensionY(), alSeg->GetDimensionX(), alSeg->GetDimensionY()); } } // in order to put aside precision differences between aliroot and o2, we // shrink a bit the area. Kind of cheating, but the point here is not // to reproduce aliroot 100% area = shrink(area); std::unique_ptr<AliMpVPadIterator> it{alSeg->CreateIterator(area)}; it->First(); std::vector<AliMpPad> alPads; while (!it->IsDone()) { AliMpPad pad = it->CurrentItem(); alPads.push_back(pad); it->Next(); } o2::mch::mapping::Segmentation o2Seg(detElemId, isBendingPlane); std::vector<int> o2Pads; o2Seg.forEachPadInArea(area.LeftBorder(), area.DownBorder(), area.RightBorder(), area.UpBorder(), [&o2Pads](int paduid) { o2Pads.push_back(paduid); }); if (alPads.size() != o2Pads.size()) { static int n{0}; std::cout << "+++ alPads.size()= " << alPads.size() << " o2Pads.size()= " << o2Pads.size() << "\n"; dumpToFile( "bug-pia-" + std::to_string(detElemId) + "-" + (isBendingPlane ? "B" : "NB") + "-" + std::to_string(n++) + ".html", o2Seg, area); } return alPads.size() == o2Pads.size(); } BOOST_DATA_TEST_CASE(SamePadsInAreaSt12, boost::unit_test::data::make({ AliMpArea{0.0, 0.0, 0.0, 0.0} /*AliMpArea{40.0, 40.0, 10.0, 10.0},*/ /*AliMpArea{60, 60, 20, 20},*/ /*AliMpArea{10,10,7,7}*/ }) * boost::unit_test::data::make(MAPPING::st12DetElemIds) * boost::unit_test::data::make({true,false}), area, detElemId, isBendingPlane) { BOOST_TEST(comparePadsInArea(mseg, detElemId, isBendingPlane, area)); } BOOST_DATA_TEST_CASE(SamePadsInAreaSt345, boost::unit_test::data::make({ AliMpArea{0.0, 0.0, 0.0, 0.0} /*AliMpArea{2.3, -5.5, 3.0, 20.0},*/ /*AliMpArea{2.3, 15.25, 3.5, 2.4}*/ // AliMpArea{0.0,0.0,50.0,10.0}, /* fully contained */ // AliMpArea{-30.0,0.0,50.0,10.0}, /* overflow left */ // AliMpArea{0.0,-15.0,50.0,10.0}, /* overflow top */ // AliMpArea{0.0,15.0,50.0,10.0}, /* overflow bottom */ // AliMpArea{-30.0,15.0,50.0,10.0}, /* overflow bottom-left */ // AliMpArea{-30.0,-15.0,50.0,10.0}, /* overflow top-left */ /// AliMpArea{30.0,0.0,50.0,10.0}, /* overflow right */ //AliMpArea{30.0,-15.0,50.0,10.0}, /* overflow top-right */ //AliMpArea{30.0,15.0,50.0,10.0} /* overflow bottom-right */ }) * boost::unit_test::data::make(MAPPING::st345DetElemIds) * boost::unit_test::data::make({true,false}), area, detElemId, isBendingPlane) { BOOST_TEST(comparePadsInArea(mseg, detElemId, isBendingPlane, area)); } BOOST_AUTO_TEST_SUITE_END() BOOST_AUTO_TEST_SUITE_END()
88cc6c3e618b5b61b32e09f1609fa7ea53a0787a
b7302b693143b939ba2a2637629ad2be6870096c
/01_Basics/0011_ConstDataType.cpp
31caa502a122d1452857bd5c95f143bbfd24f89e
[]
no_license
abdulhathidev/CPlusPlus
832f18e2f907315be961be60c6bdcd73eb1161d3
69584a4691bc00642ccdbf7e3d82de716d853c6c
refs/heads/master
2021-02-17T13:12:53.288195
2020-05-15T07:35:19
2020-05-15T07:35:19
245,099,542
0
0
null
null
null
null
UTF-8
C++
false
false
414
cpp
0011_ConstDataType.cpp
#include <iostream> using namespace std; const int EmployeeNumber = 10; const string EmployeeName = "Abdul Hathi"; const float EmployeeSalary = 10000.112; int main() { cout << "Constant value of Employee Number : " << EmployeeNumber << endl; cout << "Constant value of Employee Name : " << EmployeeName << endl; cout << "Constant value of Employee Salary : " << EmployeeSalary << endl; return 0; }
1ba8d5cb633e256a3bcc8637e729b894889675d0
dca27afb7211da7a919723f6c9ec845b705aa9cd
/src/Model/ReproductionBasic.cpp
f5c27bc35303cccf7241dfc939796227c13464c7
[]
no_license
cuista/MadingleyCPP
a8bc8253cb36a7d201135b14cce02544619aef64
e628e95077ddac5276045b8c630d40a4a6adfbf6
refs/heads/master
2021-01-18T10:12:47.001199
2017-06-29T11:45:03
2017-06-29T11:45:03
84,318,180
1
1
null
2017-06-28T12:42:44
2017-03-08T12:32:10
C++
UTF-8
C++
false
false
10,478
cpp
ReproductionBasic.cpp
#include "ReproductionBasic.h" ReproductionBasic::ReproductionBasic( std::string globalModelTimeStepUnit, bool drawRandomly ) { mTimeUnitImplementation = "month"; mMassRatioThreshold = 1.5; mMassEvolutionProbabilityThreshold = 0.95; mMassEvolutionStandardDeviation = 0.05; mSemelparityAdultMassAllocation = 0.5; // Calculate the scalar to convert from the time step units used by this implementation of dispersal to the global model time step units mDeltaT = mUtilities.ConvertTimeUnits( globalModelTimeStepUnit, mTimeUnitImplementation ); // Set the seed for the random number generator if( drawRandomly ) { unsigned seed = std::chrono::system_clock::now( ).time_since_epoch( ).count( ); mRandomNumber.SetSeed( seed ); } else { mRandomNumber.SetSeed( 4000 ); } } void ReproductionBasic::Run( GridCell& gcl, Cohort* actingCohort, unsigned currentTimestep, ThreadVariables& partial, bool iteroparous, unsigned currentMonth, MadingleyInitialisation& params ) { // Adult non-reproductive biomass lost by semelparous organisms double adultMassLost; // Offspring cohort abundance double offspringCohortAbundance; // Mass ratio of body mass + reproductive mass to adult body mass double currentMassRatio; // Individual body mass including change this time step as a result of other ecological processes double bodyMassIncludingChangeThisTimeStep; // Offspring juvenile and adult body masses std::vector< double > offspringJuvenileAndAdultBodyMasses( 2 ); // Individual reproductive mass including change this time step as a result of other ecological processes double reproductiveMassIncludingChangeThisTimeStep; // Calculate the biomass of an individual in this cohort including changes this time step from other ecological processes bodyMassIncludingChangeThisTimeStep = 0.0; for( auto& Biomass: Cohort::mMassAccounting[ "biomass" ] ) { // Add the delta biomass to net biomass bodyMassIncludingChangeThisTimeStep += Biomass.second; } bodyMassIncludingChangeThisTimeStep += actingCohort->mIndividualBodyMass; // Calculate the reproductive biomass of an individual in this cohort including changes this time step from other ecological processes reproductiveMassIncludingChangeThisTimeStep = 0.0; for( auto& ReproBiomass: Cohort::mMassAccounting[ "reproductivebiomass" ] ) { // Add the delta reproductive biomass to net biomass reproductiveMassIncludingChangeThisTimeStep += ReproBiomass.second; } reproductiveMassIncludingChangeThisTimeStep += actingCohort->mIndividualReproductivePotentialMass; if( actingCohort->mIndividualBodyMass > 1.e-200 ) { // Get the current ratio of total individual mass (including reproductive potential) to adult body mass currentMassRatio = ( bodyMassIncludingChangeThisTimeStep + reproductiveMassIncludingChangeThisTimeStep ) / actingCohort->mAdultMass; // Must have enough mass to hit reproduction threshold criterion, and either (1) be in breeding season, or (2) be a marine cell (no breeding season in marine cells) if( ( currentMassRatio > mMassRatioThreshold ) && ( ( Environment::Get( "Breeding Season", actingCohort->GetCurrentCell( ) ) == 1.0 ) || ( gcl.IsMarine( ) ) ) ) { // Iteroparous and semelparous organisms have different strategies if( iteroparous ) { // Iteroparous organisms do not allocate any of their current non-reproductive biomass to reproduction adultMassLost = 0.0; // Calculate the number of offspring that could be produced given the reproductive potential mass of individuals offspringCohortAbundance = actingCohort->mCohortAbundance * reproductiveMassIncludingChangeThisTimeStep / actingCohort->mJuvenileMass; } else { // Semelparous organisms allocate a proportion of their current non-reproductive biomass (including the effects of other ecological processes) to reproduction adultMassLost = mSemelparityAdultMassAllocation * bodyMassIncludingChangeThisTimeStep; // Calculate the number of offspring that could be produced given the reproductive potential mass of individuals offspringCohortAbundance = ( ( actingCohort->mCohortAbundance ) * ( adultMassLost + reproductiveMassIncludingChangeThisTimeStep ) ) / actingCohort->mJuvenileMass; } // Check that the abundance in the cohort to produce is greater than or equal to zero assert( offspringCohortAbundance >= 0.0 && "Offspring abundance < 0" ); // Get the adult and juvenile masses of the offspring cohort offspringJuvenileAndAdultBodyMasses = GetOffspringCohortProperties( actingCohort, params.mCohortFunctionalGroupDefinitions ); // Update cohort abundance in case juvenile mass has been altered through 'evolution' offspringCohortAbundance = offspringCohortAbundance * ( actingCohort->mJuvenileMass / offspringJuvenileAndAdultBodyMasses[ 0 ] ); // Create the offspring cohort Cohort* OffspringCohort=new Cohort( actingCohort, offspringJuvenileAndAdultBodyMasses[ 0 ], offspringJuvenileAndAdultBodyMasses[ 1 ], offspringJuvenileAndAdultBodyMasses[ 0 ], offspringCohortAbundance, currentTimestep, partial.mNextCohortID ); // Add the offspring cohort to the grid cell cohorts array //cout<<actingCohort->mCurrentCell<<" "<<&gcl<<endl; assert(actingCohort->mCurrentCell==&gcl); GridCell::mNewCohorts.push_back( OffspringCohort ); // Subtract all of the reproductive potential mass of the parent cohort, which has been used to generate the new // cohort, from the delta reproductive potential mass and delta adult body mass Cohort::mMassAccounting[ "reproductivebiomass" ][ "reproduction" ] -= reproductiveMassIncludingChangeThisTimeStep; Cohort::mMassAccounting[ "biomass" ][ "reproduction" ] -= adultMassLost; } else { // Organism is not large enough, or it is not the breeding season, so take no action } } } void ReproductionBasic::MassAssignment( GridCell& gcl, Cohort* actingCohort, unsigned currentTimestep, MadingleyInitialisation& params ) { // Biomass per individual in each cohort to be assigned to reproductive potential double BiomassToAssignToReproductivePotential; // Net biomass change from other ecological functions this time step double NetBiomassFromOtherEcologicalFunctionsThisTimeStep; // Reset variable holding net biomass change of individuals in this cohort as a result of other ecological processes NetBiomassFromOtherEcologicalFunctionsThisTimeStep = 0.0; // Loop over all items in the biomass deltas for( auto Biomass: Cohort::mMassAccounting[ "biomass" ] ) { // Add the delta biomass to net biomass NetBiomassFromOtherEcologicalFunctionsThisTimeStep += Biomass.second; } // If individual body mass after the addition of the net biomass from processes this time step will yield a body mass // greater than the adult body mass for this cohort, then assign the surplus to reproductive potential if( ( actingCohort->mIndividualBodyMass + NetBiomassFromOtherEcologicalFunctionsThisTimeStep ) > actingCohort->mAdultMass ) { // Calculate the biomass for each individual in this cohort to be assigned to reproductive potential BiomassToAssignToReproductivePotential = actingCohort->mIndividualBodyMass + NetBiomassFromOtherEcologicalFunctionsThisTimeStep - actingCohort->mAdultMass; // Check that a positive biomass is to be assigned to reproductive potential assert( BiomassToAssignToReproductivePotential >= 0.0 && "Assignment of negative reproductive potential mass" ); // If this is the first time reproductive potential mass has been assigned for this cohort, // then set the maturity time step for this cohort as the current model time step if( actingCohort->mMaturityTimeStep == std::numeric_limits< unsigned >::max( ) ) { actingCohort->mMaturityTimeStep = currentTimestep; } // Assign the specified mass to reproductive potential mass and remove it from individual biomass Cohort::mMassAccounting[ "reproductivebiomass" ][ "reproduction" ] += BiomassToAssignToReproductivePotential; Cohort::mMassAccounting[ "biomass" ][ "reproduction" ] -= BiomassToAssignToReproductivePotential; } else { // Cohort has not gained sufficient biomass to assign any to reproductive potential, so take no action } } std::vector< double > ReproductionBasic::GetOffspringCohortProperties( Cohort* actingCohort, FunctionalGroupDefinitions& cohortDefinitions ) { // A two-element vector holding adult and juvenile body masses in elements zero and one respectively std::vector< double > cohortJuvenileAdultMasses( 2 ); // Determine whether offspring cohort 'evolves' in terms of adult and juvenile body masses double RandomValue = mRandomNumber.GetUniform( ); if( RandomValue > mMassEvolutionProbabilityThreshold ) { // Determine the new juvenile body mass // MB correctly formulated? double RandomValueJ = mRandomNumber.GetNormal( actingCohort->mJuvenileMass, mMassEvolutionStandardDeviation * actingCohort->mJuvenileMass ); cohortJuvenileAdultMasses[ 0 ] = std::max( RandomValueJ, cohortDefinitions.GetBiologicalPropertyOneFunctionalGroup( "Minimum mass", actingCohort->mFunctionalGroupIndex ) ); // Determine the new adult body mass double RandomValueA = mRandomNumber.GetNormal( actingCohort->mAdultMass, mMassEvolutionStandardDeviation * actingCohort->mAdultMass ); cohortJuvenileAdultMasses[ 1 ] = std::min( RandomValueA, cohortDefinitions.GetBiologicalPropertyOneFunctionalGroup( "Maximum mass", actingCohort->mFunctionalGroupIndex ) ); } else { // If not, it just gets the same values as the parent cohort // Assign masses to the offspring cohort that are equal to those of the parent cohort cohortJuvenileAdultMasses[ 0 ] = actingCohort->mJuvenileMass; cohortJuvenileAdultMasses[ 1 ] = actingCohort->mAdultMass; } // Return the vector of adult and juvenile masses return cohortJuvenileAdultMasses; }
1ce630fb48e25a5613bb05d7f8b30966544d3ce1
c6d20b3e03270a97d6836bcb246f3e3e21388a7b
/luogu/13.cpp
783d07f21e21c1249121e4d5bc0f9a279ddf92ac
[]
no_license
CaiapoZ/Comade
68d9fa40e21b09cd598f54695f791fac5717f5cc
9750463ffaa220edbb3b0d1a925790345318a3fa
refs/heads/master
2023-07-26T16:43:08.571867
2021-09-04T11:03:12
2021-09-04T11:03:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
354
cpp
13.cpp
#include<stdio.h> int main() { int L,M,n,N=0,i; scanf("%d %d\n",&L,&M); int a[200],b[10001]; for(i=0;i<=L;i++) { b[i]=i; } for(n=1;n<=M;n++) { scanf("%d %d",&a[n*2-2],&a[n*2-1]); for(i=0;i<=L-1;i++) { if(b[i]>=a[n*2-2]&&b[i]<=a[n*2-1]) { N++; b[i]=L+1; } } } printf("%d",L+1-N); return 0; }
6d43533b80ac32492bb1c048e55350300c1485c2
2a9bb2479249dcc311dc437efdaf365f827e7cb2
/IfcPlusPlus/src/ifcpp/IFC4X3/lib/IfcMetric.cpp
39b4d25e2f805e9c94e146547f20ea27f29c149e
[ "MIT" ]
permissive
ifcquery/ifcplusplus
b889ea11bac77e34ef19c4561b24b4ac30389703
d28b77d85ed45d3da5a674ee3d3ebee88e681717
refs/heads/master
2023-08-21T21:23:49.859570
2023-08-04T15:37:54
2023-08-04T15:37:54
33,250,365
540
240
MIT
2023-08-04T14:04:20
2015-04-01T13:53:19
C++
UTF-8
C++
false
false
5,058
cpp
IfcMetric.cpp
/* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */ #include "ifcpp/model/AttributeObject.h" #include "ifcpp/model/BuildingException.h" #include "ifcpp/model/BuildingGuid.h" #include "ifcpp/reader/ReaderUtil.h" #include "ifcpp/writer/WriterUtil.h" #include "ifcpp/IFC4X3/include/IfcActorSelect.h" #include "ifcpp/IFC4X3/include/IfcBenchmarkEnum.h" #include "ifcpp/IFC4X3/include/IfcConstraintEnum.h" #include "ifcpp/IFC4X3/include/IfcDateTime.h" #include "ifcpp/IFC4X3/include/IfcExternalReferenceRelationship.h" #include "ifcpp/IFC4X3/include/IfcLabel.h" #include "ifcpp/IFC4X3/include/IfcMetric.h" #include "ifcpp/IFC4X3/include/IfcMetricValueSelect.h" #include "ifcpp/IFC4X3/include/IfcReference.h" #include "ifcpp/IFC4X3/include/IfcResourceConstraintRelationship.h" #include "ifcpp/IFC4X3/include/IfcText.h" // ENTITY IfcMetric IFC4X3::IfcMetric::IfcMetric( int tag ) { m_tag = tag; } void IFC4X3::IfcMetric::getStepLine( std::stringstream& stream, size_t precision ) const { stream << "#" << m_tag << "= IFCMETRIC" << "("; if( m_Name ) { m_Name->getStepParameter( stream, false, precision ); } else { stream << "$"; } stream << ","; if( m_Description ) { m_Description->getStepParameter( stream, false, precision ); } else { stream << "$"; } stream << ","; if( m_ConstraintGrade ) { m_ConstraintGrade->getStepParameter( stream, false, precision ); } else { stream << "$"; } stream << ","; if( m_ConstraintSource ) { m_ConstraintSource->getStepParameter( stream, false, precision ); } else { stream << "$"; } stream << ","; if( m_CreatingActor ) { m_CreatingActor->getStepParameter( stream, true, precision ); } else { stream << "$" ; } stream << ","; if( m_CreationTime ) { m_CreationTime->getStepParameter( stream, false, precision ); } else { stream << "$"; } stream << ","; if( m_UserDefinedGrade ) { m_UserDefinedGrade->getStepParameter( stream, false, precision ); } else { stream << "$"; } stream << ","; if( m_Benchmark ) { m_Benchmark->getStepParameter( stream, false, precision ); } else { stream << "$"; } stream << ","; if( m_ValueSource ) { m_ValueSource->getStepParameter( stream, false, precision ); } else { stream << "$"; } stream << ","; if( m_DataValue ) { m_DataValue->getStepParameter( stream, true, precision ); } else { stream << "$" ; } stream << ","; if( m_ReferencePath ) { stream << "#" << m_ReferencePath->m_tag; } else { stream << "$"; } stream << ");"; } void IFC4X3::IfcMetric::getStepParameter( std::stringstream& stream, bool /*is_select_type*/, size_t /*precision*/ ) const { stream << "#" << m_tag; } void IFC4X3::IfcMetric::readStepArguments( const std::vector<std::string>& args, const std::map<int,shared_ptr<BuildingEntity> >& map, std::stringstream& errorStream ) { const size_t num_args = args.size(); if( num_args > 0 ){m_Name = IfcLabel::createObjectFromSTEP( args[0], map, errorStream );} if( num_args > 1 ){m_Description = IfcText::createObjectFromSTEP( args[1], map, errorStream );} if( num_args > 2 ){m_ConstraintGrade = IfcConstraintEnum::createObjectFromSTEP( args[2], map, errorStream );} if( num_args > 3 ){m_ConstraintSource = IfcLabel::createObjectFromSTEP( args[3], map, errorStream );} if( num_args > 4 ){m_CreatingActor = IfcActorSelect::createObjectFromSTEP( args[4], map, errorStream );} if( num_args > 5 ){m_CreationTime = IfcDateTime::createObjectFromSTEP( args[5], map, errorStream );} if( num_args > 6 ){m_UserDefinedGrade = IfcLabel::createObjectFromSTEP( args[6], map, errorStream );} if( num_args > 7 ){m_Benchmark = IfcBenchmarkEnum::createObjectFromSTEP( args[7], map, errorStream );} if( num_args > 8 ){m_ValueSource = IfcLabel::createObjectFromSTEP( args[8], map, errorStream );} if( num_args > 9 ){m_DataValue = IfcMetricValueSelect::createObjectFromSTEP( args[9], map, errorStream );} if( num_args > 10 ){readEntityReference( args[10], m_ReferencePath, map, errorStream );} if( num_args != 11 ){ errorStream << "Wrong parameter count for entity IfcMetric, expecting 11, having " << num_args << ". Entity ID: " << m_tag << std::endl; } } void IFC4X3::IfcMetric::getAttributes( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes ) const { IFC4X3::IfcConstraint::getAttributes( vec_attributes ); vec_attributes.emplace_back( std::make_pair( "Benchmark", m_Benchmark ) ); vec_attributes.emplace_back( std::make_pair( "ValueSource", m_ValueSource ) ); vec_attributes.emplace_back( std::make_pair( "DataValue", m_DataValue ) ); vec_attributes.emplace_back( std::make_pair( "ReferencePath", m_ReferencePath ) ); } void IFC4X3::IfcMetric::getAttributesInverse( std::vector<std::pair<std::string, shared_ptr<BuildingObject> > >& vec_attributes_inverse ) const { IFC4X3::IfcConstraint::getAttributesInverse( vec_attributes_inverse ); } void IFC4X3::IfcMetric::setInverseCounterparts( shared_ptr<BuildingEntity> ptr_self_entity ) { IfcConstraint::setInverseCounterparts( ptr_self_entity ); } void IFC4X3::IfcMetric::unlinkFromInverseCounterparts() { IfcConstraint::unlinkFromInverseCounterparts(); }
5e386c21ce3514efe52069228cda73d47280ea32
0acf61a9a7ad69d015462fb5e8ee7ae19ed19903
/RotateString.cpp
d2a39c398f5ca12accce3b9f008023f14ee489db
[]
no_license
AntoniaReiter/OOP_Labor
215ee155f60eb1d76bbcc809af6f9aaaa588f054
ec82f6ee53c0fd7da64b8e766bcb62a63af5fe2e
refs/heads/master
2020-12-27T08:29:42.725026
2020-09-14T11:34:54
2020-09-14T11:34:54
237,833,774
0
0
null
null
null
null
UTF-8
C++
false
false
534
cpp
RotateString.cpp
#include "pch.h" #include <iostream> #include <iomanip> #include <sstream> #include <string> std::string operator<< (std::string input, int range){ return input.substr(range) + input.substr(0, range); } std::string operator>>(std::string input, int range) { return input.substr(input.size() - range, range) + input.substr(0, input.size() - range); } int main() { std::string input = "LET IT SNOW"; std::cout << std::quoted(input << 3) << '\n'; // " IT SNOWLET" std::cout << std::quoted(input >>10) <<'\n'; // "ET IT SNOWL" }
7486b2de0145576bed709b2d187b046080c400e8
c30372c629e177c61bf48176826565fd33bfd42d
/SSD/Action.h
0b6b62d8f0f1b6fa2912853637bd1bd8062bd3d0
[]
no_license
Aspenka/SSD
49140df352d81178f39f20a97435b3666568ba94
7d08ee76b88808ab801c607d3cc1363fa12b0eb6
refs/heads/master
2021-01-17T07:10:08.372171
2016-06-06T14:05:59
2016-06-06T14:05:59
55,404,307
0
0
null
null
null
null
UTF-8
C++
false
false
274
h
Action.h
#ifndef ACTION_H #define ACTION_H #include <QObject> class Action : public QObject { Q_OBJECT public: explicit Action(QObject *parent = 0); ~Action(); virtual void execute() = 0; protected: QString name; signals: public slots: }; #endif // ACTION_H
1aa1e8e5b82901f1d9bf50d3ec180f952040fa89
c040cdf326641565ab4e03c683aca331c29a7005
/UVaSolved/Volume 101/10189.cpp
1c617be1f71e31901d92bf7156401795b74604e8
[]
no_license
kmsabrin/UVaSolved
ff789d233b8116effc9afbacb1e4c5b6cc58beaa
051d648c4c9dff95bd4fbebf0ad2a7358ebccb54
refs/heads/master
2020-07-02T04:31:26.074061
2014-08-27T05:37:36
2014-08-27T05:37:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,217
cpp
10189.cpp
From apache@acm.uva.es Tue Apr 6 20:02:46 2004 Received: from acm.localnet (web.localnet [192.168.10.200]) by acm.uva.es (8.11.6/8.11.6) with ESMTP id i36I2kW21484 for <judge@juez.localnet>; Tue, 6 Apr 2004 20:02:46 +0200 Received: by acm.localnet (Postfix) id EC92510129; Tue, 6 Apr 2004 20:02:46 +0200 (CEST) Delivered-To: judge@acm.uva.es Received: by acm.localnet (Postfix, from userid 81) id EAF49100FD; Tue, 6 Apr 2004 20:02:46 +0200 (CEST) To: judge@acm.uva.es Subject: Problem 10189 From: nobody@nobody.acm.uva.es Reply-To: nobody@nobody.acm.uva.es Message-Id: <20040406180246.EAF49100FD@acm.localnet> Date: Tue, 6 Apr 2004 20:02:46 +0200 (CEST) /* @JUDGE_ID: 34556CP 10189 C++ "" */ /** Submited via Valladolid ACM Online Judge Submit page v6.00 **/ /** IP: 202.22.204.35 - CRC: F93A547 **/ /** Date: 2004-04-06 20:02:46 +0200 **/ @BEGIN_OF_SOURCE_CODE #include<stdio.h> char a[1001][111]; int n, m; int check( int i, int j) { if( i >= 0 && i < n && j >= 0 && j < m ) return 1; return 0; } int mine( int i, int j) { int mines; mines = 0; if( check( i, j + 1 ) ) if( a[i][j + 1] == '*') mines++; if( check( i, j - 1) ) if( a[i][j - 1] == '*') mines++; if( check( i - 1, j) ) if( a[i - 1][j] == '*') mines++; if( check( i - 1, j - 1 ) ) if( a[i - 1][j - 1] == '*') mines++; if( check( i - 1, j + 1) ) if( a[i - 1][j + 1] == '*') mines++; if( check( i + 1, j) ) if( a[i + 1][j] == '*') mines++; if( check( i + 1, j + 1 ) ) if( a[i + 1][j + 1] == '*') mines++; if( check( i + 1, j - 1 ) ) if( a[i + 1][j - 1] == '*') mines++; return mines; } int main() { int i, j, k, num, f; num = 1, f = 0; //freopen("always.in", "r", stdin); while( scanf( "%d %d", &n, &m) && n && m ) { getchar(); if( f == 1 ) printf("\n\n"); f = 1; for( i = 0; i < n; i++ ) gets( a[i] ); /* i IS ROW VALUE, j IS COLUMN VALUE */ for( i = 0; i < n; i++) for( j = 0; j < m; j++) if( a[i][j] == '.') { k = mine( i, j ); a[i][j] = k + 48; //printf("%d %d\n",i,j); } printf( "Field #%d:\n", num ); num++; printf( "%s", a[0] ); for( i = 1; i < n; i++) printf( "\n%s", a[i] ); } return 0; } @END_OF_SOURCE_CODE
a6dfdf0e3226602c57adcc73c6eecca08712cf2f
2875e427d9931ab8cfe2e066e1568c3130fcc3f2
/Solaris_2.6/os_net/src_ws/usr/src/cmd/rpcsvc/nis/rpc.nisd/nis_cc_main.cc
e94d987fa3afb827da3610e88377cef6c598e8c1
[]
no_license
legacy-codedigger/Solaris-2.6-Source-Code
3afaff70487fb96c864d55bd5845dd11c6c5c871
60a0b3093caa7d84e63dd891a23df0e8e720bf3d
refs/heads/master
2022-05-23T16:05:32.631954
2020-04-25T01:07:08
2020-04-25T01:07:08
258,658,903
1
1
null
null
null
null
UTF-8
C++
false
false
404
cc
nis_cc_main.cc
#pragma ident "@(#)nis_cc_main.cc 1.3 92/07/17 SMI" /* * This is needed to to satisfy the C++ system that needs the main * routine to be compiled with C++ compiler if you link with a library * that has C++ code and static intializers. * */ extern "C" { actual_main(int, char**); } main(int argc, char*argv[]) { /* call the actual main() routine in zns_main.c */ actual_main(argc, argv); }
29769122ae3bf9886f7c5ffca925e499b181e811
c39f0eb0dd081ec70721f30b74fe42dcd92bc486
/Arek_przyklady/Przykład_11_deduction_all_or_nothing_1/deduction_all_or_nothing_1.cpp
d3c1797b8713ec01d331356e0e2445c3223108a5
[ "MIT" ]
permissive
WektorZabrze/ADV_29_11_2018
925e0452a0bf5df7a80eb1a0ad4ff33df6546345
afab03af53cfd47b0cb67c60280259bef2ce1c96
refs/heads/master
2020-04-08T19:31:55.594554
2019-02-22T10:40:59
2019-02-22T10:40:59
159,659,561
0
0
null
null
null
null
UTF-8
C++
false
false
1,375
cpp
deduction_all_or_nothing_1.cpp
/** * Przykład numer 5 do automatycznej dedukcji typów w szablonach klas * * Dedukcja dla szablonow dziala na zasadzie "all or nothing" - mozemy * podac pomiedzy <> wszystkie typy, albo ŻADEN * * Nie mozna podać np połowy typów - no chyba ze mamy szablon z typami domyslnymi * to wtedy te mozna pominac */ #include <iostream> #include <tuple> #include <string> int main() { using namespace std::string_literals; /// Tak jak ponizej jest ok, ale w starym stylu std::tuple<std::string, double, int> a ("Student A"s, 2, 4.0); std::cout << "Name = " << std::get<0>(a) << "\n" << "Year = " << std::get<1>(a) << "\n" << "Grade = " << std::get<2>(a) << std::endl; /// W przykladzie powyzej podajemy wszystkie argumenty /// Mozna tez zrobic tak - i tu korzystamy z C++17: std::tuple b {"Student B"s, 3, 5.0}; std::cout << "Name = " << std::get<0>(b) << "\n" << "Year = " << std::get<1>(b) << "\n" << "Grade = " << std::get<2>(b) << std::endl; /// Tutaj zaś nie podalismy nic - jest to w zgodzie z zasada "all or nothing" /// Ponizszy przyklad natomiast juz nie zadziala: ///std::tuple<std::string, int> c {"Student C"s, 3, 2.0}; /// Podobnie jak ponizszy: ///std::tuple<std::string> c {"Student C"s, 3, 2.0}; }