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
5a6ee71bd93d633c7bf21b3b7a825f1eded97f7d
a40e16f79c0fdb192ea1b0120448e16837f40e12
/code/shaderc/singleshadercompiler.cc
7bbfdf7fa1d1e89f0cd4614fce7d7389b2e29d59
[]
no_license
gscept/nebula-toolkit
725a194484f93a7eea321249ab97870cd0c4d7f1
c91a046c93a694f839b783817c863f59667ac81e
refs/heads/master
2022-05-20T09:11:42.200340
2022-04-22T15:47:47
2022-04-22T15:47:47
281,916,112
0
2
null
null
null
null
UTF-8
C++
false
false
11,460
cc
singleshadercompiler.cc
//------------------------------------------------------------------------------ // shaderc.cc // (C) 2018-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "singleshadercompiler.h" #include "io/ioserver.h" #include "coregraphics/config.h" #include "app/application.h" #include "toolkit-common/converters/binaryxmlconverter.h" #if __ANYFX__ #include "afxcompiler.h" #endif using namespace Util; using namespace IO; namespace ToolkitUtil { //------------------------------------------------------------------------------ /** */ SingleShaderCompiler::SingleShaderCompiler() : language("SPIRV"), platform(Platform::Win32), debug(false), quiet(false) { // empty } //------------------------------------------------------------------------------ /** */ SingleShaderCompiler::~SingleShaderCompiler() { // empty } //------------------------------------------------------------------------------ /** */ bool SingleShaderCompiler::CompileShader(const Util::String& src) { if (!this->dstDir.IsValid()) { n_printf("shaderc error: No destination for shader compile"); return false; } if (!this->headerDir.IsValid()) { n_printf("shaderc error: No header output folder for shader compile"); return false; } const Ptr<IoServer>& ioServer = IoServer::Instance(); // check if source if (!ioServer->FileExists(src)) { n_printf("[shaderc] error: shader source '%s' not found!\n", src.AsCharPtr()); return false; } // make sure the target directory exists ioServer->CreateDirectory(this->dstDir + "/shaders"); ioServer->CreateDirectory(this->headerDir); // attempt compile base shaders bool retval = false; if (this->language == "GLSL") { retval = this->CompileGLSL(src); } else if (this->language == "SPIRV") { retval = this->CompileSPIRV(src); } return retval; } //------------------------------------------------------------------------------ /** */ bool SingleShaderCompiler::CompileFrameShader(const Util::String& srcf) { const Ptr<IoServer>& ioServer = IoServer::Instance(); // check if source dir exists if (!ioServer->FileExists(URI(srcf))) { n_printf("[shaderc] error: frame shader source '%s' not found!\n", srcf.AsCharPtr()); return false; } // make sure target dir exists Util::String frameDest = this->dstDir + "/frame/"; ioServer->CreateDirectory(frameDest); frameDest.Append(srcf.ExtractFileName()); ioServer->CopyFile(srcf, frameDest); n_printf("[shaderc] Converted base frame script:\n %s ---> %s \n", srcf.AsCharPtr(), frameDest.AsCharPtr()); return true; } //------------------------------------------------------------------------------ /** */ bool SingleShaderCompiler::CompileMaterial(const Util::String & srcf) { const Ptr<IoServer>& ioServer = IoServer::Instance(); // create converter BinaryXmlConverter converter; ToolkitUtil::Logger logger; logger.SetVerbose(false); converter.SetPlatform(Platform::Win32); // make sure output exists Util::String destDir = this->dstDir + "/materials"; ioServer->CreateDirectory(destDir); Util::String dest = destDir + "/" + srcf.ExtractFileName(); URI src(srcf); URI dst(dest); Logger dummy; // convert to binary xml n_printf("[shaderc] Converting base material template table:\n %s ---> %s \n", src.LocalPath().AsCharPtr(), dst.LocalPath().AsCharPtr()); return converter.ConvertFile(srcf, dest, dummy); } //------------------------------------------------------------------------------ /** Implemented using AnyFX */ bool SingleShaderCompiler::CompileGLSL(const Util::String& srcf) { const Ptr<IoServer>& ioServer = IoServer::Instance(); #ifndef __ANYFX__ n_printf("Error: Cannot compile DX11 shaders without DX11 support\n"); return false; #endif #if __ANYFX__ // start AnyFX compilation AnyFXBeginCompile(); Util::String file = srcf.ExtractFileName(); file.StripFileExtension(); // format destination String destFile = this->dstDir + "/shaders/" + file; URI src(srcf); URI dst(destFile); // compile n_printf("[shaderc] Compiling:\n %s -> %s\n", src.LocalPath().AsCharPtr(), dst.LocalPath().AsCharPtr()); std::vector<std::string> defines; std::vector<std::string> flags; Util::String define; define.Format("-D GLSL"); defines.push_back(define.AsCharPtr()); // first include this folder define.Format("-I%s/", URI(srcf).LocalPath().AsCharPtr()); defines.push_back(define.AsCharPtr()); for (auto inc = this->includeDirs.Begin(); inc != this->includeDirs.End(); inc++) { define.Format("-I%s/", URI(*inc).LocalPath().AsCharPtr()); defines.push_back(define.AsCharPtr()); } // set flags flags.push_back("/NOSUB"); // deactivate subroutine usage flags.push_back("/GBLOCK"); // put all shader variables outside of explicit buffers in one global block // if using debug, output raw shader code if (!this->debug) { flags.push_back("/O"); } AnyFXErrorBlob* errors = NULL; // this will get the highest possible value for the GL version, now clamp the minor and major to the one supported by glew int major = 4; int minor = 4; Util::String target; target.Format("gl%d%d", major, minor); Util::String escapedSrc = src.LocalPath(); Util::String escapedDst = dst.LocalPath(); bool res = AnyFXCompile(escapedSrc.AsCharPtr(), escapedDst.AsCharPtr(), target.AsCharPtr(), nullptr, "Khronos", defines, flags, &errors); if (!res) { if (errors) { n_printf("%s\n", errors->buffer); delete errors; errors = 0; } return false; } else if (errors) { n_printf("%s\n", errors->buffer); delete errors; errors = 0; } // stop AnyFX compilation AnyFXEndCompile(); #else #error "No GLSL compiler implemented! (use definition __ANYFX__ to fix this)" #endif return true; } //------------------------------------------------------------------------------ /** */ bool SingleShaderCompiler::CompileSPIRV(const Util::String& srcf) { const Ptr<IoServer>& ioServer = IoServer::Instance(); #ifndef __ANYFX__ n_printf("Error: Cannot compile DX11 shaders without DX11 support\n"); return false; #endif #if __ANYFX__ // start AnyFX compilation AnyFXBeginCompile(); Util::String file = srcf.ExtractFileName(); Util::String folder = srcf.ExtractDirName(); file.StripFileExtension(); // format destination String destFile = this->dstDir + "/shaders/" + file + ".fxb"; String destHeader = this->headerDir + "/" + file + ".h"; URI src(srcf); URI dst(destFile); URI dstH(destHeader); // compile n_printf("[shaderc] \n Compiling:\n %s -> %s", src.LocalPath().AsCharPtr(), dst.LocalPath().AsCharPtr()); n_printf(" \n Generating:\n %s -> %s\n", src.LocalPath().AsCharPtr(), dstH.LocalPath().AsCharPtr()); std::vector<std::string> defines; std::vector<std::string> flags; Util::String define; define.Format("-D GLSL"); defines.push_back(define.AsCharPtr()); // first include this folder define.Format("-I%s/", URI(folder).LocalPath().AsCharPtr()); defines.push_back(define.AsCharPtr()); for (auto inc = this->includeDirs.Begin(); inc != this->includeDirs.End(); inc++) { define.Format("-I%s/", URI(*inc).LocalPath().AsCharPtr()); defines.push_back(define.AsCharPtr()); } // set flags flags.push_back("/NOSUB"); // deactivate subroutine usage, effectively expands all subroutines as functions flags.push_back("/GBLOCK"); // put all shader variables outside of an explicit block in one global block flags.push_back(Util::String::Sprintf("/DEFAULTSET %d", NEBULA_BATCH_GROUP).AsCharPtr()); // since we want the most frequently switched set as high as possible, we send the default set to 8, must match the NEBULAT_DEFAULT_GROUP in std.fxh and DEFAULT_GROUP in coregraphics/config.h // if using debug, output raw shader code if (!this->debug) { flags.push_back("/O"); } AnyFXErrorBlob* errors = NULL; // this will get the highest possible value for the GL version, now clamp the minor and major to the one supported by glew int major = 1; int minor = 0; Util::String target; target.Format("spv%d%d", major, minor); Util::String escapedSrc = src.LocalPath(); Util::String escapedDst = dst.LocalPath(); Util::String escapedHeader = dstH.LocalPath(); bool res = AnyFXCompile(escapedSrc.AsCharPtr(), escapedDst.AsCharPtr(), escapedHeader.AsCharPtr(), target.AsCharPtr(), "Khronos", defines, flags, &errors); if (!res) { if (errors) { n_printf("%s\n", errors->buffer); delete errors; errors = 0; } return false; } else if (errors) { n_printf("%s\n", errors->buffer); delete errors; errors = 0; } // stop AnyFX compilation AnyFXEndCompile(); #else #error "No SPIR-V compiler implemented! (use definition __ANYFX__ to fix this)" #endif return true; } //------------------------------------------------------------------------------ /** */ bool SingleShaderCompiler::CreateDependencies(const Util::String& srcf) { const Ptr<IoServer>& ioServer = IoServer::Instance(); #ifndef __ANYFX__ n_printf("Error: Cannot compile DX11 shaders without DX11 support\n"); return false; #endif // start AnyFX compilation //AnyFXBeginCompile(); Util::String file = srcf.ExtractFileName(); Util::String folder = srcf.ExtractDirName(); file.StripFileExtension(); // format destination String destDir = this->dstDir + "/shaders/"; String destFile = destDir + file + ".dep"; URI src(srcf); URI dst(destFile); // compile n_printf("[shaderc] Analyzing:\n %s\n", src.LocalPath().AsCharPtr()); std::vector<std::string> defines; Util::String define; define.Format("-D GLSL"); defines.push_back(define.AsCharPtr()); // first include this folder define.Format("-I%s/", URI(folder).LocalPath().AsCharPtr()); defines.push_back(define.AsCharPtr()); for (auto inc = this->includeDirs.Begin(); inc != this->includeDirs.End(); inc++) { define.Format("-I%s/", URI(*inc).LocalPath().AsCharPtr()); defines.push_back(define.AsCharPtr()); } Util::String escapedSrc = src.LocalPath(); ioServer->CreateDirectory(destDir); Ptr<IO::Stream> output = ioServer->CreateStream(destFile); Ptr<IO::TextWriter> writer = IO::TextWriter::Create(); writer->SetStream(output); if(writer->Open()) { std::vector<std::string> deps = AnyFXGenerateDependencies(escapedSrc.AsCharPtr(), defines); for(auto str : deps) { writer->WriteString(str.c_str()); writer->WriteChar(';'); } writer->Close(); } return true; } } // namespace ToolkitUtil
9ec7a1bea3a11a33afaaf1f28aab4148119debec
2f557f60fc609c03fbb42badf2c4f41ef2e60227
/DQMOffline/Trigger/plugins/DiJetMonitor.h
c282e4c333a45be3b138b31c9f4e11e7beb96f84
[ "Apache-2.0" ]
permissive
CMS-TMTT/cmssw
91d70fc40a7110832a2ceb2dc08c15b5a299bd3b
80cb3a25c0d63594fe6455b837f7c3cbe3cf42d7
refs/heads/TMTT_1060
2020-03-24T07:49:39.440996
2020-03-04T17:21:36
2020-03-04T17:21:36
142,576,342
3
5
Apache-2.0
2019-12-05T21:16:34
2018-07-27T12:48:13
C++
UTF-8
C++
false
false
3,885
h
DiJetMonitor.h
#ifndef DIJETMETMONITOR_H #define DIJETMETMONITOR_H #include <string> #include <vector> #include <map> #include "FWCore/Utilities/interface/EDGetToken.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/ServiceRegistry/interface/Service.h" #include "DQMServices/Core/interface/MonitorElement.h" #include <DQMServices/Core/interface/DQMEDAnalyzer.h> #include "FWCore/ParameterSet/interface/ParameterSetDescription.h" #include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h" #include "FWCore/ParameterSet/interface/Registry.h" #include "DQMOffline/Trigger/plugins/TriggerDQMBase.h" #include "CommonTools/TriggerUtils/interface/GenericTriggerEventFlag.h" #include "CommonTools/Utils/interface/StringCutObjectSelector.h" //DataFormats #include "DataFormats/METReco/interface/PFMET.h" #include "DataFormats/METReco/interface/PFMETCollection.h" #include "DataFormats/JetReco/interface/PFJet.h" #include "DataFormats/JetReco/interface/PFJetCollection.h" #include "DataFormats/JetReco/interface/CaloJet.h" #include "DataFormats/JetReco/interface/CaloJetCollection.h" #include "DataFormats/JetReco/interface/GenJetCollection.h" #include "DataFormats/MuonReco/interface/Muon.h" #include "DataFormats/MuonReco/interface/MuonFwd.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "DataFormats/EgammaCandidates/interface/GsfElectron.h" #include "DataFormats/EgammaCandidates/interface/GsfElectronFwd.h" #include "DataFormats/EgammaCandidates/interface/Photon.h" #include "DataFormats/EgammaCandidates/interface/PhotonFwd.h" class GenericTriggerEventFlag; // // class declaration // class DiJetMonitor : public DQMEDAnalyzer , public TriggerDQMBase { public: DiJetMonitor( const edm::ParameterSet& ); ~DiJetMonitor() throw() override {}; static void fillDescriptions(edm::ConfigurationDescriptions & descriptions); protected: void bookHistograms(DQMStore::IBooker &, edm::Run const &, edm::EventSetup const &) override; void analyze(edm::Event const& iEvent, edm::EventSetup const& iSetup) override; bool dijet_selection(double eta_1, double phi_1, double eta_2, double phi_2, double pt_1, double pt_2, int &tag_id, int &probe_id, int Event); private: std::string folderName_; std::string histoSuffix_; edm::EDGetTokenT<reco::PFMETCollection> metToken_; edm::EDGetTokenT<reco::GsfElectronCollection> eleToken_; edm::EDGetTokenT<reco::MuonCollection> muoToken_; edm::EDGetTokenT<reco::PFJetCollection> dijetSrc_; // test for Jet MEbinning dijetpt_binning_; MEbinning dijetptThr_binning_; ObjME jetpt1ME_; ObjME jetpt2ME_; ObjME jetptAvgaME_; ObjME jetptAvgaThrME_; ObjME jetptAvgbME_; ObjME jetptTagME_; ObjME jetptPrbME_; ObjME jetptAsyME_; ObjME jetetaPrbME_; ObjME jetetaTagME_; ObjME jetphiPrbME_; ObjME jetAsyEtaME_; ObjME jetEtaPhiME_; std::unique_ptr<GenericTriggerEventFlag> num_genTriggerEventFlag_; std::unique_ptr<GenericTriggerEventFlag> den_genTriggerEventFlag_; int nmuons_; double ptcut_; // Define Phi Bin // const double DiJet_MAX_PHI = 3.2; //unsigned int DiJet_N_PHI = 64; unsigned int DiJet_N_PHI = 32; MEbinning dijet_phi_binning{ DiJet_N_PHI, -DiJet_MAX_PHI, DiJet_MAX_PHI }; // Define Eta Bin // const double DiJet_MAX_ETA = 5; //unsigned int DiJet_N_ETA = 50; unsigned int DiJet_N_ETA = 20; MEbinning dijet_eta_binning{ DiJet_N_ETA, -DiJet_MAX_ETA, DiJet_MAX_ETA }; const double MAX_asy = 1; const double MIN_asy = -1; //unsigned int N_asy = 100; unsigned int N_asy = 50; MEbinning asy_binning{ N_asy, MIN_asy, MAX_asy }; }; #endif // DIJETMETMONITOR_H
5cb5350a3bb569127515e439940bf4afafcb7dd6
174bf3a2361e6e50ded3d9fe5cd64baa5bbf122f
/examples/03_httpserver/main.cpp
81d3eb5b5b47545cc04d6fc9e64a4bfb5d522522
[ "MIT" ]
permissive
519984307/qtael
63b4fffb4ba925a60c656992536e13b0d23895f9
c0d943ec298fd2c77cbe659d3dd396439e87f07c
refs/heads/master
2023-03-20T20:01:44.933194
2017-11-30T07:47:08
2017-11-30T07:47:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,209
cpp
main.cpp
#include <QtCore/QCoreApplication> #include <QtCore/QUrl> #include <QtNetwork/QNetworkAccessManager> #include <QtNetwork/QNetworkReply> #include <QtNetwork/QNetworkRequest> #include <QtCore/QtDebug> #include "httpserver.hpp" #include "qtael.hpp" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); auto b = new qtael::Async([](const qtael::Await & await)->void { qDebug() << "wait for http server open ..."; // NOTE yield to main event loop until 1000ms passed await(1000); qDebug() << "make request"; QNetworkAccessManager nasm; QNetworkRequest r(QUrl("http://localhost:1080/")); auto reply = nasm.get(r); // NOTE yield to main event loop until request finished await(reply, &QNetworkReply::finished); auto c = reply->readAll(); qDebug() << c; }); // NOTE when coroutine finished (i.e. reaches end or return), `finished()` emitted b->connect(b, SIGNAL(finished()), SLOT(deleteLater())); a.connect(b, SIGNAL(finished()), SLOT(quit())); b->start(); HttpServer server; bool ok = server.listen(1080); qDebug() << "http server ok:" << ok; return a.exec(); }
42f5aad34ab9cfce7f9e262b432db7f12dc543bf
a090af918e3ec59140027dbddd54aa4ca1c73910
/Uva/10219.cpp
133b9a3d6c32cd0d00fb56ab503a8c852cd81c89
[]
no_license
nitesh-147/Programming-Problem-Solution
b739e2a3c9cfeb2141baf1d34e43eac0435ecb2a
df7d53e0863954ddf358539d23266b28d5504212
refs/heads/master
2023-03-16T00:37:10.236317
2019-11-28T18:11:33
2019-11-28T18:11:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
390
cpp
10219.cpp
#include<bits/stdc++.h> #define LL long long using namespace std; int main() { int i,k,j; int t,n; while(cin>>n>>k) { double sum=0.0; for(i=max(n-k,k)+1; i<=n; i++) sum+=log10(i); for(i=1;i<=min(n-k,k);i++) sum-=log10(i); LL res=floor(sum)+1; cout<<res<<endl; } return 0; } /* 20 5 100 10 200 15 */
04aae6b7749407c7267b8fb881852026f1604490
e37a4775935435eda9f176c44005912253a720d8
/datadriven/src/sgpp/datadriven/application/LearnerSVM.hpp
3d9f22011185c0bc91f5a5c031910a0424890ed2
[]
no_license
JihoYang/SGpp
b1d90d2d9e8f8be0092e1a9fa0f37a5f49213c29
7e547110584891beed194d496e23194dd90ccd20
refs/heads/master
2020-04-25T10:27:58.081281
2018-09-29T19:33:13
2018-09-29T19:33:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,689
hpp
LearnerSVM.hpp
// Copyright (C) 2008-today The SG++ project // This file is part of the SG++ project. For conditions of distribution and // use, please see the copyright notice provided with SG++ or at // sgpp.sparsegrids.org #ifndef LEARNERSVM_HPP #define LEARNERSVM_HPP #include <sgpp/datadriven/application/PrimalDualSVM.hpp> #include <sgpp/base/datatypes/DataMatrix.hpp> #include <sgpp/base/datatypes/DataVector.hpp> #include <sgpp/base/grid/Grid.hpp> #include <sgpp/globaldef.hpp> #include <string> namespace sgpp { namespace datadriven { /** * LearnerSVM learns the data using support vector machines and sparse grid * kernels. * As learning algorithm the Pegasos-method is implemented. */ class LearnerSVM { protected: std::unique_ptr<base::Grid> grid; base::DataMatrix& trainData; base::DataVector& trainLabels; base::DataMatrix& testData; base::DataVector& testLabels; base::DataMatrix* validData; base::DataVector* validLabels; base::RegularGridConfiguration gridConfig; base::AdpativityConfiguration adaptivityConfig; // the svm object std::unique_ptr<PrimalDualSVM> svm; /** * Generates a regular sparse grid. * * @return The created grid */ std::unique_ptr<base::Grid> createRegularGrid(); public: /** * Constructor. * * @param gridConfig The grid configuration * @param adaptConfig The refinement configuration * @param pTrainData The training dataset * @param pTrainLabels The corresponding training labels * @param pTestData The test dataset * @param pTestLabels The corresponding test labels * @param pValidData The validation dataset * @param pValidLabels The corresponding validation labels */ LearnerSVM(base::RegularGridConfiguration& gridConfig, base::AdpativityConfiguration& adaptConfig, base::DataMatrix& pTrainData, base::DataVector& pTrainLabels, base::DataMatrix& pTestData, base::DataVector& pTestLabels, base::DataMatrix* pValidData, base::DataVector* pValidLabels); /** * Destructor. */ ~LearnerSVM(); /** * Initializes the SVM learner. * * @param budget The max. number of stored support vectors */ void initialize(size_t budget); /** * Implements support vector learning with sparse grid kernels. * * @param maxDataPasses The number of passes over the whole training data * @param lambda The regularization parameter * @param betaRef Weighting factor for grid points; used within * combined-measure refinement * @param refType The refinement indicator (surplus, zero-crossings or * data-based) * @param refMonitor The refinement strategy (periodic or convergence-based) * @param refPeriod The refinement interval (if periodic refinement is chosen) * @param errorDeclineThreshold The convergence threshold * (if convergence-based refinement is chosen) * @param errorDeclineBufferSize The number of error measurements which are * used to check * convergence (if convergence-based refinement is chosen) * @param minRefInterval The minimum number of data points which have to be * processed before next refinement can be scheduled (if * convergence-based refinement * is chosen) */ void train(size_t maxDataPasses, double lambda, double betaRef, std::string refType, std::string refMonitor, size_t refPeriod, double errorDeclineThreshold, size_t errorDeclineBufferSize, size_t minRefInterval); /** * Stores classified data, grids and function evaluations to csv files. * * @param testDataset Data points for which the model is evaluated */ void storeResults(sgpp::base::DataMatrix& testDataset); /** * Computes the classification accuracy on the given dataset. * * @param testDataset The data for which class labels should be predicted * @param referenceLabels The corresponding actual class labels * @param threshold The decision threshold (e.g. for class labels -1, 1 -> * threshold = 0) * @return The resulting accuracy */ double getAccuracy(sgpp::base::DataMatrix& testDataset, const sgpp::base::DataVector& referenceLabels, const double threshold); /** * Computes the classification accuracy. * * @param referenceLabels The actual class labels * @param threshold The decision threshold (e.g. for class labels -1, 1 -> * threshold = 0) * @param predictedLabels The predicted class labels * @return The resulting accuracy */ double getAccuracy(const sgpp::base::DataVector& referenceLabels, const double threshold, const sgpp::base::DataVector& predictedLabels); /** * Predicts class labels based on the trained model. * * @param testData The data for which class labels should be predicted * @param predictedLabels The predicted class labels */ void predict(sgpp::base::DataMatrix& testData, sgpp::base::DataVector& predictedLabels); /** * Computes specified error type (e.g. MSE). * * @param data The data points * @param labels The corresponding class labels * @param errorType The type of the error measurement (MSE or Hinge loss) * @return The error estimation */ double getError(sgpp::base::DataMatrix& data, sgpp::base::DataVector& labels, std::string errorType); // The final classification error double error; // A vector to store error evaluations sgpp::base::DataVector avgErrors; }; } // namespace datadriven } // namespace sgpp #endif /* LEARNERSVM_HPP */
bdb83f37f385b1e829ae19574c73fdc02bbf6f57
623c1ed6a1eb86d58eba2bcdb804b33eda6bf0cb
/Cal/Al/spike/IO/MainInputArgs.cpp
17cf9bf42c4043655609bc08f93692f27efd5d01
[]
no_license
yaoguilv/Alex
761321e406b76bf401f725c0b80bc8b9dbb154c4
09ed9410026427fb6d43d130d715c4bbd6137317
refs/heads/master
2021-08-16T15:06:52.417420
2018-09-25T13:03:56
2018-09-25T13:03:56
115,491,760
0
0
null
null
null
null
UTF-8
C++
false
false
261
cpp
MainInputArgs.cpp
#include <iostream> using namespace std; // execute command: bin/ticket dd int main(int argc, char ** argv) { // argv[0] is the program name("ticket") char * a = argv[1]; string b = a; cout << a << endl; cout << b << endl; return 0; }
d82dc70ff4d49f1a5e17086f8289ef5121883330
a60145ce81b297b82d02ca29a684214d64973e65
/src/tactics/rtt_bob/unity.cpp
960a8c3412c982d9e119cf924fa3f097e326e9f2
[]
no_license
RoboTeamTwente/roboteam_tactics
0b28ef41b144b583f2bf04a88aea5cb271a08313
ba5e02464db04db48abdbcb33735dd5abccfbaae
refs/heads/master
2020-03-23T05:12:20.660153
2019-12-30T11:44:35
2019-12-30T11:44:35
69,663,932
0
0
null
null
null
null
UTF-8
C++
false
false
313
cpp
unity.cpp
#include "BestTactic.cpp" #undef RTT_CURRENT_DEBUG_TAG #include "WorstTactic.cpp" #undef RTT_CURRENT_DEBUG_TAG #include "NaiveGetBallWithSupportPlay.cpp" #undef RTT_CURRENT_DEBUG_TAG #include "SingleKeeperPlay.cpp" #undef RTT_CURRENT_DEBUG_TAG #include "old/WeirdTactic.cpp" #undef RTT_CURRENT_DEBUG_TAG
67f3c064bc6a72da0073e4fa7ebde2acf528d88b
a26109e91634197b1ea55c3e936b12bf4ddd2e49
/receiver.ino
b7c953e9cd6b7126133d9215120d2240c02b772c
[]
no_license
Arshiya-R/Arduino-NRF24L01-mod
1557c16c7fcdb64ca693ec9d887f67cda3cae101
1ab43260cb23bc0c0a8fcb25f8781250ab11be0c
refs/heads/master
2020-12-10T13:56:37.497795
2019-10-18T16:37:11
2019-10-18T16:37:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
999
ino
receiver.ino
#include <SPI.h> // Handles communication interface with the modem #include <nRF24L01.h> // Handles nRF24 #include <RF24.h> // Some other controls over radio // RF24 Object // Represents a modem connected to the UNO // 7: CE Signal Port // 8: CSN Signal Port RF24 radio(7,8); // Receiver Address const byte rxAddr[6] = "00001"; void setup() { // Set the serial communication of arduino and the computer // Wait for the USB port switches to serial COM port until we connect USB cable while (!Serial); // Set the bps for USB Serial.begin(9600); // Activate the modem and create the reading pipe radio.begin(); // Stream number is 0 radio.openReadingPipe(0, rxAddr); // Listen radio.startListening(); } void loop() { // Check whether the object is available or not if(radio.available()) { char text[32] = {0}; // Read the data radio.read(&text,sizeof(text)); // Pass the data through the Serial Communication (USB) Serial.println(text); } }
fab1ac66da3494ff78d181664269cb58646ce38e
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-ecs/source/model/ServiceConnectServiceResource.cpp
aa56fc900f065ba477337a98e93f71fdbb3b3ae3
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
1,463
cpp
ServiceConnectServiceResource.cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ecs/model/ServiceConnectServiceResource.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ECS { namespace Model { ServiceConnectServiceResource::ServiceConnectServiceResource() : m_discoveryNameHasBeenSet(false), m_discoveryArnHasBeenSet(false) { } ServiceConnectServiceResource::ServiceConnectServiceResource(JsonView jsonValue) : m_discoveryNameHasBeenSet(false), m_discoveryArnHasBeenSet(false) { *this = jsonValue; } ServiceConnectServiceResource& ServiceConnectServiceResource::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("discoveryName")) { m_discoveryName = jsonValue.GetString("discoveryName"); m_discoveryNameHasBeenSet = true; } if(jsonValue.ValueExists("discoveryArn")) { m_discoveryArn = jsonValue.GetString("discoveryArn"); m_discoveryArnHasBeenSet = true; } return *this; } JsonValue ServiceConnectServiceResource::Jsonize() const { JsonValue payload; if(m_discoveryNameHasBeenSet) { payload.WithString("discoveryName", m_discoveryName); } if(m_discoveryArnHasBeenSet) { payload.WithString("discoveryArn", m_discoveryArn); } return payload; } } // namespace Model } // namespace ECS } // namespace Aws
889fbc287a5011efc20d18f94e5a63bb3063c298
9176cec35f7e4242c5600ec20f9df86d4f0623b3
/USpeak/audiodecoder.cpp
9e0ac753ddeec393929f9d1f5c7dd0ed879bd07a
[]
no_license
krdcl/USpeak
48220716daf64ad7b3747c9d0d9ea09a7c414c05
0b1910bff510962b9cee73ae693f0f0ca8cecd28
refs/heads/master
2021-01-10T08:34:20.726530
2018-09-26T07:23:29
2018-09-26T07:23:29
45,999,762
1
0
null
null
null
null
UTF-8
C++
false
false
1,173
cpp
audiodecoder.cpp
#include "audiodecoder.h" AudioDecoder::AudioDecoder(QObject *parent) : QObject(parent) { QAudioFormat format; // Set up the format, eg. format.setSampleRate(8000); format.setChannelCount(1); format.setSampleSize(8); format.setCodec("audio/pcm"); format.setByteOrder(QAudioFormat::LittleEndian); format.setSampleType(QAudioFormat::UnSignedInt); QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice()); if (!info.isFormatSupported(format)) { qWarning() << "Raw audio format not supported by backend, cannot play audio."; return; } audio_output = new QAudioOutput(format, this); player = new QMediaPlayer(this);\ //input_io = audio_output->start(); //connect(player,SIGNAL()) } AudioDecoder::~AudioDecoder() { } void AudioDecoder::play() { player->play(); } void AudioDecoder::stop() { player->stop(); } void AudioDecoder::setNextContent(QByteArray content) { audio_buffer.setBuffer(&content); player->setMedia(QMediaContent(),&audio_buffer); } void AudioDecoder::playNextContent() { player->setMedia(QMediaContent(), &audio_buffer); player->play(); }
a2ec5103ad4648fb1a89b159be27663d9fcb0eab
dffd7156da8b71f4a743ec77d05c8ba031988508
/ac/abc139/abc139_a/19510374.cpp
a895362b49f022aa0f7e59425e7fa289153cc405
[]
no_license
e1810/kyopro
a3a9a2ee63bc178dfa110788745a208dead37da6
15cf27d9ecc70cf6d82212ca0c788e327371b2dd
refs/heads/master
2021-11-10T16:53:23.246374
2021-02-06T16:29:09
2021-10-31T06:20:50
252,388,049
0
0
null
null
null
null
UTF-8
C++
false
false
151
cpp
19510374.cpp
#include<bits/stdc++.h> int main(){ char s[3], t[3]; scanf("%s %s", s, t); printf("%d ", (s[0]==t[0]) + (s[1]==t[1]) + (s[2]==t[2])); return 0; }
53e0f8c9ea7d19659379cd8a0e87acc2448d5cb6
26524fec2231290c65a0bf126943101bb8b8300c
/3D就活ゲーム制作 - コピー (CameraRange)/GameProgramming/CRaceCourceE.cpp
b12ed5df83bd77bee8362b335a53b0fa11e0f8b1
[]
no_license
programminggp/2DLV1
d424a946fe9f92c15c20a76f5986f19a3bf628f5
fbe8394189431897312e74caf32e500ea2c8cd13
refs/heads/master
2023-09-01T13:38:35.309123
2023-09-01T11:45:01
2023-09-01T11:45:01
176,943,495
2
1
null
2022-05-26T09:56:53
2019-03-21T12:49:43
C
SHIFT_JIS
C++
false
false
4,506
cpp
CRaceCourceE.cpp
#include "CRaceCourceE.h" #include "CObj.h" #include "CObjWall.h" #include "CObjFloor.h" #include "CRoadManager.h" #include "CObjCheckPoint.h" #include "CObjNonCol.h" #include "CObjGrass.h" #include "CObjWater.h" #include "CObjJumper.h" #include "CSceneTitle.h" void CRaceCourceE::Init(){ //シーンの設定 mScene = ERACE5; CSceneRace::Init(); CVector StartPosVec = CVector(-3831.5f, 13.5f, 16011.5f);//スタート位置の基点 CVector StartPosVecs[ENEMYS_AMOUNT + 1];//スタート位置(配列) for (int i = 0; i < LIST_SIZE; i++) { StartPosVecs[i] = StartPosVec + CVector(45.0f*list[i], 0.0f, 60.0f*list[i]); if (list[i] % 2 == 1){ StartPosVecs[i].mX += 80.0f; } } //プレイヤーの生成 mPlayer = new CPlayer(); mPlayer->mpModel = &mCarWhite; //プレイヤーのリスポーンするCheckPointの設定 mPlayer->SetRespawnPoint(0, StartPosVecs[0], CVector(0.0f, -145.0f, 0.0f)); mPlayer->SetRespawnPoint(1, CVector(-16054.4f, 4915.0f, -2180.0f), CVector(0.0f, -174.6f, 0.0f)); mPlayer->SetRespawnPoint(2, CVector(4680.0f, 13.5f, -2027.0f), CVector(0.0f, 147.2f, 0.0f)); mPlayer->SetRespawnPoint(3, CVector(14809.0f, 13.5f, 4270.0f), CVector(0.0f, -9.5f, 0.0f)); mPlayer->GetReady(); //カメラの生成 mCamRange = new CCameraRange(); mCam = new CCameraPos(); //コース全体のサイズ感を設定 float mtsize = 35.0f; float height = 11.0f; new CRoadManager(&mCource05Road, CVector(0.0f, 21.0f, 0.0f), CVector(), CVector(mtsize, height, mtsize), mPlayer->mPosition, CVector(0.0f, 0.0f, -1.0f), 320.0f, 640.0f);// //GPモードのみ敵が生成される if (CSceneTitle::mMode == CSceneTitle::EMODE_GRANDPRIX){ //敵車の生成 for (int i = 0; i < ENEMYS_AMOUNT; i++){ mEnemys[i] = new CEnemy(); if (i % 8 == 0){ mEnemys[i]->mpModel = &mCarBlue; } else if (i % 8 == 1){ mEnemys[i]->mpModel = &mCarPink; } else if (i % 8 == 2){ mEnemys[i]->mpModel = &mCarRed; } else if (i % 8 == 3){ mEnemys[i]->mpModel = &mCarGreen; } else if (i % 8 == 4){ mEnemys[i]->mpModel = &mCarYellow; } else if (i % 8 == 5){ mEnemys[i]->mpModel = &mCarBlack; } else if (i % 8 == 6){ mEnemys[i]->mpModel = &mCarGray; } else if (i % 8 == 7){ mEnemys[i]->mpModel = &mCarCyan; } //スタート時の座標、回転値の設定 mEnemys[i]->mPosition = CVector(StartPosVecs[i + 1]); mEnemys[i]->mRotation.mY = -145.0f; mEnemys[i]->CCharacter::Update(); } } //中間地点(順に通らないと1周したことにならないし、順番を飛ばしてもいけない) new CObjCheckPoint(&mCheckPoint, CVector(-16054.4f, 4915.0f, -2180.0f), CVector(0.0f, 0.0f, 0.0f), CVector(180.0f, 100.0f, 180.0f), 1); new CObjCheckPoint(&mCheckPoint, CVector(4680.0f, 13.5f, -2027.0f), CVector(0.0f, 0.0f, 0.0f), CVector(200.0f, 100.0f, 200.0f), 2); new CObjCheckPoint(&mCheckPoint, CVector(14809.0f, 13.5f, 4270.0f), CVector(0.0f, 0.0f, 0.0f), CVector(200.0f, 100.0f, 200.0f), 3); //ゴール地点 new CObjCheckPoint(&mCheckPoint, CVector(-3862.5f, 21.3f, 15925.5f), CVector(0.0f, 0.0f - 145.3f, 0.0f), CVector(240.0f, 100.0f, 30.0f), 9); new CObjNonCol(&mCource05GoalTile, CVector(-3862.5f, 21.3f, 15925.5f), CVector(0.0f, -145.3f, 0.0f), CVector(3.9f, 3.9f, 3.9f)); //山道以外のオブジェクトの生成 new CObjWall(&mCource05Wall, CVector(0.0f, 21.0f, 0.0f), CVector(), CVector(mtsize, height, mtsize));// new CObjGrass(&mCource05Mountain, CVector(0.0f, 21.0f, 0.0f), CVector(), CVector(mtsize, height, mtsize));// new CObjGrass(&mCource05Grass_Floor, CVector(0.0f, 20.0f, 0.0f), CVector(), CVector(mtsize, 30.0f, mtsize)); new CObjWall(&mCource05Grass_Wall, CVector(0.0f, 20.0f, 0.0f), CVector(), CVector(mtsize, 30.0f, mtsize)); new CObjWater(&mCource05Lake, CVector(0.0f, 221.0f, 0.0f), CVector(), CVector(mtsize, 30.0f, mtsize)); new CObjNonCol(&mSign_Left, CVector(2440.0f, 321.0f, 1432.0f), CVector(0.0f, 33.0f, 0.0f), CVector(4.0f, 4.0f, 4.0f));//標識:左折 new CObjNonCol(&mSign_Right, CVector(13277.0f, 12.0f, -6939.0f), CVector(0.0f, 82.3f, 0.0f), CVector(4.0f, 4.0f, 4.0f));//標識:右折 //優先度変更 CTaskManager::Get()->ChangePriority(mPlayer, 15); if (CSceneTitle::mMode == CSceneTitle::EMODE_GRANDPRIX){ for (int i = 0; i < ENEMYS_AMOUNT; i++){ CTaskManager::Get()->ChangePriority(mEnemys[i], 15); } } //敵車のカラー情報の出力 PutCPUColor(); } void CRaceCourceE::Update(){ CSceneRace::Update(); }
237e85ddd09e1f5f88e953789ed6cef39fccbc3d
d889309ade82ab755593c049fd35ba193f419a9c
/gamestate.h
9afadf0b734809b1282d94c94a26417e044fa4f4
[ "LicenseRef-scancode-public-domain", "Unlicense" ]
permissive
caveadventure/incavead
ebb07889680f46a2371e26b6a8ae10e7ee1738d2
f90c614ef0b471d1fa453b7e55a43fcad0482ef8
refs/heads/master
2022-05-12T14:43:21.534779
2022-04-04T20:55:24
2022-04-04T20:55:24
20,128,625
5
1
null
null
null
null
UTF-8
C++
false
false
9,394
h
gamestate.h
#ifndef __GAMESTATE_H #define __GAMESTATE_H #include "random.h" #include "random_serialize.h" #include "neighbors.h" #include "celauto.h" #include "grid.h" #include "worldkey.h" #include "astar.h" #include "render_maudit.h" #include "moon.h" #include "counters.h" #include "counters_serialize.h" #include "ffeatures.h" #include "items.h" #include "monsters.h" struct GameState { size_t ticks; rnd::Generator rng; neighbors::Neighbors neigh; celauto::CaMap camap; grid::Map grid; grender::Grid render; astar::Path path; moon::Moon moon; counters::Counts designs_counts; counters::Counts species_counts; counters::Counts bonus_designs_a_counts; counters::Counts bonus_designs_b_counts; monsters::Monsters monsters; items::Items items; features::Features features; struct trigger_t { struct summon_out_of_view_t { tag_t monster; unsigned int count; summon_out_of_view_t() : count(0) {} }; summon_out_of_view_t summon_out_of_view; struct summon_genus_t { tag_t genus; unsigned int level; unsigned int count; unsigned int x; unsigned int y; summon_genus_t() : level(0), count(0), x(0), y(0) {} }; summon_genus_t summon_genus; struct summon_t { tag_t species; unsigned int count; tag_t ally; unsigned int x; unsigned int y; summon_t() : count(0), x(0), y(0) {} }; summon_t summon; struct message_t { std::string message; bool important; message_t() : important(false) {} }; message_t message; }; std::multimap<size_t, trigger_t> triggers; struct window_t { std::string message; unsigned int type; bool allow_tab; window_t() : type(0), allow_tab(true) {} window_t(const std::string& s, unsigned int t, bool tab = true) : message(s), type(t), allow_tab(tab) {} }; std::vector<window_t> window_stack; std::unordered_map<worldkey::key_t, size_t> dungeon_visits_count; template <typename T> void push_window(const std::string& m, T t, bool allow_tab = true) { window_stack.push_back(window_t{m, (unsigned int)t, allow_tab}); } // HACK bool fullwidth; GameState() : ticks(1), fullwidth(false) {} }; struct GameOptions { bool center_view; bool no_fade_colors; size_t menu_theme; GameOptions() : center_view(false), no_fade_colors(false), menu_theme(0) {} }; struct summons_t { unsigned int x; unsigned int y; enum class type_t : unsigned int { SPECIFIC, LEVEL, GENUS }; type_t type; tag_t summontag; unsigned int level; unsigned int count; tag_t summonertag; tag_t ally; std::string msg; summons_t() : x(0), y(0), type(type_t::SPECIFIC), level(0), count(0) {} summons_t(unsigned int _x, unsigned int _y, type_t _t, tag_t _st, unsigned int _l, unsigned int _c, tag_t _sut, tag_t _al, const std::string& _m) : x(_x), y(_y), type(_t), summontag(_st), level(_l), count(_c), summonertag(_sut), ally(_al), msg(_m) {} }; struct itemplace_t { unsigned int x; unsigned int y; enum class type_t : unsigned int { SPECIFIC, LEVEL, LEVEL_ANY }; type_t type; tag_t tag; unsigned int level; itemplace_t() : x(0), y(0), type(type_t::SPECIFIC), level(0) {} itemplace_t(unsigned int _x, unsigned int _y, type_t _t, tag_t _dt, unsigned int _l) : x(_x), y(_y), type(_t), tag(_dt), level(_l) {} }; /*** ***/ namespace serialize { template <> struct reader<GameState::trigger_t> { void read(Source& s, GameState::trigger_t& t) { serialize::read(s, t.summon_out_of_view.monster); serialize::read(s, t.summon_out_of_view.count); serialize::read(s, t.summon_genus.genus); serialize::read(s, t.summon_genus.level); serialize::read(s, t.summon_genus.count); serialize::read(s, t.summon_genus.x); serialize::read(s, t.summon_genus.y); serialize::read(s, t.summon.species); serialize::read(s, t.summon.count); serialize::read(s, t.message.message); serialize::read(s, t.message.important); } }; template <> struct reader<GameState::window_t> { void read(Source& s, GameState::window_t& w) { serialize::read(s, w.message); serialize::read(s, w.type); } }; template <> struct reader<GameState> { void read(Source& s, GameState& state) { serialize::read(s, state.ticks); serialize::read(s, state.rng); serialize::read(s, state.neigh); serialize::read(s, state.camap); serialize::read(s, state.grid); serialize::read(s, state.render); serialize::read(s, state.moon); serialize::read(s, state.designs_counts); serialize::read(s, state.species_counts); serialize::read(s, state.bonus_designs_a_counts); serialize::read(s, state.bonus_designs_b_counts); serialize::read(s, state.monsters); serialize::read(s, state.items); serialize::read(s, state.features); serialize::read(s, state.dungeon_visits_count); serialize::read(s, state.triggers); serialize::read(s, state.window_stack); state.path.init(state.grid.w, state.grid.h); } }; template <> struct writer<GameState::trigger_t> { void write(Sink& s, const GameState::trigger_t& t) { serialize::write(s, t.summon_out_of_view.monster); serialize::write(s, t.summon_out_of_view.count); serialize::write(s, t.summon_genus.genus); serialize::write(s, t.summon_genus.level); serialize::write(s, t.summon_genus.count); serialize::write(s, t.summon_genus.x); serialize::write(s, t.summon_genus.y); serialize::write(s, t.summon.species); serialize::write(s, t.summon.count); serialize::write(s, t.message.message); serialize::write(s, t.message.important); } }; template <> struct writer<GameState::window_t> { void write(Sink& s, const GameState::window_t& w) { serialize::write(s, w.message); serialize::write(s, w.type); } }; template <> struct writer<GameState> { void write(Sink& s, const GameState& state) { serialize::write(s, state.ticks); serialize::write(s, state.rng); serialize::write(s, state.neigh); serialize::write(s, state.camap); serialize::write(s, state.grid); serialize::write(s, state.render); serialize::write(s, state.moon); serialize::write(s, state.designs_counts); serialize::write(s, state.species_counts); serialize::write(s, state.bonus_designs_a_counts); serialize::write(s, state.bonus_designs_b_counts); serialize::write(s, state.monsters); serialize::write(s, state.items); serialize::write(s, state.features); serialize::write(s, state.dungeon_visits_count); serialize::write(s, state.triggers); serialize::write(s, state.window_stack); } }; template <> struct reader<GameOptions> { void read(Source& s, GameOptions& t) { serialize::read(s, t.center_view); serialize::read(s, t.no_fade_colors); serialize::read(s, t.menu_theme); } }; template <> struct writer<GameOptions> { void write(Sink& s, const GameOptions& t) { serialize::write(s, t.center_view); serialize::write(s, t.no_fade_colors); serialize::write(s, t.menu_theme); } }; template <> struct reader<summons_t> { void read(Source& s, summons_t& t) { serialize::read(s, t.x); serialize::read(s, t.y); unsigned int tmp; serialize::read(s, tmp); t.type = (summons_t::type_t)tmp; serialize::read(s, t.summontag); serialize::read(s, t.level); serialize::read(s, t.count); serialize::read(s, t.summonertag); serialize::read(s, t.ally); serialize::read(s, t.msg); } }; template <> struct writer<summons_t> { void write(Sink& s, const summons_t& t) { serialize::write(s, t.x); serialize::write(s, t.y); serialize::write(s, (unsigned int)t.type); serialize::write(s, t.summontag); serialize::write(s, t.level); serialize::write(s, t.count); serialize::write(s, t.summonertag); serialize::write(s, t.ally); serialize::write(s, t.msg); } }; template <> struct reader<itemplace_t> { void read(Source& s, itemplace_t& t) { serialize::read(s, t.x); serialize::read(s, t.y); unsigned int tmp; serialize::read(s, tmp); t.type = (itemplace_t::type_t)tmp; serialize::read(s, t.tag); serialize::read(s, t.level); } }; template <> struct writer<itemplace_t> { void write(Sink& s, const itemplace_t& t) { serialize::write(s, t.x); serialize::write(s, t.y); serialize::write(s, (unsigned int)t.type); serialize::write(s, t.tag); serialize::write(s, t.level); } }; } #endif
c362bec82a130bf059774ecd35c98cd8d4b7180e
0417720a0c8e977a7aeddfe047422c408deaee24
/src/util/ossimOrthoIgen.cpp
402f1ca5c5e9440ec14f4ae5b59d04619f38a95e
[ "MIT" ]
permissive
ossimlabs/ossim
e093899a1e001cf8db16fb6da121ec174a7bc6ff
3eda6223501b5d1c566e91261b832bc24975cf32
refs/heads/dev
2023-06-21T21:54:22.889489
2023-06-15T23:33:36
2023-06-15T23:33:36
41,825,646
300
161
MIT
2023-08-29T20:15:07
2015-09-02T20:20:52
C++
UTF-8
C++
false
false
120,301
cpp
ossimOrthoIgen.cpp
//---------------------------------------------------------------------------- // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // //---------------------------------------------------------------------------- // $Id: ossimOrthoIgen.cpp 22813 2014-06-04 19:52:08Z okramer $ #include <ossim/util/ossimOrthoIgen.h> #include <ossim/base/ossimCommon.h> #include <ossim/base/ossimException.h> #include <ossim/init/ossimInit.h> #include <ossim/base/ossimKeywordNames.h> #include <ossim/base/ossimGrect.h> #include <ossim/base/ossimNotifyContext.h> #include <ossim/base/ossimObjectFactoryRegistry.h> #include <ossim/base/ossimPreferences.h> #include <ossim/base/ossimScalarTypeLut.h> #include <ossim/base/ossimStdOutProgress.h> #include <ossim/base/ossimTrace.h> #include <ossim/base/ossimVisitor.h> #include <ossim/imaging/ossimBandSelector.h> #include <ossim/imaging/ossimCacheTileSource.h> #include <ossim/imaging/ossimGeoAnnotationSource.h> #include <ossim/imaging/ossimImageHandler.h> #include <ossim/imaging/ossimImageRenderer.h> #include <ossim/imaging/ossimHistogramRemapper.h> #include <ossim/imaging/ossimImageMosaic.h> #include <ossim/imaging/ossimBlendMosaic.h> #include <ossim/imaging/ossimBandMergeSource.h> #include <ossim/imaging/ossimFilterResampler.h> #include <ossim/imaging/ossimImageHandlerRegistry.h> #include <ossim/imaging/ossimOrthoImageMosaic.h> #include <ossim/imaging/ossimImageWriterFactoryRegistry.h> #include <ossim/imaging/ossimMaskFilter.h> #include <ossim/imaging/ossimTiffWriter.h> #include <ossim/imaging/ossimEsriShapeFileInterface.h> #include <ossim/imaging/ossimTilingRect.h> #include <ossim/imaging/ossimTilingPoly.h> #include <ossim/imaging/ossimGeoPolyCutter.h> #include <ossim/imaging/ossimEastingNorthingCutter.h> #include <ossim/imaging/ossimHistogramEqualization.h> #include <ossim/imaging/ossimImageHistogramSource.h> #include <ossim/imaging/ossimHistogramWriter.h> #include <ossim/imaging/ossimGeoAnnotationPolyObject.h> #include <ossim/imaging/ossimGeoAnnotationMultiPolyObject.h> #include <ossim/imaging/ossimPixelFlipper.h> #include <ossim/imaging/ossimScalarRemapper.h> #include <ossim/parallel/ossimIgen.h> #include <ossim/parallel/ossimMpi.h> #include <ossim/projection/ossimUtmProjection.h> #include <ossim/projection/ossimEquDistCylProjection.h> #include <ossim/projection/ossimEpsgProjectionFactory.h> #include <sstream> using namespace std; // In Windows, standard output is ASCII by default. // Let's include the following in case we have // to change it over to binary mode. #if defined(_WIN32) # include <io.h> # include <fcntl.h> #endif static ossimTrace traceDebug("ossimOrthoIgen:debug"); static ossimTrace traceLog("ossimOrthoIgen:log"); static const char* AUTOGENERATE_HISTOGRAM_KW = "autogenerate_histogram"; using namespace ossim; //************************************************************************************************* // Parses the file info as specified in the command line or src file. The file info is a '|'- // delimited string with filename and additional attributes such as entry and band numbers. //************************************************************************************************* bool ossimOrthoIgen::parseFilename(const ossimString& file_spec, bool decodeEntry) { ossimSrcRecord src_record; std::vector<ossimString> fileInfos = file_spec.split("|"); unsigned int num_fields = (unsigned int) fileInfos.size(); unsigned int field_idx = 0; if (num_fields == 0) return false; // First field is the actual filename: src_record.setFilename(fileInfos[field_idx]); ++field_idx; // Next field depends on whether an entry is being decoded: if ((field_idx < num_fields) && decodeEntry) { src_record.setEntryIndex(fileInfos[field_idx].trim().toInt32()); ++field_idx; } // The rest of the fields can appear in any order: while (field_idx < num_fields) { ossimString active_field (fileInfos[field_idx].trim()); ossimString downcased_field (active_field); downcased_field.downcase(); ++field_idx; // Check for overview file spec: ossimFilename filename (active_field); if (filename.contains(".ovr") || filename.isDir()) { src_record.setSupportDir(filename.path()); } else if (filename.contains(".mask") || filename.isDir()) { src_record.setSupportDir(filename.path()); } // else check for auto-minmax histogram stretch: else if ((downcased_field == "auto-minmax") || downcased_field.contains("std-stretch")) { src_record.setHistogramOp(downcased_field); } // Otherwise, this must be a band specification. Band numbers begin with 1: else { // multiple bands delimited by comma: std::vector<ossimString> bandsStr = active_field.split(","); std::vector<ossim_uint32> bands; for (unsigned int i = 0; i < bandsStr.size(); i++) { int band = bandsStr[i].toInt32() - 1; if (band >= 0) bands.push_back((ossim_uint32)band); } src_record.setBands(bands); } } // end of while loop parsing fileInfos spec theSrcRecords.push_back(src_record); return true; } //************************************************************************************************* // Constructor //************************************************************************************************* ossimOrthoIgen::ossimOrthoIgen() : ossimIgen(), theDeltaPerPixelUnit(OSSIM_UNIT_UNKNOWN), theDeltaPerPixelOverride(ossim::nan(), ossim::nan()), theProjectionType(OSSIM_UNKNOWN_PROJECTION), theProjectionName(""), theGeoScalingLatitude(ossim::nan()), theCombinerType("ossimImageMosaic"), theResamplerType("nearest neighbor"), theWriterType(""), theTemplateView(""), theTilingTemplate(""), theTilingFilename(""), theChainTemplate(""), theCombinerTemplate(""), theAnnotationTemplate(""), theWriterTemplate(""), theSupplementaryDirectory(""), theSlaveBuffers("2"), theCutOriginType(ossimOrthoIgen::OSSIM_CENTER_ORIGIN), theCutOrigin(ossim::nan(), ossim::nan()), theCutDxDy(ossim::nan(), ossim::nan()), theCutOriginUnit(OSSIM_UNIT_UNKNOWN), theCutDxDyUnit(OSSIM_UNIT_UNKNOWN), theLowPercentClip(ossim::nan()), theHighPercentClip(ossim::nan()), theStdDevClip(-1), theUseAutoMinMaxFlag(false), theClipToValidRectFlag(false), theReaderProperties(), theWriterProperties(), theTargetHistoFileName(), theProductFilename(), theReferenceProj(0), theMaskShpFile(""), theCacheExcludedFlag(false), theOutputRadiometry(""), thePixelAlignment(OSSIM_PIXEL_IS_AREA) // will revert to "point" upon first occurrence in source list { // Determine default behavior of clip from preferences: ossimString flag = ossimPreferences::instance()->findPreference("orthoigen.clip_to_valid_rect"); if (!flag.empty()) theClipToValidRectFlag = flag.toBool(); thePixelReplacementMode = ossimPreferences::instance()->findPreference("orthoigen.flip_null_pixels"); return; } //************************************************************************************************* // Initializes the argument parser //************************************************************************************************* void ossimOrthoIgen::addArguments(ossimArgumentParser& argumentParser) { // These are in ALPHABETIC ORDER. Please keep it that way. argumentParser.getApplicationUsage()->addCommandLineOption( "--annotate", "annotation keyword list"); argumentParser.getApplicationUsage()->addCommandLineOption( "--chain-template","Specify an external file that contains chain information"); argumentParser.getApplicationUsage()->addCommandLineOption( "--clamp-pixels <min> <max>","Specify the min and max allowed pixel values. All values " "outside of this get mapped to their corresponding clamp value."); argumentParser.getApplicationUsage()->addCommandLineOption( "--clip-pixels <min> <max>","Causes all pixel values between min and max (inclusive)" " to be mapped to the null pixel value. Min and max can be equal for mapping a single value." " See also related option \"--replacement-mode\" for additional explanation."); argumentParser.getApplicationUsage()->addCommandLineOption( "--clip-to-valid-rect <true|false>","When true, any requested cut rect is clipped by the " "valid image bounding rect to minimize null border pixels. If false, the output will " "correspond to the cut rect as close as possible given the product projection. This option " "overrides the ossim_preferences setting. If no cut options are supplied, this option is " "ignored."); argumentParser.getApplicationUsage()->addCommandLineOption( "--combiner-template","Specify an external file that contains combiner information"); argumentParser.getApplicationUsage()->addCommandLineOption( "--combiner-type","Specify what mosaic to use, ossimImageMosiac or ossimFeatherMosaic or " "osimBlendMosaic ... etc"); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-bbox-en","Specify the min easting, min northing, max easting, max northing"); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-bbox-ll","Specify the min lat and min lon and max lat and maxlon <minLat> <minLon> " "<maxLat> <maxLon>"); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-center-ll","Specify the center cut in lat lon space. Takes two argument <lat> <lon>"); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-pixel-width-height","Specify cut box's width and height in pixels"); argumentParser.getApplicationUsage()->addCommandLineOption( "--cut-radius-meters","Specify the cut distance in meters. A bounding box for the cut will " "be produced"); argumentParser.getApplicationUsage()->addCommandLineOption( "--degrees","Specifies an override for degrees per pixel. Takes either a single value " "applied equally to x and y directions, or two values applied correspondingly to x then y."); argumentParser.getApplicationUsage()->addCommandLineOption( "--geo","Defaults to a geographic image chain with GSD = to the input. Origin of latitude is" "on the equator."); argumentParser.getApplicationUsage()->addCommandLineOption( "--geo-auto-scaled","Computes the mosaic center latitude for purpose of scaling in the " "longitude direction so that the pixels will appear nearly square in ground space at " "specified latitude. Implies a geographic projection."); argumentParser.getApplicationUsage()->addCommandLineOption( "--geo-scaled","Takes latitude as an argument for purpose of scaling in the " "longitude direction so that the pixels will appear nearly square in ground space at " "specified latitude. Implies a geographic projection."); argumentParser.getApplicationUsage()->addCommandLineOption( "--hist-auto-minmax","uses the automatic search for the best min and max clip values." " Incompatible with other histogram options."); argumentParser.getApplicationUsage()->addCommandLineOption( "--hist-match","Takes one image filename argument for target histogram to match." " Incompatible with other histogram options."); argumentParser.getApplicationUsage()->addCommandLineOption( "--hist-std-stretch","Specify histogram stretch as a standard deviation from the mean as" " <int>, where <int> is 1, 2, or 3." " Incompatible with other histogram options."); argumentParser.getApplicationUsage()->addCommandLineOption( "--hist-stretch","Specify in normalized percent the low clip and then the high clip value" " as <low.dd> <hi.dd>." " Incompatible with other histogram options."); argumentParser.getApplicationUsage()->addCommandLineOption( "--input-proj","Makes the view equal to the input. If more than one file then the first is " "taken"); argumentParser.getApplicationUsage()->addCommandLineOption( "--mask","Specify the ESRI shape file with polygons to clip the image"); argumentParser.getApplicationUsage()->addCommandLineOption( "--meters","Specifies an override for the meters per pixel. Takes either a single value " "applied equally to x and y directions, or two values applied correspondingly to x then y."); argumentParser.getApplicationUsage()->addCommandLineOption( "--no-cache","Excludes the cache from the input image chain(s). Necessary as a workaround " " for inconsistent cache behavior for certain image types."); argumentParser.getApplicationUsage()->addCommandLineOption( "--output-radiometry","Specifies the desired product's pixel radiometry type. Possible " "values are: U8, U11, U16, S16, F32. Note this overrides the deprecated option \"scale-to" "-8-bit\"."); argumentParser.getApplicationUsage()->addCommandLineOption( "--reader-prop","Passes a name=value pair to the reader(s) for setting it's property. Any " "number of these can appear on the line."); argumentParser.getApplicationUsage()->addCommandLineOption( "--replacement-mode <mode>","Specify how to treat multi-band imagery when providing " "clip-pixels and/or clamp-pixels settings. Possible values are: REPLACE_BAND_IF_TARGET | " "REPLACE_BAND_IF_PARTIAL_TARGET | REPLACE_ALL_BANDS_IF_ANY_TARGET | " "REPLACE_ONLY_FULL_TARGETS."); argumentParser.getApplicationUsage()->addCommandLineOption( "--resample-type","Specify what resampler to use, nearest neighbor, bilinear, cubic"); argumentParser.getApplicationUsage()->addCommandLineOption( "--scale-to-8-bit","Scales the output to unsigned eight bits per band. This option has been" " deprecated by the newer \"--output-radiometry\" option."); argumentParser.getApplicationUsage()->addCommandLineOption( "--slave-buffers","number of slave tile buffers for mpi processing (default = 2)"); argumentParser.getApplicationUsage()->addCommandLineOption( "--srs","specify an output reference frame/projection. Example: --srs EPSG:4326"); argumentParser.getApplicationUsage()->addCommandLineOption( "--stdout","Output the image to standard out. This will return an error if writer does not " "support writing to standard out. Callers should combine this with the --ossim-logfile " "option to ensure output image stream does not get corrupted. You must still pass an output " "file so the writer type can be determined like \"dummy.png\"."); argumentParser.getApplicationUsage()->addCommandLineOption( "--supplementary-directory or --support","Specify the supplementary directory path where " "overviews, histograms and external geometries are located"); argumentParser.getApplicationUsage()->addCommandLineOption( "-t or --thumbnail", "thumbnail size"); argumentParser.getApplicationUsage()->addCommandLineOption( "--tiling-template","Specify an external file that contains tiling information"); argumentParser.getApplicationUsage()->addCommandLineOption( "--threads [n]","Indicates multi-threaded process using optionally-specified number of threads"); argumentParser.getApplicationUsage()->addCommandLineOption( "--utm","Defaults to a utm image chain with GSD = to the input"); argumentParser.getApplicationUsage()->addCommandLineOption( "--view-template","Specify an external file that contains view information"); argumentParser.getApplicationUsage()->addCommandLineOption( "-w or --writer","Specifies the output writer. Default uses output file extension to " "determine writer."); argumentParser.getApplicationUsage()->addCommandLineOption( "--wkt","specify an output reference frame/projection that is in a wkt format. Must have the" " ossimgdal_plugin compiled"); argumentParser.getApplicationUsage()->addCommandLineOption( "--writer-prop","Passes a name=value pair to the writer for setting it's property. Any " "number of these can appear on the line."); argumentParser.getApplicationUsage()->addCommandLineOption( "--writer-template","Specify an external file that contains tiling information"); } //************************************************************************************************* // Initializes this objects data members given the command line args //************************************************************************************************* void ossimOrthoIgen::initialize(ossimArgumentParser& argumentParser) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::initialize DEBUG:" << "Entered..... " << std::endl; } double tempDouble; double tempDouble2; double tempDouble3; double tempDouble4; ossimString tempString; unsigned int tempUint; ossimArgumentParser::ossimParameter stringParam(tempString); ossimArgumentParser::ossimParameter doubleParam(tempDouble); ossimArgumentParser::ossimParameter doubleParam2(tempDouble2); ossimArgumentParser::ossimParameter doubleParam3(tempDouble3); ossimArgumentParser::ossimParameter doubleParam4(tempDouble4); ossimArgumentParser::ossimParameter uintParam(tempUint); theCutOriginType = ossimOrthoIgen::OSSIM_CENTER_ORIGIN; theCutOrigin.makeNan(); theCutDxDy.makeNan(); theCutOriginUnit = OSSIM_UNIT_UNKNOWN; theCutDxDyUnit = OSSIM_UNIT_UNKNOWN; theLowPercentClip = ossim::nan(); theHighPercentClip = ossim::nan(); double minX=ossim::nan(), minY=ossim::nan(), maxX=ossim::nan(), maxY=ossim::nan(); theUseAutoMinMaxFlag = false; theDeltaPerPixelOverride.makeNan(); theDeltaPerPixelUnit = OSSIM_UNIT_UNKNOWN; theCacheExcludedFlag = false; theClampPixelMin = ossim::nan(); theClampPixelMax = ossim::nan(); theClipPixelMin = ossim::nan(); theClipPixelMax = ossim::nan(); if(argumentParser.read("--annotate", stringParam)) { theAnnotationTemplate = ossimFilename(tempString); } if(argumentParser.read("-t", stringParam) || argumentParser.read("--thumbnail", stringParam)) { ossimString comma (","); if (tempString.contains(comma)) { theThumbnailSize.x = tempString.before(comma).toInt(); theThumbnailSize.y = tempString.after(comma).toInt(); } else { theThumbnailSize.x = tempString.toInt(); theThumbnailSize.y = 0; } theBuildThumbnailFlag = true; } theReaderProperties.clear(); while(argumentParser.read("--reader-prop", stringParam)) { std::vector<ossimString> splitArray; tempString.split(splitArray, "="); if(splitArray.size() == 2) { theReaderProperties.insert(std::make_pair(splitArray[0], splitArray[1])); } } if(argumentParser.read("-w", stringParam) || argumentParser.read("--writer", stringParam)) { theWriterType = tempString; } theWriterProperties.clear(); while(argumentParser.read("--writer-prop", stringParam)) { std::vector<ossimString> splitArray; tempString.split(splitArray, "="); if(splitArray.size() == 2) { theWriterProperties.insert(std::make_pair(splitArray[0], splitArray[1])); } } if(argumentParser.read("--slave-buffers", stringParam)) { theSlaveBuffers = tempString; } if(argumentParser.read("--cut-center-ll", doubleParam, doubleParam2)) { theCutOrigin.lat = tempDouble; theCutOrigin.lon = tempDouble2; theCutOriginUnit = OSSIM_DEGREES; theCutOriginType = ossimOrthoIgen::OSSIM_CENTER_ORIGIN; } if(argumentParser.read("--cut-radius-meters", doubleParam)) { theCutDxDy.x = tempDouble; theCutDxDy.y = tempDouble; theCutDxDyUnit = OSSIM_METERS; } if(argumentParser.read("--cut-bbox-ll", doubleParam, doubleParam2, doubleParam3, doubleParam4)) { minY = tempDouble; minX = tempDouble2; maxY = tempDouble3; maxX = tempDouble4; theCutOriginUnit = OSSIM_DEGREES; theCutOriginType = ossimOrthoIgen::OSSIM_UPPER_LEFT_ORIGIN; theCutOrigin.lat = maxY; theCutOrigin.lon = minX; theCutDxDy.lat = (maxY-minY); if ( (maxX < 0.0) && (minX >= 0.0) ) { //--- // Min is eastern hemisphere, max is western. Crossed the international date line. // Add 360 to make it positive. // // Note no check for just max < min here??? Perhaps throw exception.(drb) //--- maxX += 360.0; } theCutDxDy.lon = (maxX-minX); theCutDxDyUnit = OSSIM_DEGREES; } if(argumentParser.read("--cut-bbox-en", doubleParam, doubleParam2, doubleParam3, doubleParam4)) { minX = tempDouble; minY = tempDouble2; maxX = tempDouble3; maxY = tempDouble4; theCutOriginUnit = OSSIM_METERS; theCutOriginType = ossimOrthoIgen::OSSIM_UPPER_LEFT_ORIGIN; theCutOrigin.x = minX; theCutOrigin.y = maxY; theCutDxDy.x = (maxX-minX); theCutDxDy.y = (maxY-minY); theCutDxDyUnit = OSSIM_METERS; } if(argumentParser.read("--cut-pixel-width-height", doubleParam, doubleParam2)) { if((ossim::isnan(minX) == false)&& (ossim::isnan(minY) == false)&& (ossim::isnan(maxX) == false)&& (ossim::isnan(maxY) == false)) { theDeltaPerPixelOverride = ossimDpt(theCutDxDy.x/(tempDouble-1), theCutDxDy.y/(tempDouble2-1)); theDeltaPerPixelUnit = theCutDxDyUnit; } else { theCutOrigin.makeNan(); ossimNotify(ossimNotifyLevel_WARN) << "Can't have option --cut-pixel-width-height without --cut-bbox-ll" << std::endl; } } int num_params = argumentParser.numberOfParams("--degrees", doubleParam); if (num_params == 1) { argumentParser.read("--degrees", doubleParam); theDeltaPerPixelUnit = OSSIM_DEGREES; theDeltaPerPixelOverride.x = tempDouble; theDeltaPerPixelOverride.y = tempDouble; } else if (num_params == 2) { argumentParser.read("--degrees", doubleParam, doubleParam2); theDeltaPerPixelUnit = OSSIM_DEGREES; theDeltaPerPixelOverride.x = tempDouble; theDeltaPerPixelOverride.y = tempDouble2; } // The three histogram options are mutually exclusive: bool histo_op_selected = false; if(argumentParser.read("--hist-match", stringParam)) { ossimFilename target_image (tempString); histo_op_selected = true; // Check for histogram matching request and initialize for that: if (target_image.isReadable()) { // Establish target histogram file: theTargetHistoFileName = target_image; theTargetHistoFileName.setExtension("his"); if (!theTargetHistoFileName.isReadable()) { ossimNotify(ossimNotifyLevel_NOTICE)<<"Target histogram file <" << theTargetHistoFileName << "> not found. Cannot perform histogram matching." << std::endl; theTargetHistoFileName.clear(); } } } if(argumentParser.read("--hist-stretch", doubleParam, doubleParam2)) { if (histo_op_selected) { ossimNotify(ossimNotifyLevel_WARN) << "Cannot specify nore than one histogram operation. " " Ignoring --hist-stretch option." << std::endl; } else { theLowPercentClip = tempDouble; theHighPercentClip = tempDouble2; histo_op_selected = true; } } if(argumentParser.read("--hist-std-stretch", stringParam)) { if (histo_op_selected) { ossimNotify(ossimNotifyLevel_WARN) << "Cannot specify nore than one histogram operation. " " Ignoring --hist-stretch option." << std::endl; } else { theStdDevClip = tempString.toInt32(); histo_op_selected = true; if ((theStdDevClip < 1) || (theStdDevClip > 3)) { ossimNotify(ossimNotifyLevel_WARN) << "Invalid standard deviation value provided with" " --hist-std-stretch option. Only 1,2, or 3 allowed. Ignoring option."<< std::endl; } } } if(argumentParser.read("--hist-auto-minmax")) { if (histo_op_selected) { ossimNotify(ossimNotifyLevel_WARN) << "Cannot specify nore than one histogram operation. " " Ignoring --hist-auto-minmax option." << std::endl; } else theUseAutoMinMaxFlag = true; } num_params = argumentParser.numberOfParams("--meters", doubleParam); if (num_params == 1) { argumentParser.read("--meters", doubleParam); theDeltaPerPixelUnit = OSSIM_METERS; theDeltaPerPixelOverride.x = tempDouble; theDeltaPerPixelOverride.y = tempDouble; } else if (num_params == 2) { argumentParser.read("--meters", doubleParam, doubleParam2); theDeltaPerPixelUnit = OSSIM_METERS; theDeltaPerPixelOverride.x = tempDouble; theDeltaPerPixelOverride.y = tempDouble2; } if(argumentParser.read("--no-cache")) { theCacheExcludedFlag = true; } if(argumentParser.read("--output-radiometry", stringParam)) { theOutputRadiometry = tempString; } if(argumentParser.read("--scale-to-8-bit")) { if (theOutputRadiometry.empty()) theOutputRadiometry = "U8"; } if (argumentParser.read("--stdout")) { #if defined(_WIN32) // In Windows, cout is ASCII by default. // Let's change it over to binary mode. int result = _setmode( _fileno(stdout), _O_BINARY ); if( result == -1 ) { ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::initialize WARNING:" << "\nCannot set standard output mode to binary." << std::endl; return; } #endif theStdoutFlag = true; } if(argumentParser.read("--writer-template", stringParam)) { theWriterTemplate = tempString; } if(argumentParser.read("--tiling-template", stringParam)) { theTilingTemplate = ossimFilename(tempString); } if(argumentParser.read("--chain-template", stringParam)) { theChainTemplate = ossimFilename(tempString); } if(argumentParser.read("--combiner-template", stringParam)) { theCombinerTemplate = ossimFilename(tempString); } theGeoScalingLatitude = ossim::nan(); if (argumentParser.read("--utm")) { theProjectionType = OSSIM_UTM_PROJECTION; theProjectionName = "ossimUtmProjection"; } else if(argumentParser.read("--geo")) { theProjectionType = OSSIM_GEO_PROJECTION; theProjectionName = "ossimEquDistCylProjection"; theGeoScalingLatitude = 0.0; } else if(argumentParser.read("--input-proj")) { theProjectionType = OSSIM_INPUT_PROJECTION; } else if (argumentParser.read("--srs", stringParam)) { theCrsString=tempString; theProjectionType = OSSIM_SRS_PROJECTION; } if(argumentParser.read("--view-template", stringParam)) { theTemplateView = ossimFilename(tempString); theProjectionType = OSSIM_EXTERNAL_PROJECTION; } if(argumentParser.read("--geo-scaled", doubleParam)) { theProjectionType = OSSIM_GEO_PROJECTION; theProjectionName = "ossimEquDistCylProjection"; if ( (tempDouble < 90.0) && (tempDouble > -90.0) ) { theGeoScalingLatitude = tempDouble; } else { ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::initialize WARNING:" << "\nLatitude out of range! Must be between -90 and 90." << std::endl; } if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::initialize DEBUG:" << "\ngeographicOriginOfLatitude: " << theGeoScalingLatitude << std::endl; } } if(argumentParser.read("--geo-auto-scaled")) { theProjectionType = OSSIM_GEO_PROJECTION; theProjectionName = "ossimEquDistCylProjection"; theGeoScalingLatitude = 999.0; // Flags computation of center lat for scaling } if(argumentParser.read("--combiner-type", stringParam)) theCombinerType = tempString; if(argumentParser.read("--resample-type", stringParam)) { theResamplerType = tempString; } if(argumentParser.read("--supplementary-directory", stringParam) || argumentParser.read("--support", stringParam)) { theSupplementaryDirectory = ossimFilename(tempString); } if (argumentParser.read("--clip-to-valid-rect", stringParam)) { theClipToValidRectFlag = tempString.toBool(); } if(argumentParser.read("--mask", stringParam)) { theMaskShpFile = tempString; } // Pixel flipper control options: if (argumentParser.read("--clip-pixels", doubleParam, doubleParam2)) { theClipPixelMin = tempDouble; theClipPixelMax = tempDouble2; } if (argumentParser.read("--clamp-pixels", doubleParam, doubleParam2)) { theClampPixelMin = tempDouble; theClampPixelMax = tempDouble2; } if (argumentParser.read("--replacement-mode", stringParam)) { thePixelReplacementMode = tempString; } // Threading: num_params = argumentParser.numberOfParams("--threads", uintParam); if (num_params == 0) // No param means system decides optimal thread count { argumentParser.read("--threads"); theThreadCount = 0; // Flags system-resolved } else if (num_params == 1) { argumentParser.read("--threads", uintParam); theThreadCount = (ossim_uint32) tempUint; } if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::initialize DEBUG:" << "Leaving..... " << std::endl; } } //************************************************************************************************* // Adds any file specifications to the files list //************************************************************************************************* void ossimOrthoIgen::addFiles(ossimArgumentParser& argumentParser, bool withDecoding, ossim_uint32 startIdx) { ossim_uint32 idx = startIdx; ossim_uint32 last_idx = argumentParser.argc()-1; while(argumentParser.argv()[idx] && (idx < last_idx)) { ossimString file_spec = argumentParser.argv()[idx]; if (file_spec.contains(".src")) { // input file spec provided via src file. Need to parse it: addSrcFile(ossimFilename(file_spec)); } else { // Filename with optional switches explicitly provided on command line: parseFilename(file_spec, withDecoding); } ++idx; } // The last filename left on the command line should be the product filename: theProductFilename = argumentParser.argv()[last_idx]; } //************************************************************************************************* // Performs the top-level management of image generation //************************************************************************************************* bool ossimOrthoIgen::execute() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::execute DEBUG: Entered ..." << std::endl; } // double start=0, stop=0; if(theSrcRecords.size() < 1) { ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::execute WARNING: No filenames to process" << std::endl; return false; } if (!theCrsString.empty() && !theProductFilename.empty()) { if ((theProductFilename.ext().upcase() == "KMZ" || theProductFilename.ext().upcase() == "KML") && theCrsString.upcase() != "EPSG:4326") { ossimNotify(ossimNotifyLevel_FATAL) << "ossimOrthoIgen::execute ERROR: Unsupported projection for kmz or kml" << std::endl; return false; } } //if(ossimMpi::instance()->getRank() == 0) //{ try { setupIgenChain(); } catch (const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << e.what() << std::endl; } throw; // re-throw exception } if (traceLog()) { generateLog(); } //} try { // theProductProjection->print(cout) << endl; outputProduct(); } catch(const ossimException& e) { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << e.what() << std::endl; } throw; // re-throw } return true; } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::clearFilenameList() { theSrcRecords.clear(); } //************************************************************************************************* // Parses the .src file specified in the command line. These contain an alternate specification // of input file and associated attributes as a KWL. //************************************************************************************************* void ossimOrthoIgen::addSrcFile(const ossimFilename& src_file) { if (!src_file.isReadable()) return; ossimKeywordlist src_kwl; src_kwl.setExpandEnvVarsFlag(true); if ( src_kwl.addFile(src_file) == false ) return; unsigned int image_idx = 0; // int entry = -1; // Loop to read all image file entries: double sum_weights = 0; while (true) { ossimSrcRecord src_record(src_kwl, image_idx++); if (!src_record.valid()) break; // Check for the presence of separate RGB file specs in this SRC record. This indicates // special processing. (comment added OLK 01/11) if (src_record.isRgbData()) { for (ossim_uint32 rgb_index = 0; rgb_index < 3; rgb_index++) { // This call creates another band-specific ossimSrcRecord that is pushed onto // theSrcRecords vector data member. (comment added OLK 01/11) if (parseFilename(src_record.getRgbFilename(rgb_index), true)) { // The parseFilename call pushes the R, G, or B band onto the back of theSrcRecords // vector. Set some additional attributes on this last entry. (OLK 01/11) theSrcRecords.back().setRgbDataBool(true); theSrcRecords.back().setHistogramOp(src_record.getRgbHistogramOp(rgb_index)); theSrcRecords.back().setHistogram(src_record.getRgbHistogramPath(rgb_index)); theSrcRecords.back().setOverview(src_record.getRgbOverviewPath(rgb_index)); } } } else { // Not RGB data, so treat as conventional image: (comment added OLK 01/11) theSrcRecords.push_back(src_record); sum_weights += src_record.getWeight(); //if the vector file exists, set the mosaic combiner type to ossimBlendMosaic if (src_record.isVectorData()) theCombinerType = "ossimBlendMosaic"; } } double max_weight = (sum_weights > 100.0 ? sum_weights : 100.0); double num_entries = (double)theSrcRecords.size(); double weight; vector<ossimSrcRecord>::iterator iter = theSrcRecords.begin(); while (iter != theSrcRecords.end()) { if (sum_weights > 0.0) { // Somebody declared opacity, so need to share the remaining contributions among // other images: theCombinerType = "ossimBlendMosaic"; if (iter->getWeight() == 0.0) { // No weight has been assigned for this image, so use default remaining partial if (num_entries == 1.0) weight = 1.0; // This is the only image, so full weight else { // share remaining contributions: weight = (1.0 - sum_weights/max_weight)/(num_entries - 1); if (weight < 0.01) weight = 0.01; } } else { // An opacity value was specified for this weight = iter->getWeight()/max_weight; } } else { // No opacity values were specified, so simply use the default equal share. Note that the // mosaic may not even be of type ossimBlendMosaic: weight = 100.0/num_entries; // default if no opacity specified } iter->setWeight(weight); iter++; } } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::setDefaultValues() { theBuildThumbnailFlag = false; theDeltaPerPixelUnit = OSSIM_UNIT_UNKNOWN; theDeltaPerPixelOverride.makeNan(); theTemplateView = ""; theProjectionType = OSSIM_UNKNOWN_PROJECTION; theGeoScalingLatitude = ossim::nan(); theCombinerType = "ossimImageMosaic"; theResamplerType = "nearest neighbor"; theTilingTemplate = ""; theTilingFilename = ""; theSupplementaryDirectory = ""; theSlaveBuffers = "2"; clearFilenameList(); theLowPercentClip = ossim::nan(); theHighPercentClip = ossim::nan(); theCutOrigin.makeNan(); theCutDxDy.makeNan(); theCutOriginUnit = OSSIM_UNIT_UNKNOWN; theCutDxDyUnit = OSSIM_UNIT_UNKNOWN; // PIXEL_IS_AREA HACK -- Set the assumed pixel alignment type to "area". Upon the first occurrence // of a pixel-is-point entry, this property will revert to point. THIS NEEDS TO BE // REMOVED WHEN THE EW GUI PROVIDES FOR THE USER TO SET THIS PROPERTY (OLK 09/11): thePixelAlignment = OSSIM_PIXEL_IS_AREA; // not a default, but necessary for later logic } //************************************************************************************************* // Initializes the processing chain from the information on the command line //************************************************************************************************* void ossimOrthoIgen::setupIgenChain() { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG)<< "ossimOrthoIgen::setupIgenChain DEBUG: Entered ..."<< std::endl; setupTiling(); if (theSlaveBuffers == "") theNumberOfTilesToBuffer = 2; else theNumberOfTilesToBuffer = theSlaveBuffers.toLong(); if(theProductFilename.empty()) throw(ossimException(std::string("Must supply an output file."))); // Create the output mosaic object, to be connected to its inputs later: ossimKeywordlist templateKwl; templateKwl.clear(); ossimRefPtr<ossimImageCombiner> mosaicObject = 0; ossimRefPtr<ossimImageCombiner> bandMergeObject = 0; if(theCombinerTemplate.exists()) { templateKwl.addFile(theCombinerTemplate); mosaicObject = PTR_CAST(ossimImageCombiner, ossimObjectFactoryRegistry::instance()->createObject(templateKwl)); } if (!mosaicObject.valid()) { mosaicObject = PTR_CAST(ossimImageCombiner, ossimObjectFactoryRegistry::instance()->createObject(theCombinerType)); if(!mosaicObject.valid()) { mosaicObject = PTR_CAST(ossimImageMosaic, ossimObjectFactoryRegistry::instance()-> createObject(ossimString("ossimImageMosaic"))); } } // Keep this pointer around for special processing if blend mosaic: ossimBlendMosaic* obm = PTR_CAST(ossimBlendMosaic, mosaicObject.get()); // An orthomosaic implies that all input images are already orthorectified to a common projection // so the input chains do not require a renderer: bool orthoMosaic = (PTR_CAST(ossimOrthoImageMosaic, mosaicObject.get()) != 0); // Establish default individual input chain from template, if any: templateKwl.clear(); ossimRefPtr<ossimImageChain> default_single_image_chain = 0; if(theChainTemplate.exists()) { templateKwl.addFile(theChainTemplate); ossimObject* obj = 0; if(templateKwl.find("type")) obj = ossimObjectFactoryRegistry::instance()->createObject(templateKwl); else if(templateKwl.find("object1.type")) obj = ossimObjectFactoryRegistry::instance()->createObject(templateKwl, "object1."); default_single_image_chain = PTR_CAST(ossimImageChain, obj); } if(!default_single_image_chain.valid()) // then create a default rendering chain { default_single_image_chain = new ossimImageChain; { // Only need a renderer if an output projection or an explicit GSD was specified. if(!orthoMosaic) { ossimImageRenderer* renderer = new ossimImageRenderer; if (renderer->getResampler()) renderer->getResampler()->setFilterType(theResamplerType); default_single_image_chain->addChild(renderer); } } } ossim_uint32 num_inputs = (ossim_uint32)theSrcRecords.size(); ossim_uint32 idx; ossimString prefix ("object1.object"); theReferenceProj = 0; // Loop over each input image file to establish a single image chain that will be added to the // output mosaic: ossimImageSource* current_source = 0; for(idx = 0; idx < num_inputs; ++idx) { // first lets add an input handler to the chain: ossimFilename input = theSrcRecords[idx].getFilename(); ossimRefPtr<ossimImageHandler> handler = ossimImageHandlerRegistry::instance()->open(input); if(!handler.valid()) { ossimNotify(ossimNotifyLevel_WARN) << "Could not open input file <" << input << ">. " << "Skipping this entry." << std::endl; continue; } // Pass on any reader properties if there are any. ossimPropertyInterface* propInterface = (ossimPropertyInterface*)handler.get(); PropertyMap::iterator iter = theReaderProperties.begin(); while(iter != theReaderProperties.end()) { propInterface->setProperty(iter->first, iter->second); ++iter; } // Presently, handler->loadState() is called only on vector data, though in the future we // should stuff many of the members in ossimSrcRecord in a KWL (similar to what is currently // done with vector properties) so that the handler is initialized via loadState() instead of // individual calls to set methods. OLK 10/10 if (theSrcRecords[idx].isVectorData()) handler->loadState(theSrcRecords[idx].getAttributesKwl()); std::vector<ossim_uint32> entryList; if(theSrcRecords[idx].getEntryIndex() > -1 ) entryList.push_back(theSrcRecords[idx].getEntryIndex()); else handler->getEntryList(entryList); // Input image file may have multiple entries. Loop over each and establish single image // chains for each: ossim_uint32 entryIdx = 0; for(entryIdx = 0; entryIdx < entryList.size(); ++entryIdx) { // Instantiate the chain for one input image source. Copy existing default chain // which may already possess a renderer (so don't do any addFirst()!): ossimImageChain* singleImageChain = (ossimImageChain*) default_single_image_chain->dup(); // Establish the image handler for this particular frame. This may be just // the handler already opened in the case of single image per file: ossimImageHandler* img_handler = 0; if (entryList.size() == 1) img_handler = handler.get(); else img_handler = (ossimImageHandler*)handler->dup(); // The user can specify an external "support" (a.k.a. supplementary directory) several ways if ( theSupplementaryDirectory.empty() == false ) { img_handler->setSupplementaryDirectory( theSupplementaryDirectory ); } else if (theSrcRecords[idx].getSupportDir().empty() == false) { img_handler->setSupplementaryDirectory(theSrcRecords[idx].getSupportDir()); } else if (theSrcRecords[idx].getOverviewPath().empty() == false) { if (theSrcRecords[idx].getOverviewPath().isDir()) img_handler->setSupplementaryDirectory(theSrcRecords[idx].getOverviewPath()); else img_handler->setSupplementaryDirectory(theSrcRecords[idx].getOverviewPath().path()); } img_handler->setCurrentEntry(entryList[entryIdx]); if ( img_handler->hasOverviews() ) { img_handler->openOverview(); } if (theSrcRecords[idx].isRgbData() && theSrcRecords[idx].getBands().size() > 0 && theSrcRecords[idx].getOverviewPath().empty()) { img_handler->setOutputBandList(theSrcRecords[idx].getBands()); } // Image handler is ready to insert on the input side of the chain: singleImageChain->addLast(img_handler); current_source = img_handler; // PIXEL_IS_AREA HACK -- Scan the pixel alignment to see if all inputs are "area", // in which case we override the command-line writer property setting. THIS NEEDS TO BE // REMOVED WHEN THE EW GUI PROVIDES FOR THE USER TO SET THIS PROPERTY (OLK 09/11): if (img_handler->getPixelType() == OSSIM_PIXEL_IS_POINT) thePixelAlignment = OSSIM_PIXEL_IS_POINT; // This call will check for the presence of a raster mask file alongside the image, // and insert the mask filter in the chain if present: current_source = setupRasterMask(singleImageChain, theSrcRecords[idx]); // If this is the first input chain, use it as the reference projection to help with // the instantiation of the product projection (the view): if (!theReferenceProj.valid()) { ossimRefPtr<ossimImageGeometry> geom = img_handler->getImageGeometry(); if ( geom.valid() ) theReferenceProj = geom->getProjection(); } // Insert a partial-pixel flipper to remap null-valued pixels to min. // This is set via preference keyword "orthoigen.flip_null_pixels" current_source = setupPixelFlipper(singleImageChain, theSrcRecords[idx]); // Install a band selector if needed: if (theSrcRecords[idx].getBands().size() && (img_handler->getNumberOfOutputBands() > 1)) { ossim_uint32 bands = img_handler->getNumberOfOutputBands(); bool validBand = true; for (ossim_uint32 i = 0; i < theSrcRecords[idx].getBands().size(); ++i) { if (theSrcRecords[idx].getBands()[i] >= bands) { validBand = false; ossimNotify(ossimNotifyLevel_FATAL) << " ERROR:" << "\nBand list range error!" << "\nHighest available band: " << bands << std::endl; } } if (validBand) { ossimRefPtr<ossimBandSelector> bs = new ossimBandSelector(); singleImageChain->insertRight(bs.get(), current_source); bs->setOutputBandList(theSrcRecords[idx].getBands()); current_source = bs.get(); } } // Install a histogram object if needed. This inserts just to the left of the resampler. setupHistogram(singleImageChain, theSrcRecords[idx]); // Add a cache just to the left of the resampler. if (!theCacheExcludedFlag) addChainCache(singleImageChain); // Add the single image chain to the mosaic and save it to the product spec file: singleImageChain->makeUniqueIds(); if (theSrcRecords[idx].isRgbData()) { if (!bandMergeObject) { bandMergeObject = new ossimBandMergeSource(); } bandMergeObject->connectMyInputTo(singleImageChain); singleImageChain->changeOwner(bandMergeObject.get()); } else { mosaicObject->connectMyInputTo(singleImageChain); singleImageChain->changeOwner(mosaicObject.get()); } //theContainer->addChild(singleImageChain); // Set the weight for this image when doing a blend mosaic: if (obm) obm->setWeight(idx, theSrcRecords[idx].getWeight()); } } // Finished initializing the inputs to the mosaic. Add the mosaic to the product chain. theProductChain = new ossimImageChain; if (bandMergeObject) { theProductChain->addFirst(bandMergeObject.get()); } theProductChain->addFirst(mosaicObject.get()); // Now need to pass the product chain through the histogram setup for possible remapper given // target histogram (used when histo-matching selected): setupHistogram(); // When mosaicking common input projections without rendering each, need to add a renderer to the // mosaic for reprojecting to output projection: if(orthoMosaic) { ossimImageRenderer* renderer = new ossimImageRenderer; renderer->getResampler()->setFilterType(theResamplerType); theProductChain->addFirst(current_source); } //--- // Now that "theProductChain" is initialized we must initialize elevation if needed as it can // affect the tie point of the output projection. //--- if ( isAffectedByElevation() ) { ossimInit::instance()->initializeElevation(); // Chain gsd's affected by elevation so recompute. reComputeChainGsds(); } // Set up the output product's projection: setupProjection(); // Annotation setup... setupAnnotation(); // Output rect cutter: setupCutter(); // Output radiometry filter: setupOutputRadiometry(); // After all the connections have been established, add the product chain to the overall // product container. This container will also hold the writer object. theContainer->addChild(theProductChain.get()); // Lastly, set up the write object (object2): setupWriter(); } //************************************************************************************************* // Initializes the Cut Rect filter to crop the mosaic to specified rectangle. // This method assumes that the view (theProductProjection) has already been propagated to all // the renderers (via call to setView()). This was done by prior call to setupProjection(). //************************************************************************************************* void ossimOrthoIgen::setupCutter() { // The command line accepts cut rect specification in several formats. Consolidate them to // a common form (UL tiepoint <theCutOrigin> and distance to LR pixel center <theCutDxDy>. This // method also updates the product projection with new bounds: consolidateCutRectSpec(); ossimImageSource* input_source = theProductChain->getFirstSource(); if((theCutDxDy.hasNans()&&theMaskShpFile.empty())||!theProductProjection.valid()||!input_source) return; //user may pass the shape filename with an query (e.g C:/myshp.shp|select * from myshp), //parse the name of mask shape file here ossimString query = ""; if (!theMaskShpFile.empty()) { if (theMaskShpFile.contains("|")) { ossimString fileName = theMaskShpFile; std::vector<ossimString> fileList = fileName.split("|"); if (fileList.size() > 1) { theMaskShpFile = fileList[0]; query = fileList[1]; } } } if (!theMaskShpFile.exists()) { if (theCutOriginUnit == OSSIM_METERS) // projection in meters... { ossimEastingNorthingCutter* cutter = new ossimEastingNorthingCutter; ossimDpt mpp (theProductProjection->getMetersPerPixel()); ossimDpt lr (theCutOrigin.x + theCutDxDy.x - mpp.x, theCutOrigin.y - theCutDxDy.y + mpp.y); cutter->setView(theProductProjection.get()); cutter->setEastingNorthingRectangle(theCutOrigin, lr); theProductChain->addFirst(cutter); } else // geographic projection, units = decimal degrees. { ossimGeoPolyCutter* cutter = new ossimGeoPolyCutter; std::vector<ossimGpt> polygon; ossimDpt dpp (theProductProjection->getDecimalDegreesPerPixel()); ossimGpt ul(theCutOrigin.lat, theCutOrigin.lon ); ossimGpt ur(theCutOrigin.lat, theCutOrigin.lon + theCutDxDy.x - dpp.x); ossimGpt lr(theCutOrigin.lat - theCutDxDy.y + dpp.y, theCutOrigin.lon + theCutDxDy.x - dpp.x); ossimGpt ll(theCutOrigin.lat - theCutDxDy.y + dpp.y, theCutOrigin.lon ); polygon.push_back(ul); polygon.push_back(ur); polygon.push_back(lr); polygon.push_back(ll); cutter->setView(theProductProjection.get()); cutter->setNumberOfPolygons(1); cutter->setPolygon(polygon); theProductChain->addFirst(cutter); } } else { ossimIrect inputRect = input_source->getBoundingRect(); ossimGeoPolyCutter* exteriorCutter = new ossimGeoPolyCutter; exteriorCutter->setView(theProductProjection.get()); ossimGeoPolyCutter* interiorCutter = NULL; ossimRefPtr<ossimImageHandler> shpHandler = ossimImageHandlerRegistry::instance()->open(theMaskShpFile); ossimEsriShapeFileInterface* shpInterface = PTR_CAST(ossimEsriShapeFileInterface, shpHandler.get()); if (shpInterface != NULL) { if (!query.empty()) { shpInterface->setQuery(query); } std::multimap<long, ossimAnnotationObject*> features = shpInterface->getFeatureTable(); if (features.size() > 0) { std::multimap<long, ossimAnnotationObject*>::iterator it = features.begin(); while (it != features.end()) { ossimAnnotationObject* anno = it->second; if (anno != NULL) { ossimGeoAnnotationPolyObject* annoPoly = PTR_CAST(ossimGeoAnnotationPolyObject, anno); ossimGeoAnnotationMultiPolyObject* annoMultiPoly = NULL; if (annoPoly == NULL) { annoMultiPoly = PTR_CAST(ossimGeoAnnotationMultiPolyObject, anno); } if (annoPoly != NULL) { std::vector<ossimGpt> polygon; //get the points of a polygon std::vector<ossimGpt> points = annoPoly->getPoints(); for (ossim_uint32 i = 0; i < points.size(); i++) { polygon.push_back(points[i]); } //get polygon type, if it is an internal polygon, initialize the internal cutter ossimGeoAnnotationPolyObject::ossimPolyType polyType = annoPoly->getPolyType(); if (polyType == ossimGeoAnnotationPolyObject::OSSIM_POLY_INTERIOR_RING) { if (interiorCutter == NULL) { interiorCutter = new ossimGeoPolyCutter; interiorCutter->setView(theProductProjection.get()); interiorCutter->setCutType(ossimPolyCutter::OSSIM_POLY_NULL_INSIDE); } interiorCutter->addPolygon(polygon); } else { exteriorCutter->addPolygon(polygon); } } else if (annoMultiPoly != NULL) { std::vector<ossimGeoPolygon> multiPolys = annoMultiPoly->getMultiPolygon(); for (ossim_uint32 i = 0; i < multiPolys.size(); i++) { ossimGeoPolygon geoPoly = multiPolys[i]; std::vector<ossimGeoPolygon> holePolys = geoPoly.getHoleList(); if (holePolys.size() > 0) { if (interiorCutter == NULL) { interiorCutter = new ossimGeoPolyCutter; interiorCutter->setView(theProductProjection.get()); interiorCutter->setCutType(ossimPolyCutter::OSSIM_POLY_NULL_INSIDE); } for (ossim_uint32 j = 0; j < holePolys.size(); j++) { interiorCutter->addPolygon(holePolys[j]); } } exteriorCutter->addPolygon(multiPolys[i]); } } else { throw(ossimException(std::string("The geometry type of the mask shape file is not polygon."))); } } it++; } } } //if user define the cut box, add it to the image chain ossimGeoPolyCutter* boundCutter = NULL; if (!theCutDxDy.hasNans() && !theCutOrigin.hasNans()) { std::vector<ossimGpt> bound; if (theCutOriginUnit == OSSIM_METERS) { ossimDpt mpp (theProductProjection->getMetersPerPixel()); ossimGpt ul = theProductProjection->inverse(ossimDpt(theCutOrigin.x, theCutOrigin.y)); ossimGpt ur = theProductProjection->inverse(ossimDpt(theCutOrigin.x + theCutDxDy.x - mpp.x, theCutOrigin.y)); ossimGpt lr = theProductProjection->inverse(ossimDpt(theCutOrigin.x + theCutDxDy.x - mpp.x, theCutOrigin.y - theCutDxDy.y + mpp.y)); ossimGpt ll = theProductProjection->inverse(ossimDpt(theCutOrigin.x, theCutOrigin.y - theCutDxDy.y + mpp.y)); bound.push_back(ul); bound.push_back(ur); bound.push_back(lr); bound.push_back(ll); } else { ossimDpt dpp (theProductProjection->getDecimalDegreesPerPixel()); ossimGpt ul(theCutOrigin.lat, theCutOrigin.lon ); ossimGpt ur(theCutOrigin.lat, theCutOrigin.lon + theCutDxDy.x - dpp.x); ossimGpt lr(theCutOrigin.lat - theCutDxDy.y + dpp.y, theCutOrigin.lon + theCutDxDy.x - dpp.x); ossimGpt ll(theCutOrigin.lat - theCutDxDy.y + dpp.y, theCutOrigin.lon ); bound.push_back(ul); bound.push_back(ur); bound.push_back(lr); bound.push_back(ll); } boundCutter = new ossimGeoPolyCutter; boundCutter->setView(theProductProjection.get()); boundCutter->setNumberOfPolygons(1); boundCutter->setPolygon(bound); } if (boundCutter == NULL) { ossimIrect shpRect = shpHandler->getBoundingRect(); if (shpRect.width() > inputRect.width() && shpRect.height() > inputRect.height()) { exteriorCutter->setRectangle(inputRect); } } theProductChain->addFirst(exteriorCutter); if (interiorCutter != NULL) { theProductChain->addFirst(interiorCutter); } if (boundCutter != NULL) { theProductChain->addFirst(boundCutter); } } } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::setupWriter() { if (!theProductChain.valid()) return; ossimRefPtr<ossimImageFileWriter> writer = 0; if (theWriterType.size()) { // User selected writer with -w or --writer option. writer = ossimImageWriterFactoryRegistry::instance()->createWriter(theWriterType); } else if ( theWriterTemplate.size() && theWriterTemplate.exists() ) { // User sent us a writer template. ossimKeywordlist kwlTemplate; kwlTemplate.addFile(theWriterTemplate); // Try first with no prefix. writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwlTemplate); if ( !writer.valid() ) writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwlTemplate, "object2."); } else if ( theTilingFilename == "%SRTM%") { ossimKeywordlist kwlWriter; kwlWriter.add("type", "ossimGeneralRasterWriter", true); kwlWriter.add("byte_order", "big_endian"); writer = ossimImageWriterFactoryRegistry::instance()->createWriter(kwlWriter); theProductFilename = theProductFilename.path(); } else if (!theTilingFilename.empty()) { if (theProductFilename.isDir()) { theProductFilename = theProductFilename + "/" + theTilingFilename; } } try { //--- // Set the output file name if not already set. // NOTE: Could be outputing to stdout in which case outputFilename does not // make sense. Leaving here though to not break code downstream. (drb) //--- if ( theProductFilename == ossimFilename::NIL ) { throw(ossimException(std::string("Writer output filename not set."))); } //--- // Final check for writer. //--- if ( !writer.valid() ) { // Derive writer from the extension. ossimFilename ext = theProductFilename.ext(); if ( ext.size() ) writer = ossimImageWriterFactoryRegistry::instance()->createWriterFromExtension(ext); //--- // Lastly default to tiff. Perhaps throw exception here instead. (drb) //--- if( !writer.valid() ) { writer = new ossimTiffWriter; theProductFilename.setExtension("tif"); } } // PIXEL_IS_AREA HACK: Temporary patch to override command line alignment type with source // image's alignment type. TO BE REMOVED ONCE EW GUI PROVIDES FOR USER-SETTING OF THIS // PROPERTY (OLK 09/11): if (thePixelAlignment == OSSIM_PIXEL_IS_AREA) { ossimString pixelType ("pixel_type"); theWriterProperties.erase(pixelType); theWriterProperties.insert(std::make_pair(pixelType, ossimString("area"))); } //--- // Set writer filename, connect and add to writer to keyword list. //--- if ( writer.valid() ) { writer->setFilename(theProductFilename); writer->connectMyInputTo(0, theProductChain.get()); ossimPropertyInterface* propInterface = (ossimPropertyInterface*)writer.get(); PropertyMap::iterator iter = theWriterProperties.begin(); while(iter != theWriterProperties.end()) { propInterface->setProperty(iter->first, iter->second); ++iter; } theContainer->addChild(writer.get()); } else { throw(ossimException(std::string("Unable to create writer."))); } } catch (const ossimException& e) { if (traceDebug()) ossimNotify(ossimNotifyLevel_DEBUG) << e.what() << std::endl; throw; // re-throw exception } } //************************************************************************************************* // This method establishes the output (view) projection of the product. // NOTE: Completely rewritten to simplify and reduce redundancy. OLK 3/10 //************************************************************************************************* void ossimOrthoIgen::setupProjection() { if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG)<<"Entering ossimOrthoIgen::setupProjection():"<<std::endl; } theProductProjection = 0; // Throw exception if no valid input image projection was established: if(!theReferenceProj.valid()) { std::string errMsg = "ossimOrthoIgen::setupProjection() -- Could not establish input image's " "projection. Cannot setup output view."; throw(ossimException(errMsg)); } // Fetch the reference input projection first. Settings may be copied to the product projection: ossimMapProjection* ref_map = PTR_CAST(ossimMapProjection, theReferenceProj.get()); // Now focus on establishing the output product projection. // Consider externally specified geometry first: if (theProjectionType == OSSIM_EXTERNAL_PROJECTION) { if (!theTemplateView.isReadable()) { ossimString errMsg = "ossimOrthoIgen::setupProjection() -- Could not read the product " "projection template file at <"; errMsg += theTemplateView; errMsg += ">. Cannot establish output projection."; throw(ossimException(errMsg)); } // Default template format is no prefix, but consider alternate with prefix if first attempt // fails: ossimKeywordlist templateKwl (theTemplateView); ossimObjectFactoryRegistry* ofr = ossimObjectFactoryRegistry::instance(); ossimRefPtr<ossimObject> productObj = ofr->createObject(templateKwl, "product.projection."); if(!productObj.valid()) productObj = ofr->createObject(templateKwl); theProductProjection = PTR_CAST(ossimMapProjection, productObj.get()); } // Geographic? (Assuming WGS 84 for now.) else if (theProjectionType == OSSIM_GEO_PROJECTION) { theProductProjection = new ossimEquDistCylProjection(); ossimGpt gpt(0.0, 0.0); if (theGeoScalingLatitude == 999.0) // flags that lat is to be computed { computeGeoScalingLatitude(); gpt = ossimGpt(theGeoScalingLatitude, 0.0); } else if (!ossim::isnan(theGeoScalingLatitude)) gpt = ossimGpt(theGeoScalingLatitude, 0.0); theProductProjection->setOrigin(gpt); } // CRS code specified on the command line else if (theProjectionType == OSSIM_SRS_PROJECTION) { ossimProjection* base_proj = ossimEpsgProjectionFactory::instance()->createProjection(theCrsString); theProductProjection = PTR_CAST(ossimMapProjection, base_proj); if(theProductProjection.valid()) { // Reassign the type for geographic. Now we know if (theProductProjection->isGeographic()) { theProjectionType = OSSIM_GEO_PROJECTION; ossimGpt gpt(0.0, 0.0); if (!ossim::isnan(theGeoScalingLatitude)) gpt = ossimGpt(theGeoScalingLatitude, 0.0); theProductProjection->setOrigin(gpt); } } else { theProjectionType = OSSIM_UNKNOWN_PROJECTION; ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::setupProjection() WARNING:" << " Unsupported spatial reference system." << " Will default to the projection from the input image." << std::endl; } } // UTM? else if (theProjectionType == OSSIM_UTM_PROJECTION) { ossimUtmProjection* utm = new ossimUtmProjection; ossimGpt refGpt; theReferenceProj->lineSampleToWorld(ossimDpt(0,0), refGpt); utm->setZone(refGpt); utm->setHemisphere(refGpt); theProductProjection = utm; } // None of the above? else { // Either OSSIM_INPUT_PROJECTION or OSSIM_UNKNOWN_PROJECTION. In both cases // just use the first image's input projection for the output. Need to make // sure the input_proj is a map projection though: if (ref_map) { theProductProjection = PTR_CAST(ossimMapProjection, ref_map->dup()); theProjectionType = OSSIM_INPUT_PROJECTION; // just in case it was unknown before } else { theProjectionType = OSSIM_GEO_PROJECTION; theProductProjection = new ossimEquDistCylProjection(); ossimGpt gpt(0.0, 0.0); if (!ossim::isnan(theGeoScalingLatitude)) gpt = ossimGpt(theGeoScalingLatitude, 0.0); theProductProjection->setOrigin(gpt); } } // At this point there should be a valid output projection defined: if (!theProductProjection.valid()) { std::string errMsg = "ossimOrthoIgen::setupProjection() -- Could not establish valid output " "projection"; throw(ossimException(errMsg)); } // HACK (OLK 06/10): The projection may not have had the PCS code initialized even though it // is an EPSG projection, so take this opportunity to identify a PCS for output: ossim_uint32 pcs_code = theProductProjection->getPcsCode(); if (pcs_code == 0) { pcs_code = ossimEpsgProjectionDatabase::instance()-> findProjectionCode(*(theProductProjection.get())); theProductProjection->setPcsCode(pcs_code); } // Bootstrap the process of establishing the mosaic tiepoint by setting it to the reference proj. if (ref_map) theProductProjection->setUlGpt(ref_map->getUlGpt()); // cout << "ref_map->getUlGpt(): " << ref_map->getUlGpt() << endl; // Base class makes sure the product view projection is properly wired into the chain. setView(); // Set the desired image GSD. This is nontrivial due to the many ways GSD can be implied and/or // explicitly provided. This method also does a setView before returning: setProductGsd(); theProjectionName = theProductProjection->getProjectionName(); // At this point, the product projection will not have a tiepoint (UL corner coordinates) // defined unless it is the same projection as the input reference. Need to set it now. Note that // if a cut-rect is specified, the tie-point will be modified later in setupCutter() establishMosaicTiePoint(); if (traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::setupProjection DEBUG:" << "Leaving...." << __LINE__ << std::endl; } } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::setupAnnotation() { ossimImageSource* input_source = theProductChain->getFirstSource(); if (!input_source) return; if(theAnnotationTemplate.exists() == false) return; ossimKeywordlist templateKwl; if (templateKwl.addFile(theAnnotationTemplate) == false) return; ossimRefPtr<ossimObject> obj = ossimObjectFactoryRegistry::instance()-> createObject(templateKwl, "object1."); if (obj.valid()) { ossimGeoAnnotationSource* oga = PTR_CAST(ossimGeoAnnotationSource, obj.get()); if (oga) { if (theProductProjection.valid()) oga->setGeometry(new ossimImageGeometry(0, theProductProjection.get())); theProductChain->addFirst(oga); } } return; } //************************************************************************************************* // Set up multi-file tiling if indicated on the command line. //************************************************************************************************* bool ossimOrthoIgen::setupTiling() { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimOrthoIgen::setupTiling: Entered......" << std::endl; } ossimKeywordlist templateKwl; ossimFilename outputFilename = theProductFilename; theTilingEnabled = false; if ((theTilingTemplate == "")||(!templateKwl.addFile(theTilingTemplate))) { if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimOrthoIgen::setupTiling: Leaving......" << __LINE__ << std::endl; } return false; } ossimString prefix ("igen.tiling."); while (1) { if(outputFilename.isDir()) { if(templateKwl.find(prefix.chars(), "type")) { theTilingFilename = templateKwl.find(prefix.chars(),"tile_name_mask"); theTilingEnabled = true; break; } else if (templateKwl.find(prefix.chars(), "tile_size") || templateKwl.find(prefix.chars(), "tile_source")) { theTilingFilename = templateKwl.find(prefix.chars(),"output_file_name"); theTilingEnabled = true; break; } } else { theTilingFilename = outputFilename.file(); if (!theTilingFilename.contains("%")) { ossimString fileNoExt = theTilingFilename.fileNoExtension(); ossimString ext = theTilingFilename.ext(); theTilingFilename = fileNoExt + "_%r%_%c%." + ext; } if(templateKwl.find(prefix.chars(), "type")) { templateKwl.add(prefix.chars(), "tile_name_mask", theTilingFilename.c_str(), true); ossimFilename path (outputFilename.path()); theProductFilename = path; theTilingEnabled = true; break; } else if (templateKwl.find(prefix.chars(), "tile_size") || templateKwl.find(prefix.chars(), "tile_source")) { templateKwl.add(prefix.chars(), "output_file_name", theTilingFilename.c_str(), true); ossimFilename path (outputFilename.path()); theProductFilename = path; theTilingEnabled = true; break; } } // If we got here, then no matches were found in the template. Try again but without a prefix: if (prefix.empty()) break; prefix.clear(); } // Initialize the tiling object if enabled: if (templateKwl.find(prefix.chars(), "tile_size")) { theTiling = 0; theTiling = new ossimTilingRect; } if (templateKwl.find(prefix.chars(), "tile_source")) { theTiling = 0; theTiling = new ossimTilingPoly; } if (theTilingEnabled && !theTiling->loadState(templateKwl, prefix)) theTilingEnabled = false; if(traceDebug()) { ossimNotify(ossimNotifyLevel_DEBUG) << "ossimOrthoIgen::setupTiling: templateKwl = \n" << templateKwl << std::endl; ossimNotify(ossimNotifyLevel_DEBUG) << "DEBUG ossimOrthoIgen::setupTiling: Leaving......" << __LINE__ << std::endl; } return true; } //************************************************************************************************* // Consolidates specification of bounding rect given various ways of specifying on the command // line. This avoids multiple, redundant checks scattered throughout the code. On exit: // // 1. theCutOriginType is converted to OSSIM_UPPER_LEFT_ORIGIN // 2. theCutOrigin is converted to the proper coordinates (lat/lon or easting/northing) and // associated theCutOriginUnits is assigned accordingly. // 3. theCutDxDy reflects the full size of the rect, in the units corresponding to the projection // and associated theCutDxDyUnit is set to METERS for UTM, DEGREES for geographic // 4. The product projection's origin (image center) and tie point are updated to reflect the // output rectangle. // //************************************************************************************************* void ossimOrthoIgen::consolidateCutRectSpec() { if (!theProductProjection.valid() || theCutDxDy.hasNans() || theCutOrigin.hasNans()) return; if ((theCutDxDyUnit != OSSIM_METERS) && (theCutDxDyUnit != OSSIM_DEGREES) && (theCutDxDyUnit != OSSIM_UNIT_UNKNOWN)) { ossimNotify(ossimNotifyLevel_WARN) << "ossimOrthoIgen::consolidateCutRectSpec: An unhandled" " type of units was encountered. The cut rect needs to be specified in either meters or" " degrees. The resulting cut rect and origin may be incorrect." << std::endl; return; } ossimGpt originPLH; ossimDpt resolution; // Geographic Projection (lat/lon cut rect) requested? if(theProductProjection->isGeographic()) { // geographic projection; units need to be decimal degrees. First check for consistent origin: if (theCutOriginUnit == OSSIM_METERS) { originPLH = theProductProjection->inverse(theCutOrigin); theCutOrigin.x = originPLH.lon; theCutOrigin.y = originPLH.lat; } else { originPLH.lat = theCutOrigin.y; originPLH.lon = theCutOrigin.x; } // Check for consistent rect size: if (theCutDxDyUnit == OSSIM_METERS) { ossimDpt mtrs_per_deg (originPLH.metersPerDegree()); theCutDxDy.x = theCutDxDy.x/mtrs_per_deg.x; theCutDxDy.y = theCutDxDy.y/mtrs_per_deg.y; } // Set these to the correct units. May already be correct, but just in case... theCutOriginUnit = OSSIM_DEGREES; theCutDxDyUnit = OSSIM_DEGREES; if (theClipToValidRectFlag) { // Now we need to clip the cut rect by the valid image footprint for the entire mosaic: ossimDrect boundingRect = theProductChain->getBoundingRect(); // in view coordinates // The bounding rect is in image space. Since pixel-is-point, the actual valid area on the // ground will extend 1/2 pixel beyond the centers, so grow the bounding rect by 1/2 p: boundingRect.expand(ossimDpt(0.5, 0.5)); ossimGpt mosaic_ul, mosaic_lr; theProductProjection->lineSampleHeightToWorld(boundingRect.ul(), 0, mosaic_ul); theProductProjection->lineSampleHeightToWorld(boundingRect.lr(), 0, mosaic_lr); // Establish the LR bound defined by the cut-rect and clip the cut-rect if necessary: ossimGpt cutrect_lr (theCutOrigin.lat - theCutDxDy.lat, theCutOrigin.lon + theCutDxDy.lon); if (mosaic_ul.lat < theCutOrigin.lat) theCutOrigin.lat = mosaic_ul.lat; if (mosaic_lr.lat > cutrect_lr.lat) theCutDxDy.lat = theCutOrigin.lat - mosaic_lr.lat; if (mosaic_ul.lon > theCutOrigin.lon) theCutOrigin.lon = mosaic_ul.lon; if (mosaic_lr.lon < cutrect_lr.lon) theCutDxDy.lon = mosaic_lr.lon - theCutOrigin.lon; } resolution = theProductProjection->getDecimalDegreesPerPixel(); } // Map Projection (easting, northing cut rect) requested? else { // Special case code to account for origin and delta being specified in geographic, leading to // offset error due to northing difference between UL and UR corners at constant lat: if ((theCutOriginType == OSSIM_UPPER_LEFT_ORIGIN) && (theCutOriginUnit == OSSIM_DEGREES) && (theCutDxDyUnit == OSSIM_DEGREES)) { ossimGpt ulgp (theCutOrigin.lat , theCutOrigin.lon , 0); ossimGpt urgp (theCutOrigin.lat , theCutOrigin.lon + theCutDxDy.lon, 0); ossimGpt llgp (theCutOrigin.lat - theCutDxDy.lat, theCutOrigin.lon , 0); ossimGpt lrgp (theCutOrigin.lat - theCutDxDy.lat, theCutOrigin.lon + theCutDxDy.lon, 0); ossimDpt ulen (theProductProjection->forward(ulgp)); ossimDpt uren (theProductProjection->forward(urgp)); ossimDpt llen (theProductProjection->forward(llgp)); ossimDpt lren (theProductProjection->forward(lrgp)); double n_top = (ulen.y > uren.y ? ulen.y : uren.y); double n_bottom = (llen.y < lren.y ? llen.y : lren.y); double e_left = (ulen.x < llen.x ? ulen.x : llen.x); double e_right = (uren.x > lren.x ? uren.x : lren.x); theCutOrigin.x = e_left; theCutOrigin.y = n_top; theCutDxDy.x = e_right - e_left; theCutDxDy.y = n_top - n_bottom; if (theClipToValidRectFlag) { // Now we need to clip the cut rect by the valid image footprint for the entire mosaic: ossimDrect boundingRect = theProductChain->getBoundingRect(); // in view coordinates boundingRect.expand(ossimDpt(0.5, 0.5)); ossimDpt mosaic_ul, mosaic_lr; theProductProjection->lineSampleToEastingNorthing(boundingRect.ul(), mosaic_ul); theProductProjection->lineSampleToEastingNorthing(boundingRect.lr(), mosaic_lr); // Establish the LR bound defined by the cut-rect and clip the cut-rect if necessary: ossimDpt cutrect_lr (theCutOrigin.x + theCutDxDy.x, theCutOrigin.y - theCutDxDy.y); if (mosaic_ul.y < theCutOrigin.y) theCutOrigin.y = mosaic_ul.y; if (mosaic_lr.y > cutrect_lr.y) theCutDxDy.y = theCutOrigin.y - mosaic_lr.y; if (mosaic_ul.x > theCutOrigin.x) theCutOrigin.x = mosaic_ul.x; if (mosaic_lr.x < cutrect_lr.x) theCutDxDy.x = mosaic_lr.x - theCutOrigin.x; } } else { // Just map the geographic coordinates to easting/northing, without regard to corner // mismatch: if (theCutOriginUnit == OSSIM_DEGREES) { originPLH.lat = theCutOrigin.y; originPLH.lon = theCutOrigin.x; theCutOrigin = theProductProjection->forward(originPLH); } else { // Determine the geographic position that might be needed for scaling below: originPLH = theProductProjection->inverse(theCutOrigin); } // Check for consistent rect size: if (theCutDxDyUnit == OSSIM_DEGREES) { // POTENTIAL BUG: conversion from degrees longitude to meters should be a function // of latitude here. Implemented here but needs testing: ossimDpt mtrs_per_deg (originPLH.metersPerDegree()); theCutDxDy.x = theCutDxDy.x * mtrs_per_deg.x; theCutDxDy.y = theCutDxDy.y * mtrs_per_deg.y; } } // Set these to the correct units. May already be correct, but just in case... theCutOriginUnit = OSSIM_METERS; theCutDxDyUnit = OSSIM_METERS; resolution = theProductProjection->getMetersPerPixel(); } // The cut rect corresponds to the edges of the pixel ("edge-to-edge"), while OSSIM considers // coordinates to correspond to the pixel centers. Need to shift the origin to the SE by 1/2p: ossimDpt half_pixel = resolution * 0.5; theCutOrigin.y -= half_pixel.y; theCutOrigin.x += half_pixel.x; // The size of the cutrect needs to be an integral number of pixels in output space: theCutDxDy.x = (floor(theCutDxDy.x/resolution.x + 0.5))* resolution.x; theCutDxDy.y = (floor(theCutDxDy.y/resolution.y + 0.5))* resolution.y; // Adjust a center origin specification to be Upper Left corner: if (theCutOriginType == OSSIM_CENTER_ORIGIN) { theCutOrigin.y += theCutDxDy.y; theCutOrigin.x -= theCutDxDy.x; // theCutDxDy in this case represented a radius. This needs to be converted to // OSSIM_UPPER_LEFT_ORIGIN form: theCutDxDy.x *= 2.0; theCutDxDy.y *= 2.0; theCutOriginType = OSSIM_UPPER_LEFT_ORIGIN; } // Finally, update the product projection with new rectangle: ossimDpt cutCenter (theCutOrigin.x + theCutDxDy.x/2.0, theCutOrigin.y - theCutDxDy.y/2.0); ossimGpt gpt; if (theCutDxDyUnit == OSSIM_METERS) { // Set the E/N values for the cut origin as the tie point: theProductProjection->setUlTiePoints(theCutOrigin); } else { // Set the projection center (origin) latitude at the center of the cut rect: gpt.lat = cutCenter.y; gpt.lon = 0.0; theProductProjection->setOrigin(gpt); // Set the lat/lon values for the cut origin as the tie point: gpt.lat = theCutOrigin.y; gpt.lon = theCutOrigin.x; theProductProjection->setUlTiePoints(gpt); } // cout << "\n**************** proj 2:\n"; // theProductProjection->print(cout); // Propagates changes to the projection to the processing chain: setView(); } //************************************************************************************************* //! Sets up the histogram operation requested for the image chain passed in. //************************************************************************************************* void ossimOrthoIgen::setupHistogram(ossimImageChain* input_chain, const ossimSrcRecord& src_record) { // Check if the source passed in is the output mosaic object, because the target // histogram remapper needs to be connected to it (only valid when histo matching is requested): if (input_chain == NULL) { if (!theTargetHistoFileName.isReadable()) return; ossimHistogramRemapper* remapper = new ossimHistogramRemapper; remapper->openHistogram(theTargetHistoFileName); theProductChain->addFirst(remapper); return; } // Check if any histo operation was requested on individual image: if ((ossim::isnan(theHighPercentClip) || ossim::isnan(theLowPercentClip)) && !theUseAutoMinMaxFlag && (theStdDevClip < 0) && src_record.getHistogramOp().empty() && theTargetHistoFileName.empty()) { return; // no histo op requested } // Remaining operations require a histogram on the input image source: ossimImageHandler* handler = PTR_CAST(ossimImageHandler, input_chain->getLastSource()); if (handler == NULL) { ossimNotify(ossimNotifyLevel_FATAL)<<"Could not locate an image handler object in the image" << "chain provided. This should not happen. Ignoring histogram request." << std::endl; return; } // Establish the ideal filename for this histogram. The following do-block is all for testing // different histogram file naming schemes since alternate directory and entry-indexing might be // used: ossimFilename histoFilename (src_record.getHistogramPath()); ossimFilename candidateHistoFilename; ossimFilename defaultHistoFilename (handler->createDefaultHistogramFilename()); ossimFilename entryName (handler->getFilenameWithThisExtension(ossimString(".his"), true)); do { if (!histoFilename.empty()) { // Try histogram filename based on specified name in the .src file: if (histoFilename.isDir()) histoFilename = histoFilename.dirCat(defaultHistoFilename.file()); if (histoFilename.exists()) break; // Try specified name with entry index: if (src_record.getEntryIndex() >= 0) { histoFilename = histoFilename.path().dirCat(entryName.file()); if (histoFilename.exists()) break; } // Not found so set the candidate filename in case we need to generate it: candidateHistoFilename = histoFilename; } // Next try looking for a histogram based on the default name: histoFilename = defaultHistoFilename; if (histoFilename.exists()) break; //--- // Last possibility is the default name with entry index. We will test // even if there is only one entry, like "file_e0.his". //--- histoFilename = entryName; if (histoFilename.exists()) break; // If not already set, set the candidate filename in case we need to generate it: if (candidateHistoFilename.empty()) candidateHistoFilename = histoFilename; } while (false); // only pass through once // If the histogram was still not located, look into creating one: if (!histoFilename.exists()) { // Check the preferences for histogram autogeneration: ossimString lookup = ossimPreferences::instance()->findPreference(AUTOGENERATE_HISTOGRAM_KW); if (lookup.toBool()) { // No histogram available for this image, need to create one: histoFilename = candidateHistoFilename; ossimNotify(ossimNotifyLevel_WARN) <<"Histogram file <" << histoFilename << "> not found. Creating one now..." << std::endl; bool success = createHistogram(input_chain, histoFilename); if (!success) { ossimNotify(ossimNotifyLevel_WARN) <<"Error encountered creating histogram file <" << histoFilename << ">. Ignoring histogram request." << std::endl; return; } } } // Need to insert any histogram object to the left of the renderer in the chain. Search for a // renderer and save for later: // ossimConnectableObject* renderer = PTR_CAST(ossimConnectableObject, // input_chain->findFirstObjectOfType(ossimString("ossimImageRenderer"))); ossimTypeNameVisitor visitor( ossimString("ossimImageRenderer"), true, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); input_chain->accept( visitor ); ossimRefPtr<ossimImageRenderer> renderer = visitor.getObjectAs<ossimImageRenderer>(0); // Histo Match? if (theTargetHistoFileName.isReadable()) { // A histogram match was requested. This involves applying a histo equalization to the input // chain and then applying an inverted equalization using the target histogram: ossimRefPtr<ossimHistogramEqualization> forwardEq = new ossimHistogramEqualization; ossimRefPtr<ossimHistogramEqualization> inverseEq = new ossimHistogramEqualization; // Init equalizers with the source and target histogram files: forwardEq->setInverseFlag(false); forwardEq->setHistogram(histoFilename); inverseEq->setInverseFlag(true); inverseEq->setHistogram(theTargetHistoFileName); // Need check that source and target histograms are compatible: ossimRefPtr<ossimMultiResLevelHistogram> sourceHisto = forwardEq->getHistogram(); ossimRefPtr<ossimMultiResLevelHistogram> targetHisto = inverseEq->getHistogram(); bool are_incompatible = false; if (!sourceHisto.valid() || !targetHisto.valid()) { are_incompatible = true; } else { ossim_uint32 num_source_bands = sourceHisto->getNumberOfBands(); if (num_source_bands != targetHisto->getNumberOfBands()) { are_incompatible = true; } else { for (ossim_uint32 band=0; band<num_source_bands; band++) { ossimRefPtr<ossimHistogram> sourceBandHisto = sourceHisto->getHistogram(band); ossimRefPtr<ossimHistogram> targetBandHisto = targetHisto->getHistogram(band); if (!sourceBandHisto.valid() || !targetBandHisto.valid() || (sourceBandHisto->GetRes() != targetBandHisto->GetRes())) { are_incompatible = true; break; } } } } if (are_incompatible) { // Error was encountered establishing histograms for match operation: ossimNotify(ossimNotifyLevel_WARN)<<"Error encountered setting up histogram match " "operation. Check that source and target histograms are compatible. No histogram " "operations will be performed on this image." << std::endl; return; } // The source and target histos are compatible, insert to the left of renderer if one exists: if ( renderer.valid() ) input_chain->insertLeft( forwardEq.get(), renderer.get() ); else input_chain->addFirst(forwardEq.get()); input_chain->insertRight(inverseEq.get(), forwardEq.get()); return; } // Remaining possibilities (clip or stretch) require a remapper. // Insert to the left of renderer if one exists: ossimRefPtr<ossimHistogramRemapper> remapper = new ossimHistogramRemapper; if ( renderer.valid() ) input_chain->insertLeft( remapper.get(), renderer.get() ); else input_chain->addFirst(remapper.get()); // Fetch the input histogram: bool histo_read_ok = remapper->openHistogram(histoFilename); if (!histo_read_ok) { // No histogram available for this image, need to create one (TODO): ossimNotify(ossimNotifyLevel_WARN)<<"Error encountered loading histogram file <" << histoFilename << ">. No histogram operations will be performed on this image." << std::endl; return; } // Set values to construct remap table: if (!ossim::isnan(theHighPercentClip) && !ossim::isnan(theLowPercentClip)) { // Hi/Lo clip requested remapper->setHighNormalizedClipPoint(1.0-theHighPercentClip); remapper->setLowNormalizedClipPoint(theLowPercentClip); } else { // Consider histogram stretch operations. These can be on a per-image basis or global for all // input images. Give priority to the img_histo_op (per-image spec) over general flags below: ossimHistogramRemapper::StretchMode mode = ossimHistogramRemapper::STRETCH_UNKNOWN; ossimString img_histo_op (src_record.getHistogramOp()); if (img_histo_op=="auto-minmax") mode = ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX; else if (img_histo_op.contains("std-stretch")) { if (img_histo_op.contains("1")) mode = ossimHistogramRemapper::LINEAR_1STD_FROM_MEAN; else if (img_histo_op.contains("2")) mode = ossimHistogramRemapper::LINEAR_2STD_FROM_MEAN; else if (img_histo_op.contains("3")) mode = ossimHistogramRemapper::LINEAR_3STD_FROM_MEAN; } else if (theUseAutoMinMaxFlag) mode = ossimHistogramRemapper::LINEAR_AUTO_MIN_MAX; else if (theStdDevClip > 0) mode = (ossimHistogramRemapper::StretchMode) theStdDevClip; // Finally init the remapper with proper stretch mode: if (mode != ossimHistogramRemapper::STRETCH_UNKNOWN) remapper->setStretchMode(mode, true); } return; } //************************************************************************************************* //! Utility method for creating a histogram for an input image. Returns TRUE if successful. //************************************************************************************************* bool ossimOrthoIgen::createHistogram(ossimImageChain* chain, const ossimFilename& histo_filename) { ossimRefPtr<ossimImageHistogramSource> histoSource = new ossimImageHistogramSource; ossimRefPtr<ossimHistogramWriter> writer = new ossimHistogramWriter; histoSource->connectMyInputTo(chain); histoSource->enableSource(); histoSource->setComputationMode(OSSIM_HISTO_MODE_FAST); writer->connectMyInputTo(histoSource.get()); writer->setFilename(histo_filename); writer->addListener(&theStdOutProgress); bool success = writer->execute(); writer=0; histoSource=0; if (success) { ossimNotify(ossimNotifyLevel_NOTICE)<<std::endl; } else { ossimNotify(ossimNotifyLevel_WARN)<<"Error encountered creating Histogram file <" << histo_filename << ">. No histogram operations will be performed on this image." << std::endl; } return success; } //************************************************************************************************* // METHOD //************************************************************************************************* void ossimOrthoIgen::addChainCache(ossimImageChain* chain) const { if (chain) { //ossimConnectableObject* renderer = // PTR_CAST(ossimConnectableObject, // chain->findFirstObjectOfType(ossimString("ossimImageRenderer"))); ossimTypeNameVisitor visitor( ossimString("ossimImageRenderer"), true, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); chain->accept( visitor ); ossimRefPtr<ossimImageRenderer> renderer = visitor.getObjectAs<ossimImageRenderer>(0); if ( renderer.valid() ) { ossimCacheTileSource* cache = new ossimCacheTileSource(); chain->insertLeft( cache, renderer.get() ); } } } //************************************************************************************************* // Generates a log KWL file that could be fed directly to Igen. Used for verifying chain. //************************************************************************************************* void ossimOrthoIgen::generateLog() { if (!theSrcRecords.size() || !theProductChain.valid() || theProductFilename.empty()) return; // Establish output filename: ossimFilename logFile = theProductFilename; logFile.setExtension("log"); // Fill a KWL with all info: ossimKeywordlist kwl; theContainer->saveState(kwl); if (theProductProjection.valid()) theProductProjection->saveState(kwl, "product.projection."); kwl.write(logFile.chars()); } //************************************************************************************************* //! Determines the UL corner tiepoint of the product projection as the overall UL corner of the //! mosaic. This may not be the final tiepoint, since a cut origin may have been specified, and the //************************************************************************************************* void ossimOrthoIgen::establishMosaicTiePoint() { if (!theProductChain.valid()) return; // Need to find all image handlers to query for their UL ground point: #if 0 ossimConnectableObject::ConnectableObjectList clientList; theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimImageHandler), true, true); if (clientList.size() == 0) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimOrthoIgen::establishMosaicTiePoint() WARNING -- " "Expected to find image handler in the chain but none was identified."<<std::endl; return; } #endif ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); if ( visitor.getObjects().empty() ) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimOrthoIgen::establishMosaicTiePoint() WARNING -- " "Expected to find image handler in the chain but none was identified."<<std::endl; return; } ossimGpt tie_gpt_i, tie_gpt; ossimDpt tie_dpt_i, tie_dpt; tie_gpt.makeNan(); tie_gpt.height(0.0); tie_dpt.makeNan(); // Loop over all input handlers and latch the most NW tiepoint as the mosaic TP: // ossimConnectableObject::ConnectableObjectList::iterator iter = clientList.begin(); // while (iter != clientList.end()) for( ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i ) { // ossimImageHandler* handler = PTR_CAST(ossimImageHandler, (*iter).get()); // iter++; ossimImageHandler* handler = visitor.getObjectAs<ossimImageHandler>( i ); if (!handler) break; ossimRefPtr<ossimImageGeometry> geom = handler->getImageGeometry(); if (!geom.valid()) continue; // Skip over any non geometry inputs (e.g., masks) if ( theProductProjection->isGeographic() ) { geom->getTiePoint( tie_gpt_i, true ); // True to get edge of tie. if ( tie_gpt_i.hasNans() == false ) { if (tie_gpt.hasNans()) tie_gpt = tie_gpt_i; else { if (tie_gpt_i.lat > tie_gpt.lat) tie_gpt.lat = tie_gpt_i.lat; if (tie_gpt_i.lon < tie_gpt.lon) tie_gpt.lon = tie_gpt_i.lon; } } } else { geom->getTiePoint( tie_dpt_i, true ); // True to get edge of tie. if ( tie_dpt_i.hasNans() == false ) { if (tie_dpt.hasNans()) tie_dpt = tie_dpt_i; else { if (tie_dpt_i.y > tie_dpt.y) tie_dpt.y = tie_dpt_i.y; if (tie_dpt_i.x < tie_dpt.x) tie_dpt.x = tie_dpt_i.x; } } } } #if 0 // Establish input image bounding rect, making sure to expand to include the FULL pixel since // pixel is point -- i.e. the pixel coordinate corresponds to the center of the pixel area, // not the edge. Therefore shift the image point by 1/2 pixel to correspond to edges: // (OLK 09/11) ossimDrect boundingRect (handler->getBoundingRect()); vector<ossimDpt> img_vertices; img_vertices.push_back(boundingRect.ul() + ossimDpt(-0.5, -0.5)); img_vertices.push_back(boundingRect.ur() + ossimDpt( 0.5, -0.5)); img_vertices.push_back(boundingRect.lr() + ossimDpt( 0.5, 0.5)); img_vertices.push_back(boundingRect.ll() + ossimDpt(-0.5, 0.5)); // The tie point will be in easting/northing or lat/lon depending on the type of projection // used for the product. Need to consider all image corners since the orientation of the image // is not known: for (int j=0; j<4; j++) { geom->localToWorld(img_vertices[j], tie_gpt_i); if (theProductProjection->isGeographic()) { tie_gpt.height(0.0); if (tie_gpt.hasNans()) tie_gpt = tie_gpt_i; else { if (tie_gpt_i.lat > tie_gpt.lat) tie_gpt.lat = tie_gpt_i.lat; if (tie_gpt_i.lon < tie_gpt.lon) tie_gpt.lon = tie_gpt_i.lon; } } else { tie_dpt_i = theProductProjection->forward(tie_gpt_i); if (tie_dpt.hasNans()) tie_dpt = tie_dpt_i; else { if (tie_dpt_i.y > tie_dpt.y) tie_dpt.y = tie_dpt_i.y; if (tie_dpt_i.x < tie_dpt.x) tie_dpt.x = tie_dpt_i.x; } } } } #endif // The tie point coordinates currently reflect the UL edge of the UL pixel. We'll need to shift // the tie point from the edge to the center. (OLK 09/11) ossimDpt half_pixel_shift(0,0); if (theProductProjection->isGeographic()) { half_pixel_shift = theProductProjection->getDecimalDegreesPerPixel() * 0.5; if (!tie_gpt.hasNans()) { tie_gpt.lat -= half_pixel_shift.lat; tie_gpt.lon += half_pixel_shift.lon; theProductProjection->setUlTiePoints(tie_gpt); } } else { half_pixel_shift = theProductProjection->getMetersPerPixel() * 0.5; tie_dpt.y -= half_pixel_shift.y; tie_dpt.x += half_pixel_shift.x; theProductProjection->setUlTiePoints(tie_dpt); } // Propagates changes to the projection to the processing chain: setView(); } //************************************************************************************************* //! Computes the center latitude of the mosaic for use as the geographic scaling latitude //************************************************************************************************* void ossimOrthoIgen::computeGeoScalingLatitude() { if (!theProductChain.valid()) return; // Need to find all image handlers to query for their UL ground point: ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); if ( visitor.getObjects().empty() ) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimOrthoIgen::establishMosaicTiePoint() WARNING -- " "Expected to find image handler in the chain but none was identified."<<std::endl; return; } ossimGpt ul_i, ur_i, lr_i, ll_i; ossimGrect bbox; bbox.makeNan(); // Loop over all input handlers and latch the extremes of the corner points: for (ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i) { ossimImageHandler* handler = visitor.getObjectAs<ossimImageHandler>(i); if (!handler) break; ossimRefPtr<ossimImageGeometry> geom = handler->getImageGeometry(); if (!geom.valid()) continue; // Skip over any non geometry inputs (e.g., masks) geom->getCornerGpts(ul_i, ur_i, lr_i, ll_i); ossimGrect bbox_i(ul_i, ur_i, lr_i, ll_i); bbox = bbox.combine(bbox_i); } // Fetch midpoint and assign scaling latitude: ossimGpt midPoint (bbox.midPoint()); if (!midPoint.isLatNan()) theGeoScalingLatitude = midPoint.lat; else theGeoScalingLatitude = 0.0; } //************************************************************************************************* // Initialize the pixel flipper in the source chain if one is called for //************************************************************************************************* ossimImageSource* ossimOrthoIgen::setupPixelFlipper(ossimImageChain* singleImageChain, const ossimSrcRecord& src_record) { if (singleImageChain == NULL) return NULL; // Fetch the image handler that should be the last (left-most) source in the chain: ossimImageSource* current_source = singleImageChain->getLastSource(); if (current_source == NULL) return NULL; // There are two possibilities for specifying pixel flipping -- either as a command line option // that applies to all input imagery, or specified for a particular input via the .src file. // The .src file takes precedence: const ossimSrcRecord::PixelFlipParams& flipParams = src_record.getPixelFlipParams(); // The replacement can be specified globally in the preferences if none found in the src record: ossimString replaceModeStr = flipParams.replacementMode; if (replaceModeStr.empty()) replaceModeStr = thePixelReplacementMode; // First consider if a range of clipped pixels was specified: ossim_float64 clip_min = flipParams.clipMin; if (ossim::isnan(clip_min)) clip_min = theClipPixelMin; ossim_float64 clip_max = flipParams.clipMax; if (ossim::isnan(clip_max)) clip_max = theClipPixelMax; ossimPixelFlipper* flipper = 0; if (!ossim::isnan(clip_min) && !ossim::isnan(clip_max)) { // A clip within a range of pixel values was requested. All pixels within the specified range // are mapped to NULL. Create the remapper and insert it into the chain just after the handler flipper = new ossimPixelFlipper(); flipper->setTargetRange(clip_min, clip_max); flipper->setReplacementValue(current_source->getNullPixelValue()); flipper->setReplacementMode(replaceModeStr); singleImageChain->insertRight(flipper, current_source); current_source = flipper; } // The user can also specify a clamping similar to the pixel clipping above. This would be a // second flipper object in the chain: ossim_float64 clamp_min = flipParams.clampMin; if (ossim::isnan(clamp_min)) clamp_min = theClampPixelMin; ossim_float64 clamp_max = flipParams.clampMax; if (ossim::isnan(clamp_max)) clamp_max = theClampPixelMax; flipper = 0; // no leak since chain assumes ownership of prior instance. if (!ossim::isnan(clamp_min)) { // A bottom clamping was requested. All pixels below this value are set to this value: flipper = new ossimPixelFlipper(); flipper->setClampValue(clamp_min, false); // false = clamp bottom } if (!ossim::isnan(clamp_max)) { // A top clamping was requested. All pixels above this value are set to this value. // The same flipper object can be used as the bottom clamp (if created): if (!flipper) flipper = new ossimPixelFlipper(); flipper->setClampValue(clamp_max, true); // true = clamp top } if (flipper) { // Common code for top and bottom clamping: flipper->setReplacementMode(replaceModeStr); singleImageChain->insertRight(flipper, current_source); current_source = flipper; } return current_source; } //************************************************************************************************* // Checks for the presence of a raster mask file alongside the image, and inserts the mask // filter in the chain if mask file exists. Returns pointer to the "current (last added) source // in the single image chain. //************************************************************************************************* ossimImageSource* ossimOrthoIgen::setupRasterMask(ossimImageChain* singleImageChain, const ossimSrcRecord& src_record) { if (singleImageChain == NULL) return NULL; // Search for the image handler in the chain: ossimImageHandler* img_handler = dynamic_cast<ossimImageHandler*>(singleImageChain->getLastSource()); if (img_handler == NULL) return NULL; // See if a raster mask was specified in the SRC record: ossimFilename mask_file = src_record.getMaskPath(); if (!mask_file.exists()) return img_handler; // Open up the mask file and verify it is good: ossimImageHandler* mask_handler = ossimImageHandlerRegistry::instance()->open(mask_file); if (mask_handler == NULL) { ossimNotify(ossimNotifyLevel_WARN)<<"ossimOrthoIgen::setupRasterMask() -- Could not open " "raster mask file <"<<mask_file<<">. Maske request will be ignored."<<endl; return img_handler; } // Create the mask filter and give it the image and mask tile sources. Add it to the chain. // IMPORTANT NOTE: the mask filter is an image combiner. It is being inserted into a single // image chain. Since it owns its two inputs (the image handler and the mask), it must // replace the handler in the chain. Also, see note in ossimMaskFilter::setInputSources(). //singleImageChain->deleteLast(); // Remove the handler // ossimImageSource* nextInChain = singleImageChain->getLastSource(); ossimRefPtr<ossimMaskFilter> mask_filter = new ossimMaskFilter; singleImageChain->insertRight(mask_filter.get(), img_handler); mask_filter->setMaskSource(mask_handler); // assumes ownership of object //--- // Set the mode to SELECT_CLAMP_MIN. This clamps data to min pixel value in the valid image // area if the input pixel is null(essentially a pixel flip). //--- mask_filter->setMaskType(ossimMaskFilter::OSSIM_MASK_TYPE_SELECT_CLAMP_MIN); return mask_filter.get(); } //************************************************************************************************* // Adds a scalar remapper to the extreme right of the chain is specified by the // --output-radiometry option. //************************************************************************************************* void ossimOrthoIgen::setupOutputRadiometry() { if (theOutputRadiometry.empty()) return; // Map the specified radiometry to a valid type: ossimScalarType scalar_type = ossimScalarTypeLut::instance()->getScalarTypeFromString(theOutputRadiometry); if (scalar_type == OSSIM_SCALAR_UNKNOWN) return; // Add a scalar remapper to the product chain: if(theProductChain->getOutputScalarType() != scalar_type) { ossimScalarRemapper* remapper = new ossimScalarRemapper; remapper->setOutputScalarType(scalar_type); theProductChain->addFirst(remapper); } } //************************************************************************************************* // Private method to see if any image chain input projections are affected by elevation. //************************************************************************************************* bool ossimOrthoIgen::isAffectedByElevation() { bool result = false; // Get a list of all the image handlers. // ossimConnectableObject::ConnectableObjectList clientList; // theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimImageHandler), // true, true); ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); // Loop over all input handlers and see if affected by elevation. // ossimConnectableObject::ConnectableObjectList::iterator iter = clientList.begin(); // while (iter != clientList.end()) for( ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i ) { // ossimRefPtr<ossimImageHandler> handler = PTR_CAST(ossimImageHandler, (*iter).get()); ossimRefPtr<ossimImageHandler> handler = visitor.getObjectAs<ossimImageHandler>( i ); if ( handler.valid() ) { ossimRefPtr<ossimImageGeometry> geom = handler->getImageGeometry(); if (geom.valid()) { ossimRefPtr<const ossimProjection> proj = geom->getProjection(); if ( proj.valid() ) { if ( proj->isAffectedByElevation() ) { result = true; break; } } } } // ++iter; } return result; } //************************************************************************************************* // Private method to recompute the gsd on all image handlers that have projections affected by // elevation. //************************************************************************************************* void ossimOrthoIgen::reComputeChainGsds() { // Get a list of all the image handlers. // ossimConnectableObject::ConnectableObjectList clientList; // theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimImageHandler), // true, true); // Loop over all input handlers and see if affected by elevation. // ossimConnectableObject::ConnectableObjectList::iterator iter = clientList.begin(); // while (iter != clientList.end()) ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); for( ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i ) { // ossimRefPtr<ossimImageHandler> handler = PTR_CAST(ossimImageHandler, (*iter).get()); ossimRefPtr<ossimImageHandler> handler = visitor.getObjectAs<ossimImageHandler>( i ); if ( handler.valid() ) { ossimRefPtr<ossimImageGeometry> geom = handler->getImageGeometry(); if (geom.valid()) { ossimRefPtr<ossimProjection> proj = geom->getProjection(); if ( proj.valid() ) { if ( proj->isAffectedByElevation() ) proj->getMetersPerPixel(); } } } // ++iter; } } //************************************************************************************************* // GSD Determination is nontrivial since there are various command-line options that control // this quantity. This method considers all information before setting the product's GSD. //************************************************************************************************* void ossimOrthoIgen::setProductGsd() { if (!theProductChain.valid()) return; // Fetch the reference input projection first. Settings may be copied to the product projection: ossimMapProjection* ref_map = PTR_CAST(ossimMapProjection, theReferenceProj.get()); ossimGpt origin; // The geo-scaling latitude effectively specifies the map projection's origin latitude, which // may affect the scaling of GSD in x-direction. This is only relevant for geographic projections if (theProductProjection->isGeographic()) { ossimGpt origin (0.0, theProductProjection->getOrigin().lon, 0.0); if (ossim::isnan(theGeoScalingLatitude)) { // Loop over all input handlers and accumulate the geographic centers. This will allow // computing mosaic center point (approximate) for purposes of establishing reference // latitude for scale: origin.lat = 0.0; origin.lon = theProductProjection->getOrigin().lon; // ossimConnectableObject::ConnectableObjectList clientList; // theProductChain->findAllInputsOfType(clientList, STATIC_TYPE_INFO(ossimImageHandler), 1, 1); // ossimConnectableObject::ConnectableObjectList::iterator iter = clientList.begin(); ossimTypeNameVisitor visitor( ossimString("ossimImageHandler"), false, // firstofTypeFlag (ossimVisitor::VISIT_INPUTS| ossimVisitor::VISIT_CHILDREN) ); theProductChain->accept( visitor ); ossimDpt center_pt; ossimGpt geocenter; int num_contributors = 0; // while (iter != clientList.end()) for( ossim_uint32 i = 0; i < visitor.getObjects().size(); ++i ) { // ossimImageHandler* handler = PTR_CAST(ossimImageHandler, (*iter).get()); ossimRefPtr<ossimImageHandler> handler = visitor.getObjectAs<ossimImageHandler>( i ); if ( handler.valid() ) { // iter++; ossimRefPtr<ossimImageGeometry> geom = handler->getImageGeometry(); if (!geom.valid()) continue; // Skip over any non geometry inputs (e.g., masks) handler->getBoundingRect().getCenter(center_pt); if (!geom->localToWorld(center_pt, geocenter)) continue; if (num_contributors == 0) origin.lat = geocenter.lat; else origin.lat += geocenter.lat; ++num_contributors; } else { break; } } // Compute average latitude among all contributors: if (num_contributors) origin.lat /= (double)num_contributors; } else { // A geo-scaling reference latitude was provided on the command line: origin.lat = theGeoScalingLatitude; } // Set the latitude of origin to the reference latitude (either specified on command line or // computed as scene center): theProductProjection->setOrigin(origin); // proj now can handle meters and degrees correctly } // Establish the resolution based on either command line option or reference proj if no values // provided on command line (--degrees or --meters): ossimDpt resolution (theDeltaPerPixelOverride); ossimUnitType resUnits = theDeltaPerPixelUnit; if (resolution.hasNans()) { // No GSD specified, so copy it from the input projection: if (ref_map && ref_map->isGeographic()) { resolution = ref_map->getDecimalDegreesPerPixel(); resUnits = OSSIM_DEGREES; } else { resolution = theReferenceProj->getMetersPerPixel(); resUnits = OSSIM_METERS; } } // Set the desired image GSD, accounting for possible mixing of units: if (resUnits == OSSIM_DEGREES) { // Need to adjust the resolution in the longitude direction if the user requested geo-scaling: if (!ossim::isnan(theGeoScalingLatitude)) resolution.lon = resolution.lat/ossim::cosd(theGeoScalingLatitude); theProductProjection->setDecimalDegreesPerPixel(resolution); } else theProductProjection->setMetersPerPixel(resolution); // Propagates changes to the projection to the processing chain: setView(); }
4ed74cb8284b51e3e5f94c5d487f176cc8d974e4
211dc4d24f6c06cb1d3b67f9106517d6ab1a2159
/ABC/105/CakesandDonuts.cpp
d826c0737cecfe09c3038207dcad72a7a6123e2d
[]
no_license
oonota/atcoder
afe565f89fa646a1d0d4c30aeff51a9cf8150343
e7a6e0220583ad91e3fbb40257eb94d9f2b85565
refs/heads/master
2021-04-15T03:41:17.775133
2018-12-21T12:24:03
2018-12-21T12:24:03
126,293,973
0
0
null
null
null
null
UTF-8
C++
false
false
265
cpp
CakesandDonuts.cpp
#include <bits/stdc++.h> #define print(x) std::cout << x << std::endl int main(void){ int N; std::cin >> N; for(int x=0;x<=(N/4);++x){ for(int y=0;y<=(N/7);++y){ if(4*x+7*y == N){ print("Yes"); return 0; } } } print("No"); return 0; }
2c91561974ae9b4d55e679588ab3fce0cbe2a78d
a4bbc60bcc82ee6212825ce21fc9e4fa7b04e870
/Algorithms/Labirinth/Gyl_lab.cc
19bbc4ef6bc85265870b7107ccf4eaa8dd5f55fc
[]
no_license
Luksys5/LT_programos
3a7cabb6c5e8a23a856983c1938d2d492cddf916
959ab74029df334767fcad84adc46ae36cf7cdf1
refs/heads/master
2021-01-19T19:33:11.505596
2017-03-12T18:08:14
2017-03-12T18:08:14
16,478,166
0
1
null
null
null
null
UTF-8
C++
false
false
5,059
cc
Gyl_lab.cc
#include <stdio.h> #include <string> #include <math.h> #include <stdlib.h> #include <vector> #include <iostream> #include <fstream> using namespace std; struct map_bool { vector< vector<int> > m1; bool check; }; void output_Labirinth(vector< vector<int> > LAB, int maxval, int size, string tarp, string del, bool on) { float mkiek = (float)maxval; int mtarp = 1; while(mkiek > 1) { mkiek = mkiek / 10; mtarp++; } cout << " ^\n"; for(int i = 0; i < size; i++) { if(size - i < 10) cout << size - i << " | "; else cout << size - i << " | "; int index = 0; for(int j = 0; j < LAB[i].size(); j++) { //if(on) if(LAB[size - i - 1][j] > 9) cout << LAB[size - i - 1][j] << " "; else cout << LAB[size - i - 1][j] << " "; //else //cout << " " << LAB[i-1][j] << " "; }cout << "\n"; } cout << " "; for(int j = 0; j < size; j++) cout << "-----"; cout << "--> X\n"; cout << tarp; for(int j = 1; j < size + 1; j++) { if(j > 9) cout << j << del; else cout << j << del + " "; } cout << "\n"; } bool eiti(vector< vector<int> > &LAB,vector< vector<int> > &newmap, vector<int> CX, vector<int> CY, int N, int M, int &X, int &Y, int &BANDSK, int &L, bool YRA, int &max, vector<pair<int, int> > &coord, string tarp, vector<string> &rod, vector<int> RV) { int K, U, V; int size = LAB.size(); max = LAB[Y][X]; //newmap[Y][X] = max; //cout << "X: " << X << " Y: " << Y << "\n"; if(X == 0 || X == (M-1) || Y == 0 || Y == (N-1)) { YRA = true; return YRA; }else { K = 0; while(YRA != true && K < 4) { U = X + CX[K]; V = Y + CY[K]; //cout << V + 1 << ' ' << U + 1 << "\n"; string R = "R" + to_string(RV[K]); cout << tarp << R << ": X=" << U + 1 << " Y=" << V + 1; if(LAB[V][U] == 1) cout << " Siena"; else if(LAB[V][U] != 0) cout << " Siulas"; cout << "\n"; if(LAB[V][U] == 0) { rod.push_back(R); coord.push_back(make_pair(U + 1, V + 1)); BANDSK++; if( L < 2 ) L = 2; L++; //if(V == 4 && U == 4) // L += 2; newmap[V][U] = L; LAB[V][U] = L; YRA = eiti(LAB, newmap, CX, CY, N, M, U, V, BANDSK, L, YRA, max, coord, tarp + " ", rod, RV); if(YRA != true) { rod.pop_back(); coord.pop_back(); LAB[V][U] = 0; L--; if( L < 2) L = 2; } } K++; } } return YRA; } int main(int argc, char* argv[]) { ifstream fh(argv[1]); vector< vector<int> > map; vector<int> info; int BANDSK = 0; int L = 2; int sk, X, Y, maxas; bool siena = true; bool yra = false; vector<string> rod; vector< pair<int, int> > coord; while(fh >> sk) { info.push_back(sk); } int size = sqrt(info.size()); for(int i = 0; i < size; i++) { vector<int> col; map.push_back(col); } for(int i = 0; i < size; i++) { for(int j = 0; j < size; j++) { map[size - 1 - i].push_back( info[(i*size) + j] ); } } int N = map.size(); int M = map[0].size(); vector<int> rv = {2, 1, 3, 4}; //vector<int> cy = {1, -1, 0, 0}; //vector<int> cx = {0, 0, 1, -1}; //vector<int> cx = {0, -1, 0, 1, }; //vector<int> cy = {-1, 0, 1, 0, }; vector<int> cy = {-1, 0, 0, 1 }; vector<int> cx = {0, -1, 1, 0 }; cout << "1. Labirintas\n\n"; output_Labirinth(map, 1, size, " ", " ", false); while(siena) { cout << "\nIveskite pradines X, Y koordinates\n"; cin >> X; cin >> Y; X -= 1; Y -= 1; cout << "X: " << X << "\n"; cout << "Y: " << Y << "\n"; cout << map[Y][X] << "\n"; if(map[Y][X] != 1) siena = false; else cout << "Rasta siena kartojama iš naujo\n"; } int pradX = X; int pradY = Y; cout << "\n"; map[Y][X] = L; L = 3; vector< vector<int> > newmap = map; //output_Labirinth(map, 1, size, " ", " ", true); bool ats = eiti(map, newmap, cx, cy, N, M, X, Y, L, BANDSK, yra, maxas, coord, "", rod, rv); cout << "\n\n"; if(ats) cout << "3.1 Kelias egzistuoja\n\n"; else { cout << "3.1 Kelias neegzistuoja\n\n"; output_Labirinth(newmap, 1, size, " ", " ", false); return 0; } cout << "3.2 Kelias pagal rodykles\n"; for(int i = 0; i < rod.size(); i++) { cout << rod[i] << "; "; if((i+1) % 6 == 0) cout << "\n"; }cout << "\n\n"; cout << "3.3 Kelias pagal virsunes\n"; int last = coord[0].second; cout << "["<< pradX + 1 << ", " << pradY + 1 << "]; "; for(int i = 0; i < coord.size(); i++) { cout << "[" << coord[i].first <<", " << coord[i].second << "]; "; if((i+1) % 6 == 0) cout << "\n"; }cout << "\n"; cout << "\n3.4 Kelias pagal Labirinta\n Y\n"; //output_Labirinth(newmap, maxas, size, " ", " ", false); output_Labirinth(newmap, 1, size, " ", " ", false); return 0; }
a71d01a72e104ebedaabf92457f08aeea192ab6a
0db30cde38602258683fb4a296ed23e4536b6dcf
/DP/Bitonic Subsequence.cpp
3563679abea3445ca740ab8ca57692ab47347ac6
[]
no_license
naitik179/DataStructures-PlacementPrep
470f91de3ea8ee5e5776e45bdbec48786a23a9fc
9ad2fd44c29f6e530abcf5e555b5d1479b583271
refs/heads/master
2022-12-16T00:29:12.815143
2020-09-18T19:33:33
2020-09-18T19:33:33
261,490,152
0
0
null
null
null
null
UTF-8
C++
false
false
859
cpp
Bitonic Subsequence.cpp
#include <iostream> #include<bits/stdc++.h> using namespace std; int main() { //code int t; cin>>t; while(t--){ int n; cin>>n; int a[n]; for(int i=0;i<n;i++){ cin>>a[i]; } int lis[n] , lds[n]; for(int i=0;i<n;i++){ lis[i] = 1; lds[i] = 1; } for(int i=1;i<n;i++){ for(int j=0;j<i;j++){ if(a[i] > a[j] && lis[i] < lis[j]+1){ lis[i] = lis[j]+1; } } } for(int i=n-2;i>=0;i--){ for(int j=n-1;j>i;j--){ if(a[i] > a[j] && lds[i] < lds[j]+1){ lds[i] = lds[j]+1; } } } int maxi = lis[0] + lds[0] -1; for(int i=1;i<n;i++){ maxi = max(lis[i] + lds[i] -1,maxi); } cout<<maxi<<"\n"; } return 0; }
17fddf6dbe8e58ab58cb00d7c7b83cc4fd0ee4b9
f76015b61f7796f06eaf6e0e4ad0095f0427ac20
/testpackage.cpp
ee4fe142030e8e959bfc2f6b4bdc3fc1a50d3fc1
[]
no_license
A-Shafei/miscellaneous-c-
54480a53b10bc3c21a81a531ce5d2d74690cc03a
220399a23c5d96d307f24e6d4f60a1553a0d303d
refs/heads/master
2023-03-21T06:11:24.124866
2021-03-16T20:38:17
2021-03-16T20:38:17
221,711,568
0
0
null
null
null
null
UTF-8
C++
false
false
411
cpp
testpackage.cpp
#include "Package.h" #include "TwoDayPackage.h" #include <iostream> using namespace std; int main() { Package toys("Adam", "Eve", "5th street", "7th street", "Cairo", "Istanbul", 02615, 05262, 700, 2); cout << toys.calculateCost() << endl; TwoDayPackage fastToys("Lucifer", "John", "5th street", "7th street", "Cairo", "Istanbul", 02615, 05262, 800, 3, 50); cout << fastToys.calculateCost() << endl; }
d8f5aa3bd48ce4855b37bca6d71a73e3ffaaf9ba
4e0e547faea00915da80df29ad803b36207058d8
/src/smf_parser.cpp
65cbb7210f004965ff3959b04439eb8d89e4989a
[]
no_license
fshamshirdar/3DShapeSynthesis
5a9c734cb2b89f57381722e39c901512cfb273b4
64757a6f85c57882dafaf48b303ef75d3d637c79
refs/heads/master
2021-08-30T05:53:32.294500
2017-12-16T09:00:55
2017-12-16T09:00:55
112,975,245
1
0
null
null
null
null
UTF-8
C++
false
false
6,555
cpp
smf_parser.cpp
#include "smf_parser.h" SMFParser::SMFParser() { } SMFParser::~SMFParser() { } Data* SMFParser::load(const std::string &filename) { Data* data = new Data(); data->path = filename; std::ifstream infile(filename.c_str()); if (! infile.good()) { return NULL; } bool size_parsed = false; std::string line; int p = 0; int i = 0; // total vertex number int j = 0; int k = 0; int partType; float minDistance = 100.0; Data::Part* currentPart = NULL; Data::Region* currentRegion = new Data::Region(); Data::Region* previousRegion; // load line by line while (std::getline(infile, line)) { if (line.size() < 1) { continue; } std::istringstream iss(line.substr(1)); // switch by the leading character switch (line[0]) { case 'v': { float x, y, z; iss >> x >> y >> z; Data::Vertex* newVertex = new Data::Vertex; newVertex->id = i; newVertex->regionId = k; newVertex->pos[0] = x; newVertex->pos[1] = y; newVertex->pos[2] = z; newVertex->pos[3] = 1; if (x < currentRegion->boundingBox.min()[0]) { currentRegion->boundingBox.min()[0] = x; } if (y < currentRegion->boundingBox.min()[1]) { currentRegion->boundingBox.min()[1] = y; } if (z < currentRegion->boundingBox.min()[2]) { currentRegion->boundingBox.min()[2] = z; } if (x > currentRegion->boundingBox.max()[0]) { currentRegion->boundingBox.max()[0] = x; } if (y > currentRegion->boundingBox.max()[1]) { currentRegion->boundingBox.max()[1] = y; } if (z > currentRegion->boundingBox.max()[2]) { currentRegion->boundingBox.max()[2] = z; } currentRegion->vertices.push_back(newVertex); // TODO: modify smf file to store number of vertices as well i++; } break; case 'g': currentRegion->id = k; // currentRegion->name = line.substr(2); iss >> currentRegion->name >> partType; currentPart = data->findPartByType(static_cast<Data::Part::Type>(partType)); currentPart->regions.push_back(currentRegion); for (int bi = 0; bi < 3; bi++) { if (currentRegion->boundingBox.min()[bi] < currentPart->boundingBox.min()[bi]) { currentPart->boundingBox.min()[bi] = currentRegion->boundingBox.min()[bi]; } if (currentRegion->boundingBox.max()[bi] > currentPart->boundingBox.max()[bi]) { currentPart->boundingBox.max()[bi] = currentRegion->boundingBox.max()[bi]; } } k++; previousRegion = currentRegion; currentRegion = new Data::Region(); // std::cout << partType << " " << previousRegion->name << std::endl; break; case 'f': { bool e1f = false, e2f = false, e3f = false; bool e1e = true, e2e = true, e3e = true; int v1, v2, v3; int ov1, ov2, ov3; iss >> v1 >> v2 >> v3; v1 --; v2 --; v3 --; v1 -= (i - previousRegion->vertices.size()); v2 -= (i - previousRegion->vertices.size()); v3 -= (i - previousRegion->vertices.size()); ov1 = v1; ov2 = v2; ov3 = v3; Data::Face* newFace = new Data::Face; if (v1 > v2) { ov2 = v1; ov1 = v2; e1f = true; } Data::W_edge* e1 = data->findEdge(previousRegion, previousRegion->vertices[ov1], previousRegion->vertices[ov2]); if (! e1) { e1e = false; e1 = new Data::W_edge; e1->start = previousRegion->vertices[ov1]; e1->end = previousRegion->vertices[ov2]; e1->left = NULL; e1->right = NULL; e1->left_next = NULL; e1->left_prev = NULL; e1->right_next = NULL; e1->right_prev = NULL; previousRegion->edges.push_back(e1); } ov1 = v1; ov2 = v2; ov3 = v3; if (v2 > v3) { ov3 = v2; ov2 = v3; e2f = true; } Data::W_edge* e2 = data->findEdge(previousRegion, previousRegion->vertices[ov2], previousRegion->vertices[ov3]); if (! e2) { e2e = false; e2 = new Data::W_edge; e2->start = previousRegion->vertices[ov2]; e2->end = previousRegion->vertices[ov3]; e2->left = NULL; e2->right = NULL; e2->left_next = NULL; e2->left_prev = NULL; e2->right_next = NULL; e2->right_prev = NULL; previousRegion->edges.push_back(e2); } ov1 = v1; ov2 = v2; ov3 = v3; if (v3 > v1) { ov3 = v1; ov1 = v3; e3f = true; } Data::W_edge* e3 = data->findEdge(previousRegion, previousRegion->vertices[ov3], previousRegion->vertices[ov1]); if (! e3) { e3e = false; e3 = new Data::W_edge; e3->start = previousRegion->vertices[ov3]; e3->end = previousRegion->vertices[ov1]; e3->left = NULL; e3->right = NULL; e3->left_next = NULL; e3->left_prev = NULL; e3->right_next = NULL; e3->right_prev = NULL; previousRegion->edges.push_back(e3); } if (e1f) { e1->right = newFace; e1->right_prev = e2; e1->right_next = e3; } else { e1->left = newFace; e1->left_prev = e2; e1->left_next = e3; } if (e2f) { e2->right = newFace; e2->right_prev = e3; e2->right_next = e1; } else { e2->left = newFace; e2->left_prev = e3; e2->left_next = e1; } if (e3f) { e3->right = newFace; e3->right_prev = e1; e3->right_next = e2; } else { e3->left = newFace; e3->left_prev = e1; e3->left_next = e2; } previousRegion->vertices[v1]->edge = e1; previousRegion->vertices[v2]->edge = e2; previousRegion->vertices[v3]->edge = e3; // previousRegion->vertices[v1]->pairs.push_back(vertices[v2]); // previousRegion->vertices[v2]->pairs.push_back(vertices[v3]); // previousRegion->vertices[v3]->pairs.push_back(vertices[v1]); newFace->id = j; newFace->regionId = previousRegion->id; newFace->edge = e1; newFace->v1 = previousRegion->vertices[v1]; newFace->v2 = previousRegion->vertices[v2]; newFace->v3 = previousRegion->vertices[v3]; newFace->calculateFaceNormal(); previousRegion->faces.push_back(newFace); j++; } break; case '#': if (size_parsed == false || false) { // TODO: text format required, off for now iss >> data->vertices_size >> data->faces_size; size_parsed = true; currentRegion->vertices.resize(data->vertices_size); currentRegion->faces.resize(data->faces_size); } break; default: break; } } infile.close(); std::cout << "loadFile " << filename << std::endl; for (int i = 0; i < data->parts.size(); i++) { for (int j = 0; j < data->parts[i]->regions.size(); j++) { for (int k = 0; k < data->parts[i]->regions[j]->vertices.size(); k++) { data->parts[i]->regions[j]->vertices[k]->calculateVertexNormal(); } } } // parse edge list and face map return data; }
bf84476ccd2a61957484dd6c691c1b60662e93f8
d16b8dcbd0d618c58e9ff0a6ed07fcf20a837094
/gw/gw.h
f43fc8f412d3ede67a84646a6443ea5f52291953
[]
no_license
liuyang81s/TraitsGW
f50db1bf156da18170e7333cd2a6226365be526f
65529160a6de85ff13c87268e4bc8d9e62b6feef
refs/heads/master
2020-04-12T07:35:19.182257
2016-06-07T09:44:28
2016-06-07T09:44:28
58,275,373
1
0
null
null
null
null
UTF-8
C++
false
false
1,836
h
gw.h
#ifndef TRAITS_GW_H #define TRAITS_GW_H #include <string> #include <stdint.h> #include "serial.h" #include "timerlist.h" #include "packetfilemgr.h" #include "traits.h" using namespace std; extern bool GW_RUNNING; extern bool HB_RUNNING; void* gw_run(void* arg); void* hb_run(void* arg); typedef enum{ SEND_NOTHING = 0, //no need to send any SEND_ASCII, //send data in ascii format SEND_HEX, //send data in hex format SEND_INVALID, }SEND_TYPE; typedef enum{ PROTO_NONE = 0, //protocol NOT found PROTO_MODBUS, //modbus protocol PROTO_OTHER, //protocol but not modbus PROTO_INVALID, }PROTO_TYPE; typedef enum{ PLAN_NONE = 0, //there is no plan PLAN_UPDATE, //update to new plan PLAN_REMAIN, //remain old plan PLAN_INVALID, }PLAN_MODE; class TraitsGW { public: TraitsGW(); TraitsGW(const string& url); ~TraitsGW(); TRAITScode init(); TRAITScode request_init(); TRAITScode heartbeat(); TRAITScode report(uint8_t *packet, const int size); string get_port() const; UART_MODE get_uart_mode() const; SEND_TYPE get_send_type() const; PROTO_TYPE get_proto_type() const; PLAN_MODE get_plan_mode() const; TimerList* get_timerlist() const; protected: string get_self_id(); TRAITScode init_response_handler(const string& response); TRAITScode data_response_handler(const string& response); TRAITScode hb_response_handler(const string& response); /* device related */ string gage_name; string vendor; string gage_type; string gage_no; string self_id; string server_url; string port; UART_MODE uart_mode; SEND_TYPE send_type; PROTO_TYPE proto; PLAN_MODE plan_mode; TimerList* tmlist; uint8_t collect_cycle; PacketFileMgr pfmgr; }; #endif
cbaa052abe113ee8d199d20827863f841d0b55a1
6728d26c33ba897e02502e0747821e780d73e418
/Coding-Ninja/Patterns-1/charSquarePattern.cpp
5be1fc5359d6683da80cb33b3cc9110282808d66
[]
no_license
khusharth/DSA-practice
eb97b241c773ff6ad375680f0fa1bc872c1f7fc2
f512b45e15e46eace8ff7b1e97127f0aada8466d
refs/heads/master
2023-01-20T10:44:24.518878
2020-11-21T14:05:28
2020-11-21T14:05:28
299,550,403
0
0
null
null
null
null
UTF-8
C++
false
false
471
cpp
charSquarePattern.cpp
/* Print the following pattern for the given N number of rows. Pattern for N = 3 ABCD ABCD ABCD Input format : Integer N (Total no. of rows) Output format : Pattern in N lines Constraints 0 <= N <= 26 */ #include<iostream> using namespace std; int main(){ int n; cin >> n; int i = 1; while(i <= n) { int j = 1; while (j <= n) { char ch = 'A' + j - 1; cout<<ch; j++; } cout<<endl; i++; } }
ec232e6856c5078fb99b3ec44f521fceaeab9e38
facaa188a63679dd91c307f330a87d79609b8471
/myunp/4_server_kanyun.cc
f78e4122cf524c0c6affa6dd83756ee46c041ee9
[]
no_license
Jerling/study_notes
760986830d6a8a1526f393ea37f93cbd0a321219
cf6f4b78b910920871ee3024f7dda0765c0586c4
refs/heads/master
2020-04-05T04:53:44.690336
2019-01-18T08:04:57
2019-01-18T08:04:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,104
cc
4_server_kanyun.cc
#include "unp.h" #include <iostream> int main(int argc, char **argv) { int listenfd, connfd; char buff[MAXLINE]; pid_t pid; time_t ticks; struct sockaddr_in servaddr; struct sockaddr_in cliaddr; socklen_t cliLen; listenfd = socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(9877); bind(listenfd, (SA *)&servaddr, sizeof(servaddr)); listen(listenfd, 5); for ( ; ; ){ cliLen = sizeof(cliaddr); connfd = accept(listenfd, (SA *)&cliaddr, &cliLen); if ((pid = fork()) == 0){ close(listenfd); ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); std::cout << buff << "\n"; write(connfd, buff, strlen(buff)); _exit(0); } if (waitpid(pid, NULL, 0) != pid){ printf("waitpid error\n"); exit(1); } close(connfd); } return 0; }
401d9479ad9a19d510b423cdcc13328aac1ca195
72e0c56e7e8e310b03e2f1c36148cc9bbe41fbf5
/cfiles/test1.cpp
95b9f5fed426563e3b571795f70374dcb36c38b5
[ "Apache-2.0" ]
permissive
justinmann/sj-test-json
3c937484073ca05294ca73b84125826595f9beba
9a0e0650c8c1355cf9f49e9acd49ea5757e43fa8
refs/heads/master
2021-05-11T21:02:03.004259
2018-01-15T23:30:15
2018-01-15T23:30:15
117,457,723
0
0
null
null
null
null
UTF-8
C++
false
false
180,083
cpp
test1.cpp
#include <lib/sj-lib-common/common.h> struct { int refcount; int size; int count; char data[593]; } sjg_string1 = { 1, 593, 592, " "}; struct { int refcount; int size; int count; char data[3]; } sjg_string10 = { 1, 3, 2, "[ "}; struct { int refcount; int size; int count; char data[3]; } sjg_string11 = { 1, 3, 2, " ]"}; struct { int refcount; int size; int count; char data[6]; } sjg_string12 = { 1, 6, 5, "\"abc\""}; struct { int refcount; int size; int count; char data[3]; } sjg_string13 = { 1, 3, 2, "12"}; struct { int refcount; int size; int count; char data[13]; } sjg_string14 = { 1, 13, 12, "[\"abc\" , 12]"}; struct { int refcount; int size; int count; char data[4]; } sjg_string15 = { 1, 4, 3, "{ }"}; struct { int refcount; int size; int count; char data[20]; } sjg_string16 = { 1, 20, 19, "{ \n\n\"abc\" : \"foo\" }"}; struct { int refcount; int size; int count; char data[33]; } sjg_string17 = { 1, 33, 32, "{ \n\n\"abc\" : { \"foo\" : \"bar\" } }"}; struct { int refcount; int size; int count; char data[301]; } sjg_string18 = { 1, 301, 300, "{\r\n \"title\" : \"This is a title\",\r\n \"parentalAdvisory\" : \"This is a parental advisory\",\r\n \"hasAdultText\" : true,\r\n \"strings\" : {\r\n \"adult_17481\" : \"Adult Text\",\r\n \"dp_product_info_energy_class\" : \"Energy Class Level\"\r\n },\r\n \"energyEfficiencyClass\" : \"Energy Class\"\r\n}"}; struct { int refcount; int size; int count; char data[370]; } sjg_string19 = { 1, 370, 369, "{\r\n \"title\" : \"This is a title\",\r\n \"parentalAdvisory\" : \"This is a parental advisory\",\r\n \"formatList\" : [\r\n \"Format 1\",\r\n \"Format 2\"\r\n ],\r\n \"hasAdultText\" : true,\r\n \"strings\" : {\r\n \"adult_17481\" : \"Adult Text\",\r\n \"dp_product_info_energy_class\" : \"Energy Class Level\"\r\n },\r\n \"energyEfficiencyClass\" : \"Energy Class\"\r\n}"}; struct { int refcount; int size; int count; char data[1]; } sjg_string2 = { 1, 1, 0, ""}; struct { int refcount; int size; int count; char data[14]; } sjg_string3 = { 1, 14, 13, "out of bounds"}; struct { int refcount; int size; int count; char data[12]; } sjg_string4 = { 1, 12, 11, "Parse Error"}; struct { int refcount; int size; int count; char data[3]; } sjg_string5 = { 1, 3, 2, "{ "}; struct { int refcount; int size; int count; char data[2]; } sjg_string6 = { 1, 2, 1, "\""}; struct { int refcount; int size; int count; char data[5]; } sjg_string7 = { 1, 5, 4, "\" : "}; struct { int refcount; int size; int count; char data[3]; } sjg_string8 = { 1, 3, 2, ", "}; struct { int refcount; int size; int count; char data[3]; } sjg_string9 = { 1, 3, 2, " }"}; struct { int refcount; int size; int count; char data[0]; } g_empty = { 1, 0, 0 }; #define sjs_hash_type_bool_typeId 15 #define sjs_log_typeId 20 #define sjs_array_char_typeId 23 #define sjs_string_typeId 21 #define sjs_array_value_typeId 45 #define sjs_hash_string_value_typeId 35 #define sjs_json_value_typeId 28 #define sjs_tuple2_i32_string_typeId 40 #define sjs_tuple2_i32_value_typeId 30 #define sjs_list_value_typeId 46 #define sjs_array_string_typeId 59 #define cb_value_string_typeId 78 #define cb_value_string_heap_typeId 78 #define sjs_lambda3_typeId 80 #define cb_value_string_heap_string_typeId 82 #define cb_value_string_heap_string_heap_typeId 82 #define sjs_list_string_typeId 58 #define cb_string_value_void_typeId 61 #define cb_string_value_void_heap_typeId 61 #define cb_string_value_string_typeId 57 #define cb_string_value_string_heap_typeId 57 #define sjs_lambda1_typeId 62 #define sjs_lambda2_typeId 69 #define cb_string_value_string_heap_string_typeId 73 #define cb_string_value_string_heap_string_heap_typeId 73 typedef struct td_sjs_hash_type_bool sjs_hash_type_bool; typedef struct td_sjs_log sjs_log; typedef struct td_sjs_array_char sjs_array_char; typedef struct td_sjs_string sjs_string; typedef struct td_sjs_array_value sjs_array_value; typedef struct td_sjs_hash_string_value sjs_hash_string_value; typedef struct td_sjs_json_value sjs_json_value; typedef struct td_sjs_tuple2_i32_string sjs_tuple2_i32_string; typedef struct td_sjs_tuple2_i32_value sjs_tuple2_i32_value; typedef struct td_sjs_list_value sjs_list_value; typedef struct td_sjs_array_string sjs_array_string; typedef struct td_cb_value_string cb_value_string; typedef struct td_cb_value_string_heap cb_value_string_heap; typedef struct td_sjs_lambda3 sjs_lambda3; typedef struct td_cb_value_string_heap_string cb_value_string_heap_string; typedef struct td_cb_value_string_heap_string_heap cb_value_string_heap_string_heap; typedef struct td_sjs_list_string sjs_list_string; typedef struct td_cb_string_value_void cb_string_value_void; typedef struct td_cb_string_value_void_heap cb_string_value_void_heap; typedef struct td_cb_string_value_string cb_string_value_string; typedef struct td_cb_string_value_string_heap cb_string_value_string_heap; typedef struct td_sjs_lambda1 sjs_lambda1; typedef struct td_sjs_lambda2 sjs_lambda2; typedef struct td_cb_string_value_string_heap_string cb_string_value_string_heap_string; typedef struct td_cb_string_value_string_heap_string_heap cb_string_value_string_heap_string_heap; struct td_sjs_hash_type_bool { int _refCount; void* _hash; }; struct td_sjs_log { int _refCount; int32_t minlevel; sjs_hash_type_bool traceincludes; sjs_hash_type_bool debugincludes; sjs_hash_type_bool infoincludes; sjs_hash_type_bool warnincludes; sjs_hash_type_bool errorincludes; sjs_hash_type_bool fatalincludes; }; struct td_sjs_array_char { int _refCount; void* v; }; struct td_sjs_string { int _refCount; int32_t offset; int32_t count; sjs_array_char data; bool _isnullterminated; }; struct td_sjs_array_value { int _refCount; void* v; }; struct td_sjs_hash_string_value { int _refCount; void* _hash; }; struct td_sjs_json_value { int _refCount; sjs_string s; sjs_array_value a; sjs_hash_string_value h; }; struct td_sjs_tuple2_i32_string { int _refCount; int32_t item1; sjs_string item2; }; struct td_sjs_tuple2_i32_value { int _refCount; int32_t item1; sjs_json_value item2; }; struct td_sjs_list_value { int _refCount; sjs_array_value arr; }; struct td_sjs_array_string { int _refCount; void* v; }; struct td_cb_value_string { sjs_object* _parent; void (*_cb)(sjs_object* _parent, sjs_json_value*, sjs_string* _return); }; struct td_cb_value_string_heap { cb_value_string inner; void (*_destroy)(sjs_object*); }; struct td_sjs_lambda3 { int _refCount; }; struct td_cb_value_string_heap_string { sjs_object* _parent; void (*_cb)(sjs_object* _parent, sjs_json_value*, sjs_string* _return); void (*_cb_heap)(sjs_object* _parent, sjs_json_value*, sjs_string** _return); }; struct td_cb_value_string_heap_string_heap { cb_value_string_heap_string inner; void (*_destroy)(sjs_object*); }; struct td_sjs_list_string { int _refCount; sjs_array_string arr; }; struct td_cb_string_value_void { sjs_object* _parent; void (*_cb)(sjs_object* _parent, sjs_string*, sjs_json_value*); }; struct td_cb_string_value_void_heap { cb_string_value_void inner; void (*_destroy)(sjs_object*); }; struct td_cb_string_value_string { sjs_object* _parent; void (*_cb)(sjs_object* _parent, sjs_string*, sjs_json_value*, sjs_string* _return); }; struct td_cb_string_value_string_heap { cb_string_value_string inner; void (*_destroy)(sjs_object*); }; struct td_sjs_lambda1 { int _refCount; sjs_list_string* lambdaparam1; cb_string_value_string lambdaparam2; cb_string_value_string lambdaparam3; }; struct td_sjs_lambda2 { int _refCount; }; struct td_cb_string_value_string_heap_string { sjs_object* _parent; void (*_cb)(sjs_object* _parent, sjs_string*, sjs_json_value*, sjs_string* _return); void (*_cb_heap)(sjs_object* _parent, sjs_string*, sjs_json_value*, sjs_string** _return); }; struct td_cb_string_value_string_heap_string_heap { cb_string_value_string_heap_string inner; void (*_destroy)(sjs_object*); }; #ifndef type_bool_hash_typedef #define type_bool_hash_typedef KHASH_INIT_TYPEDEF(type_bool_hash_type, int32_t, bool) #endif #ifndef type_bool_hash_typedef #define type_bool_hash_typedef KHASH_INIT_TYPEDEF(type_bool_hash_type, int32_t, bool) #endif char* string_char(sjs_string* str); #ifndef string_value_hash_typedef #define string_value_hash_typedef KHASH_INIT_TYPEDEF(string_value_hash_type, sjs_string, sjs_json_value) #endif #ifndef string_value_hash_typedef #define string_value_hash_typedef KHASH_INIT_TYPEDEF(string_value_hash_type, sjs_string, sjs_json_value) #endif int32_t g_loglevel_debug; int32_t g_loglevel_error; int32_t g_loglevel_fatal; int32_t g_loglevel_info; int32_t g_loglevel_trace; int32_t g_loglevel_warn; sjs_string g_allthespaces = { -1 }; int32_t g_clocks_per_sec; float g_f32_pi; int32_t g_i32_maxvalue; int32_t g_i32_minvalue; sjs_log g_log = { -1 }; sjs_hash_type_bool g_log_excludeall = { -1 }; sjs_hash_type_bool g_log_includeall = { -1 }; uint32_t g_u32_maxvalue; int32_t result1; sjs_string sjt_call56 = { -1 }; sjs_string sjt_call57 = { -1 }; sjs_string sjt_call58 = { -1 }; sjs_string sjt_call59 = { -1 }; sjs_string sjt_call60 = { -1 }; sjs_string sjt_call61 = { -1 }; sjs_string sjt_call62 = { -1 }; sjs_string sjt_call63 = { -1 }; sjs_string* sjt_functionParam176 = 0; sjs_string* sjt_functionParam177 = 0; sjs_string* sjt_functionParam178 = 0; sjs_string* sjt_functionParam179 = 0; sjs_string* sjt_functionParam180 = 0; sjs_string* sjt_functionParam181 = 0; sjs_string* sjt_functionParam182 = 0; sjs_string* sjt_functionParam183 = 0; sjs_hash_type_bool sjt_value1 = { -1 }; void sjf_array_char(sjs_array_char* _this); void sjf_array_char_clone(sjs_array_char* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_char* _return); void sjf_array_char_clone_heap(sjs_array_char* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_char** _return); void sjf_array_char_copy(sjs_array_char* _this, sjs_array_char* _from); void sjf_array_char_destroy(sjs_array_char* _this); void sjf_array_char_getat(sjs_array_char* _parent, int32_t index, char* _return); void sjf_array_char_getcount(sjs_array_char* _parent, int32_t* _return); void sjf_array_char_gettotalcount(sjs_array_char* _parent, int32_t* _return); void sjf_array_char_heap(sjs_array_char* _this); void sjf_array_char_initat(sjs_array_char* _parent, int32_t index, char item); void sjf_array_string(sjs_array_string* _this); void sjf_array_string_asstring(sjs_array_string* _parent, sjs_string* sep, sjs_string* _return); void sjf_array_string_asstring_heap(sjs_array_string* _parent, sjs_string* sep, sjs_string** _return); void sjf_array_string_clone(sjs_array_string* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_string* _return); void sjf_array_string_clone_heap(sjs_array_string* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_string** _return); void sjf_array_string_copy(sjs_array_string* _this, sjs_array_string* _from); void sjf_array_string_destroy(sjs_array_string* _this); void sjf_array_string_getat(sjs_array_string* _parent, int32_t index, sjs_string* _return); void sjf_array_string_getat_heap(sjs_array_string* _parent, int32_t index, sjs_string** _return); void sjf_array_string_getcount(sjs_array_string* _parent, int32_t* _return); void sjf_array_string_gettotalcount(sjs_array_string* _parent, int32_t* _return); void sjf_array_string_heap(sjs_array_string* _this); void sjf_array_string_initat(sjs_array_string* _parent, int32_t index, sjs_string* item); void sjf_array_value(sjs_array_value* _this); void sjf_array_value_clone(sjs_array_value* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_value* _return); void sjf_array_value_clone_heap(sjs_array_value* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_value** _return); void sjf_array_value_copy(sjs_array_value* _this, sjs_array_value* _from); void sjf_array_value_destroy(sjs_array_value* _this); void sjf_array_value_getat(sjs_array_value* _parent, int32_t index, sjs_json_value* _return); void sjf_array_value_getat_heap(sjs_array_value* _parent, int32_t index, sjs_json_value** _return); void sjf_array_value_getcount(sjs_array_value* _parent, int32_t* _return); void sjf_array_value_gettotalcount(sjs_array_value* _parent, int32_t* _return); void sjf_array_value_heap(sjs_array_value* _this); void sjf_array_value_initat(sjs_array_value* _parent, int32_t index, sjs_json_value* item); void sjf_array_value_map_string(sjs_array_value* _parent, cb_value_string cb, sjs_array_string* _return); void sjf_array_value_map_string_heap(sjs_array_value* _parent, cb_value_string cb, sjs_array_string** _return); void sjf_debug_writeline(sjs_string* data); void sjf_halt(sjs_string* reason); void sjf_hash_string_value(sjs_hash_string_value* _this); void sjf_hash_string_value__weakptrremovekey(sjs_hash_string_value* _parent, sjs_string* key); void sjf_hash_string_value__weakptrremovevalue(sjs_hash_string_value* _parent, sjs_json_value* val); void sjf_hash_string_value_asarray_string(sjs_hash_string_value* _parent, cb_string_value_string cb, sjs_array_string* _return); void sjf_hash_string_value_asarray_string_heap(sjs_hash_string_value* _parent, cb_string_value_string cb, sjs_array_string** _return); void sjf_hash_string_value_copy(sjs_hash_string_value* _this, sjs_hash_string_value* _from); void sjf_hash_string_value_destroy(sjs_hash_string_value* _this); void sjf_hash_string_value_each(sjs_hash_string_value* _parent, cb_string_value_void cb); void sjf_hash_string_value_heap(sjs_hash_string_value* _this); void sjf_hash_string_value_setat(sjs_hash_string_value* _parent, sjs_string* key, sjs_json_value* val); void sjf_hash_type_bool(sjs_hash_type_bool* _this); void sjf_hash_type_bool__weakptrremovekey(sjs_hash_type_bool* _parent, int32_t key); void sjf_hash_type_bool__weakptrremovevalue(sjs_hash_type_bool* _parent, bool val); void sjf_hash_type_bool_copy(sjs_hash_type_bool* _this, sjs_hash_type_bool* _from); void sjf_hash_type_bool_destroy(sjs_hash_type_bool* _this); void sjf_hash_type_bool_heap(sjs_hash_type_bool* _this); void sjf_i32_max(int32_t a, int32_t b, int32_t* _return); void sjf_json_parse(sjs_string* s, sjs_json_value* _return); void sjf_json_parse_heap(sjs_string* s, sjs_json_value** _return); void sjf_json_parse_number(sjs_string* s, int32_t startindex, sjs_tuple2_i32_string* _return); void sjf_json_parse_number_heap(sjs_string* s, int32_t startindex, sjs_tuple2_i32_string** _return); void sjf_json_parse_string(sjs_string* s, int32_t startindex, sjs_tuple2_i32_string* _return); void sjf_json_parse_string_heap(sjs_string* s, int32_t startindex, sjs_tuple2_i32_string** _return); void sjf_json_parse_value(sjs_string* s, int32_t startindex, sjs_tuple2_i32_value* _return); void sjf_json_parse_value_heap(sjs_string* s, int32_t startindex, sjs_tuple2_i32_value** _return); void sjf_json_parse_whitespace(sjs_string* s, int32_t startindex, int32_t* _return); void sjf_json_value(sjs_json_value* _this); void sjf_json_value_copy(sjs_json_value* _this, sjs_json_value* _from); void sjf_json_value_destroy(sjs_json_value* _this); void sjf_json_value_heap(sjs_json_value* _this); void sjf_json_value_render(sjs_json_value* _parent, sjs_string* _return); void sjf_json_value_render_heap(sjs_json_value* _parent, sjs_string** _return); void sjf_lambda1(sjs_lambda1* _this); void sjf_lambda1_copy(sjs_lambda1* _this, sjs_lambda1* _from); void sjf_lambda1_destroy(sjs_lambda1* _this); void sjf_lambda1_heap(sjs_lambda1* _this); void sjf_lambda1_invoke(sjs_lambda1* _parent, sjs_string* _1, sjs_json_value* _2); void sjf_lambda2(sjs_lambda2* _this); void sjf_lambda2_copy(sjs_lambda2* _this, sjs_lambda2* _from); void sjf_lambda2_destroy(sjs_lambda2* _this); void sjf_lambda2_heap(sjs_lambda2* _this); void sjf_lambda2_invoke(sjs_lambda2* _parent, sjs_string* _1, sjs_json_value* _2, sjs_string* _return); void sjf_lambda2_invoke_heap(sjs_lambda2* _parent, sjs_string* _1, sjs_json_value* _2, sjs_string** _return); void sjf_lambda3(sjs_lambda3* _this); void sjf_lambda3_copy(sjs_lambda3* _this, sjs_lambda3* _from); void sjf_lambda3_destroy(sjs_lambda3* _this); void sjf_lambda3_heap(sjs_lambda3* _this); void sjf_lambda3_invoke(sjs_lambda3* _parent, sjs_json_value* _1, sjs_string* _return); void sjf_lambda3_invoke_heap(sjs_lambda3* _parent, sjs_json_value* _1, sjs_string** _return); void sjf_list_string(sjs_list_string* _this); void sjf_list_string_add(sjs_list_string* _parent, sjs_string* item); void sjf_list_string_copy(sjs_list_string* _this, sjs_list_string* _from); void sjf_list_string_destroy(sjs_list_string* _this); void sjf_list_string_heap(sjs_list_string* _this); void sjf_list_value(sjs_list_value* _this); void sjf_list_value_add(sjs_list_value* _parent, sjs_json_value* item); void sjf_list_value_copy(sjs_list_value* _this, sjs_list_value* _from); void sjf_list_value_destroy(sjs_list_value* _this); void sjf_list_value_heap(sjs_list_value* _this); void sjf_log(sjs_log* _this); void sjf_log_copy(sjs_log* _this, sjs_log* _from); void sjf_log_destroy(sjs_log* _this); void sjf_log_heap(sjs_log* _this); void sjf_string(sjs_string* _this); void sjf_string_add(sjs_string* _parent, sjs_string* item, sjs_string* _return); void sjf_string_add_heap(sjs_string* _parent, sjs_string* item, sjs_string** _return); void sjf_string_asstring(sjs_string* _parent, sjs_string* _return); void sjf_string_asstring_heap(sjs_string* _parent, sjs_string** _return); void sjf_string_copy(sjs_string* _this, sjs_string* _from); void sjf_string_destroy(sjs_string* _this); void sjf_string_getat(sjs_string* _parent, int32_t index, char* _return); void sjf_string_hash(sjs_string* _parent, uint32_t* _return); void sjf_string_heap(sjs_string* _this); void sjf_string_isequal(sjs_string* _parent, sjs_string* test, bool* _return); void sjf_string_nullterminate(sjs_string* _parent); void sjf_string_substr(sjs_string* _parent, int32_t o, int32_t c, sjs_string* _return); void sjf_string_substr_heap(sjs_string* _parent, int32_t o, int32_t c, sjs_string** _return); void sjf_test(sjs_string* s); void sjf_tuple2_i32_string(sjs_tuple2_i32_string* _this); void sjf_tuple2_i32_string_copy(sjs_tuple2_i32_string* _this, sjs_tuple2_i32_string* _from); void sjf_tuple2_i32_string_destroy(sjs_tuple2_i32_string* _this); void sjf_tuple2_i32_string_heap(sjs_tuple2_i32_string* _this); void sjf_tuple2_i32_value(sjs_tuple2_i32_value* _this); void sjf_tuple2_i32_value_copy(sjs_tuple2_i32_value* _this, sjs_tuple2_i32_value* _from); void sjf_tuple2_i32_value_destroy(sjs_tuple2_i32_value* _this); void sjf_tuple2_i32_value_heap(sjs_tuple2_i32_value* _this); void sjf_type_hash(int32_t val, uint32_t* _return); void sjf_type_isequal(int32_t l, int32_t r, bool* _return); void main_destroy(void); #ifndef type_bool_hash_function #define type_bool_hash_function #if false KHASH_INIT_FUNCTION_DEREF(type_bool_hash_type, int32_t, bool, 1, sjf_type_hash, sjf_type_isequal) #else KHASH_INIT_FUNCTION(type_bool_hash_type, int32_t, bool, 1, sjf_type_hash, sjf_type_isequal) #endif #endif #ifndef type_bool_hash_function #define type_bool_hash_function #if false KHASH_INIT_FUNCTION_DEREF(type_bool_hash_type, int32_t, bool, 1, sjf_type_hash, sjf_type_isequal) #else KHASH_INIT_FUNCTION(type_bool_hash_type, int32_t, bool, 1, sjf_type_hash, sjf_type_isequal) #endif #endif char* string_char(sjs_string* str) { sjf_string_nullterminate(str); return ((sjs_array*)str->data.v)->data + str->offset; } #include <lib/sj-lib-common/common.cpp> #ifndef string_value_hash_function #define string_value_hash_function #if true KHASH_INIT_FUNCTION_DEREF(string_value_hash_type, sjs_string, sjs_json_value, 1, sjf_string_hash, sjf_string_isequal) #else KHASH_INIT_FUNCTION(string_value_hash_type, sjs_string, sjs_json_value, 1, sjf_string_hash, sjf_string_isequal) #endif #endif #ifndef string_value_hash_function #define string_value_hash_function #if true KHASH_INIT_FUNCTION_DEREF(string_value_hash_type, sjs_string, sjs_json_value, 1, sjf_string_hash, sjf_string_isequal) #else KHASH_INIT_FUNCTION(string_value_hash_type, sjs_string, sjs_json_value, 1, sjf_string_hash, sjf_string_isequal) #endif #endif void sjf_array_char(sjs_array_char* _this) { #line 363 "lib/sj-lib-common/array.sj" if (_this->v == 0) { #line 364 _this->v = &g_empty; #line 365 } #line 366 sjs_array* arr = (sjs_array*)_this->v; #line 367 arr->refcount++; } void sjf_array_char_clone(sjs_array_char* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_char* _return) { void* newv; #line 169 "lib/sj-lib-common/array.sj" newv = 0; #line 171 sjs_array* arr = (sjs_array*)_parent->v; #line 172 if (offset + count > arr->count) { #line 173 halt("grow: offset %d count %d out of bounds %d\n", offset, count, arr->count); #line 174 } #line 176 if (count > arr->count - offset) { #line 177 halt("grow: new count larger than old count %d:%d\n", count, arr->count - offset); #line 178 } #line 180 sjs_array* newArr = createarray(sizeof(char), newsize); #line 181 if (!newArr) { #line 182 halt("grow: out of memory\n"); #line 183 } #line 185 newv = newArr; #line 186 char* p = (char*)arr->data + offset; #line 187 char* newp = (char*)newArr->data; #line 189 newArr->size = newsize; #line 190 newArr->count = count; #line 192 #if true #line 193 memcpy(newp, p, sizeof(char) * count); #line 194 #else #line 195 for (int i = 0; i < count; i++) { #line 196 #line 170 "lib/sj-lib-common/array.sj" newp[i] = p[i]; ; #line 197 } #line 198 #endif #line 198 _return->_refCount = 1; #line 200 _return->v = newv; #line 200 sjf_array_char(_return); } void sjf_array_char_clone_heap(sjs_array_char* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_char** _return) { void* newv; #line 169 "lib/sj-lib-common/array.sj" newv = 0; #line 171 sjs_array* arr = (sjs_array*)_parent->v; #line 172 if (offset + count > arr->count) { #line 173 halt("grow: offset %d count %d out of bounds %d\n", offset, count, arr->count); #line 174 } #line 176 if (count > arr->count - offset) { #line 177 halt("grow: new count larger than old count %d:%d\n", count, arr->count - offset); #line 178 } #line 180 sjs_array* newArr = createarray(sizeof(char), newsize); #line 181 if (!newArr) { #line 182 halt("grow: out of memory\n"); #line 183 } #line 185 newv = newArr; #line 186 char* p = (char*)arr->data + offset; #line 187 char* newp = (char*)newArr->data; #line 189 newArr->size = newsize; #line 190 newArr->count = count; #line 192 #if true #line 193 memcpy(newp, p, sizeof(char) * count); #line 194 #else #line 195 for (int i = 0; i < count; i++) { #line 196 #line 170 "lib/sj-lib-common/array.sj" newp[i] = p[i]; ; #line 197 } #line 198 #endif #line 198 (*_return) = (sjs_array_char*)malloc(sizeof(sjs_array_char)); #line 198 (*_return)->_refCount = 1; #line 200 (*_return)->v = newv; #line 200 sjf_array_char_heap((*_return)); } void sjf_array_char_copy(sjs_array_char* _this, sjs_array_char* _from) { #line 26 "lib/sj-lib-common/array.sj" _this->v = _from->v; #line 372 sjs_array* arr = (sjs_array*)_this->v; #line 373 arr->refcount++; } void sjf_array_char_destroy(sjs_array_char* _this) { #line 377 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_this->v; #line 378 arr->refcount--; #line 379 if (arr->refcount == 0) { #line 380 #if !true && !false #line 381 char* p = (char*)arr->data; #line 382 for (int i = 0; i < arr->count; i++) { #line 383 ; #line 384 } #line 385 #endif #line 386 free(arr); #line 387 } } void sjf_array_char_getat(sjs_array_char* _parent, int32_t index, char* _return) { #line 43 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_parent->v; #line 44 if (index >= arr->count || index < 0) { #line 45 halt("getAt: out of bounds\n"); #line 46 } #line 47 char* p = (char*)arr->data; #line 48 #line 42 "lib/sj-lib-common/array.sj" (*_return) = p[index]; return;; } void sjf_array_char_getcount(sjs_array_char* _parent, int32_t* _return) { #line 31 "lib/sj-lib-common/array.sj" #line 30 "lib/sj-lib-common/array.sj" (*_return) = ((sjs_array*)_parent->v)->count; return;; } void sjf_array_char_gettotalcount(sjs_array_char* _parent, int32_t* _return) { #line 37 "lib/sj-lib-common/array.sj" #line 36 "lib/sj-lib-common/array.sj" (*_return) = ((sjs_array*)_parent->v)->size; return;; } void sjf_array_char_heap(sjs_array_char* _this) { #line 363 "lib/sj-lib-common/array.sj" if (_this->v == 0) { #line 364 _this->v = &g_empty; #line 365 } #line 366 sjs_array* arr = (sjs_array*)_this->v; #line 367 arr->refcount++; } void sjf_array_char_initat(sjs_array_char* _parent, int32_t index, char item) { #line 54 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_parent->v; #line 55 if (index != arr->count) { #line 56 halt("initAt: can only initialize last element\n"); #line 57 } #line 58 if (index >= arr->size || index < 0) { #line 59 halt("initAt: out of bounds %d:%d\n", index, arr->size); #line 60 } #line 62 char* p = (char*)arr->data; #line 63 #line 52 "lib/sj-lib-common/array.sj" p[index] = item; ; #line 64 arr->count = index + 1; } void sjf_array_string(sjs_array_string* _this) { #line 363 "lib/sj-lib-common/array.sj" if (_this->v == 0) { #line 364 _this->v = &g_empty; #line 365 } #line 366 sjs_array* arr = (sjs_array*)_this->v; #line 367 arr->refcount++; } void sjf_array_string_asstring(sjs_array_string* _parent, sjs_string* sep, sjs_string* _return) { int32_t i; sjs_string result = { -1 }; int32_t sjt_forEnd5; int32_t sjt_forStart5; result._refCount = 1; #line 295 "lib/sj-lib-common/array.sj" result.offset = 0; #line 295 result.count = 0; #line 295 result.data._refCount = 1; #line 295 result.data.v = &sjg_string2; #line 295 sjf_array_char(&result.data); #line 16 "lib/sj-lib-common/string.sj" result._isnullterminated = false; #line 16 sjf_string(&result); #line 296 "lib/sj-lib-common/array.sj" sjt_forStart5 = 0; #line 296 sjf_array_string_getcount(_parent, &sjt_forEnd5); #line 296 i = sjt_forStart5; while (i < sjt_forEnd5) { sjs_string sjt_call11 = { -1 }; sjs_string sjt_call12 = { -1 }; sjs_string sjt_funcold17 = { -1 }; sjs_string sjt_funcold18 = { -1 }; sjs_string* sjt_functionParam133 = 0; int32_t sjt_functionParam134; sjs_string* sjt_parent66 = 0; sjs_string* sjt_parent67 = 0; if (i != 0) { sjs_string* sjt_functionParam132 = 0; sjs_string* sjt_parent65 = 0; #line 18 "lib/sj-lib-common/string.sj" sjt_parent65 = &result; #line 294 "lib/sj-lib-common/array.sj" sjt_functionParam132 = sep; #line 294 sjf_string_add(sjt_parent65, sjt_functionParam132, &sjt_funcold17); #line 294 if (result._refCount == 1) { sjf_string_destroy(&result); } ; #line 18 "lib/sj-lib-common/string.sj" sjf_string_copy(&result, &sjt_funcold17); } #line 18 "lib/sj-lib-common/string.sj" sjt_parent66 = &result; #line 296 "lib/sj-lib-common/array.sj" sjt_functionParam134 = i; #line 296 sjf_array_string_getat(_parent, sjt_functionParam134, &sjt_call12); #line 300 sjt_parent67 = &sjt_call12; #line 300 sjf_string_asstring(sjt_parent67, &sjt_call11); #line 300 sjt_functionParam133 = &sjt_call11; #line 300 sjf_string_add(sjt_parent66, sjt_functionParam133, &sjt_funcold18); #line 300 if (result._refCount == 1) { sjf_string_destroy(&result); } ; #line 18 "lib/sj-lib-common/string.sj" sjf_string_copy(&result, &sjt_funcold18); #line 296 "lib/sj-lib-common/array.sj" i++; if (sjt_call11._refCount == 1) { sjf_string_destroy(&sjt_call11); } ; if (sjt_call12._refCount == 1) { sjf_string_destroy(&sjt_call12); } ; if (sjt_funcold17._refCount == 1) { sjf_string_destroy(&sjt_funcold17); } ; if (sjt_funcold18._refCount == 1) { sjf_string_destroy(&sjt_funcold18); } ; } #line 296 _return->_refCount = 1; #line 294 sjf_string_copy(_return, &result); if (result._refCount == 1) { sjf_string_destroy(&result); } ; } void sjf_array_string_asstring_heap(sjs_array_string* _parent, sjs_string* sep, sjs_string** _return) { int32_t i; sjs_string result = { -1 }; int32_t sjt_forEnd6; int32_t sjt_forStart6; result._refCount = 1; #line 295 "lib/sj-lib-common/array.sj" result.offset = 0; #line 295 result.count = 0; #line 295 result.data._refCount = 1; #line 295 result.data.v = &sjg_string2; #line 295 sjf_array_char(&result.data); #line 16 "lib/sj-lib-common/string.sj" result._isnullterminated = false; #line 16 sjf_string(&result); #line 296 "lib/sj-lib-common/array.sj" sjt_forStart6 = 0; #line 296 sjf_array_string_getcount(_parent, &sjt_forEnd6); #line 296 i = sjt_forStart6; while (i < sjt_forEnd6) { sjs_string sjt_call13 = { -1 }; sjs_string sjt_call14 = { -1 }; sjs_string sjt_funcold19 = { -1 }; sjs_string sjt_funcold20 = { -1 }; sjs_string* sjt_functionParam136 = 0; int32_t sjt_functionParam137; sjs_string* sjt_parent69 = 0; sjs_string* sjt_parent70 = 0; if (i != 0) { sjs_string* sjt_functionParam135 = 0; sjs_string* sjt_parent68 = 0; #line 18 "lib/sj-lib-common/string.sj" sjt_parent68 = &result; #line 294 "lib/sj-lib-common/array.sj" sjt_functionParam135 = sep; #line 294 sjf_string_add(sjt_parent68, sjt_functionParam135, &sjt_funcold19); #line 294 if (result._refCount == 1) { sjf_string_destroy(&result); } ; #line 18 "lib/sj-lib-common/string.sj" sjf_string_copy(&result, &sjt_funcold19); } #line 18 "lib/sj-lib-common/string.sj" sjt_parent69 = &result; #line 296 "lib/sj-lib-common/array.sj" sjt_functionParam137 = i; #line 296 sjf_array_string_getat(_parent, sjt_functionParam137, &sjt_call14); #line 300 sjt_parent70 = &sjt_call14; #line 300 sjf_string_asstring(sjt_parent70, &sjt_call13); #line 300 sjt_functionParam136 = &sjt_call13; #line 300 sjf_string_add(sjt_parent69, sjt_functionParam136, &sjt_funcold20); #line 300 if (result._refCount == 1) { sjf_string_destroy(&result); } ; #line 18 "lib/sj-lib-common/string.sj" sjf_string_copy(&result, &sjt_funcold20); #line 296 "lib/sj-lib-common/array.sj" i++; if (sjt_call13._refCount == 1) { sjf_string_destroy(&sjt_call13); } ; if (sjt_call14._refCount == 1) { sjf_string_destroy(&sjt_call14); } ; if (sjt_funcold19._refCount == 1) { sjf_string_destroy(&sjt_funcold19); } ; if (sjt_funcold20._refCount == 1) { sjf_string_destroy(&sjt_funcold20); } ; } #line 296 (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); #line 296 (*_return)->_refCount = 1; #line 294 sjf_string_copy((*_return), &result); if (result._refCount == 1) { sjf_string_destroy(&result); } ; } void sjf_array_string_clone(sjs_array_string* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_string* _return) { void* newv; #line 169 "lib/sj-lib-common/array.sj" newv = 0; #line 171 sjs_array* arr = (sjs_array*)_parent->v; #line 172 if (offset + count > arr->count) { #line 173 halt("grow: offset %d count %d out of bounds %d\n", offset, count, arr->count); #line 174 } #line 176 if (count > arr->count - offset) { #line 177 halt("grow: new count larger than old count %d:%d\n", count, arr->count - offset); #line 178 } #line 180 sjs_array* newArr = createarray(sizeof(sjs_string), newsize); #line 181 if (!newArr) { #line 182 halt("grow: out of memory\n"); #line 183 } #line 185 newv = newArr; #line 186 sjs_string* p = (sjs_string*)arr->data + offset; #line 187 sjs_string* newp = (sjs_string*)newArr->data; #line 189 newArr->size = newsize; #line 190 newArr->count = count; #line 192 #if false #line 193 memcpy(newp, p, sizeof(sjs_string) * count); #line 194 #else #line 195 for (int i = 0; i < count; i++) { #line 196 newp[i]._refCount = 1; #line 170 "lib/sj-lib-common/array.sj" sjf_string_copy(&newp[i], &p[i]); ; #line 197 } #line 198 #endif #line 198 _return->_refCount = 1; #line 200 _return->v = newv; #line 200 sjf_array_string(_return); } void sjf_array_string_clone_heap(sjs_array_string* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_string** _return) { void* newv; #line 169 "lib/sj-lib-common/array.sj" newv = 0; #line 171 sjs_array* arr = (sjs_array*)_parent->v; #line 172 if (offset + count > arr->count) { #line 173 halt("grow: offset %d count %d out of bounds %d\n", offset, count, arr->count); #line 174 } #line 176 if (count > arr->count - offset) { #line 177 halt("grow: new count larger than old count %d:%d\n", count, arr->count - offset); #line 178 } #line 180 sjs_array* newArr = createarray(sizeof(sjs_string), newsize); #line 181 if (!newArr) { #line 182 halt("grow: out of memory\n"); #line 183 } #line 185 newv = newArr; #line 186 sjs_string* p = (sjs_string*)arr->data + offset; #line 187 sjs_string* newp = (sjs_string*)newArr->data; #line 189 newArr->size = newsize; #line 190 newArr->count = count; #line 192 #if false #line 193 memcpy(newp, p, sizeof(sjs_string) * count); #line 194 #else #line 195 for (int i = 0; i < count; i++) { #line 196 newp[i]._refCount = 1; #line 170 "lib/sj-lib-common/array.sj" sjf_string_copy(&newp[i], &p[i]); ; #line 197 } #line 198 #endif #line 198 (*_return) = (sjs_array_string*)malloc(sizeof(sjs_array_string)); #line 198 (*_return)->_refCount = 1; #line 200 (*_return)->v = newv; #line 200 sjf_array_string_heap((*_return)); } void sjf_array_string_copy(sjs_array_string* _this, sjs_array_string* _from) { #line 26 "lib/sj-lib-common/array.sj" _this->v = _from->v; #line 372 sjs_array* arr = (sjs_array*)_this->v; #line 373 arr->refcount++; } void sjf_array_string_destroy(sjs_array_string* _this) { #line 377 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_this->v; #line 378 arr->refcount--; #line 379 if (arr->refcount == 0) { #line 380 #if !false && !true #line 381 sjs_string* p = (sjs_string*)arr->data; #line 382 for (int i = 0; i < arr->count; i++) { #line 383 ; #line 384 } #line 385 #endif #line 386 free(arr); #line 387 } } void sjf_array_string_getat(sjs_array_string* _parent, int32_t index, sjs_string* _return) { #line 43 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_parent->v; #line 44 if (index >= arr->count || index < 0) { #line 45 halt("getAt: out of bounds\n"); #line 46 } #line 47 sjs_string* p = (sjs_string*)arr->data; #line 48 _return->_refCount = 1; #line 42 "lib/sj-lib-common/array.sj" sjf_string_copy(_return, &p[index]); return;; } void sjf_array_string_getat_heap(sjs_array_string* _parent, int32_t index, sjs_string** _return) { #line 43 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_parent->v; #line 44 if (index >= arr->count || index < 0) { #line 45 halt("getAt: out of bounds\n"); #line 46 } #line 47 sjs_string* p = (sjs_string*)arr->data; #line 48 (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); (*_return)->_refCount = 1; #line 42 "lib/sj-lib-common/array.sj" sjf_string_copy((*_return), &p[index]); return;; } void sjf_array_string_getcount(sjs_array_string* _parent, int32_t* _return) { #line 31 "lib/sj-lib-common/array.sj" #line 30 "lib/sj-lib-common/array.sj" (*_return) = ((sjs_array*)_parent->v)->count; return;; } void sjf_array_string_gettotalcount(sjs_array_string* _parent, int32_t* _return) { #line 37 "lib/sj-lib-common/array.sj" #line 36 "lib/sj-lib-common/array.sj" (*_return) = ((sjs_array*)_parent->v)->size; return;; } void sjf_array_string_heap(sjs_array_string* _this) { #line 363 "lib/sj-lib-common/array.sj" if (_this->v == 0) { #line 364 _this->v = &g_empty; #line 365 } #line 366 sjs_array* arr = (sjs_array*)_this->v; #line 367 arr->refcount++; } void sjf_array_string_initat(sjs_array_string* _parent, int32_t index, sjs_string* item) { #line 54 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_parent->v; #line 55 if (index != arr->count) { #line 56 halt("initAt: can only initialize last element\n"); #line 57 } #line 58 if (index >= arr->size || index < 0) { #line 59 halt("initAt: out of bounds %d:%d\n", index, arr->size); #line 60 } #line 62 sjs_string* p = (sjs_string*)arr->data; #line 63 p[index]._refCount = 1; #line 52 "lib/sj-lib-common/array.sj" sjf_string_copy(&p[index], item); ; #line 64 arr->count = index + 1; } void sjf_array_value(sjs_array_value* _this) { #line 363 "lib/sj-lib-common/array.sj" if (_this->v == 0) { #line 364 _this->v = &g_empty; #line 365 } #line 366 sjs_array* arr = (sjs_array*)_this->v; #line 367 arr->refcount++; } void sjf_array_value_clone(sjs_array_value* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_value* _return) { void* newv; #line 169 "lib/sj-lib-common/array.sj" newv = 0; #line 171 sjs_array* arr = (sjs_array*)_parent->v; #line 172 if (offset + count > arr->count) { #line 173 halt("grow: offset %d count %d out of bounds %d\n", offset, count, arr->count); #line 174 } #line 176 if (count > arr->count - offset) { #line 177 halt("grow: new count larger than old count %d:%d\n", count, arr->count - offset); #line 178 } #line 180 sjs_array* newArr = createarray(sizeof(sjs_json_value), newsize); #line 181 if (!newArr) { #line 182 halt("grow: out of memory\n"); #line 183 } #line 185 newv = newArr; #line 186 sjs_json_value* p = (sjs_json_value*)arr->data + offset; #line 187 sjs_json_value* newp = (sjs_json_value*)newArr->data; #line 189 newArr->size = newsize; #line 190 newArr->count = count; #line 192 #if false #line 193 memcpy(newp, p, sizeof(sjs_json_value) * count); #line 194 #else #line 195 for (int i = 0; i < count; i++) { #line 196 newp[i]._refCount = 1; #line 170 "lib/sj-lib-common/array.sj" sjf_json_value_copy(&newp[i], &p[i]); ; #line 197 } #line 198 #endif #line 198 _return->_refCount = 1; #line 200 _return->v = newv; #line 200 sjf_array_value(_return); } void sjf_array_value_clone_heap(sjs_array_value* _parent, int32_t offset, int32_t count, int32_t newsize, sjs_array_value** _return) { void* newv; #line 169 "lib/sj-lib-common/array.sj" newv = 0; #line 171 sjs_array* arr = (sjs_array*)_parent->v; #line 172 if (offset + count > arr->count) { #line 173 halt("grow: offset %d count %d out of bounds %d\n", offset, count, arr->count); #line 174 } #line 176 if (count > arr->count - offset) { #line 177 halt("grow: new count larger than old count %d:%d\n", count, arr->count - offset); #line 178 } #line 180 sjs_array* newArr = createarray(sizeof(sjs_json_value), newsize); #line 181 if (!newArr) { #line 182 halt("grow: out of memory\n"); #line 183 } #line 185 newv = newArr; #line 186 sjs_json_value* p = (sjs_json_value*)arr->data + offset; #line 187 sjs_json_value* newp = (sjs_json_value*)newArr->data; #line 189 newArr->size = newsize; #line 190 newArr->count = count; #line 192 #if false #line 193 memcpy(newp, p, sizeof(sjs_json_value) * count); #line 194 #else #line 195 for (int i = 0; i < count; i++) { #line 196 newp[i]._refCount = 1; #line 170 "lib/sj-lib-common/array.sj" sjf_json_value_copy(&newp[i], &p[i]); ; #line 197 } #line 198 #endif #line 198 (*_return) = (sjs_array_value*)malloc(sizeof(sjs_array_value)); #line 198 (*_return)->_refCount = 1; #line 200 (*_return)->v = newv; #line 200 sjf_array_value_heap((*_return)); } void sjf_array_value_copy(sjs_array_value* _this, sjs_array_value* _from) { #line 26 "lib/sj-lib-common/array.sj" _this->v = _from->v; #line 372 sjs_array* arr = (sjs_array*)_this->v; #line 373 arr->refcount++; } void sjf_array_value_destroy(sjs_array_value* _this) { #line 377 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_this->v; #line 378 arr->refcount--; #line 379 if (arr->refcount == 0) { #line 380 #if !false && !true #line 381 sjs_json_value* p = (sjs_json_value*)arr->data; #line 382 for (int i = 0; i < arr->count; i++) { #line 383 ; #line 384 } #line 385 #endif #line 386 free(arr); #line 387 } } void sjf_array_value_getat(sjs_array_value* _parent, int32_t index, sjs_json_value* _return) { #line 43 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_parent->v; #line 44 if (index >= arr->count || index < 0) { #line 45 halt("getAt: out of bounds\n"); #line 46 } #line 47 sjs_json_value* p = (sjs_json_value*)arr->data; #line 48 _return->_refCount = 1; #line 42 "lib/sj-lib-common/array.sj" sjf_json_value_copy(_return, &p[index]); return;; } void sjf_array_value_getat_heap(sjs_array_value* _parent, int32_t index, sjs_json_value** _return) { #line 43 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_parent->v; #line 44 if (index >= arr->count || index < 0) { #line 45 halt("getAt: out of bounds\n"); #line 46 } #line 47 sjs_json_value* p = (sjs_json_value*)arr->data; #line 48 (*_return) = (sjs_json_value*)malloc(sizeof(sjs_json_value)); (*_return)->_refCount = 1; #line 42 "lib/sj-lib-common/array.sj" sjf_json_value_copy((*_return), &p[index]); return;; } void sjf_array_value_getcount(sjs_array_value* _parent, int32_t* _return) { #line 31 "lib/sj-lib-common/array.sj" #line 30 "lib/sj-lib-common/array.sj" (*_return) = ((sjs_array*)_parent->v)->count; return;; } void sjf_array_value_gettotalcount(sjs_array_value* _parent, int32_t* _return) { #line 37 "lib/sj-lib-common/array.sj" #line 36 "lib/sj-lib-common/array.sj" (*_return) = ((sjs_array*)_parent->v)->size; return;; } void sjf_array_value_heap(sjs_array_value* _this) { #line 363 "lib/sj-lib-common/array.sj" if (_this->v == 0) { #line 364 _this->v = &g_empty; #line 365 } #line 366 sjs_array* arr = (sjs_array*)_this->v; #line 367 arr->refcount++; } void sjf_array_value_initat(sjs_array_value* _parent, int32_t index, sjs_json_value* item) { #line 54 "lib/sj-lib-common/array.sj" sjs_array* arr = (sjs_array*)_parent->v; #line 55 if (index != arr->count) { #line 56 halt("initAt: can only initialize last element\n"); #line 57 } #line 58 if (index >= arr->size || index < 0) { #line 59 halt("initAt: out of bounds %d:%d\n", index, arr->size); #line 60 } #line 62 sjs_json_value* p = (sjs_json_value*)arr->data; #line 63 p[index]._refCount = 1; #line 52 "lib/sj-lib-common/array.sj" sjf_json_value_copy(&p[index], item); ; #line 64 arr->count = index + 1; } void sjf_array_value_map_string(sjs_array_value* _parent, cb_value_string cb, sjs_array_string* _return) { int32_t i; void* newdata; int32_t sjt_forEnd7; int32_t sjt_forStart7; #line 115 "lib/sj-lib-common/array.sj" newdata = 0; #line 117 sjs_array* arr = (sjs_array*)_parent->v; #line 118 sjs_array* newArr = createarray(sizeof(sjs_string), arr->count); #line 119 newArr->count = arr->count; #line 120 newdata = (void*)newArr; #line 122 sjt_forStart7 = 0; #line 122 sjf_array_value_getcount(_parent, &sjt_forEnd7); #line 122 i = sjt_forStart7; while (i < sjt_forEnd7) { sjs_string newitem = { -1 }; sjs_json_value sjt_call16 = { -1 }; sjs_json_value* sjt_functionParam138 = 0; int32_t sjt_functionParam139; #line 122 "lib/sj-lib-common/array.sj" sjt_functionParam139 = i; #line 122 sjf_array_value_getat(_parent, sjt_functionParam139, &sjt_call16); #line 123 sjt_functionParam138 = &sjt_call16; #line 123 cb._cb(cb._parent, sjt_functionParam138, &newitem); #line 125 sjs_string* p = (sjs_string*)newArr->data; #line 126 p[i]._refCount = 1; #line 124 "lib/sj-lib-common/array.sj" sjf_string_copy(&p[i], &newitem); ; #line 122 i++; if (newitem._refCount == 1) { sjf_string_destroy(&newitem); } ; if (sjt_call16._refCount == 1) { sjf_json_value_destroy(&sjt_call16); } ; } #line 122 _return->_refCount = 1; #line 129 _return->v = newdata; #line 129 sjf_array_string(_return); } void sjf_array_value_map_string_heap(sjs_array_value* _parent, cb_value_string cb, sjs_array_string** _return) { int32_t i; void* newdata; int32_t sjt_forEnd8; int32_t sjt_forStart8; #line 115 "lib/sj-lib-common/array.sj" newdata = 0; #line 117 sjs_array* arr = (sjs_array*)_parent->v; #line 118 sjs_array* newArr = createarray(sizeof(sjs_string), arr->count); #line 119 newArr->count = arr->count; #line 120 newdata = (void*)newArr; #line 122 sjt_forStart8 = 0; #line 122 sjf_array_value_getcount(_parent, &sjt_forEnd8); #line 122 i = sjt_forStart8; while (i < sjt_forEnd8) { sjs_string newitem = { -1 }; sjs_json_value sjt_call17 = { -1 }; sjs_json_value* sjt_functionParam140 = 0; int32_t sjt_functionParam141; #line 122 "lib/sj-lib-common/array.sj" sjt_functionParam141 = i; #line 122 sjf_array_value_getat(_parent, sjt_functionParam141, &sjt_call17); #line 123 sjt_functionParam140 = &sjt_call17; #line 123 cb._cb(cb._parent, sjt_functionParam140, &newitem); #line 125 sjs_string* p = (sjs_string*)newArr->data; #line 126 p[i]._refCount = 1; #line 124 "lib/sj-lib-common/array.sj" sjf_string_copy(&p[i], &newitem); ; #line 122 i++; if (newitem._refCount == 1) { sjf_string_destroy(&newitem); } ; if (sjt_call17._refCount == 1) { sjf_json_value_destroy(&sjt_call17); } ; } #line 122 (*_return) = (sjs_array_string*)malloc(sizeof(sjs_array_string)); #line 122 (*_return)->_refCount = 1; #line 129 (*_return)->v = newdata; #line 129 sjf_array_string_heap((*_return)); } void sjf_debug_writeline(sjs_string* data) { #line 10 "lib/sj-lib-common/debug.sj" debugout("%s\n", string_char(data)); } void sjf_halt(sjs_string* reason) { #line 3 "lib/sj-lib-common/halt.sj" halt("%s\n", string_char(reason)); } void sjf_hash_string_value(sjs_hash_string_value* _this) { #line 233 "lib/sj-lib-common/hash.sj" _this->_hash = kh_init(string_value_hash_type); } void sjf_hash_string_value__weakptrremovekey(sjs_hash_string_value* _parent, sjs_string* key) { #line 188 "lib/sj-lib-common/hash.sj" #if false #line 189 khash_t(string_value_hash_type)* p = (khash_t(string_value_hash_type)*)_parent->_hash; #line 190 khiter_t k = kh_get(string_value_hash_type, p, key); #line 191 if (k != kh_end(p)) { #line 192 kh_del(string_value_hash_type, p, k); #line 193 } #line 194 #endif } void sjf_hash_string_value__weakptrremovevalue(sjs_hash_string_value* _parent, sjs_json_value* val) { #line 200 "lib/sj-lib-common/hash.sj" #if false #line 201 khash_t(string_value_hash_type)* p = (khash_t(string_value_hash_type)*)_parent->_hash; #line 202 for (khiter_t k = kh_begin(p); k != kh_end(p); ++k) { #line 203 if (kh_exist(p, k)) { #line 204 sjs_json_value t = kh_value(p, k); #line 205 if (t == val) { #line 206 kh_del(string_value_hash_type, p, k); #line 207 } #line 208 } #line 209 } #line 210 #endif } void sjf_hash_string_value_asarray_string(sjs_hash_string_value* _parent, cb_string_value_string cb, sjs_array_string* _return) { sjs_list_string result = { -1 }; sjs_lambda1 sjt_call25 = { -1 }; cb_string_value_void sjt_functionParam146; result._refCount = 1; result.arr._refCount = 1; #line 27 "lib/sj-lib-common/array.sj" result.arr.v = 0; #line 27 sjf_array_string(&result.arr); #line 27 sjf_list_string(&result); #line 172 "lib/sj-lib-common/hash.sj" sjs_lambda1* lambainit1; #line 172 sjt_call25._refCount = 1; #line 172 sjt_call25.lambdaparam1 = &result; #line 170 sjt_call25.lambdaparam2 = cb; #line 170 sjt_call25.lambdaparam3 = cb; #line 170 sjf_lambda1(&sjt_call25); #line 172 lambainit1 = &sjt_call25; #line 172 sjt_functionParam146._parent = (sjs_object*)lambainit1; #line 172 sjt_functionParam146._cb = (void(*)(sjs_object*,sjs_string*,sjs_json_value*))sjf_lambda1_invoke; #line 172 sjf_hash_string_value_each(_parent, sjt_functionParam146); #line 172 _return->_refCount = 1; #line 170 sjf_array_string_copy(_return, &(&result)->arr); if (result._refCount == 1) { sjf_list_string_destroy(&result); } ; if (sjt_call25._refCount == 1) { sjf_lambda1_destroy(&sjt_call25); } ; } void sjf_hash_string_value_asarray_string_heap(sjs_hash_string_value* _parent, cb_string_value_string cb, sjs_array_string** _return) { sjs_list_string result = { -1 }; sjs_lambda1 sjt_call27 = { -1 }; cb_string_value_void sjt_functionParam157; result._refCount = 1; result.arr._refCount = 1; #line 27 "lib/sj-lib-common/array.sj" result.arr.v = 0; #line 27 sjf_array_string(&result.arr); #line 27 sjf_list_string(&result); #line 172 "lib/sj-lib-common/hash.sj" sjs_lambda1* lambainit2; #line 172 sjt_call27._refCount = 1; #line 172 sjt_call27.lambdaparam1 = &result; #line 170 sjt_call27.lambdaparam2 = cb; #line 170 sjt_call27.lambdaparam3 = cb; #line 170 sjf_lambda1(&sjt_call27); #line 172 lambainit2 = &sjt_call27; #line 172 sjt_functionParam157._parent = (sjs_object*)lambainit2; #line 172 sjt_functionParam157._cb = (void(*)(sjs_object*,sjs_string*,sjs_json_value*))sjf_lambda1_invoke; #line 172 sjf_hash_string_value_each(_parent, sjt_functionParam157); #line 172 (*_return) = (sjs_array_string*)malloc(sizeof(sjs_array_string)); #line 172 (*_return)->_refCount = 1; #line 170 sjf_array_string_copy((*_return), &(&result)->arr); if (result._refCount == 1) { sjf_list_string_destroy(&result); } ; if (sjt_call27._refCount == 1) { sjf_lambda1_destroy(&sjt_call27); } ; } void sjf_hash_string_value_copy(sjs_hash_string_value* _this, sjs_hash_string_value* _from) { #line 238 "lib/sj-lib-common/hash.sj" _this->_hash = _from->_hash; #line 239 khash_t(string_value_hash_type)* p = (khash_t(string_value_hash_type)*)_this->_hash; #line 240 p->refcount++; } void sjf_hash_string_value_destroy(sjs_hash_string_value* _this) { #line 244 "lib/sj-lib-common/hash.sj" khash_t(string_value_hash_type)* p = (khash_t(string_value_hash_type)*)_this->_hash; #line 245 p->refcount--; #line 246 if (p->refcount == 0) { #line 247 for (khiter_t k = kh_begin(p); k != kh_end(p); ++k) { #line 248 if (kh_exist(p, k)) { #line 250 #if false #line 251 delete_cb cb = { p, (void(*)(void*, void*))sjf_hash_string_value__weakptrremovekey }; #line 252 weakptr_cb_remove(kh_key(p, k), cb); #line 253 #else #line 254 ; #line 255 #endif #line 257 #if false #line 258 delete_cb cb = { p, (void(*)(void*, void*))sjf_hash_string_value__weakptrremovevalue }; #line 259 weakptr_cb_remove(kh_value(p, k), cb); #line 260 #else #line 261 ; #line 262 #endif #line 263 } #line 264 } #line 265 kh_destroy(string_value_hash_type, (khash_t(string_value_hash_type)*)_this->_hash); #line 266 } } void sjf_hash_string_value_each(sjs_hash_string_value* _parent, cb_string_value_void cb) { #line 98 "lib/sj-lib-common/hash.sj" khash_t(string_value_hash_type)* p = (khash_t(string_value_hash_type)*)_parent->_hash; #line 99 for (khiter_t k = kh_begin(p); k != kh_end(p); ++k) { #line 100 if (kh_exist(p, k)) { #line 101 cb._cb( #line 102 cb._parent, #line 103 #if true #line 104 &kh_key(p, k), #line 105 #else #line 106 kh_key(p, k), #line 107 #endif #line 109 #if true #line 110 &kh_value(p, k) #line 111 #else #line 112 kh_value(p, k) #line 113 #endif #line 114 ); #line 115 } #line 116 } } void sjf_hash_string_value_heap(sjs_hash_string_value* _this) { #line 233 "lib/sj-lib-common/hash.sj" _this->_hash = kh_init(string_value_hash_type); } void sjf_hash_string_value_setat(sjs_hash_string_value* _parent, sjs_string* key, sjs_json_value* val) { #line 40 "lib/sj-lib-common/hash.sj" khash_t(string_value_hash_type)* p = (khash_t(string_value_hash_type)*)_parent->_hash; #line 42 #if true #line 43 khiter_t k = kh_get(string_value_hash_type, p, *key); #line 44 #else #line 45 khiter_t k = kh_get(string_value_hash_type, p, key); #line 46 #endif #line 48 if (k != kh_end(p)) { #line 49 ; #line 50 } #line 52 int ret; #line 53 #if true #line 54 k = kh_put(string_value_hash_type, p, *key, &ret); #line 55 #else #line 56 k = kh_put(string_value_hash_type, p, key, &ret); #line 57 #endif #line 59 if (!ret) kh_del(string_value_hash_type, p, k); #line 61 #if false #line 62 delete_cb cb = { _parent, (void(*)(void*, void*))sjf_hash_string_value__weakptrremovekey }; #line 63 weakptr_cb_add(key, cb); #line 64 #else #line 65 sjs_string t; #line 66 t._refCount = 1; #line 38 "lib/sj-lib-common/hash.sj" sjf_string_copy(&t, key); ; #line 67 #endif #line 69 #if false #line 70 delete_cb cb = { _parent, (void(*)(void*, void*))sjf_hash_string_value__weakptrremovevalue }; #line 71 weakptr_cb_add(val, cb); #line 72 kh_val(p, k) = val; #line 73 #else #line 74 kh_val(p, k)._refCount = 1; #line 38 "lib/sj-lib-common/hash.sj" sjf_json_value_copy(&kh_val(p, k), val); ; #line 75 #endif } void sjf_hash_type_bool(sjs_hash_type_bool* _this) { #line 233 "lib/sj-lib-common/hash.sj" _this->_hash = kh_init(type_bool_hash_type); } void sjf_hash_type_bool__weakptrremovekey(sjs_hash_type_bool* _parent, int32_t key) { #line 188 "lib/sj-lib-common/hash.sj" #if false #line 189 khash_t(type_bool_hash_type)* p = (khash_t(type_bool_hash_type)*)_parent->_hash; #line 190 khiter_t k = kh_get(type_bool_hash_type, p, key); #line 191 if (k != kh_end(p)) { #line 192 kh_del(type_bool_hash_type, p, k); #line 193 } #line 194 #endif } void sjf_hash_type_bool__weakptrremovevalue(sjs_hash_type_bool* _parent, bool val) { #line 200 "lib/sj-lib-common/hash.sj" #if false #line 201 khash_t(type_bool_hash_type)* p = (khash_t(type_bool_hash_type)*)_parent->_hash; #line 202 for (khiter_t k = kh_begin(p); k != kh_end(p); ++k) { #line 203 if (kh_exist(p, k)) { #line 204 bool t = kh_value(p, k); #line 205 if (t == val) { #line 206 kh_del(type_bool_hash_type, p, k); #line 207 } #line 208 } #line 209 } #line 210 #endif } void sjf_hash_type_bool_copy(sjs_hash_type_bool* _this, sjs_hash_type_bool* _from) { #line 238 "lib/sj-lib-common/hash.sj" _this->_hash = _from->_hash; #line 239 khash_t(type_bool_hash_type)* p = (khash_t(type_bool_hash_type)*)_this->_hash; #line 240 p->refcount++; } void sjf_hash_type_bool_destroy(sjs_hash_type_bool* _this) { #line 244 "lib/sj-lib-common/hash.sj" khash_t(type_bool_hash_type)* p = (khash_t(type_bool_hash_type)*)_this->_hash; #line 245 p->refcount--; #line 246 if (p->refcount == 0) { #line 247 for (khiter_t k = kh_begin(p); k != kh_end(p); ++k) { #line 248 if (kh_exist(p, k)) { #line 250 #if false #line 251 delete_cb cb = { p, (void(*)(void*, void*))sjf_hash_type_bool__weakptrremovekey }; #line 252 weakptr_cb_remove(kh_key(p, k), cb); #line 253 #else #line 254 ; #line 255 #endif #line 257 #if false #line 258 delete_cb cb = { p, (void(*)(void*, void*))sjf_hash_type_bool__weakptrremovevalue }; #line 259 weakptr_cb_remove(kh_value(p, k), cb); #line 260 #else #line 261 ; #line 262 #endif #line 263 } #line 264 } #line 265 kh_destroy(type_bool_hash_type, (khash_t(type_bool_hash_type)*)_this->_hash); #line 266 } } void sjf_hash_type_bool_heap(sjs_hash_type_bool* _this) { #line 233 "lib/sj-lib-common/hash.sj" _this->_hash = kh_init(type_bool_hash_type); } void sjf_i32_max(int32_t a, int32_t b, int32_t* _return) { if (a < b) { #line 6 "lib/sj-lib-common/i32.sj" (*_return) = b; } else { #line 6 "lib/sj-lib-common/i32.sj" (*_return) = a; } } void sjf_json_parse(sjs_string* s, sjs_json_value* _return) { sjs_tuple2_i32_value result = { -1 }; sjs_string* sjt_functionParam107 = 0; int32_t sjt_functionParam108; sjs_json_value sjt_value2 = { -1 }; #line 168 "lib/sj-lib-json/parse.sj" sjt_functionParam107 = s; #line 169 sjt_functionParam108 = 0; #line 169 sjf_json_parse_value(sjt_functionParam107, sjt_functionParam108, &result); if ((&result)->item1 == s->count) { sjt_value2._refCount = 1; #line 171 "lib/sj-lib-json/parse.sj" sjf_json_value_copy(&sjt_value2, &(&result)->item2); #line 171 sjs_json_value* copyoption25 = &sjt_value2; if (copyoption25 != 0) { _return->_refCount = 1; #line 171 "lib/sj-lib-json/parse.sj" sjf_json_value_copy(_return, copyoption25); } else { _return->_refCount = -1; } } else { #line 173 "lib/sj-lib-json/parse.sj" _return->_refCount = -1; } if (result._refCount == 1) { sjf_tuple2_i32_value_destroy(&result); } ; if (sjt_value2._refCount == 1) { sjf_json_value_destroy(&sjt_value2); } ; } void sjf_json_parse_heap(sjs_string* s, sjs_json_value** _return) { sjs_tuple2_i32_value result = { -1 }; sjs_string* sjt_functionParam109 = 0; int32_t sjt_functionParam110; #line 168 "lib/sj-lib-json/parse.sj" sjt_functionParam109 = s; #line 169 sjt_functionParam110 = 0; #line 169 sjf_json_parse_value(sjt_functionParam109, sjt_functionParam110, &result); if ((&result)->item1 == s->count) { sjs_json_value* sjt_value3 = 0; sjt_value3 = (sjs_json_value*)malloc(sizeof(sjs_json_value)); sjt_value3->_refCount = 1; #line 171 "lib/sj-lib-json/parse.sj" sjf_json_value_copy(sjt_value3, (&(&result)->item2)); #line 171 (*_return) = sjt_value3; if ((*_return) != 0) { (*_return)->_refCount++; } sjt_value3->_refCount--; if (sjt_value3->_refCount <= 0) { weakptr_release(sjt_value3); sjf_json_value_destroy(sjt_value3); free(sjt_value3); } } else { #line 173 "lib/sj-lib-json/parse.sj" (*_return) = 0; if ((*_return) != 0) { (*_return)->_refCount++; } } if (result._refCount == 1) { sjf_tuple2_i32_value_destroy(&result); } ; } void sjf_json_parse_number(sjs_string* s, int32_t startindex, sjs_tuple2_i32_string* _return) { int32_t index; bool isescaped; bool ismatched; int32_t sjt_functionParam60; int32_t sjt_functionParam61; sjs_string* sjt_parent32 = 0; bool sjt_while6; #line 41 "lib/sj-lib-json/parse.sj" isescaped = false; #line 40 index = startindex; #line 43 ismatched = true; if (index < s->count) { #line 44 "lib/sj-lib-json/parse.sj" sjt_while6 = ismatched; } else { #line 44 "lib/sj-lib-json/parse.sj" sjt_while6 = false; } while (sjt_while6) { char ch; bool sjt_capture23; bool sjt_capture24; int32_t sjt_functionParam59; sjs_string* sjt_parent31 = 0; #line 40 "lib/sj-lib-json/parse.sj" sjt_parent31 = s; #line 45 sjt_functionParam59 = index; #line 45 sjf_string_getat(sjt_parent31, sjt_functionParam59, &ch); if (ch >= '0') { #line 46 "lib/sj-lib-json/parse.sj" sjt_capture23 = (ch <= '9'); } else { #line 46 "lib/sj-lib-json/parse.sj" sjt_capture23 = false; } if (ch >= 'a') { #line 46 "lib/sj-lib-json/parse.sj" sjt_capture24 = (ch <= 'z'); } else { #line 46 "lib/sj-lib-json/parse.sj" sjt_capture24 = false; } if (sjt_capture23 || ((ch == '.') || sjt_capture24)) { #line 47 "lib/sj-lib-json/parse.sj" index = index + 1; } else { #line 49 "lib/sj-lib-json/parse.sj" ismatched = false; } if (index < s->count) { #line 44 "lib/sj-lib-json/parse.sj" sjt_while6 = ismatched; } else { #line 44 "lib/sj-lib-json/parse.sj" sjt_while6 = false; } } #line 43 _return->_refCount = 1; #line 53 _return->item1 = index; #line 40 sjt_parent32 = s; #line 40 sjt_functionParam60 = startindex; #line 53 sjt_functionParam61 = index - startindex; #line 53 sjf_string_substr(sjt_parent32, sjt_functionParam60, sjt_functionParam61, &_return->item2); #line 53 sjf_tuple2_i32_string(_return); } void sjf_json_parse_number_heap(sjs_string* s, int32_t startindex, sjs_tuple2_i32_string** _return) { int32_t index; bool isescaped; bool ismatched; int32_t sjt_functionParam63; int32_t sjt_functionParam64; sjs_string* sjt_parent34 = 0; bool sjt_while7; #line 41 "lib/sj-lib-json/parse.sj" isescaped = false; #line 40 index = startindex; #line 43 ismatched = true; if (index < s->count) { #line 44 "lib/sj-lib-json/parse.sj" sjt_while7 = ismatched; } else { #line 44 "lib/sj-lib-json/parse.sj" sjt_while7 = false; } while (sjt_while7) { char ch; bool sjt_capture25; bool sjt_capture26; int32_t sjt_functionParam62; sjs_string* sjt_parent33 = 0; #line 40 "lib/sj-lib-json/parse.sj" sjt_parent33 = s; #line 45 sjt_functionParam62 = index; #line 45 sjf_string_getat(sjt_parent33, sjt_functionParam62, &ch); if (ch >= '0') { #line 46 "lib/sj-lib-json/parse.sj" sjt_capture25 = (ch <= '9'); } else { #line 46 "lib/sj-lib-json/parse.sj" sjt_capture25 = false; } if (ch >= 'a') { #line 46 "lib/sj-lib-json/parse.sj" sjt_capture26 = (ch <= 'z'); } else { #line 46 "lib/sj-lib-json/parse.sj" sjt_capture26 = false; } if (sjt_capture25 || ((ch == '.') || sjt_capture26)) { #line 47 "lib/sj-lib-json/parse.sj" index = index + 1; } else { #line 49 "lib/sj-lib-json/parse.sj" ismatched = false; } if (index < s->count) { #line 44 "lib/sj-lib-json/parse.sj" sjt_while7 = ismatched; } else { #line 44 "lib/sj-lib-json/parse.sj" sjt_while7 = false; } } #line 43 (*_return) = (sjs_tuple2_i32_string*)malloc(sizeof(sjs_tuple2_i32_string)); #line 43 (*_return)->_refCount = 1; #line 53 (*_return)->item1 = index; #line 40 sjt_parent34 = s; #line 40 sjt_functionParam63 = startindex; #line 53 sjt_functionParam64 = index - startindex; #line 53 sjf_string_substr(sjt_parent34, sjt_functionParam63, sjt_functionParam64, &(*_return)->item2); #line 53 sjf_tuple2_i32_string_heap((*_return)); } void sjf_json_parse_string(sjs_string* s, int32_t startindex, sjs_tuple2_i32_string* _return) { int32_t index; bool isescaped; bool ismatched; bool sjt_while3; #line 17 "lib/sj-lib-json/parse.sj" isescaped = false; #line 18 index = startindex + 1; #line 19 ismatched = false; if (index < s->count) { bool result3; #line 20 "lib/sj-lib-json/parse.sj" result3 = !ismatched; #line 20 sjt_while3 = result3; } else { #line 20 "lib/sj-lib-json/parse.sj" sjt_while3 = false; } while (sjt_while3) { char ch; bool result4; bool sjt_capture8; int32_t sjt_functionParam16; sjs_string* sjt_parent10 = 0; #line 16 "lib/sj-lib-json/parse.sj" sjt_parent10 = s; #line 21 sjt_functionParam16 = index; #line 21 sjf_string_getat(sjt_parent10, sjt_functionParam16, &ch); #line 22 result4 = !isescaped; if (result4) { #line 22 "lib/sj-lib-json/parse.sj" sjt_capture8 = (ch == '\\'); } else { #line 22 "lib/sj-lib-json/parse.sj" sjt_capture8 = false; } if (sjt_capture8) { #line 23 "lib/sj-lib-json/parse.sj" isescaped = true; } else { if (ch == '\"') { #line 26 "lib/sj-lib-json/parse.sj" ismatched = true; } #line 28 "lib/sj-lib-json/parse.sj" isescaped = false; } #line 30 index = index + 1; if (index < s->count) { bool result5; #line 20 "lib/sj-lib-json/parse.sj" result5 = !ismatched; #line 20 sjt_while3 = result5; } else { #line 20 "lib/sj-lib-json/parse.sj" sjt_while3 = false; } } if (ismatched) { int32_t sjt_functionParam19; int32_t sjt_functionParam20; sjs_string* sjt_parent13 = 0; _return->_refCount = 1; #line 34 "lib/sj-lib-json/parse.sj" _return->item1 = index; #line 16 sjt_parent13 = s; #line 16 sjt_functionParam19 = startindex; #line 34 sjt_functionParam20 = index - startindex; #line 34 sjf_string_substr(sjt_parent13, sjt_functionParam19, sjt_functionParam20, &_return->item2); #line 34 sjf_tuple2_i32_string(_return); } else { _return->_refCount = 1; #line 36 "lib/sj-lib-json/parse.sj" _return->item1 = s->count + 1; #line 36 _return->item2._refCount = 1; #line 36 _return->item2.offset = 0; #line 36 _return->item2.count = 0; #line 36 _return->item2.data._refCount = 1; #line 36 _return->item2.data.v = &sjg_string2; #line 36 sjf_array_char(&_return->item2.data); #line 16 "lib/sj-lib-common/string.sj" _return->item2._isnullterminated = false; #line 16 sjf_string(&_return->item2); #line 16 sjf_tuple2_i32_string(_return); } } void sjf_json_parse_string_heap(sjs_string* s, int32_t startindex, sjs_tuple2_i32_string** _return) { int32_t index; bool isescaped; bool ismatched; bool sjt_while4; #line 17 "lib/sj-lib-json/parse.sj" isescaped = false; #line 18 index = startindex + 1; #line 19 ismatched = false; if (index < s->count) { bool result6; #line 20 "lib/sj-lib-json/parse.sj" result6 = !ismatched; #line 20 sjt_while4 = result6; } else { #line 20 "lib/sj-lib-json/parse.sj" sjt_while4 = false; } while (sjt_while4) { char ch; bool result7; bool sjt_capture11; int32_t sjt_functionParam21; sjs_string* sjt_parent14 = 0; #line 16 "lib/sj-lib-json/parse.sj" sjt_parent14 = s; #line 21 sjt_functionParam21 = index; #line 21 sjf_string_getat(sjt_parent14, sjt_functionParam21, &ch); #line 22 result7 = !isescaped; if (result7) { #line 22 "lib/sj-lib-json/parse.sj" sjt_capture11 = (ch == '\\'); } else { #line 22 "lib/sj-lib-json/parse.sj" sjt_capture11 = false; } if (sjt_capture11) { #line 23 "lib/sj-lib-json/parse.sj" isescaped = true; } else { if (ch == '\"') { #line 26 "lib/sj-lib-json/parse.sj" ismatched = true; } #line 28 "lib/sj-lib-json/parse.sj" isescaped = false; } #line 30 index = index + 1; if (index < s->count) { bool result8; #line 20 "lib/sj-lib-json/parse.sj" result8 = !ismatched; #line 20 sjt_while4 = result8; } else { #line 20 "lib/sj-lib-json/parse.sj" sjt_while4 = false; } } if (ismatched) { int32_t sjt_functionParam22; int32_t sjt_functionParam23; sjs_string* sjt_parent15 = 0; (*_return) = (sjs_tuple2_i32_string*)malloc(sizeof(sjs_tuple2_i32_string)); (*_return)->_refCount = 1; #line 34 "lib/sj-lib-json/parse.sj" (*_return)->item1 = index; #line 16 sjt_parent15 = s; #line 16 sjt_functionParam22 = startindex; #line 34 sjt_functionParam23 = index - startindex; #line 34 sjf_string_substr(sjt_parent15, sjt_functionParam22, sjt_functionParam23, &(*_return)->item2); #line 34 sjf_tuple2_i32_string_heap((*_return)); } else { (*_return) = (sjs_tuple2_i32_string*)malloc(sizeof(sjs_tuple2_i32_string)); (*_return)->_refCount = 1; #line 36 "lib/sj-lib-json/parse.sj" (*_return)->item1 = s->count + 1; #line 36 (*_return)->item2._refCount = 1; #line 36 (*_return)->item2.offset = 0; #line 36 (*_return)->item2.count = 0; #line 36 (*_return)->item2.data._refCount = 1; #line 36 (*_return)->item2.data.v = &sjg_string2; #line 36 sjf_array_char(&(*_return)->item2.data); #line 16 "lib/sj-lib-common/string.sj" (*_return)->item2._isnullterminated = false; #line 16 sjf_string(&(*_return)->item2); #line 16 sjf_tuple2_i32_string_heap((*_return)); } } void sjf_json_parse_value(sjs_string* s, int32_t startindex, sjs_tuple2_i32_value* _return) { int32_t index; sjs_string* sjt_functionParam6 = 0; int32_t sjt_functionParam7; int32_t sjt_functionParam8; sjs_string* sjt_parent6 = 0; char underscore1; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam6 = s; #line 56 sjt_functionParam7 = startindex; #line 56 sjf_json_parse_whitespace(sjt_functionParam6, sjt_functionParam7, &index); #line 56 sjt_parent6 = s; #line 59 sjt_functionParam8 = index; #line 59 sjf_string_getat(sjt_parent6, sjt_functionParam8, &underscore1); if (underscore1 == '{') { sjs_hash_string_value h = { -1 }; bool isfirst; bool shouldcontinue; bool sjt_while2; h._refCount = 1; sjf_hash_string_value(&h); #line 63 "lib/sj-lib-json/parse.sj" index = index + 1; #line 64 isfirst = true; #line 65 shouldcontinue = true; if (index < s->count) { #line 66 "lib/sj-lib-json/parse.sj" sjt_while2 = shouldcontinue; } else { #line 66 "lib/sj-lib-json/parse.sj" sjt_while2 = false; } while (sjt_while2) { sjs_string key = { -1 }; sjs_tuple2_i32_string keyresult = { -1 }; int32_t sjt_funcold2; int32_t sjt_functionParam10; sjs_string* sjt_functionParam9 = 0; sjs_json_value value = { -1 }; sjs_tuple2_i32_value valueresult = { -1 }; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam9 = s; #line 67 sjt_functionParam10 = index; #line 67 sjf_json_parse_whitespace(sjt_functionParam9, sjt_functionParam10, &sjt_funcold2); #line 2 index = sjt_funcold2; if (isfirst) { bool sjt_capture3; #line 69 "lib/sj-lib-json/parse.sj" isfirst = false; if (index < s->count) { char sjt_capture4; int32_t sjt_functionParam11; sjs_string* sjt_parent7 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent7 = s; #line 70 sjt_functionParam11 = index; #line 70 sjf_string_getat(sjt_parent7, sjt_functionParam11, &sjt_capture4); #line 70 sjt_capture3 = (sjt_capture4 == '}'); } else { #line 70 "lib/sj-lib-json/parse.sj" sjt_capture3 = false; } if (sjt_capture3) { #line 71 "lib/sj-lib-json/parse.sj" index = index + 1; #line 72 shouldcontinue = false; } } else { char sjt_capture5; int32_t sjt_functionParam12; sjs_string* sjt_parent8 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent8 = s; #line 75 sjt_functionParam12 = index; #line 75 sjf_string_getat(sjt_parent8, sjt_functionParam12, &sjt_capture5); if (sjt_capture5 == ',') { int32_t sjt_funcold3; sjs_string* sjt_functionParam13 = 0; int32_t sjt_functionParam14; #line 76 "lib/sj-lib-json/parse.sj" index = index + 1; #line 56 sjt_functionParam13 = s; #line 77 sjt_functionParam14 = index; #line 77 sjf_json_parse_whitespace(sjt_functionParam13, sjt_functionParam14, &sjt_funcold3); #line 2 index = sjt_funcold3; } else { #line 79 "lib/sj-lib-json/parse.sj" index = s->count + 1; } } if (shouldcontinue) { bool sjt_capture6; if (index < s->count) { char sjt_capture7; int32_t sjt_functionParam15; sjs_string* sjt_parent9 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent9 = s; #line 84 sjt_functionParam15 = index; #line 84 sjf_string_getat(sjt_parent9, sjt_functionParam15, &sjt_capture7); #line 84 sjt_capture6 = (sjt_capture7 == '\"'); } else { #line 84 "lib/sj-lib-json/parse.sj" sjt_capture6 = false; } if (sjt_capture6) { char sjt_capture12; bool sjt_capture13; int32_t sjt_funcold4; int32_t sjt_funcold5; int32_t sjt_funcold6; sjs_string* sjt_functionParam24 = 0; int32_t sjt_functionParam25; sjs_string* sjt_functionParam28 = 0; int32_t sjt_functionParam29; int32_t sjt_functionParam30; sjs_string* sjt_functionParam31 = 0; int32_t sjt_functionParam32; sjs_string* sjt_functionParam33 = 0; int32_t sjt_functionParam34; sjs_string* sjt_functionParam35 = 0; sjs_json_value* sjt_functionParam36 = 0; sjs_string* sjt_functionParam37 = 0; int32_t sjt_functionParam38; sjs_string* sjt_parent17 = 0; sjs_hash_string_value* sjt_parent18 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam24 = s; #line 85 sjt_functionParam25 = index; #line 85 sjf_json_parse_string(sjt_functionParam24, sjt_functionParam25, &keyresult); #line 86 index = (&keyresult)->item1 + 1; if ((&(&keyresult)->item2)->count > 0) { int32_t sjt_functionParam26; int32_t sjt_functionParam27; sjs_string* sjt_parent16 = 0; #line 47 "lib/sj-lib-common/string.sj" sjt_parent16 = &(&keyresult)->item2; #line 87 "lib/sj-lib-json/parse.sj" sjt_functionParam26 = 1; #line 87 sjt_functionParam27 = (&(&keyresult)->item2)->count - 2; #line 87 sjf_string_substr(sjt_parent16, sjt_functionParam26, sjt_functionParam27, &key); } else { key._refCount = 1; #line 87 "lib/sj-lib-json/parse.sj" key.offset = 0; #line 87 key.count = 0; #line 87 key.data._refCount = 1; #line 87 key.data.v = &sjg_string2; #line 87 sjf_array_char(&key.data); #line 16 "lib/sj-lib-common/string.sj" key._isnullterminated = false; #line 16 sjf_string(&key); } #line 56 sjt_functionParam28 = s; #line 89 sjt_functionParam29 = index; #line 89 sjf_json_parse_whitespace(sjt_functionParam28, sjt_functionParam29, &sjt_funcold4); #line 2 index = sjt_funcold4; #line 56 sjt_parent17 = s; #line 91 sjt_functionParam30 = index; #line 91 sjf_string_getat(sjt_parent17, sjt_functionParam30, &sjt_capture12); if (sjt_capture12 == ':') { #line 92 "lib/sj-lib-json/parse.sj" index = index + 1; } else { #line 94 "lib/sj-lib-json/parse.sj" index = s->count + 1; } #line 56 sjt_functionParam31 = s; #line 97 sjt_functionParam32 = index; #line 97 sjf_json_parse_whitespace(sjt_functionParam31, sjt_functionParam32, &sjt_funcold5); #line 2 index = sjt_funcold5; #line 56 sjt_functionParam33 = s; #line 99 sjt_functionParam34 = index; #line 99 sjf_json_parse_value(sjt_functionParam33, sjt_functionParam34, &valueresult); #line 100 index = (&valueresult)->item1; #line 100 value._refCount = 1; #line 101 sjf_json_value_copy(&value, &(&valueresult)->item2); #line 38 "lib/sj-lib-common/hash.sj" sjt_parent18 = &h; #line 103 "lib/sj-lib-json/parse.sj" sjt_functionParam35 = &key; #line 103 sjt_functionParam36 = &value; #line 103 sjf_hash_string_value_setat(sjt_parent18, sjt_functionParam35, sjt_functionParam36); #line 56 sjt_functionParam37 = s; #line 105 sjt_functionParam38 = index; #line 105 sjf_json_parse_whitespace(sjt_functionParam37, sjt_functionParam38, &sjt_funcold6); #line 2 index = sjt_funcold6; if (index < s->count) { char sjt_capture14; int32_t sjt_functionParam39; sjs_string* sjt_parent19 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent19 = s; #line 107 sjt_functionParam39 = index; #line 107 sjf_string_getat(sjt_parent19, sjt_functionParam39, &sjt_capture14); #line 107 sjt_capture13 = (sjt_capture14 == '}'); } else { #line 107 "lib/sj-lib-json/parse.sj" sjt_capture13 = false; } if (sjt_capture13) { #line 108 "lib/sj-lib-json/parse.sj" index = index + 1; #line 109 shouldcontinue = false; } } else { #line 112 "lib/sj-lib-json/parse.sj" index = s->count + 1; } } if (index < s->count) { #line 66 "lib/sj-lib-json/parse.sj" sjt_while2 = shouldcontinue; } else { #line 66 "lib/sj-lib-json/parse.sj" sjt_while2 = false; } if (key._refCount == 1) { sjf_string_destroy(&key); } ; if (keyresult._refCount == 1) { sjf_tuple2_i32_string_destroy(&keyresult); } ; if (value._refCount == 1) { sjf_json_value_destroy(&value); } ; if (valueresult._refCount == 1) { sjf_tuple2_i32_value_destroy(&valueresult); } ; } #line 65 _return->_refCount = 1; #line 116 _return->item1 = index; #line 116 _return->item2._refCount = 1; #line 3 "lib/sj-lib-json/value.sj" _return->item2.s._refCount = -1; #line 4 _return->item2.a._refCount = -1; #line 116 "lib/sj-lib-json/parse.sj" sjs_hash_string_value* copyoption17 = &h; if (copyoption17 != 0) { _return->item2.h._refCount = 1; #line 116 "lib/sj-lib-json/parse.sj" sjf_hash_string_value_copy(&_return->item2.h, copyoption17); } else { _return->item2.h._refCount = -1; } #line 116 sjf_json_value(&_return->item2); #line 116 sjf_tuple2_i32_value(_return); if (h._refCount == 1) { sjf_hash_string_value_destroy(&h); } ; } else { if (underscore1 == '[') { bool isfirst; sjs_list_value l = { -1 }; bool shouldcontinue; bool sjt_while5; l._refCount = 1; l.arr._refCount = 1; #line 27 "lib/sj-lib-common/array.sj" l.arr.v = 0; #line 27 sjf_array_value(&l.arr); #line 27 sjf_list_value(&l); #line 121 "lib/sj-lib-json/parse.sj" index = index + 1; #line 122 isfirst = true; #line 123 shouldcontinue = true; if (index < s->count) { #line 124 "lib/sj-lib-json/parse.sj" sjt_while5 = shouldcontinue; } else { #line 124 "lib/sj-lib-json/parse.sj" sjt_while5 = false; } while (sjt_while5) { bool sjt_capture21; int32_t sjt_funcold7; int32_t sjt_funcold9; sjs_string* sjt_functionParam40 = 0; int32_t sjt_functionParam41; sjs_string* sjt_functionParam44 = 0; int32_t sjt_functionParam45; sjs_json_value* sjt_functionParam53 = 0; sjs_string* sjt_functionParam54 = 0; int32_t sjt_functionParam55; sjs_list_value* sjt_parent29 = 0; sjs_json_value value = { -1 }; sjs_tuple2_i32_value valueresult = { -1 }; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam40 = s; #line 125 sjt_functionParam41 = index; #line 125 sjf_json_parse_whitespace(sjt_functionParam40, sjt_functionParam41, &sjt_funcold7); #line 2 index = sjt_funcold7; if (isfirst) { bool sjt_capture15; #line 127 "lib/sj-lib-json/parse.sj" isfirst = false; if (index < s->count) { char sjt_capture16; int32_t sjt_functionParam42; sjs_string* sjt_parent20 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent20 = s; #line 128 sjt_functionParam42 = index; #line 128 sjf_string_getat(sjt_parent20, sjt_functionParam42, &sjt_capture16); #line 128 sjt_capture15 = (sjt_capture16 == ']'); } else { #line 128 "lib/sj-lib-json/parse.sj" sjt_capture15 = false; } if (sjt_capture15) { #line 129 "lib/sj-lib-json/parse.sj" index = index + 1; #line 130 shouldcontinue = false; } } else { char sjt_capture17; int32_t sjt_functionParam43; sjs_string* sjt_parent21 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent21 = s; #line 133 sjt_functionParam43 = index; #line 133 sjf_string_getat(sjt_parent21, sjt_functionParam43, &sjt_capture17); if (sjt_capture17 == ',') { #line 134 "lib/sj-lib-json/parse.sj" index = index + 1; } else { #line 136 "lib/sj-lib-json/parse.sj" index = s->count + 1; } } #line 56 sjt_functionParam44 = s; #line 140 sjt_functionParam45 = index; #line 140 sjf_json_parse_value(sjt_functionParam44, sjt_functionParam45, &valueresult); #line 141 index = (&valueresult)->item1; #line 141 value._refCount = 1; #line 142 sjf_json_value_copy(&value, &(&valueresult)->item2); #line 44 "lib/sj-lib-common/list.sj" sjt_parent29 = &l; #line 144 "lib/sj-lib-json/parse.sj" sjt_functionParam53 = &value; #line 144 sjf_list_value_add(sjt_parent29, sjt_functionParam53); #line 56 sjt_functionParam54 = s; #line 146 sjt_functionParam55 = index; #line 146 sjf_json_parse_whitespace(sjt_functionParam54, sjt_functionParam55, &sjt_funcold9); #line 2 index = sjt_funcold9; if (index < s->count) { char sjt_capture22; int32_t sjt_functionParam56; sjs_string* sjt_parent30 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent30 = s; #line 148 sjt_functionParam56 = index; #line 148 sjf_string_getat(sjt_parent30, sjt_functionParam56, &sjt_capture22); #line 148 sjt_capture21 = (sjt_capture22 == ']'); } else { #line 148 "lib/sj-lib-json/parse.sj" sjt_capture21 = false; } if (sjt_capture21) { #line 149 "lib/sj-lib-json/parse.sj" index = index + 1; #line 150 shouldcontinue = false; } if (index < s->count) { #line 124 "lib/sj-lib-json/parse.sj" sjt_while5 = shouldcontinue; } else { #line 124 "lib/sj-lib-json/parse.sj" sjt_while5 = false; } if (value._refCount == 1) { sjf_json_value_destroy(&value); } ; if (valueresult._refCount == 1) { sjf_tuple2_i32_value_destroy(&valueresult); } ; } #line 123 _return->_refCount = 1; #line 153 _return->item1 = index; #line 153 _return->item2._refCount = 1; #line 3 "lib/sj-lib-json/value.sj" _return->item2.s._refCount = -1; #line 153 "lib/sj-lib-json/parse.sj" sjs_array_value* copyoption18 = &(&l)->arr; if (copyoption18 != 0) { _return->item2.a._refCount = 1; #line 153 "lib/sj-lib-json/parse.sj" sjf_array_value_copy(&_return->item2.a, copyoption18); } else { _return->item2.a._refCount = -1; } #line 5 "lib/sj-lib-json/value.sj" _return->item2.h._refCount = -1; #line 5 sjf_json_value(&_return->item2); #line 5 sjf_tuple2_i32_value(_return); if (l._refCount == 1) { sjf_list_value_destroy(&l); } ; } else { if (underscore1 == '\"') { sjs_tuple2_i32_string result = { -1 }; sjs_string* sjt_functionParam57 = 0; int32_t sjt_functionParam58; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam57 = s; #line 157 sjt_functionParam58 = index; #line 157 sjf_json_parse_string(sjt_functionParam57, sjt_functionParam58, &result); #line 157 _return->_refCount = 1; #line 158 _return->item1 = (&result)->item1; #line 158 _return->item2._refCount = 1; #line 158 sjs_string* copyoption19 = &(&result)->item2; if (copyoption19 != 0) { _return->item2.s._refCount = 1; #line 158 "lib/sj-lib-json/parse.sj" sjf_string_copy(&_return->item2.s, copyoption19); } else { _return->item2.s._refCount = -1; } #line 4 "lib/sj-lib-json/value.sj" _return->item2.a._refCount = -1; #line 5 _return->item2.h._refCount = -1; #line 5 sjf_json_value(&_return->item2); #line 5 sjf_tuple2_i32_value(_return); if (result._refCount == 1) { sjf_tuple2_i32_string_destroy(&result); } ; } else { sjs_tuple2_i32_string result = { -1 }; sjs_string* sjt_functionParam65 = 0; int32_t sjt_functionParam66; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam65 = s; #line 162 sjt_functionParam66 = index; #line 162 sjf_json_parse_number(sjt_functionParam65, sjt_functionParam66, &result); #line 162 _return->_refCount = 1; #line 163 _return->item1 = (&result)->item1; #line 163 _return->item2._refCount = 1; #line 163 sjs_string* copyoption20 = &(&result)->item2; if (copyoption20 != 0) { _return->item2.s._refCount = 1; #line 163 "lib/sj-lib-json/parse.sj" sjf_string_copy(&_return->item2.s, copyoption20); } else { _return->item2.s._refCount = -1; } #line 4 "lib/sj-lib-json/value.sj" _return->item2.a._refCount = -1; #line 5 _return->item2.h._refCount = -1; #line 5 sjf_json_value(&_return->item2); #line 5 sjf_tuple2_i32_value(_return); if (result._refCount == 1) { sjf_tuple2_i32_string_destroy(&result); } ; } } } } void sjf_json_parse_value_heap(sjs_string* s, int32_t startindex, sjs_tuple2_i32_value** _return) { int32_t index; sjs_string* sjt_functionParam67 = 0; int32_t sjt_functionParam68; int32_t sjt_functionParam69; sjs_string* sjt_parent35 = 0; char underscore2; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam67 = s; #line 56 sjt_functionParam68 = startindex; #line 56 sjf_json_parse_whitespace(sjt_functionParam67, sjt_functionParam68, &index); #line 56 sjt_parent35 = s; #line 59 sjt_functionParam69 = index; #line 59 sjf_string_getat(sjt_parent35, sjt_functionParam69, &underscore2); if (underscore2 == '{') { sjs_hash_string_value h = { -1 }; bool isfirst; bool shouldcontinue; sjs_tuple2_i32_value sjt_call3 = { -1 }; bool sjt_while8; h._refCount = 1; sjf_hash_string_value(&h); #line 63 "lib/sj-lib-json/parse.sj" index = index + 1; #line 64 isfirst = true; #line 65 shouldcontinue = true; if (index < s->count) { #line 66 "lib/sj-lib-json/parse.sj" sjt_while8 = shouldcontinue; } else { #line 66 "lib/sj-lib-json/parse.sj" sjt_while8 = false; } while (sjt_while8) { sjs_string key = { -1 }; sjs_tuple2_i32_string keyresult = { -1 }; int32_t sjt_funcold10; sjs_string* sjt_functionParam70 = 0; int32_t sjt_functionParam71; sjs_json_value value = { -1 }; sjs_tuple2_i32_value valueresult = { -1 }; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam70 = s; #line 67 sjt_functionParam71 = index; #line 67 sjf_json_parse_whitespace(sjt_functionParam70, sjt_functionParam71, &sjt_funcold10); #line 2 index = sjt_funcold10; if (isfirst) { bool sjt_capture27; #line 69 "lib/sj-lib-json/parse.sj" isfirst = false; if (index < s->count) { char sjt_capture28; int32_t sjt_functionParam72; sjs_string* sjt_parent36 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent36 = s; #line 70 sjt_functionParam72 = index; #line 70 sjf_string_getat(sjt_parent36, sjt_functionParam72, &sjt_capture28); #line 70 sjt_capture27 = (sjt_capture28 == '}'); } else { #line 70 "lib/sj-lib-json/parse.sj" sjt_capture27 = false; } if (sjt_capture27) { #line 71 "lib/sj-lib-json/parse.sj" index = index + 1; #line 72 shouldcontinue = false; } } else { char sjt_capture29; int32_t sjt_functionParam73; sjs_string* sjt_parent37 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent37 = s; #line 75 sjt_functionParam73 = index; #line 75 sjf_string_getat(sjt_parent37, sjt_functionParam73, &sjt_capture29); if (sjt_capture29 == ',') { int32_t sjt_funcold11; sjs_string* sjt_functionParam74 = 0; int32_t sjt_functionParam75; #line 76 "lib/sj-lib-json/parse.sj" index = index + 1; #line 56 sjt_functionParam74 = s; #line 77 sjt_functionParam75 = index; #line 77 sjf_json_parse_whitespace(sjt_functionParam74, sjt_functionParam75, &sjt_funcold11); #line 2 index = sjt_funcold11; } else { #line 79 "lib/sj-lib-json/parse.sj" index = s->count + 1; } } if (shouldcontinue) { bool sjt_capture30; if (index < s->count) { char sjt_capture31; int32_t sjt_functionParam76; sjs_string* sjt_parent38 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent38 = s; #line 84 sjt_functionParam76 = index; #line 84 sjf_string_getat(sjt_parent38, sjt_functionParam76, &sjt_capture31); #line 84 sjt_capture30 = (sjt_capture31 == '\"'); } else { #line 84 "lib/sj-lib-json/parse.sj" sjt_capture30 = false; } if (sjt_capture30) { char sjt_capture32; bool sjt_capture33; int32_t sjt_funcold12; int32_t sjt_funcold13; int32_t sjt_funcold14; sjs_string* sjt_functionParam77 = 0; int32_t sjt_functionParam78; sjs_string* sjt_functionParam81 = 0; int32_t sjt_functionParam82; int32_t sjt_functionParam83; sjs_string* sjt_functionParam84 = 0; int32_t sjt_functionParam85; sjs_string* sjt_functionParam86 = 0; int32_t sjt_functionParam87; sjs_string* sjt_functionParam88 = 0; sjs_json_value* sjt_functionParam89 = 0; sjs_string* sjt_functionParam90 = 0; int32_t sjt_functionParam91; sjs_string* sjt_parent40 = 0; sjs_hash_string_value* sjt_parent41 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam77 = s; #line 85 sjt_functionParam78 = index; #line 85 sjf_json_parse_string(sjt_functionParam77, sjt_functionParam78, &keyresult); #line 86 index = (&keyresult)->item1 + 1; if ((&(&keyresult)->item2)->count > 0) { int32_t sjt_functionParam79; int32_t sjt_functionParam80; sjs_string* sjt_parent39 = 0; #line 47 "lib/sj-lib-common/string.sj" sjt_parent39 = &(&keyresult)->item2; #line 87 "lib/sj-lib-json/parse.sj" sjt_functionParam79 = 1; #line 87 sjt_functionParam80 = (&(&keyresult)->item2)->count - 2; #line 87 sjf_string_substr(sjt_parent39, sjt_functionParam79, sjt_functionParam80, &key); } else { key._refCount = 1; #line 87 "lib/sj-lib-json/parse.sj" key.offset = 0; #line 87 key.count = 0; #line 87 key.data._refCount = 1; #line 87 key.data.v = &sjg_string2; #line 87 sjf_array_char(&key.data); #line 16 "lib/sj-lib-common/string.sj" key._isnullterminated = false; #line 16 sjf_string(&key); } #line 56 sjt_functionParam81 = s; #line 89 sjt_functionParam82 = index; #line 89 sjf_json_parse_whitespace(sjt_functionParam81, sjt_functionParam82, &sjt_funcold12); #line 2 index = sjt_funcold12; #line 56 sjt_parent40 = s; #line 91 sjt_functionParam83 = index; #line 91 sjf_string_getat(sjt_parent40, sjt_functionParam83, &sjt_capture32); if (sjt_capture32 == ':') { #line 92 "lib/sj-lib-json/parse.sj" index = index + 1; } else { #line 94 "lib/sj-lib-json/parse.sj" index = s->count + 1; } #line 56 sjt_functionParam84 = s; #line 97 sjt_functionParam85 = index; #line 97 sjf_json_parse_whitespace(sjt_functionParam84, sjt_functionParam85, &sjt_funcold13); #line 2 index = sjt_funcold13; #line 56 sjt_functionParam86 = s; #line 99 sjt_functionParam87 = index; #line 99 sjf_json_parse_value(sjt_functionParam86, sjt_functionParam87, &valueresult); #line 100 index = (&valueresult)->item1; #line 100 value._refCount = 1; #line 101 sjf_json_value_copy(&value, &(&valueresult)->item2); #line 38 "lib/sj-lib-common/hash.sj" sjt_parent41 = &h; #line 103 "lib/sj-lib-json/parse.sj" sjt_functionParam88 = &key; #line 103 sjt_functionParam89 = &value; #line 103 sjf_hash_string_value_setat(sjt_parent41, sjt_functionParam88, sjt_functionParam89); #line 56 sjt_functionParam90 = s; #line 105 sjt_functionParam91 = index; #line 105 sjf_json_parse_whitespace(sjt_functionParam90, sjt_functionParam91, &sjt_funcold14); #line 2 index = sjt_funcold14; if (index < s->count) { char sjt_capture34; int32_t sjt_functionParam92; sjs_string* sjt_parent42 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent42 = s; #line 107 sjt_functionParam92 = index; #line 107 sjf_string_getat(sjt_parent42, sjt_functionParam92, &sjt_capture34); #line 107 sjt_capture33 = (sjt_capture34 == '}'); } else { #line 107 "lib/sj-lib-json/parse.sj" sjt_capture33 = false; } if (sjt_capture33) { #line 108 "lib/sj-lib-json/parse.sj" index = index + 1; #line 109 shouldcontinue = false; } } else { #line 112 "lib/sj-lib-json/parse.sj" index = s->count + 1; } } if (index < s->count) { #line 66 "lib/sj-lib-json/parse.sj" sjt_while8 = shouldcontinue; } else { #line 66 "lib/sj-lib-json/parse.sj" sjt_while8 = false; } if (key._refCount == 1) { sjf_string_destroy(&key); } ; if (keyresult._refCount == 1) { sjf_tuple2_i32_string_destroy(&keyresult); } ; if (value._refCount == 1) { sjf_json_value_destroy(&value); } ; if (valueresult._refCount == 1) { sjf_tuple2_i32_value_destroy(&valueresult); } ; } #line 65 sjt_call3._refCount = 1; #line 116 sjt_call3.item1 = index; #line 116 sjt_call3.item2._refCount = 1; #line 3 "lib/sj-lib-json/value.sj" sjt_call3.item2.s._refCount = -1; #line 4 sjt_call3.item2.a._refCount = -1; #line 116 "lib/sj-lib-json/parse.sj" sjs_hash_string_value* copyoption21 = &h; if (copyoption21 != 0) { sjt_call3.item2.h._refCount = 1; #line 116 "lib/sj-lib-json/parse.sj" sjf_hash_string_value_copy(&sjt_call3.item2.h, copyoption21); } else { sjt_call3.item2.h._refCount = -1; } #line 116 sjf_json_value(&sjt_call3.item2); #line 116 sjf_tuple2_i32_value(&sjt_call3); #line 116 (*_return) = (sjs_tuple2_i32_value*)malloc(sizeof(sjs_tuple2_i32_value)); #line 116 (*_return)->_refCount = 1; #line 116 sjf_tuple2_i32_value_copy((*_return), &sjt_call3); if (h._refCount == 1) { sjf_hash_string_value_destroy(&h); } ; if (sjt_call3._refCount == 1) { sjf_tuple2_i32_value_destroy(&sjt_call3); } ; } else { if (underscore2 == '[') { bool isfirst; sjs_list_value l = { -1 }; bool shouldcontinue; sjs_tuple2_i32_value sjt_call4 = { -1 }; bool sjt_while9; l._refCount = 1; l.arr._refCount = 1; #line 27 "lib/sj-lib-common/array.sj" l.arr.v = 0; #line 27 sjf_array_value(&l.arr); #line 27 sjf_list_value(&l); #line 121 "lib/sj-lib-json/parse.sj" index = index + 1; #line 122 isfirst = true; #line 123 shouldcontinue = true; if (index < s->count) { #line 124 "lib/sj-lib-json/parse.sj" sjt_while9 = shouldcontinue; } else { #line 124 "lib/sj-lib-json/parse.sj" sjt_while9 = false; } while (sjt_while9) { bool sjt_capture38; int32_t sjt_funcold15; int32_t sjt_funcold16; sjs_string* sjt_functionParam100 = 0; int32_t sjt_functionParam101; sjs_string* sjt_functionParam93 = 0; int32_t sjt_functionParam94; sjs_string* sjt_functionParam97 = 0; int32_t sjt_functionParam98; sjs_json_value* sjt_functionParam99 = 0; sjs_list_value* sjt_parent45 = 0; sjs_json_value value = { -1 }; sjs_tuple2_i32_value valueresult = { -1 }; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam93 = s; #line 125 sjt_functionParam94 = index; #line 125 sjf_json_parse_whitespace(sjt_functionParam93, sjt_functionParam94, &sjt_funcold15); #line 2 index = sjt_funcold15; if (isfirst) { bool sjt_capture35; #line 127 "lib/sj-lib-json/parse.sj" isfirst = false; if (index < s->count) { char sjt_capture36; int32_t sjt_functionParam95; sjs_string* sjt_parent43 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent43 = s; #line 128 sjt_functionParam95 = index; #line 128 sjf_string_getat(sjt_parent43, sjt_functionParam95, &sjt_capture36); #line 128 sjt_capture35 = (sjt_capture36 == ']'); } else { #line 128 "lib/sj-lib-json/parse.sj" sjt_capture35 = false; } if (sjt_capture35) { #line 129 "lib/sj-lib-json/parse.sj" index = index + 1; #line 130 shouldcontinue = false; } } else { char sjt_capture37; int32_t sjt_functionParam96; sjs_string* sjt_parent44 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent44 = s; #line 133 sjt_functionParam96 = index; #line 133 sjf_string_getat(sjt_parent44, sjt_functionParam96, &sjt_capture37); if (sjt_capture37 == ',') { #line 134 "lib/sj-lib-json/parse.sj" index = index + 1; } else { #line 136 "lib/sj-lib-json/parse.sj" index = s->count + 1; } } #line 56 sjt_functionParam97 = s; #line 140 sjt_functionParam98 = index; #line 140 sjf_json_parse_value(sjt_functionParam97, sjt_functionParam98, &valueresult); #line 141 index = (&valueresult)->item1; #line 141 value._refCount = 1; #line 142 sjf_json_value_copy(&value, &(&valueresult)->item2); #line 44 "lib/sj-lib-common/list.sj" sjt_parent45 = &l; #line 144 "lib/sj-lib-json/parse.sj" sjt_functionParam99 = &value; #line 144 sjf_list_value_add(sjt_parent45, sjt_functionParam99); #line 56 sjt_functionParam100 = s; #line 146 sjt_functionParam101 = index; #line 146 sjf_json_parse_whitespace(sjt_functionParam100, sjt_functionParam101, &sjt_funcold16); #line 2 index = sjt_funcold16; if (index < s->count) { char sjt_capture39; int32_t sjt_functionParam102; sjs_string* sjt_parent46 = 0; #line 56 "lib/sj-lib-json/parse.sj" sjt_parent46 = s; #line 148 sjt_functionParam102 = index; #line 148 sjf_string_getat(sjt_parent46, sjt_functionParam102, &sjt_capture39); #line 148 sjt_capture38 = (sjt_capture39 == ']'); } else { #line 148 "lib/sj-lib-json/parse.sj" sjt_capture38 = false; } if (sjt_capture38) { #line 149 "lib/sj-lib-json/parse.sj" index = index + 1; #line 150 shouldcontinue = false; } if (index < s->count) { #line 124 "lib/sj-lib-json/parse.sj" sjt_while9 = shouldcontinue; } else { #line 124 "lib/sj-lib-json/parse.sj" sjt_while9 = false; } if (value._refCount == 1) { sjf_json_value_destroy(&value); } ; if (valueresult._refCount == 1) { sjf_tuple2_i32_value_destroy(&valueresult); } ; } #line 123 sjt_call4._refCount = 1; #line 153 sjt_call4.item1 = index; #line 153 sjt_call4.item2._refCount = 1; #line 3 "lib/sj-lib-json/value.sj" sjt_call4.item2.s._refCount = -1; #line 153 "lib/sj-lib-json/parse.sj" sjs_array_value* copyoption22 = &(&l)->arr; if (copyoption22 != 0) { sjt_call4.item2.a._refCount = 1; #line 153 "lib/sj-lib-json/parse.sj" sjf_array_value_copy(&sjt_call4.item2.a, copyoption22); } else { sjt_call4.item2.a._refCount = -1; } #line 5 "lib/sj-lib-json/value.sj" sjt_call4.item2.h._refCount = -1; #line 5 sjf_json_value(&sjt_call4.item2); #line 5 sjf_tuple2_i32_value(&sjt_call4); #line 5 (*_return) = (sjs_tuple2_i32_value*)malloc(sizeof(sjs_tuple2_i32_value)); #line 5 (*_return)->_refCount = 1; #line 153 "lib/sj-lib-json/parse.sj" sjf_tuple2_i32_value_copy((*_return), &sjt_call4); if (l._refCount == 1) { sjf_list_value_destroy(&l); } ; if (sjt_call4._refCount == 1) { sjf_tuple2_i32_value_destroy(&sjt_call4); } ; } else { if (underscore2 == '\"') { sjs_tuple2_i32_string result = { -1 }; sjs_tuple2_i32_value sjt_call5 = { -1 }; sjs_string* sjt_functionParam103 = 0; int32_t sjt_functionParam104; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam103 = s; #line 157 sjt_functionParam104 = index; #line 157 sjf_json_parse_string(sjt_functionParam103, sjt_functionParam104, &result); #line 157 sjt_call5._refCount = 1; #line 158 sjt_call5.item1 = (&result)->item1; #line 158 sjt_call5.item2._refCount = 1; #line 158 sjs_string* copyoption23 = &(&result)->item2; if (copyoption23 != 0) { sjt_call5.item2.s._refCount = 1; #line 158 "lib/sj-lib-json/parse.sj" sjf_string_copy(&sjt_call5.item2.s, copyoption23); } else { sjt_call5.item2.s._refCount = -1; } #line 4 "lib/sj-lib-json/value.sj" sjt_call5.item2.a._refCount = -1; #line 5 sjt_call5.item2.h._refCount = -1; #line 5 sjf_json_value(&sjt_call5.item2); #line 5 sjf_tuple2_i32_value(&sjt_call5); #line 5 (*_return) = (sjs_tuple2_i32_value*)malloc(sizeof(sjs_tuple2_i32_value)); #line 5 (*_return)->_refCount = 1; #line 158 "lib/sj-lib-json/parse.sj" sjf_tuple2_i32_value_copy((*_return), &sjt_call5); if (result._refCount == 1) { sjf_tuple2_i32_string_destroy(&result); } ; if (sjt_call5._refCount == 1) { sjf_tuple2_i32_value_destroy(&sjt_call5); } ; } else { sjs_tuple2_i32_string result = { -1 }; sjs_tuple2_i32_value sjt_call6 = { -1 }; sjs_string* sjt_functionParam105 = 0; int32_t sjt_functionParam106; #line 56 "lib/sj-lib-json/parse.sj" sjt_functionParam105 = s; #line 162 sjt_functionParam106 = index; #line 162 sjf_json_parse_number(sjt_functionParam105, sjt_functionParam106, &result); #line 162 sjt_call6._refCount = 1; #line 163 sjt_call6.item1 = (&result)->item1; #line 163 sjt_call6.item2._refCount = 1; #line 163 sjs_string* copyoption24 = &(&result)->item2; if (copyoption24 != 0) { sjt_call6.item2.s._refCount = 1; #line 163 "lib/sj-lib-json/parse.sj" sjf_string_copy(&sjt_call6.item2.s, copyoption24); } else { sjt_call6.item2.s._refCount = -1; } #line 4 "lib/sj-lib-json/value.sj" sjt_call6.item2.a._refCount = -1; #line 5 sjt_call6.item2.h._refCount = -1; #line 5 sjf_json_value(&sjt_call6.item2); #line 5 sjf_tuple2_i32_value(&sjt_call6); #line 5 (*_return) = (sjs_tuple2_i32_value*)malloc(sizeof(sjs_tuple2_i32_value)); #line 5 (*_return)->_refCount = 1; #line 163 "lib/sj-lib-json/parse.sj" sjf_tuple2_i32_value_copy((*_return), &sjt_call6); if (result._refCount == 1) { sjf_tuple2_i32_string_destroy(&result); } ; if (sjt_call6._refCount == 1) { sjf_tuple2_i32_value_destroy(&sjt_call6); } ; } } } } void sjf_json_parse_whitespace(sjs_string* s, int32_t startindex, int32_t* _return) { int32_t index; bool ismatched; bool sjt_while1; #line 2 "lib/sj-lib-json/parse.sj" index = startindex; #line 4 ismatched = true; if (index < s->count) { #line 5 "lib/sj-lib-json/parse.sj" sjt_while1 = ismatched; } else { #line 5 "lib/sj-lib-json/parse.sj" sjt_while1 = false; } while (sjt_while1) { char ch; int32_t sjt_functionParam5; sjs_string* sjt_parent5 = 0; #line 2 "lib/sj-lib-json/parse.sj" sjt_parent5 = s; #line 6 sjt_functionParam5 = index; #line 6 sjf_string_getat(sjt_parent5, sjt_functionParam5, &ch); if ((ch == '\r') || ((ch == '\n') || ((ch == '\t') || (ch == (' '))))) { #line 8 "lib/sj-lib-json/parse.sj" index = index + 1; } else { #line 10 "lib/sj-lib-json/parse.sj" ismatched = false; } if (index < s->count) { #line 5 "lib/sj-lib-json/parse.sj" sjt_while1 = ismatched; } else { #line 5 "lib/sj-lib-json/parse.sj" sjt_while1 = false; } } #line 2 (*_return) = index; } void sjf_json_value(sjs_json_value* _this) { } void sjf_json_value_copy(sjs_json_value* _this, sjs_json_value* _from) { #line 2 "lib/sj-lib-json/value.sj" sjs_string* copyoption14 = (_from->s._refCount != -1 ? &_from->s : 0); if (copyoption14 != 0) { _this->s._refCount = 1; #line 2 "lib/sj-lib-json/value.sj" sjf_string_copy(&_this->s, copyoption14); } else { _this->s._refCount = -1; } #line 2 sjs_array_value* copyoption15 = (_from->a._refCount != -1 ? &_from->a : 0); if (copyoption15 != 0) { _this->a._refCount = 1; #line 2 "lib/sj-lib-json/value.sj" sjf_array_value_copy(&_this->a, copyoption15); } else { _this->a._refCount = -1; } #line 2 sjs_hash_string_value* copyoption16 = (_from->h._refCount != -1 ? &_from->h : 0); if (copyoption16 != 0) { _this->h._refCount = 1; #line 2 "lib/sj-lib-json/value.sj" sjf_hash_string_value_copy(&_this->h, copyoption16); } else { _this->h._refCount = -1; } } void sjf_json_value_destroy(sjs_json_value* _this) { if (_this->s._refCount == 1) { sjf_string_destroy(&_this->s); } ; if (_this->a._refCount == 1) { sjf_array_value_destroy(&_this->a); } ; if (_this->h._refCount == 1) { sjf_hash_string_value_destroy(&_this->h); } ; } void sjf_json_value_heap(sjs_json_value* _this) { } void sjf_json_value_render(sjs_json_value* _parent, sjs_string* _return) { if (((_parent->s._refCount != -1 ? &_parent->s : 0) != 0)) { sjs_string* ifValue2 = 0; #line 40 "lib/sj-lib-json/value.sj" ifValue2 = (_parent->s._refCount != -1 ? &_parent->s : 0); #line 40 _return->_refCount = 1; #line 41 sjf_string_copy(_return, ifValue2); } else { if (((_parent->a._refCount != -1 ? &_parent->a : 0) != 0)) { sjs_array_value* ifValue3 = 0; sjs_string sjt_call10 = { -1 }; sjs_array_string sjt_call15 = { -1 }; sjs_lambda3 sjt_call18 = { -1 }; sjs_string sjt_call19 = { -1 }; sjs_string sjt_call20 = { -1 }; sjs_string sjt_call8 = { -1 }; sjs_string sjt_call9 = { -1 }; sjs_string* sjt_functionParam131 = 0; cb_value_string sjt_functionParam142; sjs_string* sjt_functionParam143 = 0; sjs_string* sjt_functionParam144 = 0; sjs_string* sjt_parent63 = 0; sjs_string* sjt_parent64 = 0; sjs_array_string* sjt_parent71 = 0; sjs_array_value* sjt_parent72 = 0; #line 43 "lib/sj-lib-json/value.sj" ifValue3 = (_parent->a._refCount != -1 ? &_parent->a : 0); #line 43 sjt_call9._refCount = 1; #line 44 sjt_call9.offset = 0; #line 44 sjt_call9.count = 2; #line 44 sjt_call9.data._refCount = 1; #line 44 sjt_call9.data.v = &sjg_string10; #line 44 sjf_array_char(&sjt_call9.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call9._isnullterminated = false; #line 16 sjf_string(&sjt_call9); #line 44 "lib/sj-lib-json/value.sj" sjt_parent64 = &sjt_call9; #line 114 "lib/sj-lib-common/array.sj" sjt_parent72 = ifValue3; #line 44 "lib/sj-lib-json/value.sj" sjs_lambda3* lambainit4; #line 44 sjt_call18._refCount = 1; #line 44 sjf_lambda3(&sjt_call18); #line 44 lambainit4 = &sjt_call18; #line 44 sjt_functionParam142._parent = (sjs_object*)lambainit4; #line 44 sjt_functionParam142._cb = (void(*)(sjs_object*,sjs_json_value*, sjs_string*))sjf_lambda3_invoke; #line 44 sjf_array_value_map_string(sjt_parent72, sjt_functionParam142, &sjt_call15); #line 44 sjt_parent71 = &sjt_call15; #line 44 sjt_call19._refCount = 1; #line 294 "lib/sj-lib-common/array.sj" sjt_call19.offset = 0; #line 294 sjt_call19.count = 2; #line 294 sjt_call19.data._refCount = 1; #line 294 sjt_call19.data.v = &sjg_string8; #line 294 sjf_array_char(&sjt_call19.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call19._isnullterminated = false; #line 16 sjf_string(&sjt_call19); #line 294 "lib/sj-lib-common/array.sj" sjt_functionParam143 = &sjt_call19; #line 294 sjf_array_string_asstring(sjt_parent71, sjt_functionParam143, &sjt_call10); #line 44 "lib/sj-lib-json/value.sj" sjt_functionParam131 = &sjt_call10; #line 44 sjf_string_add(sjt_parent64, sjt_functionParam131, &sjt_call8); #line 44 sjt_parent63 = &sjt_call8; #line 44 sjt_call20._refCount = 1; #line 44 sjt_call20.offset = 0; #line 44 sjt_call20.count = 2; #line 44 sjt_call20.data._refCount = 1; #line 44 sjt_call20.data.v = &sjg_string11; #line 44 sjf_array_char(&sjt_call20.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call20._isnullterminated = false; #line 16 sjf_string(&sjt_call20); #line 44 "lib/sj-lib-json/value.sj" sjt_functionParam144 = &sjt_call20; #line 44 sjf_string_add(sjt_parent63, sjt_functionParam144, _return); if (sjt_call10._refCount == 1) { sjf_string_destroy(&sjt_call10); } ; if (sjt_call15._refCount == 1) { sjf_array_string_destroy(&sjt_call15); } ; if (sjt_call18._refCount == 1) { sjf_lambda3_destroy(&sjt_call18); } ; if (sjt_call19._refCount == 1) { sjf_string_destroy(&sjt_call19); } ; if (sjt_call20._refCount == 1) { sjf_string_destroy(&sjt_call20); } ; if (sjt_call8._refCount == 1) { sjf_string_destroy(&sjt_call8); } ; if (sjt_call9._refCount == 1) { sjf_string_destroy(&sjt_call9); } ; } else { if (((_parent->h._refCount != -1 ? &_parent->h : 0) != 0)) { sjs_hash_string_value* ifValue4 = 0; sjs_string sjt_call21 = { -1 }; sjs_string sjt_call22 = { -1 }; sjs_string sjt_call23 = { -1 }; sjs_array_string sjt_call24 = { -1 }; sjs_lambda2 sjt_call28 = { -1 }; sjs_string sjt_call39 = { -1 }; sjs_string sjt_call40 = { -1 }; sjs_string* sjt_functionParam145 = 0; cb_string_value_string sjt_functionParam158; sjs_string* sjt_functionParam165 = 0; sjs_string* sjt_functionParam166 = 0; sjs_string* sjt_parent75 = 0; sjs_string* sjt_parent76 = 0; sjs_array_string* sjt_parent77 = 0; sjs_hash_string_value* sjt_parent86 = 0; #line 46 "lib/sj-lib-json/value.sj" ifValue4 = (_parent->h._refCount != -1 ? &_parent->h : 0); #line 46 sjt_call22._refCount = 1; #line 47 sjt_call22.offset = 0; #line 47 sjt_call22.count = 2; #line 47 sjt_call22.data._refCount = 1; #line 47 sjt_call22.data.v = &sjg_string5; #line 47 sjf_array_char(&sjt_call22.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call22._isnullterminated = false; #line 16 sjf_string(&sjt_call22); #line 47 "lib/sj-lib-json/value.sj" sjt_parent76 = &sjt_call22; #line 170 "lib/sj-lib-common/hash.sj" sjt_parent86 = ifValue4; #line 47 "lib/sj-lib-json/value.sj" sjs_lambda2* lambainit3; #line 47 sjt_call28._refCount = 1; #line 47 sjf_lambda2(&sjt_call28); #line 47 lambainit3 = &sjt_call28; #line 47 sjt_functionParam158._parent = (sjs_object*)lambainit3; #line 47 sjt_functionParam158._cb = (void(*)(sjs_object*,sjs_string*,sjs_json_value*, sjs_string*))sjf_lambda2_invoke; #line 47 sjf_hash_string_value_asarray_string(sjt_parent86, sjt_functionParam158, &sjt_call24); #line 47 sjt_parent77 = &sjt_call24; #line 47 sjt_call39._refCount = 1; #line 294 "lib/sj-lib-common/array.sj" sjt_call39.offset = 0; #line 294 sjt_call39.count = 2; #line 294 sjt_call39.data._refCount = 1; #line 294 sjt_call39.data.v = &sjg_string8; #line 294 sjf_array_char(&sjt_call39.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call39._isnullterminated = false; #line 16 sjf_string(&sjt_call39); #line 294 "lib/sj-lib-common/array.sj" sjt_functionParam165 = &sjt_call39; #line 294 sjf_array_string_asstring(sjt_parent77, sjt_functionParam165, &sjt_call23); #line 47 "lib/sj-lib-json/value.sj" sjt_functionParam145 = &sjt_call23; #line 47 sjf_string_add(sjt_parent76, sjt_functionParam145, &sjt_call21); #line 47 sjt_parent75 = &sjt_call21; #line 47 sjt_call40._refCount = 1; #line 49 sjt_call40.offset = 0; #line 49 sjt_call40.count = 2; #line 49 sjt_call40.data._refCount = 1; #line 49 sjt_call40.data.v = &sjg_string9; #line 49 sjf_array_char(&sjt_call40.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call40._isnullterminated = false; #line 16 sjf_string(&sjt_call40); #line 49 "lib/sj-lib-json/value.sj" sjt_functionParam166 = &sjt_call40; #line 49 sjf_string_add(sjt_parent75, sjt_functionParam166, _return); if (sjt_call21._refCount == 1) { sjf_string_destroy(&sjt_call21); } ; if (sjt_call22._refCount == 1) { sjf_string_destroy(&sjt_call22); } ; if (sjt_call23._refCount == 1) { sjf_string_destroy(&sjt_call23); } ; if (sjt_call24._refCount == 1) { sjf_array_string_destroy(&sjt_call24); } ; if (sjt_call28._refCount == 1) { sjf_lambda2_destroy(&sjt_call28); } ; if (sjt_call39._refCount == 1) { sjf_string_destroy(&sjt_call39); } ; if (sjt_call40._refCount == 1) { sjf_string_destroy(&sjt_call40); } ; } else { _return->_refCount = 1; #line 51 "lib/sj-lib-json/value.sj" _return->offset = 0; #line 51 _return->count = 0; #line 51 _return->data._refCount = 1; #line 51 _return->data.v = &sjg_string2; #line 51 sjf_array_char(&_return->data); #line 16 "lib/sj-lib-common/string.sj" _return->_isnullterminated = false; #line 16 sjf_string(_return); } } } } void sjf_json_value_render_heap(sjs_json_value* _parent, sjs_string** _return) { if (((_parent->s._refCount != -1 ? &_parent->s : 0) != 0)) { sjs_string* ifValue5 = 0; #line 40 "lib/sj-lib-json/value.sj" ifValue5 = (_parent->s._refCount != -1 ? &_parent->s : 0); #line 40 (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); #line 40 (*_return)->_refCount = 1; #line 41 sjf_string_copy((*_return), ifValue5); } else { if (((_parent->a._refCount != -1 ? &_parent->a : 0) != 0)) { sjs_array_value* ifValue6 = 0; sjs_string sjt_call41 = { -1 }; sjs_string sjt_call42 = { -1 }; sjs_string sjt_call43 = { -1 }; sjs_array_string sjt_call44 = { -1 }; sjs_lambda3 sjt_call45 = { -1 }; sjs_string sjt_call46 = { -1 }; sjs_string sjt_call47 = { -1 }; sjs_string* sjt_functionParam167 = 0; cb_value_string sjt_functionParam168; sjs_string* sjt_functionParam169 = 0; sjs_string* sjt_functionParam170 = 0; sjs_string* sjt_parent95 = 0; sjs_string* sjt_parent96 = 0; sjs_array_string* sjt_parent97 = 0; sjs_array_value* sjt_parent98 = 0; #line 43 "lib/sj-lib-json/value.sj" ifValue6 = (_parent->a._refCount != -1 ? &_parent->a : 0); #line 43 sjt_call42._refCount = 1; #line 44 sjt_call42.offset = 0; #line 44 sjt_call42.count = 2; #line 44 sjt_call42.data._refCount = 1; #line 44 sjt_call42.data.v = &sjg_string10; #line 44 sjf_array_char(&sjt_call42.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call42._isnullterminated = false; #line 16 sjf_string(&sjt_call42); #line 44 "lib/sj-lib-json/value.sj" sjt_parent96 = &sjt_call42; #line 114 "lib/sj-lib-common/array.sj" sjt_parent98 = ifValue6; #line 44 "lib/sj-lib-json/value.sj" sjs_lambda3* lambainit6; #line 44 sjt_call45._refCount = 1; #line 44 sjf_lambda3(&sjt_call45); #line 44 lambainit6 = &sjt_call45; #line 44 sjt_functionParam168._parent = (sjs_object*)lambainit6; #line 44 sjt_functionParam168._cb = (void(*)(sjs_object*,sjs_json_value*, sjs_string*))sjf_lambda3_invoke; #line 44 sjf_array_value_map_string(sjt_parent98, sjt_functionParam168, &sjt_call44); #line 44 sjt_parent97 = &sjt_call44; #line 44 sjt_call46._refCount = 1; #line 294 "lib/sj-lib-common/array.sj" sjt_call46.offset = 0; #line 294 sjt_call46.count = 2; #line 294 sjt_call46.data._refCount = 1; #line 294 sjt_call46.data.v = &sjg_string8; #line 294 sjf_array_char(&sjt_call46.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call46._isnullterminated = false; #line 16 sjf_string(&sjt_call46); #line 294 "lib/sj-lib-common/array.sj" sjt_functionParam169 = &sjt_call46; #line 294 sjf_array_string_asstring(sjt_parent97, sjt_functionParam169, &sjt_call43); #line 44 "lib/sj-lib-json/value.sj" sjt_functionParam167 = &sjt_call43; #line 44 sjf_string_add(sjt_parent96, sjt_functionParam167, &sjt_call41); #line 44 sjt_parent95 = &sjt_call41; #line 44 sjt_call47._refCount = 1; #line 44 sjt_call47.offset = 0; #line 44 sjt_call47.count = 2; #line 44 sjt_call47.data._refCount = 1; #line 44 sjt_call47.data.v = &sjg_string11; #line 44 sjf_array_char(&sjt_call47.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call47._isnullterminated = false; #line 16 sjf_string(&sjt_call47); #line 44 "lib/sj-lib-json/value.sj" sjt_functionParam170 = &sjt_call47; #line 44 sjf_string_add_heap(sjt_parent95, sjt_functionParam170, _return); if (sjt_call41._refCount == 1) { sjf_string_destroy(&sjt_call41); } ; if (sjt_call42._refCount == 1) { sjf_string_destroy(&sjt_call42); } ; if (sjt_call43._refCount == 1) { sjf_string_destroy(&sjt_call43); } ; if (sjt_call44._refCount == 1) { sjf_array_string_destroy(&sjt_call44); } ; if (sjt_call45._refCount == 1) { sjf_lambda3_destroy(&sjt_call45); } ; if (sjt_call46._refCount == 1) { sjf_string_destroy(&sjt_call46); } ; if (sjt_call47._refCount == 1) { sjf_string_destroy(&sjt_call47); } ; } else { if (((_parent->h._refCount != -1 ? &_parent->h : 0) != 0)) { sjs_hash_string_value* ifValue7 = 0; sjs_string sjt_call48 = { -1 }; sjs_string sjt_call49 = { -1 }; sjs_string sjt_call50 = { -1 }; sjs_array_string sjt_call51 = { -1 }; sjs_lambda2 sjt_call52 = { -1 }; sjs_string sjt_call53 = { -1 }; sjs_string sjt_call54 = { -1 }; sjs_string* sjt_functionParam171 = 0; cb_string_value_string sjt_functionParam172; sjs_string* sjt_functionParam173 = 0; sjs_string* sjt_functionParam174 = 0; sjs_string* sjt_parent100 = 0; sjs_array_string* sjt_parent101 = 0; sjs_hash_string_value* sjt_parent102 = 0; sjs_string* sjt_parent99 = 0; #line 46 "lib/sj-lib-json/value.sj" ifValue7 = (_parent->h._refCount != -1 ? &_parent->h : 0); #line 46 sjt_call49._refCount = 1; #line 47 sjt_call49.offset = 0; #line 47 sjt_call49.count = 2; #line 47 sjt_call49.data._refCount = 1; #line 47 sjt_call49.data.v = &sjg_string5; #line 47 sjf_array_char(&sjt_call49.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call49._isnullterminated = false; #line 16 sjf_string(&sjt_call49); #line 47 "lib/sj-lib-json/value.sj" sjt_parent100 = &sjt_call49; #line 170 "lib/sj-lib-common/hash.sj" sjt_parent102 = ifValue7; #line 47 "lib/sj-lib-json/value.sj" sjs_lambda2* lambainit5; #line 47 sjt_call52._refCount = 1; #line 47 sjf_lambda2(&sjt_call52); #line 47 lambainit5 = &sjt_call52; #line 47 sjt_functionParam172._parent = (sjs_object*)lambainit5; #line 47 sjt_functionParam172._cb = (void(*)(sjs_object*,sjs_string*,sjs_json_value*, sjs_string*))sjf_lambda2_invoke; #line 47 sjf_hash_string_value_asarray_string(sjt_parent102, sjt_functionParam172, &sjt_call51); #line 47 sjt_parent101 = &sjt_call51; #line 47 sjt_call53._refCount = 1; #line 294 "lib/sj-lib-common/array.sj" sjt_call53.offset = 0; #line 294 sjt_call53.count = 2; #line 294 sjt_call53.data._refCount = 1; #line 294 sjt_call53.data.v = &sjg_string8; #line 294 sjf_array_char(&sjt_call53.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call53._isnullterminated = false; #line 16 sjf_string(&sjt_call53); #line 294 "lib/sj-lib-common/array.sj" sjt_functionParam173 = &sjt_call53; #line 294 sjf_array_string_asstring(sjt_parent101, sjt_functionParam173, &sjt_call50); #line 47 "lib/sj-lib-json/value.sj" sjt_functionParam171 = &sjt_call50; #line 47 sjf_string_add(sjt_parent100, sjt_functionParam171, &sjt_call48); #line 47 sjt_parent99 = &sjt_call48; #line 47 sjt_call54._refCount = 1; #line 49 sjt_call54.offset = 0; #line 49 sjt_call54.count = 2; #line 49 sjt_call54.data._refCount = 1; #line 49 sjt_call54.data.v = &sjg_string9; #line 49 sjf_array_char(&sjt_call54.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call54._isnullterminated = false; #line 16 sjf_string(&sjt_call54); #line 49 "lib/sj-lib-json/value.sj" sjt_functionParam174 = &sjt_call54; #line 49 sjf_string_add_heap(sjt_parent99, sjt_functionParam174, _return); if (sjt_call48._refCount == 1) { sjf_string_destroy(&sjt_call48); } ; if (sjt_call49._refCount == 1) { sjf_string_destroy(&sjt_call49); } ; if (sjt_call50._refCount == 1) { sjf_string_destroy(&sjt_call50); } ; if (sjt_call51._refCount == 1) { sjf_array_string_destroy(&sjt_call51); } ; if (sjt_call52._refCount == 1) { sjf_lambda2_destroy(&sjt_call52); } ; if (sjt_call53._refCount == 1) { sjf_string_destroy(&sjt_call53); } ; if (sjt_call54._refCount == 1) { sjf_string_destroy(&sjt_call54); } ; } else { (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); (*_return)->_refCount = 1; #line 51 "lib/sj-lib-json/value.sj" (*_return)->offset = 0; #line 51 (*_return)->count = 0; #line 51 (*_return)->data._refCount = 1; #line 51 (*_return)->data.v = &sjg_string2; #line 51 sjf_array_char(&(*_return)->data); #line 16 "lib/sj-lib-common/string.sj" (*_return)->_isnullterminated = false; #line 16 sjf_string_heap((*_return)); } } } } void sjf_lambda1(sjs_lambda1* _this) { } void sjf_lambda1_copy(sjs_lambda1* _this, sjs_lambda1* _from) { #line 172 "lib/sj-lib-common/hash.sj" _this->lambdaparam1 = _from->lambdaparam1; #line 172 _this->lambdaparam2 = _from->lambdaparam2; #line 172 _this->lambdaparam3 = _from->lambdaparam3; } void sjf_lambda1_destroy(sjs_lambda1* _this) { } void sjf_lambda1_heap(sjs_lambda1* _this) { } void sjf_lambda1_invoke(sjs_lambda1* _parent, sjs_string* _1, sjs_json_value* _2) { sjs_string sjt_call26 = { -1 }; sjs_string* sjt_functionParam154 = 0; sjs_string* sjt_functionParam155 = 0; sjs_json_value* sjt_functionParam156 = 0; sjs_list_string* sjt_parent85 = 0; #line 44 "lib/sj-lib-common/list.sj" sjt_parent85 = _parent->lambdaparam1; #line 172 "lib/sj-lib-common/hash.sj" sjt_functionParam155 = _1; #line 172 sjt_functionParam156 = _2; #line 172 _parent->lambdaparam2._cb(_parent->lambdaparam2._parent, sjt_functionParam155, sjt_functionParam156, &sjt_call26); #line 173 sjt_functionParam154 = &sjt_call26; #line 173 sjf_list_string_add(sjt_parent85, sjt_functionParam154); if (sjt_call26._refCount == 1) { sjf_string_destroy(&sjt_call26); } ; } void sjf_lambda2(sjs_lambda2* _this) { } void sjf_lambda2_copy(sjs_lambda2* _this, sjs_lambda2* _from) { } void sjf_lambda2_destroy(sjs_lambda2* _this) { } void sjf_lambda2_heap(sjs_lambda2* _this) { } void sjf_lambda2_invoke(sjs_lambda2* _parent, sjs_string* _1, sjs_json_value* _2, sjs_string* _return) { sjs_string sjt_call29 = { -1 }; sjs_string sjt_call30 = { -1 }; sjs_string sjt_call31 = { -1 }; sjs_string sjt_call32 = { -1 }; sjs_string sjt_call33 = { -1 }; sjs_string* sjt_functionParam159 = 0; sjs_string* sjt_functionParam160 = 0; sjs_string* sjt_functionParam161 = 0; sjs_string* sjt_parent87 = 0; sjs_string* sjt_parent88 = 0; sjs_string* sjt_parent89 = 0; sjs_json_value* sjt_parent90 = 0; sjt_call31._refCount = 1; #line 48 "lib/sj-lib-json/value.sj" sjt_call31.offset = 0; #line 48 sjt_call31.count = 1; #line 48 sjt_call31.data._refCount = 1; #line 48 sjt_call31.data.v = &sjg_string6; #line 48 sjf_array_char(&sjt_call31.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call31._isnullterminated = false; #line 16 sjf_string(&sjt_call31); #line 48 "lib/sj-lib-json/value.sj" sjt_parent89 = &sjt_call31; #line 47 sjt_functionParam159 = _1; #line 47 sjf_string_add(sjt_parent89, sjt_functionParam159, &sjt_call30); #line 48 sjt_parent88 = &sjt_call30; #line 48 sjt_call32._refCount = 1; #line 48 sjt_call32.offset = 0; #line 48 sjt_call32.count = 4; #line 48 sjt_call32.data._refCount = 1; #line 48 sjt_call32.data.v = &sjg_string7; #line 48 sjf_array_char(&sjt_call32.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call32._isnullterminated = false; #line 16 sjf_string(&sjt_call32); #line 48 "lib/sj-lib-json/value.sj" sjt_functionParam160 = &sjt_call32; #line 48 sjf_string_add(sjt_parent88, sjt_functionParam160, &sjt_call29); #line 48 sjt_parent87 = &sjt_call29; #line 47 sjt_parent90 = _2; #line 47 sjf_json_value_render(sjt_parent90, &sjt_call33); #line 48 sjt_functionParam161 = &sjt_call33; #line 48 sjf_string_add(sjt_parent87, sjt_functionParam161, _return); if (sjt_call29._refCount == 1) { sjf_string_destroy(&sjt_call29); } ; if (sjt_call30._refCount == 1) { sjf_string_destroy(&sjt_call30); } ; if (sjt_call31._refCount == 1) { sjf_string_destroy(&sjt_call31); } ; if (sjt_call32._refCount == 1) { sjf_string_destroy(&sjt_call32); } ; if (sjt_call33._refCount == 1) { sjf_string_destroy(&sjt_call33); } ; } void sjf_lambda2_invoke_heap(sjs_lambda2* _parent, sjs_string* _1, sjs_json_value* _2, sjs_string** _return) { sjs_string sjt_call34 = { -1 }; sjs_string sjt_call35 = { -1 }; sjs_string sjt_call36 = { -1 }; sjs_string sjt_call37 = { -1 }; sjs_string sjt_call38 = { -1 }; sjs_string* sjt_functionParam162 = 0; sjs_string* sjt_functionParam163 = 0; sjs_string* sjt_functionParam164 = 0; sjs_string* sjt_parent91 = 0; sjs_string* sjt_parent92 = 0; sjs_string* sjt_parent93 = 0; sjs_json_value* sjt_parent94 = 0; sjt_call36._refCount = 1; #line 48 "lib/sj-lib-json/value.sj" sjt_call36.offset = 0; #line 48 sjt_call36.count = 1; #line 48 sjt_call36.data._refCount = 1; #line 48 sjt_call36.data.v = &sjg_string6; #line 48 sjf_array_char(&sjt_call36.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call36._isnullterminated = false; #line 16 sjf_string(&sjt_call36); #line 48 "lib/sj-lib-json/value.sj" sjt_parent93 = &sjt_call36; #line 47 sjt_functionParam162 = _1; #line 47 sjf_string_add(sjt_parent93, sjt_functionParam162, &sjt_call35); #line 48 sjt_parent92 = &sjt_call35; #line 48 sjt_call37._refCount = 1; #line 48 sjt_call37.offset = 0; #line 48 sjt_call37.count = 4; #line 48 sjt_call37.data._refCount = 1; #line 48 sjt_call37.data.v = &sjg_string7; #line 48 sjf_array_char(&sjt_call37.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call37._isnullterminated = false; #line 16 sjf_string(&sjt_call37); #line 48 "lib/sj-lib-json/value.sj" sjt_functionParam163 = &sjt_call37; #line 48 sjf_string_add(sjt_parent92, sjt_functionParam163, &sjt_call34); #line 48 sjt_parent91 = &sjt_call34; #line 47 sjt_parent94 = _2; #line 47 sjf_json_value_render(sjt_parent94, &sjt_call38); #line 48 sjt_functionParam164 = &sjt_call38; #line 48 sjf_string_add_heap(sjt_parent91, sjt_functionParam164, _return); if (sjt_call34._refCount == 1) { sjf_string_destroy(&sjt_call34); } ; if (sjt_call35._refCount == 1) { sjf_string_destroy(&sjt_call35); } ; if (sjt_call36._refCount == 1) { sjf_string_destroy(&sjt_call36); } ; if (sjt_call37._refCount == 1) { sjf_string_destroy(&sjt_call37); } ; if (sjt_call38._refCount == 1) { sjf_string_destroy(&sjt_call38); } ; } void sjf_lambda3(sjs_lambda3* _this) { } void sjf_lambda3_copy(sjs_lambda3* _this, sjs_lambda3* _from) { } void sjf_lambda3_destroy(sjs_lambda3* _this) { } void sjf_lambda3_heap(sjs_lambda3* _this) { } void sjf_lambda3_invoke(sjs_lambda3* _parent, sjs_json_value* _1, sjs_string* _return) { sjs_json_value* sjt_parent73 = 0; #line 44 "lib/sj-lib-json/value.sj" sjt_parent73 = _1; #line 44 sjf_json_value_render(sjt_parent73, _return); } void sjf_lambda3_invoke_heap(sjs_lambda3* _parent, sjs_json_value* _1, sjs_string** _return) { sjs_json_value* sjt_parent74 = 0; #line 44 "lib/sj-lib-json/value.sj" sjt_parent74 = _1; #line 44 sjf_json_value_render_heap(sjt_parent74, _return); } void sjf_list_string(sjs_list_string* _this) { } void sjf_list_string_add(sjs_list_string* _parent, sjs_string* item) { int32_t sjt_capture46; int32_t sjt_capture47; sjs_array_string sjt_funcold21 = { -1 }; int32_t sjt_functionParam152; sjs_string* sjt_functionParam153 = 0; sjs_array_string* sjt_parent78 = 0; sjs_array_string* sjt_parent79 = 0; sjs_array_string* sjt_parent83 = 0; sjs_array_string* sjt_parent84 = 0; #line 29 "lib/sj-lib-common/array.sj" sjt_parent78 = &_parent->arr; #line 29 sjf_array_string_getcount(sjt_parent78, &sjt_capture46); #line 35 sjt_parent79 = &_parent->arr; #line 35 sjf_array_string_gettotalcount(sjt_parent79, &sjt_capture47); if (sjt_capture46 == sjt_capture47) { int32_t sjt_capture48; int32_t sjt_functionParam147; int32_t sjt_functionParam148; int32_t sjt_functionParam149; int32_t sjt_functionParam150; int32_t sjt_functionParam151; sjs_array_string* sjt_parent80 = 0; sjs_array_string* sjt_parent81 = 0; sjs_array_string* sjt_parent82 = 0; #line 168 "lib/sj-lib-common/array.sj" sjt_parent80 = &_parent->arr; #line 46 "lib/sj-lib-common/list.sj" sjt_functionParam147 = 0; #line 29 "lib/sj-lib-common/array.sj" sjt_parent81 = &_parent->arr; #line 29 sjf_array_string_getcount(sjt_parent81, &sjt_functionParam148); #line 46 "lib/sj-lib-common/list.sj" sjt_functionParam150 = 10; #line 35 "lib/sj-lib-common/array.sj" sjt_parent82 = &_parent->arr; #line 35 sjf_array_string_gettotalcount(sjt_parent82, &sjt_capture48); #line 46 "lib/sj-lib-common/list.sj" sjt_functionParam151 = sjt_capture48 * 2; #line 46 sjf_i32_max(sjt_functionParam150, sjt_functionParam151, &sjt_functionParam149); #line 46 sjf_array_string_clone(sjt_parent80, sjt_functionParam147, sjt_functionParam148, sjt_functionParam149, &sjt_funcold21); #line 46 if (_parent->arr._refCount == 1) { sjf_array_string_destroy(&_parent->arr); } ; #line 168 "lib/sj-lib-common/array.sj" sjf_array_string_copy(&_parent->arr, &sjt_funcold21); } #line 52 sjt_parent83 = &_parent->arr; #line 29 sjt_parent84 = &_parent->arr; #line 29 sjf_array_string_getcount(sjt_parent84, &sjt_functionParam152); #line 44 "lib/sj-lib-common/list.sj" sjt_functionParam153 = item; #line 44 sjf_array_string_initat(sjt_parent83, sjt_functionParam152, sjt_functionParam153); if (sjt_funcold21._refCount == 1) { sjf_array_string_destroy(&sjt_funcold21); } ; } void sjf_list_string_copy(sjs_list_string* _this, sjs_list_string* _from) { _this->arr._refCount = 1; #line 1 "lib/sj-lib-common/list.sj" sjf_array_string_copy(&_this->arr, &_from->arr); } void sjf_list_string_destroy(sjs_list_string* _this) { if (_this->arr._refCount == 1) { sjf_array_string_destroy(&_this->arr); } ; } void sjf_list_string_heap(sjs_list_string* _this) { } void sjf_list_value(sjs_list_value* _this) { } void sjf_list_value_add(sjs_list_value* _parent, sjs_json_value* item) { int32_t sjt_capture18; int32_t sjt_capture19; sjs_array_value sjt_funcold8 = { -1 }; int32_t sjt_functionParam51; sjs_json_value* sjt_functionParam52 = 0; sjs_array_value* sjt_parent22 = 0; sjs_array_value* sjt_parent23 = 0; sjs_array_value* sjt_parent27 = 0; sjs_array_value* sjt_parent28 = 0; #line 29 "lib/sj-lib-common/array.sj" sjt_parent22 = &_parent->arr; #line 29 sjf_array_value_getcount(sjt_parent22, &sjt_capture18); #line 35 sjt_parent23 = &_parent->arr; #line 35 sjf_array_value_gettotalcount(sjt_parent23, &sjt_capture19); if (sjt_capture18 == sjt_capture19) { int32_t sjt_capture20; int32_t sjt_functionParam46; int32_t sjt_functionParam47; int32_t sjt_functionParam48; int32_t sjt_functionParam49; int32_t sjt_functionParam50; sjs_array_value* sjt_parent24 = 0; sjs_array_value* sjt_parent25 = 0; sjs_array_value* sjt_parent26 = 0; #line 168 "lib/sj-lib-common/array.sj" sjt_parent24 = &_parent->arr; #line 46 "lib/sj-lib-common/list.sj" sjt_functionParam46 = 0; #line 29 "lib/sj-lib-common/array.sj" sjt_parent25 = &_parent->arr; #line 29 sjf_array_value_getcount(sjt_parent25, &sjt_functionParam47); #line 46 "lib/sj-lib-common/list.sj" sjt_functionParam49 = 10; #line 35 "lib/sj-lib-common/array.sj" sjt_parent26 = &_parent->arr; #line 35 sjf_array_value_gettotalcount(sjt_parent26, &sjt_capture20); #line 46 "lib/sj-lib-common/list.sj" sjt_functionParam50 = sjt_capture20 * 2; #line 46 sjf_i32_max(sjt_functionParam49, sjt_functionParam50, &sjt_functionParam48); #line 46 sjf_array_value_clone(sjt_parent24, sjt_functionParam46, sjt_functionParam47, sjt_functionParam48, &sjt_funcold8); #line 46 if (_parent->arr._refCount == 1) { sjf_array_value_destroy(&_parent->arr); } ; #line 168 "lib/sj-lib-common/array.sj" sjf_array_value_copy(&_parent->arr, &sjt_funcold8); } #line 52 sjt_parent27 = &_parent->arr; #line 29 sjt_parent28 = &_parent->arr; #line 29 sjf_array_value_getcount(sjt_parent28, &sjt_functionParam51); #line 44 "lib/sj-lib-common/list.sj" sjt_functionParam52 = item; #line 44 sjf_array_value_initat(sjt_parent27, sjt_functionParam51, sjt_functionParam52); if (sjt_funcold8._refCount == 1) { sjf_array_value_destroy(&sjt_funcold8); } ; } void sjf_list_value_copy(sjs_list_value* _this, sjs_list_value* _from) { _this->arr._refCount = 1; #line 1 "lib/sj-lib-common/list.sj" sjf_array_value_copy(&_this->arr, &_from->arr); } void sjf_list_value_destroy(sjs_list_value* _this) { if (_this->arr._refCount == 1) { sjf_array_value_destroy(&_this->arr); } ; } void sjf_list_value_heap(sjs_list_value* _this) { } void sjf_log(sjs_log* _this) { } void sjf_log_copy(sjs_log* _this, sjs_log* _from) { #line 13 "lib/sj-lib-common/log.sj" _this->minlevel = _from->minlevel; #line 13 sjs_hash_type_bool* copyoption2 = (_from->traceincludes._refCount != -1 ? &_from->traceincludes : 0); if (copyoption2 != 0) { _this->traceincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&_this->traceincludes, copyoption2); } else { _this->traceincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption3 = (_from->debugincludes._refCount != -1 ? &_from->debugincludes : 0); if (copyoption3 != 0) { _this->debugincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&_this->debugincludes, copyoption3); } else { _this->debugincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption4 = (_from->infoincludes._refCount != -1 ? &_from->infoincludes : 0); if (copyoption4 != 0) { _this->infoincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&_this->infoincludes, copyoption4); } else { _this->infoincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption5 = (_from->warnincludes._refCount != -1 ? &_from->warnincludes : 0); if (copyoption5 != 0) { _this->warnincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&_this->warnincludes, copyoption5); } else { _this->warnincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption6 = (_from->errorincludes._refCount != -1 ? &_from->errorincludes : 0); if (copyoption6 != 0) { _this->errorincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&_this->errorincludes, copyoption6); } else { _this->errorincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption7 = (_from->fatalincludes._refCount != -1 ? &_from->fatalincludes : 0); if (copyoption7 != 0) { _this->fatalincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&_this->fatalincludes, copyoption7); } else { _this->fatalincludes._refCount = -1; } } void sjf_log_destroy(sjs_log* _this) { if (_this->traceincludes._refCount == 1) { sjf_hash_type_bool_destroy(&_this->traceincludes); } ; if (_this->debugincludes._refCount == 1) { sjf_hash_type_bool_destroy(&_this->debugincludes); } ; if (_this->infoincludes._refCount == 1) { sjf_hash_type_bool_destroy(&_this->infoincludes); } ; if (_this->warnincludes._refCount == 1) { sjf_hash_type_bool_destroy(&_this->warnincludes); } ; if (_this->errorincludes._refCount == 1) { sjf_hash_type_bool_destroy(&_this->errorincludes); } ; if (_this->fatalincludes._refCount == 1) { sjf_hash_type_bool_destroy(&_this->fatalincludes); } ; } void sjf_log_heap(sjs_log* _this) { } void sjf_string(sjs_string* _this) { } void sjf_string_add(sjs_string* _parent, sjs_string* item, sjs_string* _return) { sjs_array_char newdata = { -1 }; if (item->count == 0) { _return->_refCount = 1; #line 20 "lib/sj-lib-common/string.sj" sjf_string_copy(_return, _parent); } else { bool sjt_capture40; int32_t sjt_capture41; sjs_array_char* sjt_parent47 = 0; #line 35 "lib/sj-lib-common/array.sj" sjt_parent47 = &_parent->data; #line 35 sjf_array_char_gettotalcount(sjt_parent47, &sjt_capture41); if (((_parent->offset + _parent->count) + item->count) < sjt_capture41) { int32_t sjt_capture42; sjs_array_char* sjt_parent48 = 0; #line 29 "lib/sj-lib-common/array.sj" sjt_parent48 = &_parent->data; #line 29 sjf_array_char_getcount(sjt_parent48, &sjt_capture42); #line 24 "lib/sj-lib-common/string.sj" sjt_capture40 = ((_parent->offset + _parent->count) == sjt_capture42); } else { #line 24 "lib/sj-lib-common/string.sj" sjt_capture40 = false; } if (sjt_capture40) { int32_t i; int32_t newcount; int32_t sjt_forEnd1; int32_t sjt_forStart1; #line 25 "lib/sj-lib-common/string.sj" newcount = _parent->count; #line 27 sjt_forStart1 = 0; #line 27 sjt_forEnd1 = item->count; #line 27 i = sjt_forStart1; while (i < sjt_forEnd1) { int32_t sjt_functionParam113; char sjt_functionParam114; int32_t sjt_functionParam115; sjs_array_char* sjt_parent49 = 0; sjs_string* sjt_parent50 = 0; #line 52 "lib/sj-lib-common/array.sj" sjt_parent49 = &_parent->data; #line 28 "lib/sj-lib-common/string.sj" sjt_functionParam113 = newcount; #line 18 sjt_parent50 = item; #line 27 sjt_functionParam115 = i; #line 27 sjf_string_getat(sjt_parent50, sjt_functionParam115, &sjt_functionParam114); #line 27 sjf_array_char_initat(sjt_parent49, sjt_functionParam113, sjt_functionParam114); #line 29 newcount = newcount + 1; #line 27 i++; } #line 27 _return->_refCount = 1; #line 32 _return->offset = _parent->offset; #line 32 _return->count = newcount; #line 32 _return->data._refCount = 1; #line 32 sjf_array_char_copy(&_return->data, &_parent->data); #line 16 _return->_isnullterminated = false; #line 16 sjf_string(_return); } else { int32_t i; int32_t newcount; int32_t sjt_forEnd2; int32_t sjt_forStart2; int32_t sjt_functionParam116; int32_t sjt_functionParam117; int32_t sjt_functionParam118; sjs_array_char* sjt_parent51 = 0; sjs_array_char* sjt_parent52 = 0; #line 168 "lib/sj-lib-common/array.sj" sjt_parent51 = &_parent->data; #line 34 "lib/sj-lib-common/string.sj" sjt_functionParam116 = _parent->offset; #line 34 sjt_functionParam117 = _parent->count; #line 34 sjt_functionParam118 = ((((_parent->count + item->count) - 1) / 256) + 1) * 256; #line 34 sjf_array_char_clone(sjt_parent51, sjt_functionParam116, sjt_functionParam117, sjt_functionParam118, &newdata); #line 29 "lib/sj-lib-common/array.sj" sjt_parent52 = &newdata; #line 29 sjf_array_char_getcount(sjt_parent52, &newcount); #line 37 "lib/sj-lib-common/string.sj" sjt_forStart2 = 0; #line 37 sjt_forEnd2 = item->count; #line 37 i = sjt_forStart2; while (i < sjt_forEnd2) { int32_t sjt_functionParam119; char sjt_functionParam120; int32_t sjt_functionParam121; sjs_array_char* sjt_parent53 = 0; sjs_string* sjt_parent54 = 0; #line 52 "lib/sj-lib-common/array.sj" sjt_parent53 = &newdata; #line 38 "lib/sj-lib-common/string.sj" sjt_functionParam119 = newcount; #line 18 sjt_parent54 = item; #line 37 sjt_functionParam121 = i; #line 37 sjf_string_getat(sjt_parent54, sjt_functionParam121, &sjt_functionParam120); #line 37 sjf_array_char_initat(sjt_parent53, sjt_functionParam119, sjt_functionParam120); #line 39 newcount = newcount + 1; #line 37 i++; } #line 37 _return->_refCount = 1; #line 42 _return->offset = 0; #line 42 _return->count = newcount; #line 42 _return->data._refCount = 1; #line 42 sjf_array_char_copy(&_return->data, &newdata); #line 16 _return->_isnullterminated = false; #line 16 sjf_string(_return); } } if (newdata._refCount == 1) { sjf_array_char_destroy(&newdata); } ; } void sjf_string_add_heap(sjs_string* _parent, sjs_string* item, sjs_string** _return) { sjs_array_char newdata = { -1 }; if (item->count == 0) { (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); (*_return)->_refCount = 1; #line 20 "lib/sj-lib-common/string.sj" sjf_string_copy((*_return), _parent); } else { bool sjt_capture43; int32_t sjt_capture44; sjs_array_char* sjt_parent55 = 0; #line 35 "lib/sj-lib-common/array.sj" sjt_parent55 = &_parent->data; #line 35 sjf_array_char_gettotalcount(sjt_parent55, &sjt_capture44); if (((_parent->offset + _parent->count) + item->count) < sjt_capture44) { int32_t sjt_capture45; sjs_array_char* sjt_parent56 = 0; #line 29 "lib/sj-lib-common/array.sj" sjt_parent56 = &_parent->data; #line 29 sjf_array_char_getcount(sjt_parent56, &sjt_capture45); #line 24 "lib/sj-lib-common/string.sj" sjt_capture43 = ((_parent->offset + _parent->count) == sjt_capture45); } else { #line 24 "lib/sj-lib-common/string.sj" sjt_capture43 = false; } if (sjt_capture43) { int32_t i; int32_t newcount; int32_t sjt_forEnd3; int32_t sjt_forStart3; #line 25 "lib/sj-lib-common/string.sj" newcount = _parent->count; #line 27 sjt_forStart3 = 0; #line 27 sjt_forEnd3 = item->count; #line 27 i = sjt_forStart3; while (i < sjt_forEnd3) { int32_t sjt_functionParam122; char sjt_functionParam123; int32_t sjt_functionParam124; sjs_array_char* sjt_parent57 = 0; sjs_string* sjt_parent58 = 0; #line 52 "lib/sj-lib-common/array.sj" sjt_parent57 = &_parent->data; #line 28 "lib/sj-lib-common/string.sj" sjt_functionParam122 = newcount; #line 18 sjt_parent58 = item; #line 27 sjt_functionParam124 = i; #line 27 sjf_string_getat(sjt_parent58, sjt_functionParam124, &sjt_functionParam123); #line 27 sjf_array_char_initat(sjt_parent57, sjt_functionParam122, sjt_functionParam123); #line 29 newcount = newcount + 1; #line 27 i++; } #line 27 (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); #line 27 (*_return)->_refCount = 1; #line 32 (*_return)->offset = _parent->offset; #line 32 (*_return)->count = newcount; #line 32 (*_return)->data._refCount = 1; #line 32 sjf_array_char_copy(&(*_return)->data, &_parent->data); #line 16 (*_return)->_isnullterminated = false; #line 16 sjf_string_heap((*_return)); } else { int32_t i; int32_t newcount; int32_t sjt_forEnd4; int32_t sjt_forStart4; int32_t sjt_functionParam125; int32_t sjt_functionParam126; int32_t sjt_functionParam127; sjs_array_char* sjt_parent59 = 0; sjs_array_char* sjt_parent60 = 0; #line 168 "lib/sj-lib-common/array.sj" sjt_parent59 = &_parent->data; #line 34 "lib/sj-lib-common/string.sj" sjt_functionParam125 = _parent->offset; #line 34 sjt_functionParam126 = _parent->count; #line 34 sjt_functionParam127 = ((((_parent->count + item->count) - 1) / 256) + 1) * 256; #line 34 sjf_array_char_clone(sjt_parent59, sjt_functionParam125, sjt_functionParam126, sjt_functionParam127, &newdata); #line 29 "lib/sj-lib-common/array.sj" sjt_parent60 = &newdata; #line 29 sjf_array_char_getcount(sjt_parent60, &newcount); #line 37 "lib/sj-lib-common/string.sj" sjt_forStart4 = 0; #line 37 sjt_forEnd4 = item->count; #line 37 i = sjt_forStart4; while (i < sjt_forEnd4) { int32_t sjt_functionParam128; char sjt_functionParam129; int32_t sjt_functionParam130; sjs_array_char* sjt_parent61 = 0; sjs_string* sjt_parent62 = 0; #line 52 "lib/sj-lib-common/array.sj" sjt_parent61 = &newdata; #line 38 "lib/sj-lib-common/string.sj" sjt_functionParam128 = newcount; #line 18 sjt_parent62 = item; #line 37 sjt_functionParam130 = i; #line 37 sjf_string_getat(sjt_parent62, sjt_functionParam130, &sjt_functionParam129); #line 37 sjf_array_char_initat(sjt_parent61, sjt_functionParam128, sjt_functionParam129); #line 39 newcount = newcount + 1; #line 37 i++; } #line 37 (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); #line 37 (*_return)->_refCount = 1; #line 42 (*_return)->offset = 0; #line 42 (*_return)->count = newcount; #line 42 (*_return)->data._refCount = 1; #line 42 sjf_array_char_copy(&(*_return)->data, &newdata); #line 16 (*_return)->_isnullterminated = false; #line 16 sjf_string_heap((*_return)); } } if (newdata._refCount == 1) { sjf_array_char_destroy(&newdata); } ; } void sjf_string_asstring(sjs_string* _parent, sjs_string* _return) { _return->_refCount = 1; #line 60 "lib/sj-lib-common/string.sj" sjf_string_copy(_return, _parent); } void sjf_string_asstring_heap(sjs_string* _parent, sjs_string** _return) { (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); (*_return)->_refCount = 1; #line 60 "lib/sj-lib-common/string.sj" sjf_string_copy((*_return), _parent); } void sjf_string_copy(sjs_string* _this, sjs_string* _from) { #line 12 "lib/sj-lib-common/string.sj" _this->offset = _from->offset; #line 12 _this->count = _from->count; #line 12 _this->data._refCount = 1; #line 12 sjf_array_char_copy(&_this->data, &_from->data); #line 12 _this->_isnullterminated = _from->_isnullterminated; } void sjf_string_destroy(sjs_string* _this) { if (_this->data._refCount == 1) { sjf_array_char_destroy(&_this->data); } ; } void sjf_string_getat(sjs_string* _parent, int32_t index, char* _return) { int32_t sjt_functionParam4; sjs_array_char* sjt_parent4 = 0; #line 41 "lib/sj-lib-common/array.sj" sjt_parent4 = &_parent->data; #line 64 "lib/sj-lib-common/string.sj" sjt_functionParam4 = _parent->offset + index; #line 64 sjf_array_char_getat(sjt_parent4, sjt_functionParam4, _return); } void sjf_string_hash(sjs_string* _parent, uint32_t* _return) { #line 148 "lib/sj-lib-common/string.sj" #line 147 "lib/sj-lib-common/string.sj" (*_return) = kh_str_hash_func(((sjs_array*)_parent->data.v)->data + _parent->offset, _parent->count); return;; } void sjf_string_heap(sjs_string* _this) { } void sjf_string_isequal(sjs_string* _parent, sjs_string* test, bool* _return) { #line 73 "lib/sj-lib-common/string.sj" sjs_array* arr1 = (sjs_array*)_parent->data.v; #line 74 sjs_array* arr2 = (sjs_array*)test->data.v; #line 75 if (_parent->count != test->count) { #line 76 #line 72 "lib/sj-lib-common/string.sj" (*_return) = false; return;; #line 77 } #line 78 bool result = memcmp(arr1->data + _parent->offset, arr2->data + test->offset, _parent->count) == 0; #line 79 #line 72 "lib/sj-lib-common/string.sj" (*_return) = result; return;; } void sjf_string_nullterminate(sjs_string* _parent) { bool result2; sjs_array_char sjt_funcold1 = { -1 }; #line 133 "lib/sj-lib-common/string.sj" result2 = !_parent->_isnullterminated; if (result2) { int32_t sjt_capture1; int32_t sjt_capture2; sjs_array_char* sjt_parent1 = 0; sjs_array_char* sjt_parent2 = 0; #line 35 "lib/sj-lib-common/array.sj" sjt_parent1 = &_parent->data; #line 35 sjf_array_char_gettotalcount(sjt_parent1, &sjt_capture1); #line 29 sjt_parent2 = &_parent->data; #line 29 sjf_array_char_getcount(sjt_parent2, &sjt_capture2); if ((((_parent->offset + _parent->count) + 1) > sjt_capture1) || ((_parent->offset + _parent->count) != sjt_capture2)) { int32_t sjt_functionParam1; int32_t sjt_functionParam2; int32_t sjt_functionParam3; sjs_array_char* sjt_parent3 = 0; #line 168 "lib/sj-lib-common/array.sj" sjt_parent3 = &_parent->data; #line 135 "lib/sj-lib-common/string.sj" sjt_functionParam1 = _parent->offset; #line 135 sjt_functionParam2 = _parent->count; #line 135 sjt_functionParam3 = _parent->count + 1; #line 135 sjf_array_char_clone(sjt_parent3, sjt_functionParam1, sjt_functionParam2, sjt_functionParam3, &sjt_funcold1); #line 135 if (_parent->data._refCount == 1) { sjf_array_char_destroy(&_parent->data); } ; #line 168 "lib/sj-lib-common/array.sj" sjf_array_char_copy(&_parent->data, &sjt_funcold1); #line 136 "lib/sj-lib-common/string.sj" _parent->offset = 0; } #line 139 "lib/sj-lib-common/string.sj" ((sjs_array*)_parent->data.v)->data[_parent->offset + _parent->count] = 0; #line 141 _parent->_isnullterminated = true; } if (sjt_funcold1._refCount == 1) { sjf_array_char_destroy(&sjt_funcold1); } ; } void sjf_string_substr(sjs_string* _parent, int32_t o, int32_t c, sjs_string* _return) { sjs_string sjt_call1 = { -1 }; int32_t sjt_capture9; sjs_array_char* sjt_parent11 = 0; #line 29 "lib/sj-lib-common/array.sj" sjt_parent11 = &_parent->data; #line 29 sjf_array_char_getcount(sjt_parent11, &sjt_capture9); if (((_parent->offset + o) + c) > sjt_capture9) { sjs_string* sjt_functionParam17 = 0; sjt_call1._refCount = 1; #line 49 "lib/sj-lib-common/string.sj" sjt_call1.offset = 0; #line 49 sjt_call1.count = 13; #line 49 sjt_call1.data._refCount = 1; #line 49 sjt_call1.data.v = &sjg_string3; #line 49 sjf_array_char(&sjt_call1.data); #line 16 sjt_call1._isnullterminated = false; #line 16 sjf_string(&sjt_call1); #line 49 sjt_functionParam17 = &sjt_call1; #line 49 sjf_halt(sjt_functionParam17); } #line 29 _return->_refCount = 1; #line 53 "lib/sj-lib-common/string.sj" _return->offset = _parent->offset + o; #line 47 _return->count = c; #line 47 _return->data._refCount = 1; #line 52 sjf_array_char_copy(&_return->data, &_parent->data); #line 16 _return->_isnullterminated = false; #line 16 sjf_string(_return); if (sjt_call1._refCount == 1) { sjf_string_destroy(&sjt_call1); } ; } void sjf_string_substr_heap(sjs_string* _parent, int32_t o, int32_t c, sjs_string** _return) { sjs_string sjt_call2 = { -1 }; int32_t sjt_capture10; sjs_array_char* sjt_parent12 = 0; #line 29 "lib/sj-lib-common/array.sj" sjt_parent12 = &_parent->data; #line 29 sjf_array_char_getcount(sjt_parent12, &sjt_capture10); if (((_parent->offset + o) + c) > sjt_capture10) { sjs_string* sjt_functionParam18 = 0; sjt_call2._refCount = 1; #line 49 "lib/sj-lib-common/string.sj" sjt_call2.offset = 0; #line 49 sjt_call2.count = 13; #line 49 sjt_call2.data._refCount = 1; #line 49 sjt_call2.data.v = &sjg_string3; #line 49 sjf_array_char(&sjt_call2.data); #line 16 sjt_call2._isnullterminated = false; #line 16 sjf_string(&sjt_call2); #line 49 sjt_functionParam18 = &sjt_call2; #line 49 sjf_halt(sjt_functionParam18); } #line 29 (*_return) = (sjs_string*)malloc(sizeof(sjs_string)); #line 29 (*_return)->_refCount = 1; #line 53 "lib/sj-lib-common/string.sj" (*_return)->offset = _parent->offset + o; #line 47 (*_return)->count = c; #line 47 (*_return)->data._refCount = 1; #line 52 sjf_array_char_copy(&(*_return)->data, &_parent->data); #line 16 (*_return)->_isnullterminated = false; #line 16 sjf_string_heap((*_return)); if (sjt_call2._refCount == 1) { sjf_string_destroy(&sjt_call2); } ; } void sjf_test(sjs_string* s) { sjs_json_value data = { -1 }; sjs_string* sjt_functionParam111 = 0; #line 3 "test1.sj" sjt_functionParam111 = s; #line 3 sjf_json_parse(sjt_functionParam111, &data); if (((data._refCount != -1 ? &data : 0) != 0)) { sjs_json_value* ifValue1 = 0; sjs_string sjt_call7 = { -1 }; sjs_string* sjt_functionParam112 = 0; sjs_json_value* sjt_parent103 = 0; #line 5 "test1.sj" ifValue1 = (data._refCount != -1 ? &data : 0); #line 39 "lib/sj-lib-json/value.sj" sjt_parent103 = ifValue1; #line 39 sjf_json_value_render(sjt_parent103, &sjt_call7); #line 6 "test1.sj" sjt_functionParam112 = &sjt_call7; #line 6 sjf_debug_writeline(sjt_functionParam112); if (sjt_call7._refCount == 1) { sjf_string_destroy(&sjt_call7); } ; } else { sjs_string sjt_call55 = { -1 }; sjs_string* sjt_functionParam175 = 0; sjt_call55._refCount = 1; #line 8 "test1.sj" sjt_call55.offset = 0; #line 8 sjt_call55.count = 11; #line 8 sjt_call55.data._refCount = 1; #line 8 sjt_call55.data.v = &sjg_string4; #line 8 sjf_array_char(&sjt_call55.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call55._isnullterminated = false; #line 16 sjf_string(&sjt_call55); #line 8 "test1.sj" sjt_functionParam175 = &sjt_call55; #line 8 sjf_debug_writeline(sjt_functionParam175); if (sjt_call55._refCount == 1) { sjf_string_destroy(&sjt_call55); } ; } if (data._refCount == 1) { sjf_json_value_destroy(&data); } ; } void sjf_tuple2_i32_string(sjs_tuple2_i32_string* _this) { } void sjf_tuple2_i32_string_copy(sjs_tuple2_i32_string* _this, sjs_tuple2_i32_string* _from) { #line 5 "lib/sj-lib-common/tuple.sj" _this->item1 = _from->item1; #line 5 _this->item2._refCount = 1; #line 5 sjf_string_copy(&_this->item2, &_from->item2); } void sjf_tuple2_i32_string_destroy(sjs_tuple2_i32_string* _this) { if (_this->item2._refCount == 1) { sjf_string_destroy(&_this->item2); } ; } void sjf_tuple2_i32_string_heap(sjs_tuple2_i32_string* _this) { } void sjf_tuple2_i32_value(sjs_tuple2_i32_value* _this) { } void sjf_tuple2_i32_value_copy(sjs_tuple2_i32_value* _this, sjs_tuple2_i32_value* _from) { #line 5 "lib/sj-lib-common/tuple.sj" _this->item1 = _from->item1; #line 5 _this->item2._refCount = 1; #line 5 sjf_json_value_copy(&_this->item2, &_from->item2); } void sjf_tuple2_i32_value_destroy(sjs_tuple2_i32_value* _this) { if (_this->item2._refCount == 1) { sjf_json_value_destroy(&_this->item2); } ; } void sjf_tuple2_i32_value_heap(sjs_tuple2_i32_value* _this) { } void sjf_type_hash(int32_t val, uint32_t* _return) { int32_t sjt_cast1; #line 5 "lib/sj-lib-common/type.sj" sjt_cast1 = val; #line 6 (*_return) = (uint32_t)sjt_cast1; } void sjf_type_isequal(int32_t l, int32_t r, bool* _return) { #line 10 "lib/sj-lib-common/type.sj" (*_return) = l == r; } int main(int argc, char** argv) { #line 1 "lib/sj-lib-common/log.sj" g_loglevel_trace = 0; #line 1 g_loglevel_debug = 1; #line 1 g_loglevel_info = 2; #line 1 g_loglevel_warn = 3; #line 1 g_loglevel_error = 4; #line 1 g_loglevel_fatal = 5; #line 1 "lib/sj-lib-common/f32.sj" g_f32_pi = 3.14159265358979323846f; #line 1 "lib/sj-lib-common/i32.sj" g_u32_maxvalue = (uint32_t)4294967295u; #line 3 result1 = -1; #line 3 g_i32_maxvalue = result1 - 2147483647; #line 4 g_i32_minvalue = 2147483647; #line 10 "lib/sj-lib-common/log.sj" g_log_includeall._refCount = -1; #line 10 sjt_value1._refCount = 1; #line 10 sjf_hash_type_bool(&sjt_value1); #line 11 sjs_hash_type_bool* copyoption1 = &sjt_value1; if (copyoption1 != 0) { g_log_excludeall._refCount = 1; #line 11 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&g_log_excludeall, copyoption1); } else { g_log_excludeall._refCount = -1; } #line 11 g_log._refCount = 1; #line 13 g_log.minlevel = g_loglevel_warn; #line 13 sjs_hash_type_bool* copyoption8 = (g_log_includeall._refCount != -1 ? &g_log_includeall : 0); if (copyoption8 != 0) { g_log.traceincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&g_log.traceincludes, copyoption8); } else { g_log.traceincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption9 = (g_log_includeall._refCount != -1 ? &g_log_includeall : 0); if (copyoption9 != 0) { g_log.debugincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&g_log.debugincludes, copyoption9); } else { g_log.debugincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption10 = (g_log_includeall._refCount != -1 ? &g_log_includeall : 0); if (copyoption10 != 0) { g_log.infoincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&g_log.infoincludes, copyoption10); } else { g_log.infoincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption11 = (g_log_includeall._refCount != -1 ? &g_log_includeall : 0); if (copyoption11 != 0) { g_log.warnincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&g_log.warnincludes, copyoption11); } else { g_log.warnincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption12 = (g_log_includeall._refCount != -1 ? &g_log_includeall : 0); if (copyoption12 != 0) { g_log.errorincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&g_log.errorincludes, copyoption12); } else { g_log.errorincludes._refCount = -1; } #line 13 sjs_hash_type_bool* copyoption13 = (g_log_includeall._refCount != -1 ? &g_log_includeall : 0); if (copyoption13 != 0) { g_log.fatalincludes._refCount = 1; #line 13 "lib/sj-lib-common/log.sj" sjf_hash_type_bool_copy(&g_log.fatalincludes, copyoption13); } else { g_log.fatalincludes._refCount = -1; } #line 13 sjf_log(&g_log); #line 2 "lib/sj-lib-common/weakptr.sj" ptr_init(); #line 3 weakptr_init(); #line 7 "lib/sj-lib-common/clock.sj" g_clocks_per_sec = 0; #line 9 g_clocks_per_sec = CLOCKS_PER_SEC; #line 9 g_allthespaces._refCount = 1; #line 79 "lib/sj-lib-json/value.sj" g_allthespaces.offset = 0; #line 79 g_allthespaces.count = 592; #line 79 g_allthespaces.data._refCount = 1; #line 79 g_allthespaces.data.v = &sjg_string1; #line 79 sjf_array_char(&g_allthespaces.data); #line 16 "lib/sj-lib-common/string.sj" g_allthespaces._isnullterminated = false; #line 16 sjf_string(&g_allthespaces); #line 16 sjt_call56._refCount = 1; #line 12 "test1.sj" sjt_call56.offset = 0; #line 12 sjt_call56.count = 5; #line 12 sjt_call56.data._refCount = 1; #line 12 sjt_call56.data.v = &sjg_string12; #line 12 sjf_array_char(&sjt_call56.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call56._isnullterminated = false; #line 16 sjf_string(&sjt_call56); #line 12 "test1.sj" sjt_functionParam176 = &sjt_call56; #line 12 sjf_test(sjt_functionParam176); #line 12 sjt_call57._refCount = 1; #line 13 sjt_call57.offset = 0; #line 13 sjt_call57.count = 2; #line 13 sjt_call57.data._refCount = 1; #line 13 sjt_call57.data.v = &sjg_string13; #line 13 sjf_array_char(&sjt_call57.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call57._isnullterminated = false; #line 16 sjf_string(&sjt_call57); #line 13 "test1.sj" sjt_functionParam177 = &sjt_call57; #line 13 sjf_test(sjt_functionParam177); #line 13 sjt_call58._refCount = 1; #line 14 sjt_call58.offset = 0; #line 14 sjt_call58.count = 12; #line 14 sjt_call58.data._refCount = 1; #line 14 sjt_call58.data.v = &sjg_string14; #line 14 sjf_array_char(&sjt_call58.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call58._isnullterminated = false; #line 16 sjf_string(&sjt_call58); #line 14 "test1.sj" sjt_functionParam178 = &sjt_call58; #line 14 sjf_test(sjt_functionParam178); #line 14 sjt_call59._refCount = 1; #line 15 sjt_call59.offset = 0; #line 15 sjt_call59.count = 3; #line 15 sjt_call59.data._refCount = 1; #line 15 sjt_call59.data.v = &sjg_string15; #line 15 sjf_array_char(&sjt_call59.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call59._isnullterminated = false; #line 16 sjf_string(&sjt_call59); #line 15 "test1.sj" sjt_functionParam179 = &sjt_call59; #line 15 sjf_test(sjt_functionParam179); #line 15 sjt_call60._refCount = 1; #line 16 sjt_call60.offset = 0; #line 16 sjt_call60.count = 19; #line 16 sjt_call60.data._refCount = 1; #line 16 sjt_call60.data.v = &sjg_string16; #line 16 sjf_array_char(&sjt_call60.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call60._isnullterminated = false; #line 16 sjf_string(&sjt_call60); #line 16 "test1.sj" sjt_functionParam180 = &sjt_call60; #line 16 sjf_test(sjt_functionParam180); #line 16 sjt_call61._refCount = 1; #line 17 sjt_call61.offset = 0; #line 17 sjt_call61.count = 32; #line 17 sjt_call61.data._refCount = 1; #line 17 sjt_call61.data.v = &sjg_string17; #line 17 sjf_array_char(&sjt_call61.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call61._isnullterminated = false; #line 16 sjf_string(&sjt_call61); #line 17 "test1.sj" sjt_functionParam181 = &sjt_call61; #line 17 sjf_test(sjt_functionParam181); #line 17 sjt_call62._refCount = 1; #line 18 sjt_call62.offset = 0; #line 18 sjt_call62.count = 300; #line 18 sjt_call62.data._refCount = 1; #line 18 sjt_call62.data.v = &sjg_string18; #line 18 sjf_array_char(&sjt_call62.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call62._isnullterminated = false; #line 16 sjf_string(&sjt_call62); #line 18 "test1.sj" sjt_functionParam182 = &sjt_call62; #line 18 sjf_test(sjt_functionParam182); #line 18 sjt_call63._refCount = 1; #line 19 sjt_call63.offset = 0; #line 19 sjt_call63.count = 369; #line 19 sjt_call63.data._refCount = 1; #line 19 sjt_call63.data.v = &sjg_string19; #line 19 sjf_array_char(&sjt_call63.data); #line 16 "lib/sj-lib-common/string.sj" sjt_call63._isnullterminated = false; #line 16 sjf_string(&sjt_call63); #line 19 "test1.sj" sjt_functionParam183 = &sjt_call63; #line 19 sjf_test(sjt_functionParam183); main_destroy(); return 0; } void main_destroy() { if (g_allthespaces._refCount == 1) { sjf_string_destroy(&g_allthespaces); } ; if (g_log._refCount == 1) { sjf_log_destroy(&g_log); } ; if (g_log_excludeall._refCount == 1) { sjf_hash_type_bool_destroy(&g_log_excludeall); } ; if (g_log_includeall._refCount == 1) { sjf_hash_type_bool_destroy(&g_log_includeall); } ; if (sjt_call56._refCount == 1) { sjf_string_destroy(&sjt_call56); } ; if (sjt_call57._refCount == 1) { sjf_string_destroy(&sjt_call57); } ; if (sjt_call58._refCount == 1) { sjf_string_destroy(&sjt_call58); } ; if (sjt_call59._refCount == 1) { sjf_string_destroy(&sjt_call59); } ; if (sjt_call60._refCount == 1) { sjf_string_destroy(&sjt_call60); } ; if (sjt_call61._refCount == 1) { sjf_string_destroy(&sjt_call61); } ; if (sjt_call62._refCount == 1) { sjf_string_destroy(&sjt_call62); } ; if (sjt_call63._refCount == 1) { sjf_string_destroy(&sjt_call63); } ; if (sjt_value1._refCount == 1) { sjf_hash_type_bool_destroy(&sjt_value1); } ; }
97afb303074782957f8fe95fc48f57c5795bfbc4
4afdaa5578fd017adf97ff79f4450b2196afc49f
/src/Converter.hpp
e8de3078025fe77c9f3ff8403f6d665f8c6201c0
[ "MIT" ]
permissive
gschwann/qt-ts-csv
c10626135340fa0fd13a0bc4c687a74cde5cfd0d
a69f1cf899791a1f5122f0d829a177c2c44b3ddd
refs/heads/master
2021-01-05T19:15:54.516839
2020-02-18T09:13:57
2020-02-18T09:13:57
241,112,696
0
0
MIT
2020-02-17T13:20:50
2020-02-17T13:20:49
null
UTF-8
C++
false
false
573
hpp
Converter.hpp
#pragma once #include <string> class Converter { public: explicit Converter(const std::string &input, const std::string &output); Converter() = default; Converter(const Converter &other) = default; Converter(Converter &&other) = default; virtual ~Converter() = default; Converter &operator=(const Converter &other) = default; Converter &operator=(Converter &&other) = default; virtual void process() const; protected: std::string input_; std::string output_; };
4c76bc452e0a141a4470d0d19fe7c6a414a83609
a436ce09ad45aba66f29093f09bd046e6f2b1dc4
/Troubleshooting/MaxDuino_v1.59/TimerCounter.h
c14458a3739edad3a84e4bf806aa8213ad1d19ac
[]
no_license
rcmolina/MaxDuino_BETA
12de7d9479c798a178e68af39086806ab75142ae
781aab0899ee26bcd9259a5c1f7788a283111045
refs/heads/master
2023-09-03T22:32:40.799909
2023-08-23T10:50:19
2023-08-23T10:50:19
128,559,979
2
6
null
null
null
null
UTF-8
C++
false
false
7,972
h
TimerCounter.h
/* * Interrupt and PWM utilities for 16 bit Timer1 on ATmega168/328 * Original code by Jesse Tane for http://labs.ideo.com August 2008 */ #define TIMER1_A_PIN 9 #define TIMER1_B_PIN 10 #define TIMER1_ICP_PIN 8 #define TIMER1_CLK_PIN 5 #define TIMER1_RESOLUTION 65536UL // Timer1 is 16 bit // Placing nearly all the code in this .h file allows the functions to be // inlined by the compiler. In the very common case with constant values // the compiler will perform all calculations and simply write constants // to the hardware registers (for example, setPeriod). class TimerCounter { #ifdef __AVR_ATmega4809__ public: //**************************** // Configuration //**************************** void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) { TCA0.SINGLE.CTRLB = TCA_SINGLE_WGMODE_DSBOTTOM_gc; // set mode as DSBOTTOM, stop the timer //TCA0.SINGLE.CTRLB = TCA_SINGLE_WGMODE_SINGLESLOPE_gc; // set mode as SINGLESLOPE, stop the timer //TCA0.SINGLE.CTRLA |= (TCA_SINGLE_CLKSEL_DIV64_gc) | (TCA_SINGLE_ENABLE_bm); //TCA0.SINGLE.CTRLA &= ~(TCA_SINGLE_ENABLE_bm); //stop the timer /* disable event counting */ //TCA0.SINGLE.EVCTRL &= ~(TCA_SINGLE_CNTEI_bm); setPeriod(microseconds); } void setPeriod(unsigned long microseconds) __attribute__((always_inline)) { //const unsigned long cycles = 16 * microseconds; //WGMODE_NORMAL //DSBOTTOM: the counter runs backwards after TOP, interrupt is at BOTTOM so divide microseconds by 2 const unsigned long cycles = (F_CPU / 2000000) * microseconds; /* if (cycles < TIMER1_RESOLUTION * 1) { clockSelectBits = TCA_SINGLE_CLKSEL_DIV1_gc; pwmPeriod = cycles / 1; } else { clockSelectBits = TCA_SINGLE_CLKSEL_DIV64_gc; pwmPeriod = TIMER1_RESOLUTION - 1; } */ if (cycles < TIMER1_RESOLUTION) { //clockSelectBits = _BV(CS10); clockSelectBits = TCA_SINGLE_CLKSEL_DIV1_gc; pwmPeriod = cycles; } else if (cycles < TIMER1_RESOLUTION * 2) { //clockSelectBits = _BV(CS10); clockSelectBits = TCA_SINGLE_CLKSEL_DIV2_gc; pwmPeriod = cycles / 2; } else if (cycles < TIMER1_RESOLUTION * 4) { //clockSelectBits = _BV(CS10); clockSelectBits = TCA_SINGLE_CLKSEL_DIV4_gc; pwmPeriod = cycles / 4; } else if (cycles < TIMER1_RESOLUTION * 8) { //clockSelectBits = _BV(CS11); clockSelectBits = TCA_SINGLE_CLKSEL_DIV8_gc; pwmPeriod = cycles / 8; } else if (cycles < TIMER1_RESOLUTION * 16) { //clockSelectBits = _BV(CS10); clockSelectBits = TCA_SINGLE_CLKSEL_DIV16_gc; pwmPeriod = cycles / 16; } else if (cycles < TIMER1_RESOLUTION * 64) { //clockSelectBits = _BV(CS11) | _BV(CS10); clockSelectBits = TCA_SINGLE_CLKSEL_DIV64_gc; pwmPeriod = cycles / 64; } else if (cycles < TIMER1_RESOLUTION * 256) { //clockSelectBits = _BV(CS12); clockSelectBits = TCA_SINGLE_CLKSEL_DIV256_gc; pwmPeriod = cycles / 256; } else if (cycles < TIMER1_RESOLUTION * 1024) { //clockSelectBits = _BV(CS12) | _BV(CS10); clockSelectBits = TCA_SINGLE_CLKSEL_DIV1024_gc; pwmPeriod = cycles / 1024; } else { //clockSelectBits = _BV(CS12) | _BV(CS10); clockSelectBits = TCA_SINGLE_CLKSEL_DIV1024_gc; pwmPeriod = TIMER1_RESOLUTION - 1; } //ICR1 = pwmPeriod; TCA0.SINGLE.PER = pwmPeriod; //TCA0.SINGLE.PER = cycles / 64; // set clock source and start timer TCA0.SINGLE.CTRLA = clockSelectBits | TCA_SINGLE_ENABLE_bm; //TCA0.SINGLE.INTCTRL |= (TCA_SINGLE_OVF_bm); // Enable timer interrupts on overflow on timer A } //**************************** // Run Control //**************************** void start() __attribute__((always_inline)) { //TCCR1B = 0; //TCA0.SINGLE.CTRLB=TCA_SINGLE_WGMODE_NORMAL_gc; //TCA0.SINGLE.CTRLA = ~(TCA_SINGLE_ENABLE_bm); //TCNT1 = 0; // TODO: does this cause an undesired interrupt? //TCA0.SINGLE.CNT = 0; resume(); } void stop() __attribute__((always_inline)) { //TCCR1B = _BV(WGM13); //TCA0.SINGLE.CTRLB=TCA_SINGLE_WGMODE_NORMAL_gc; //TCA0.SINGLE.CTRLA =0; TCA0.SINGLE.CTRLA &= ~(TCA_SINGLE_ENABLE_bm); } void restart() __attribute__((always_inline)) { start(); } void resume() __attribute__((always_inline)) { //TCCR1B = _BV(WGM13) | clockSelectBits; //TCA0.SINGLE.CTRLB = TCA_SINGLE_WGMODE_NORMAL_gc; //TCA0.SINGLE.CTRLA = clockSelectBits /* set clock source (sys_clk/256) */ // | TCA_SINGLE_ENABLE_bm; /* start timer */ TCA0.SINGLE.CTRLA |= TCA_SINGLE_ENABLE_bm; } //**************************** // Interrupt Function //**************************** void attachInterrupt(void (*isr)()) __attribute__((always_inline)) { isrCallback = isr; //TIMSK1 = _BV(TOIE1); /* enable overflow interrupt */ TCA0.SINGLE.INTCTRL |= TCA_SINGLE_OVF_bm; } void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) { if(microseconds > 0) setPeriod(microseconds); attachInterrupt(isr); } void detachInterrupt() __attribute__((always_inline)) { //TIMSK1 = 0; /* disable overflow interrupt */ TCA0.SINGLE.INTCTRL &= ~(TCA_SINGLE_OVF_bm); } static void (*isrCallback)(); private: // properties static unsigned short pwmPeriod; static unsigned char clockSelectBits; #else //__AVR_ATmega328P__ public: //**************************** // Configuration //**************************** void initialize(unsigned long microseconds=1000000) __attribute__((always_inline)) { TCCR1B = _BV(WGM13); // set mode as phase and frequency correct pwm, stop the timer TCCR1A = 0; // clear control register A setPeriod(microseconds); } void setPeriod(unsigned long microseconds) __attribute__((always_inline)) { const unsigned long cycles = (F_CPU / 2000000) * microseconds; if (cycles < TIMER1_RESOLUTION) { clockSelectBits = _BV(CS10); pwmPeriod = cycles; } else if (cycles < TIMER1_RESOLUTION * 8) { clockSelectBits = _BV(CS11); pwmPeriod = cycles / 8; } else if (cycles < TIMER1_RESOLUTION * 64) { clockSelectBits = _BV(CS11) | _BV(CS10); pwmPeriod = cycles / 64; } else if (cycles < TIMER1_RESOLUTION * 256) { clockSelectBits = _BV(CS12); pwmPeriod = cycles / 256; } else if (cycles < TIMER1_RESOLUTION * 1024) { clockSelectBits = _BV(CS12) | _BV(CS10); pwmPeriod = cycles / 1024; } else { clockSelectBits = _BV(CS12) | _BV(CS10); pwmPeriod = TIMER1_RESOLUTION - 1; } ICR1 = pwmPeriod; TCCR1B = _BV(WGM13) | clockSelectBits; } //**************************** // Run Control //**************************** void start() __attribute__((always_inline)) { TCCR1B = 0; TCNT1 = 0; // TODO: does this cause an undesired interrupt? resume(); } void stop() __attribute__((always_inline)) { TCCR1B = _BV(WGM13); } void restart() __attribute__((always_inline)) { start(); } void resume() __attribute__((always_inline)) { TCCR1B = _BV(WGM13) | clockSelectBits; } //**************************** // Interrupt Function //**************************** void attachInterrupt(void (*isr)()) __attribute__((always_inline)) { isrCallback = isr; TIMSK1 = _BV(TOIE1); } void attachInterrupt(void (*isr)(), unsigned long microseconds) __attribute__((always_inline)) { if(microseconds > 0) setPeriod(microseconds); attachInterrupt(isr); } void detachInterrupt() __attribute__((always_inline)) { TIMSK1 = 0; } static void (*isrCallback)(); private: // properties static unsigned short pwmPeriod; static unsigned char clockSelectBits; #endif }; //extern TimerCounter Timer1;
ce7555964fad2860aa02b07a663f773a617c5cc1
cffe14032f0c84968599772f485eb77b59891ebe
/record interview/C++相关/重载各种运算符/friend_+-.cpp
068bda6559370581a6c0a07f68f480b2a76ac2d7
[]
no_license
lb9726/Classic-examples-of-practice
7b7f8fb840f84d6ab89b775efd9b36a7ff8a7cca
6c2f593622b8e1f91c264a82968981d5e1386ace
refs/heads/master
2020-04-08T10:26:42.024610
2019-04-08T15:26:08
2019-04-08T15:26:08
92,397,993
0
3
null
null
null
null
UTF-8
C++
false
false
1,725
cpp
friend_+-.cpp
#include <iostream> using namespace std; class complex { public: complex() { real = imag = 0; } complex(double r, double i) { real = r, imag = i; } friend complex operator + (const complex &c1, const complex &c2); friend complex operator - (const complex &c1, const complex &c2); friend complex operator * (const complex &c1, const complex &c2); friend complex operator / (const complex &c1, const complex &c2); friend void print(const complex &c); private: double real, imag; }; complex operator + (const complex &c1, const complex &c2) { return complex(c1.real + c2.real, c1.imag + c2.imag); } complex operator - (const complex &c1, const complex &c2) { return complex(c1.real - c2.real, c1.imag - c2.imag); } complex operator * (const complex &c1, const complex &c2) { return complex(c1.real * c2.real - c1.imag * c2.imag, c1.real * c2.imag + c1.imag * c2.real); } complex operator / (const complex &c1, const complex &c2) { return complex((c1.real * c2.real + c1.imag * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag), (c1.imag * c2.real - c1.real * c2.imag) / (c2.real * c2.real + c2.imag * c2.imag)); } void print(const complex &c) { if (c.imag < 0) cout<<c.real<<c.imag<<'i'; else cout<<c.real<<" + "<<c.imag<<'i'; } int main() { complex c1(2.0, 3.0), c2(4.0, -2.0), c3; c3 = c1 + c2; cout<<"\nc1 + c2 = "; print(c3); c3 = c1 - c2; cout<<"\nc1 - c2 = "; print(c3); c3 = c1 * c2; cout<<"\nc1 * c2 = "; print(c3); c3 = c1 / c2; cout<<"\nc1 / c2 = "; print(c3); c3 = (c1+c2) * (c1-c2) * c2/c1; cout<<"\n(c1 + c2) * (c1 - c2) * c2 / c1 = "; print(c3); cout<<endl; }
b7ea26461674de1d30719e4b3a4ac5c14b3c46c3
a0bc9908be9d42d58af7a1a8f8398c2f7dcfa561
/SlonEngine/slon/Graphics/GPUSideMesh.h
0fda551e5b827182625cf1014a3e9d9fa86f36e6
[]
no_license
BackupTheBerlios/slon
e0ca1137a84e8415798b5323bc7fd8f71fe1a9c6
dc10b00c8499b5b3966492e3d2260fa658fee2f3
refs/heads/master
2016-08-05T09:45:23.467442
2011-10-28T16:19:31
2011-10-28T16:19:31
39,895,039
0
0
null
null
null
null
UTF-8
C++
false
false
13,819
h
GPUSideMesh.h
#ifndef __SLON_ENGINE_GRAPHICS_GPU_SIDE_MESH_H__ #define __SLON_ENGINE_GRAPHICS_GPU_SIDE_MESH_H__ #include <boost/shared_array.hpp> #include <boost/iterator/iterator_facade.hpp> #include <sgl/IndexBuffer.h> #include <sgl/Math/AABB.hpp> #include <sgl/Program.h> #include <sgl/VertexBuffer.h> #include <vector> #include "../Database/Serializable.h" #include "Detail/AttributeTable.h" #include "Effect.h" #include "Renderable.h" #include "Forward.h" namespace slon { namespace graphics { /** Mesh representation convenient for rendering */ class SLON_PUBLIC GPUSideMesh : public Referenced, public database::Serializable { public: static const int LOCK_READ = 1; static const int LOCK_WRITE = 1 << 1; class SLON_PUBLIC buffer_lock_impl { public: buffer_lock_impl(sgl::Buffer* buffer, const int mask); ~buffer_lock_impl(); void* data() { return ptr; } private: void* ptr; sgl::ref_ptr<sgl::Buffer> buffer; }; typedef boost::shared_ptr<buffer_lock_impl> buffer_lock; enum SEMANTIC { POSITION, NORMAL, TANGENT, COLOR, BONE_INDEX, BONE_WEIGHT, ATTRIBUTE, TEXCOORD, }; struct SLON_PUBLIC attribute { detail::AttributeTable::binding_ptr binding; unsigned size; unsigned offset; SEMANTIC semantic; sgl::SCALAR_TYPE type; }; typedef std::vector<attribute> attribute_vector; typedef attribute_vector::iterator attribute_iterator; typedef attribute_vector::const_iterator attribute_const_iterator; /** Description for constructing mesh. */ struct DESC { math::AABBf aabb; /// AABB covering mesh size_t vertexSize; /// Size of the vertex size_t numAttributes; /// Number of attributes in the mesh vertex buffer const attribute* attributes; /// Array of attributes sgl::IndexBuffer::INDEX_TYPE indexType; /// Type of the indices in the index buffer sgl::ref_ptr<sgl::VertexBuffer> vertexBuffer; /// Vertex buffer storing vertices sgl::ref_ptr<sgl::IndexBuffer> indexBuffer; /// Index buffer storing indices (can be NULL) }; struct SLON_PUBLIC subset : public Referenced, public Renderable { friend class GPUSideMesh; protected: subset(GPUSideMesh* _mesh) : mesh(_mesh) {} subset( GPUSideMesh* _mesh, Effect* _effect) : mesh(_mesh), effect(_effect) {} virtual ~subset() {} public: // Override Renderable Effect* getEffect() const { return effect.get(); } public: GPUSideMesh* mesh; effect_ptr effect; }; typedef boost::intrusive_ptr<subset> subset_ptr; typedef std::vector<subset_ptr> subset_vector; typedef subset_vector::iterator subset_iterator; typedef subset_vector::const_iterator subset_const_iterator; public: struct SLON_PUBLIC plain_subset : public subset { friend class GPUSideMesh; private: plain_subset( GPUSideMesh* mesh ) : subset(mesh) {} plain_subset( GPUSideMesh* mesh, Effect* effect, sgl::PRIMITIVE_TYPE _primitiveType, unsigned _startVertex, unsigned _numVertices ) : subset(mesh, effect), primitiveType(_primitiveType), startVertex(_startVertex), numVertices(_numVertices) {} public: // Override Renderable void render() const; public: sgl::PRIMITIVE_TYPE primitiveType; unsigned startVertex; unsigned numVertices; }; struct SLON_PUBLIC indexed_subset : public subset { friend class GPUSideMesh; private: indexed_subset( GPUSideMesh* mesh ) : subset(mesh) {} indexed_subset( GPUSideMesh* mesh, Effect* effect, sgl::PRIMITIVE_TYPE _primitiveType, unsigned _startIndex, unsigned _numIndices ) : subset(mesh, effect), primitiveType(_primitiveType), startIndex(_startIndex), numIndices(_numIndices) {} public: // Override Renderable void render() const; sgl::PRIMITIVE_TYPE getPrimitiveType() const { return primitiveType; } unsigned getStartIndex() const { return startIndex; } unsigned getNumIndices() const { return numIndices; } private: sgl::PRIMITIVE_TYPE primitiveType; unsigned startIndex; unsigned numIndices; }; typedef boost::intrusive_ptr<plain_subset> plain_subset_ptr; typedef boost::intrusive_ptr<indexed_subset> indexed_subset_ptr; template<typename T> class SLON_PUBLIC accessor { private: template<typename Y> class iterator_impl : public boost::iterator_facade< iterator_impl<Y>, Y, boost::random_access_traversal_tag > { private: friend class accessor; friend class boost::iterator_core_access; private: iterator_impl(void* data_, size_t offset, size_t stride_) : data((char*)data_), stride(stride_) { data += offset; } void increment() { data += stride; } void decrement() { data -= stride; } void advance(ptrdiff_t n) { data += stride * n; } ptrdiff_t distance_to(const iterator_impl& iter) const { assert( abs(iter.data - data) % stride == 0 ); return (iter.data - data) / static_cast<ptrdiff_t>(stride); } Y& dereference() const { return (*reinterpret_cast<Y*>(data)); } bool equal(const iterator_impl& iter) const { return data == iter.data && stride == iter.stride; } private: char* data; size_t stride; }; public: typedef iterator_impl<T> iterator; typedef iterator_impl<const T> const_iterator; public: accessor( GPUSideMesh* mesh_, attribute_const_iterator attr, const buffer_lock& lock_ ) : mesh(mesh_), lock(lock_), offset(attr->offset) { stride = mesh->getVertexSize(); } accessor( GPUSideMesh* mesh_, const buffer_lock& lock_ ) : mesh(mesh_), lock(lock_), offset(0) { stride = sizeof(T); } // item access T& operator [] (unsigned i) { return *reinterpret_cast<T*>( (char*)lock->data() + stride * i + offset); } const T& operator [] (unsigned i) const { return *reinterpret_cast<const T*>( (char*)lock->data() + stride * i + offset); } // iterator access iterator begin() { return iterator(lock->data(), offset, stride); } const_iterator begin() const { return iterator(lock->data(), offset, stride); } iterator end() { return begin() + size(); } const_iterator end() const { return begin() + size(); } size_t size() const { return mesh->getNumVertices(); } private: GPUSideMesh* mesh; buffer_lock lock; size_t stride; size_t offset; }; typedef accessor<math::Vector4f> vec4f_accessor; typedef accessor<math::Vector3f> vec3f_accessor; typedef accessor<math::Vector2f> vec2f_accessor; typedef accessor<float> float_accessor; typedef accessor<math::Vector4i> vec4i_accessor; typedef accessor<math::Vector3i> vec3i_accessor; typedef accessor<math::Vector2i> vec2i_accessor; typedef accessor<int> int_accessor; typedef accessor<unsigned int> uint_accessor; typedef accessor<math::Vector4s> vec4s_accessor; typedef accessor<math::Vector3s> vec3s_accessor; typedef accessor<math::Vector2s> vec2s_accessor; typedef accessor<short> short_accessor; typedef accessor<unsigned short> ushort_accessor; typedef accessor<math::Vector4c> vec4c_accessor; typedef accessor<math::Vector3c> vec3c_accessor; typedef accessor<math::Vector2c> vec2c_accessor; typedef accessor<char> char_accessor; typedef accessor<unsigned char> uchar_accessor; private: // noncopyable GPUSideMesh(const GPUSideMesh&); GPUSideMesh& operator = (const GPUSideMesh&); public: GPUSideMesh(); explicit GPUSideMesh(const DESC& desc); // Override Serializable const char* serialize(database::OArchive& ar) const; void deserialize(database::IArchive& ar); /** Add primitives subset to the mesh. * @param effect - effect for rendering subset. * @param primitiveType - sgl primitive type. * @param startVertex - starting vertex in the vertex array. * @param numVertices - number of vertices comprising the subset. */ plain_subset* addPlainSubset( Effect* effect, sgl::PRIMITIVE_TYPE primitiveType, unsigned startVertex, unsigned numVertices ); /** Add indexed subset to the mesh. * @param effect - effect for rendering subset. * @param primitiveType - sgl primitive type. * @param startIndex - start index in the index buffer. * @param numIndices - number of indices comprising the subset. */ indexed_subset* addIndexedSubset( Effect* effect, sgl::PRIMITIVE_TYPE primitiveType, unsigned startIndex, unsigned numIndices ); /** Remove subset from the mesh. * @return true if mesh successfully removed. */ bool removeSubset(subset* meshSubset); /** Get iterator addressing first vertex attribute definition. */ attribute_const_iterator firstAttribute() const { return attributes.begin(); } /** Get iterator addressing end vertex attribute definition. */ attribute_const_iterator endAttribute() const { return attributes.end(); } /** Get iterator addressing first subset of the mesh. */ subset_iterator firstSubset() { return subsets.begin(); } /** Get iterator addressing end subset of the mesh. */ subset_iterator endSubset() { return subsets.end(); } /** Get iterator addressing first subset of the mesh. */ subset_const_iterator firstSubset() const { return subsets.begin(); } /** Get iterator addressing end subset of the mesh. */ subset_const_iterator endSubset() const { return subsets.end(); } /** Get i'th mesh subset. */ subset& getSubset(unsigned i) { assert(i < subsets.size() ); return *subsets[i]; } /** Get circumscribed AABB. */ const math::AABBf& getBounds() const { return aabb; } /** Get size of the single vertex of the mesh. */ size_t getVertexSize() const { return vertexSize; } /** Get number of vertices in the mesh */ size_t getNumVertices() const { return vertexBuffer->Size() / vertexSize; } sgl::IndexBuffer::INDEX_TYPE getIndexType() const { return indexType; } /** Lock mesh vertex data. Lock fails if buffer is already locked. */ buffer_lock lockVertexBuffer(int mask) { return buffer_lock(new buffer_lock_impl(vertexBuffer.get(), mask)); } /** Lock mesh index data. Lock fails if buffer is already locked. */ buffer_lock lockIndexBuffer(int mask) { return buffer_lock(new buffer_lock_impl(indexBuffer.get(), mask)); } /** Clone mesh. * @param copyVBO - copy vertex buffer data (otherwise hold pointer). * @param copyIBO - copy index buffer data (otherwise hold pointer). */ gpu_side_mesh_ptr clone(bool copyVBO = false, bool copyIBO = false) const; private: void dirtyVertexLayout(); private: math::AABBf aabb; sgl::IndexBuffer::INDEX_TYPE indexType; sgl::ref_ptr<sgl::VertexLayout> vertexLayout; sgl::ref_ptr<sgl::VertexBuffer> vertexBuffer; sgl::ref_ptr<sgl::IndexBuffer> indexBuffer; size_t vertexSize; subset_vector subsets; attribute_vector attributes; }; } // namespace graphics } // namespace slon #endif // __SLON_ENGINE_GRAPHICS_GPU_SIDE_MESH_H__
3f2977e17cba47621fe00656dbb4a670ec1d3815
a84f78aa1ef38177d1754447804001c4901ba76b
/Surrounded Regions.cpp
eb6de0fff945f07a2dfc2ed41024ff4576e19d7f
[]
no_license
zungry/leetcodeCode
b2094dcc9b1349db65508e7a101c64d7f129e31a
2f58d6464e1e7a6d346d415dd9266b3c35ab13c5
refs/heads/master
2021-01-22T04:41:52.738919
2015-06-01T12:40:14
2015-06-01T12:40:14
27,812,266
0
0
null
null
null
null
UTF-8
C++
false
false
917
cpp
Surrounded Regions.cpp
class Solution { private: int rows; int cols; public: void dfs(int row, int col,vector<vector<char> >& board) { if(row < 0 || row >= rows || col < 0 || col >= cols) return; if(board[row][col] != 'O') return; board[row][col] = '+'; dfs(row - 1, col, board);//up dfs(row, col + 1, board);//right dfs(row + 1, col, board);//down dfs(row, col - 1, board);//left } void solve(vector<vector<char> > &board) { if(board.size() == 0 || board[0].size() == 0) return; rows = board.size(); cols = board[0].size(); for(int i = 0; i < rows; ++i){ dfs(i, 0, board); dfs(i, cols - 1, board); } for (int j = 0; j < cols; ++j) { dfs(0, j, board); dfs(rows - 1, j, board); } for(int i = 0; i < rows; ++i) for (int j = 0; j < cols; ++j) { if(board[i][j] == 'O') board[i][j] = 'X'; else if(board[i][j] == '+') board[i][j] = 'O'; } } };
e0c7e82116d6ab0eab24efc4246e35e8cb5adbf9
966a61375edbcba091b40470b3a5f64bde8e5ede
/header/DisplayNoWordCount.hpp
4939a886abc9f0466476e2a7ae32dcccce8d4173
[]
no_license
DJVonrhein/NotesProgram
b45992ee989d762f03a9da96ed70002a8f391ea0
06ff2b13ec889f2195819617eaefd2d7f61870df
refs/heads/master
2023-02-04T22:00:22.573219
2020-12-11T06:33:23
2020-12-11T06:33:23
325,421,284
0
0
null
null
null
null
UTF-8
C++
false
false
454
hpp
DisplayNoWordCount.hpp
#ifndef __DISPLAY_NO_WORD_COUNT_HPP__ #define __DISPLAY_NO_WORD_COUNT_HPP__ #include "DisplayStrat.hpp" #include "NotebookEntry.hpp" #include <iostream> #include <string> #include "Note.hpp" #include <fstream> #include <cstdlib> #include <cstring> using namespace std; class NotebookEntry; class DisplayStrat; class DisplayNoWordCount : public DisplayStrat { public: DisplayNoWordCount(); virtual void display(NotebookEntry* ); }; #endif
f1aae1f3d57b64025733ac5d2573b500ab94bfd4
dc26d617d97fa6a1fcb7cf14f0d0adb4f6fb7006
/opencv_laser/obj_generator.cpp
76d9748a9736609345e924abbc9b333888d15520
[]
no_license
ArtisticZhao/opencv_laser
c580cccadbe98ce744edd48b1faef3116d50e906
6cf180b7ce7ba1834b7baba31f06916320f4ea3f
refs/heads/master
2021-08-22T13:04:09.868885
2020-01-13T15:03:16
2020-01-13T15:03:16
189,351,635
3
3
null
null
null
null
GB18030
C++
false
false
6,493
cpp
obj_generator.cpp
#include "obj_generator.h" #include "vector2.h" #include "delaunay.h" #include "triangle.h" #include <fstream> Vector3d OBJ_Model::get_old_point(int index) { return this->points.at(index); } void OBJ_Model::add_point(Vector3d new_point, Vector2d new_uv, Vector2i volt) { this->points.push_back(new_point); this->uvs.push_back(new_uv); this->current_frame_index.push_back(this->uvs.size() - 1); this->volts.push_back(volt); cout << "[INFO]add new point: " << this->uvs.size() - 1 << endl; cout << new_point(0) << " " << new_point(1) << " " << new_point(2) << endl; } void OBJ_Model::add_old_point(int index) { this->current_frame_index.push_back(index); printf("[INFO]readd point: %d\n", index); } void OBJ_Model::create_new_frame() { cout << "new frame index:"; for (int i = 0; i < this->current_frame_index.size(); i++) { cout << " " << this->current_frame_index.at(i); } cout << endl; //----------使用 DT 算法对多边形进行分形 if (this->current_frame_index.size() < 3) { cout << "[ERROR] 当前平面的点数小于3!" << endl; vector<int>().swap(current_frame_index); // 清空当前平面vector return; } // 首先随便估算下该平面的法向量 Vector3d vnn = this->calc_normal_vector(this->current_frame_index.at(0), this->current_frame_index.at(1), this->current_frame_index.at(2)); // 找到平面法向量的最大值的位置, 这是投影方向 int direction = this->find_max_index(vnn); int projection_index1 = 0; int projection_index2 = 0; // 根据投影方向 找到索引值 switch (direction) { case 0: projection_index1 = 1; projection_index2 = 2; break; case 1: projection_index1 = 0; projection_index2 = 2; break; case 2: projection_index1 = 0; projection_index2 = 1; break; default: break; } vector<Vector2> dt_points; // 根据投影方向 投影三角形 for (int i = 0; i < this->current_frame_index.size(); i++) { dt_points.push_back(Vector2{ this->points.at(current_frame_index.at(i))(projection_index1), this->points.at(current_frame_index.at(i))(projection_index2) }); } Delaunay triangulation; vector<Triangle> triangles = triangulation.triangulate(dt_points); cout << "find triangles: " << triangles.size() << endl; if (triangles.size() > 0) { for (int i = 0; i < triangles.size(); i++) { int a_index = this->find_point(triangles.at(i).a->x, triangles.at(i).a->y, projection_index1, projection_index2); int b_index = this->find_point(triangles.at(i).b->x, triangles.at(i).b->y, projection_index1, projection_index2); int c_index = this->find_point(triangles.at(i).c->x, triangles.at(i).c->y, projection_index1, projection_index2); // 计算平面法向量 Vector3d vn = this->calc_normal_vector(a_index, b_index, c_index); this->triangle_frame.push_back(OBJ_Triangle{ vn, {a_index, b_index, c_index} }); } } vector<int>().swap(current_frame_index); // 清空当前平面vector } void OBJ_Model::save_obj() { // save obj ofstream outfile; outfile.open("data/1.obj"); // mtllib outfile << "mtllib testvt.mtl" << endl; // v 顶点数据 for (auto iter = this->points.begin(); iter != this->points.end(); iter++) { outfile << "v " << (*iter)(0) << " " << (*iter)(1) << " " << (*iter)(2) << endl; } // vt uv纹理数据 for (auto iter = this->uvs.begin(); iter != this->uvs.end(); iter++) { outfile << "vt " << (*iter)(0) << " " << (*iter)(1) << endl; } // vn 法线 for (auto iter = this->triangle_frame.begin(); iter != this->triangle_frame.end(); iter++) { outfile << "vn " << (*iter).vn(0) << " " << (*iter).vn(1) << " " << (*iter).vn(2) << endl; } // use mtl outfile << "usemtl xxx" << endl; // f outfile << "s off" << endl; for (int i = 0; i < this->triangle_frame.size(); i++) { outfile << "f " << this->triangle_frame.at(i).indexs[0] + 1 << "/" << this->triangle_frame.at(i).indexs[0] + 1 << "/" << i + 1 << " " << this->triangle_frame.at(i).indexs[1] + 1 << "/" << this->triangle_frame.at(i).indexs[1] + 1 << "/" << i + 1 << " " << this->triangle_frame.at(i).indexs[2] + 1 << "/" << this->triangle_frame.at(i).indexs[2] + 1 << "/" << i + 1 << endl; } // 关闭打开的文件 outfile.close(); cout << "[INFO] obj saved" << endl; } // 给DT算法之后用, 用于找出对应的顶点号, 只需要在current frame index 中索引的位置查找, 加快效率 int OBJ_Model::find_point(double x, double y, int pi1, int pi2) { int index = 0; for (auto iter = this->current_frame_index.begin(); iter != this->current_frame_index.end(); iter++){ index = (*iter); if (this->points.at(index)(pi1) == x && this->points.at(index)(pi2) == y) { return index; } } cout << "[ERROR] 未找到的顶点" << endl; return 0; } // 计算平面法向量 Vector3d OBJ_Model::calc_normal_vector(int a_index, int b_index, int c_index) { return (this->points.at(a_index) - this->points.at(b_index)).cross(this->points.at(c_index) - this->points.at(b_index)); } int OBJ_Model::find_max_index(Vector3d vnn) { double t; double max = (t = vnn(0) >= vnn(1) ? vnn(0) : vnn(1)) >= vnn(2) ? t : vnn(2); // debug cout << "max is " << max << endl << vnn << endl; if (max == vnn(0)) return 0; if (max == vnn(1)) return 1; if (max == vnn(2)) return 2; } void OBJ_Model::point_infos() { cout << "----------------------" << endl << "points size:" << this->points.size() << endl << "triangles size" << this->triangle_frame.size() << endl; cout << "----------------------" << endl; } void OBJ_Model::frame_from_file() { ifstream frame_file; frame_file.open("data/frame.txt"); char cmd[100]; char* p; vector<int>().swap(current_frame_index); // 清空当前平面vector while (frame_file.getline(cmd, 100)) { p = cmd; while (*p != EOF) { this->current_frame_index.push_back(stod(p)); p = strchr(p, ' '); if (p == NULL) { break; } p++; } this->create_new_frame(); } this->save_obj(); frame_file.close(); } void OBJ_Model::save_volts() { ofstream outfile; outfile.open("data/volts.txt"); // vt uv纹理数据 for (auto iter = this->volts.begin(); iter != this->volts.end(); iter++) { outfile<< (*iter)(0) << " " << (*iter)(1) << endl; } // 关闭打开的文件 outfile.close(); cout << "[INFO] volts saved" << endl; } void OBJ_Model::delete_point() { this->points.pop_back(); this->uvs.pop_back(); this->volts.pop_back(); this->current_frame_index.pop_back(); cout << "[INFO]delete a point: " << this->points.size() << endl; }
d90063af995e9df6b6a68e3d1a94a953e7aafa53
643abe992b0ffad9502dce56d986d975496421b0
/src/camera/QvkCameraWindow.cpp
bee6f1564425e052fd9cc2af6b1cc34e24558554
[]
no_license
feiser2016/vokoscreenNG
187f6c664bd8108b3c5fc9b987f4c5634917bdc4
13281aac11322e9e2022afa8c349555878477389
refs/heads/master
2020-04-20T10:18:31.506402
2019-02-01T16:25:02
2019-02-01T16:25:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,342
cpp
QvkCameraWindow.cpp
#include "QvkCameraWindow.h" #include <QPoint> QvkCameraWindow::QvkCameraWindow() { move( 0, 0 ); // Es wird ein move benötigt das das Fenster beim erneuten öffnen an der selben stelle erscheint setWindowFlags( Qt::WindowStaysOnTopHint ); setStyleSheet( "background-color:black;" ); widgetSize = QSize( 30, 30 ); margin = 10; widgetMenueBackground = new QvkWidgetMenueBackground( this ); widgetMenueBackground->setVisible( false ); myWidgetHelp = new QvkWidgetHelp( this ); myWidgetHelp->resize( widgetSize ); myWidgetHelp->setToolTip( tr( "Help" ) ); myWidgetHelp->setVisible( false ); myFrameWidget = new frameWidget( this ); myFrameWidget->resize( widgetSize ); myFrameWidget->setToolTip( tr( "Border" ) ); myFrameWidget->setVisible( false ); connect( myFrameWidget, SIGNAL( clicked( bool ) ), SLOT( slot_frameOnOff( bool ) ) ); mySettingsWidget = new QvkWidgetSettings( this ); mySettingsWidget->resize( widgetSize ); mySettingsWidget->setToolTip( tr( "Settings" ) ); mySettingsWidget->setVisible( false ); myWidgetExit = new QvkWidgetExit( this ); myWidgetExit->resize( widgetSize ); myWidgetExit->setToolTip( tr( "Close" ) ); myWidgetExit->setVisible( false ); connect( myWidgetExit, SIGNAL( clicked() ), SLOT( close() ) ); } QvkCameraWindow::~QvkCameraWindow() { } void QvkCameraWindow::closeEvent(QCloseEvent *event) { Q_UNUSED(event); emit signal_cameraWindow_close( false ); } void QvkCameraWindow::leaveEvent(QEvent *event) { Q_UNUSED(event); widgetMenueBackground->setVisible( false ); myWidgetHelp->setVisible( false ); myFrameWidget->setVisible( false ); mySettingsWidget->setVisible( false ); myWidgetExit->setVisible( false ); } void QvkCameraWindow::enterEvent(QEvent *event) { Q_UNUSED(event); widgetMenueBackground->setVisible( true ); myWidgetHelp->setVisible( true ); myFrameWidget->setVisible( true ); mySettingsWidget->setVisible( true ); myWidgetExit->setVisible( true ); } void QvkCameraWindow::resizeEvent(QResizeEvent *event) { Q_UNUSED(event); widgetMenueBackground->setGeometry( width() - margin/2 - widgetSize.width() - margin/2, margin/2, widgetSize.width() + margin/2, height() - margin ); myWidgetHelp->move( this->width() - widgetSize.width() - margin, 1*margin ); myFrameWidget->move( this->width() - widgetSize.width() - margin, 2*margin + 1*widgetSize.height() ); mySettingsWidget->move( this->width() - widgetSize.width() - margin, 3*margin + 2*widgetSize.height() ); myWidgetExit->move( this->width() - widgetSize.width() - margin, 4*margin + 3*widgetSize.height() ); } void QvkCameraWindow::slot_frameOnOff( bool value ) { if ( value == true ) { this->setWindowFlags( Qt::Window | Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint ); } if ( value == false ) { this->setWindowFlags( Qt::Window | Qt::WindowStaysOnTopHint ); } show(); } void QvkCameraWindow::slot_set160x120() { resize( 160, 120 ); } void QvkCameraWindow::slot_set320x240() { resize( 320, 240 ); } void QvkCameraWindow::slot_set640x480() { resize( 640, 480 ); }
6a86b6c4acb5753c07744b7ec90082e122911cd5
bf36d45da89f495294b499ae70b0465e2a4e097f
/Misc.h
2ff194e0844cb09b4ca24ba89c9857a4a03f3e42
[]
no_license
Shadowmeth/Network_Emulator
4971679095d5c0227c119a6bff2c894e3bd49579
91b62ab87382347a819bd6a0f3c62d68deaec69d
refs/heads/main
2023-07-03T17:14:04.265168
2021-07-30T11:11:37
2021-07-30T11:11:37
391,034,095
0
0
null
null
null
null
UTF-8
C++
false
false
1,374
h
Misc.h
#pragma once #include <string> struct Msg { int id; // unique id int priority; // 1 to 10 std::string sourceAddress; // senders machine name std::string destinationAddress; // receivers machine name std::string payload; // the actual data/message std::string trace; // contains the path taken from start machine to the end machine }; // array of pairs class Set { private: int size; std::string* setData; public: Set() { size = 0; setData = nullptr; } int getSize() { return size; } std::string getData(int index) { return setData[index]; } // simple linear search through the array bool alreadyExists(std::string& data) { for (int i = 0; i < size; i++) { if (data == setData[i]) { return true; } } return false; } bool push(std::string& data) { if (!alreadyExists(data)) { if (size == 0) { size++; setData = new std::string[size]; setData[0] = data; } else { std::string* temp = new std::string[size + 1]; for (int i = 0; i < size; i++) { temp[i] = setData[i]; } temp[size] = data; delete[] setData; size++; setData = temp; } return true; } return false; } void clear() { delete[] setData; setData = nullptr; size = 0; } ~Set() { delete[] setData; } };
fe8f3f17174130030d9fa51a1115a5a000679479
4ebc59e5ba5668f3a8b8a3716b800933edebd082
/Homework/Assignment_5/Gaddis_8thEd_Chap5_Prob2_AscciCode/main.cpp
3adc95b5224185cfa57aaf981fd682527d9425c0
[]
no_license
hdiego47/HernandezDiego_CIS5_Spring2017
aae2154e9055ee4e6f0865d82db32c99cea24e72
428a615b8d541b9039f86bf706a8b5b4aa7211ed
refs/heads/master
2020-05-18T13:01:05.196914
2017-05-30T19:13:40
2017-05-30T19:13:40
84,238,691
0
0
null
null
null
null
UTF-8
C++
false
false
629
cpp
main.cpp
/* * File: main.cpp * Author: Diego Hernandez * Created on March 30, 2017, 10:35 AM * Purpose: Display the Ascii character set */ //System Libraries #include <iostream> //Imput - Output Library using namespace std; //Namespace under which system libraries exist //User Libraries //Global Constants //Function Prototypes //Execution begins here int main(int argc, char** argv) { //Map inputs to outputs or process the data for(int i=0;i<=127;i++){ cout<<static_cast<char>(i); if(i%16==15)cout<<endl; } //Output the transformed data //Exit stage right! return 0; }
92d88e5a9d68ef2e88046bc864a0c933f4ef8ce5
d4a95622b71886b009c1700455744d36740d91b8
/objectc++/kurs2/question.h
2e3ba29e2aa94a5fef86a34921f7a76627d3a715
[]
no_license
Matthew5U/courses
907fe848b9aafdf4a890e72453c249647599dccc
154d7a5415d20ac6e10810bdd273fbc120be4c7e
refs/heads/master
2022-05-27T18:54:06.523486
2020-03-14T15:30:43
2020-03-14T15:30:43
245,460,535
0
0
null
2020-04-30T11:16:36
2020-03-06T15:56:02
C++
UTF-8
C++
false
false
773
h
question.h
#include <iostream> using namespace std; class Question { public: string contents; // tresc pytania string a, b, c, d; // odpowiedzi int number; // numer pytania string correct; // poprawna odpowiedz na pytanie string answer; // odpowiedz uzytkownika int point; // (1 albo 0) zmienna odpowiedzialna za zliczanie punktow za poprawna odpoweidz // nie dozwolone inicjalizacja zmiennej w klasie, mozna to zrobic tylko przez //metodenie dozwolone inicjalizacja zmiennej w klasie, mozna to zrobic tylko //przez metode ( uzycie konstruktora) // METODY void load(); // wczytuje dane z pliku void ask(); // pokazuje pytanie, czyta odpowiedzi void check(); // sprawdz poprwanosc podanej odpowiedzi };
cdbd8ad6c5849dd3ad354e66147eea7921af05c3
986ad3e8419f87f189275709de8b6cae0c19a044
/src/nodes/angleNodes/doubleToAngleArrayNode.cpp
2338984cecb6a7cd5781d2206c6478817b090802
[ "MIT" ]
permissive
dseeni/xformArrayNodes
5f6ed2187a92a4140cbe3b15c2e66f3bb46c57a0
2affb8c1818255c3e86d766a91a978bcdca819b9
refs/heads/master
2023-03-16T18:31:28.306400
2018-02-25T18:12:04
2018-02-25T18:12:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,070
cpp
doubleToAngleArrayNode.cpp
/** Copyright (c) 2017 Ryan Porter You may use, distribute, or modify this code under the terms of the MIT license. */ /** doubleToAngleArray node This node converts an array of double values to an array of doubleAngle values. input (i) doubleArray An array of double values. output (o) angleArray An array of doubleAngle values. */ #include "../../data/angleArrayData.h" #include "../nodeData.h" #include "doubleToAngleArrayNode.h" #include <vector> #include <maya/MDataBlock.h> #include <maya/MDoubleArray.h> #include <maya/MFnData.h> #include <maya/MFnDoubleArrayData.h> #include <maya/MFnTypedAttribute.h> #include <maya/MPlug.h> #include <maya/MPxNode.h> #include <maya/MString.h> #include <maya/MTypeId.h> MObject DoubleToAngleArrayNode::inputAttr; MObject DoubleToAngleArrayNode::outputAttr; void* DoubleToAngleArrayNode::creator() { return new DoubleToAngleArrayNode(); } MStatus DoubleToAngleArrayNode::initialize() { MStatus status; MFnTypedAttribute T; inputAttr = T.create("input", "i", MFnData::kDoubleArray, MObject::kNullObj, &status); addAttribute(inputAttr); outputAttr = T.create("output", "o", AngleArrayData::TYPE_ID, MObject::kNullObj, &status); T.setStorable(false); addAttribute(outputAttr); attributeAffects(inputAttr, outputAttr); return MStatus::kSuccess; } MStatus DoubleToAngleArrayNode::compute(const MPlug& plug, MDataBlock& data) { MStatus status; if (plug != outputAttr) { return MStatus::kInvalidParameter; } MDataHandle inputHandle = data.inputValue(inputAttr); std::vector<double> input = getMayaArray<double, MFnDoubleArrayData>(inputHandle); std::vector<MAngle> output(input.size()); MAngle::Unit unit = MAngle::uiUnit(); for (size_t i = 0; i < input.size(); i++) { output[i] = MAngle(input[i], unit); } MDataHandle outputHandle = data.outputValue(outputAttr); setUserArray<MAngle, AngleArrayData>(outputHandle, output); return MStatus::kSuccess; }
bec38793f254865c51f5359d2689919d42a47a36
ff1f8e352bcbf059e2c1c0aaafff120c56f3cf49
/Luogu/LuoguP3721.cpp
6a0e8b5a7dd76306c61925b27eda2530366f70d7
[]
no_license
keywet06/code
040bc189fbabd06fc3026525ae3553cd4f395bf3
fe0d570144e580f37281b13fd4106438d3169ab9
refs/heads/master
2022-12-19T12:12:16.635994
2022-11-27T11:39:29
2022-11-27T11:39:29
182,518,309
6
1
null
null
null
null
UTF-8
C++
false
false
1,853
cpp
LuoguP3721.cpp
#include <bits/stdc++.h> const int N = 200005; int cnt, m, c, k; int son[N][2], fa[N], plus[N], max[N], min[N], opt[N], val[N], lsh[N], p[N], to[N]; void build(int v, int l, int r); void pushup(int v); void pushdown(int v); void insert(int v, int x, int l, int r, int lm, int rm); inline void build(int v, int l, int r) { if (l == r) { to[l] = v; p[v] = l; return; } int mid = l + r >> 1; build(v << 1, l, mid); build(v << 1 | 1, mid + 1, r); } inline void pushup(int v) { max[v] = max[v << 1 | 1] ? max[v << 1 | 1] : max[v << 1]; min[v] = min[v << 1] ? min[v << 1] : min[v << 1 | 1]; } inline void pushdown(int v) { plus[v << 1] += plus[v]; plus[v << 1 | 1] += plus[v]; plus[v] = 0; } inline void insert(int v, int x, int l, int r, int lm, int rm) { if (l == r) { fa[l] = std::max(lm, rm); min[v] = max[v] = plus[v] = l; son[fa[l]][lm < rm] = l; return; } int mid = l + r >> 1; pushdown(v); if (x <= mid) { insert(v << 1, x, l, mid, lm, min[son[v][1]] ? min[son[v][1]] : rm); } else { insert(v << 1 | 1, x, mid + 1, r, max[son[v][0]] ? max[son[v][0]] : lm, rm); } pushup(v); } int main() { std::ios::sync_with_stdio(0); std::cin.tie(0); std::cout.tie(0); std::cin >> m; for (int i = 1; i <= m; ++i) { std::cin >> opt[i]; if (opt[i] == 1) { std::cin >> val[i]; lsh[cnt++] = i; } } std::sort(lsh, lsh + cnt, [](int x, int y) { return val[x] < val[y]; }); for (int i = 0; i < cnt; ++i) { val[lsh[i]] = i + 1; } build(1, 1, cnt); for (int i = 1; i <= m; ++i) { if (opt[i] == 1) { insert(1, val[i], 1, cnt, 0, 0); } else if (opt[i] == 2) { } } return 0; }
96a6a268282a35c1788704f2d2bc3376c2d718b6
a17f2f1a8df7036c2ea51c27f31acf3fb2443e0b
/uva/UVA10129 Play on Words.cpp
fdc02237080e99086f64d5f744ea81fb0bd33f53
[]
no_license
xUhEngwAng/oj-problems
c6409bc6ba72765600b8a844b2b18bc9a4ff6f6b
0c21fad1ff689cbd4be9bd150d3b30c836bd3753
refs/heads/master
2022-11-04T01:59:08.502480
2022-10-18T03:34:41
2022-10-18T03:34:41
165,620,152
3
1
null
null
null
null
UTF-8
C++
false
false
2,126
cpp
UVA10129 Play on Words.cpp
#include <string> #include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; /* * 此题我觉得非常巧妙,是用欧拉环路来做的。具体说来,将26个 * 可能出现的字符作为图中的节点,对于每一个单词,即建立了 * 从首字符到尾字符的一条路径。这个题就是要找对于这样一张图, * 是否存在一条欧拉路径。 * * 我一开始的做法只是分别将首尾字符出现的数量各自存储在两个 * hashtable 当中,然后判断两者的差距是否 <= 2。然而考虑下 * 面一种情况: aa bb,此时两个 hashtable 完全相同,而这个 * 输入则是不可行的。 * * 究其原因,是我忽略了存在欧拉环路的充要条件,乃是 * * 1. 除了起点终点外,所有其他节点的入度都等于出度。起点可以 * 出度比入度大一,终点反之。 * 2. 图是连通的。 * * 上述情况正是因为图不连通而造成的。 */ vector<int> head(26), tail(26); vector<set<int>> graph; vector<bool> visited(26); void dfs(int src){ visited[src] = true; for(int e : graph[src]) if(!visited[e]) dfs(e); } int main(){ //freopen("1.out", "w", stdout); int T, N, diff, src, ix; bool isconnect; cin >> T; string str; while(T--){ cin >> N; fill(head.begin(), head.end(), 0); fill(tail.begin(), tail.end(), 0); fill(visited.begin(), visited.end(), false); graph.clear(); graph.resize(26); for(int ix = 0; ix != N; ++ix){ cin >> str; head[str.front() - 'a']++; tail[str.back() - 'a']++; graph[str.front() - 'a'].insert(str.back() - 'a'); } diff = 0; ix = 0; while(!head[ix]) ++ix; src = ix; for(;ix != 26; ++ix){ if(tail[ix] < head[ix]) src = ix; diff += abs(head[ix] - tail[ix]); } dfs(src); isconnect = true; for(int ix = 0; ix != 26; ++ix){ if(!head[ix] && !tail[ix]) continue; if(!visited[ix]){ isconnect = false; break; } } if(diff > 2 || !isconnect) cout << "The door cannot be opened." << endl; else cout << "Ordering is possible." << endl; } return 0; }
e1bdabae3033cb28f35fe13a4fbaf3dd131f95e6
a00ba558bd947cf8782458ca37a4949c842aceb0
/source/mpi/mpi_commands.hpp
bf9bc4fa522c6e5831abd48383a4918e60630767
[]
no_license
patrickbergel/huji-rich
bda83962d08ac160e722437153bf93b5045d37dd
08509250aec1ffdfa744515ddbef6a835c053f5a
refs/heads/master
2020-05-19T11:48:24.597748
2019-01-22T15:28:16
2019-01-22T15:28:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,964
hpp
mpi_commands.hpp
#ifndef MPI_COMMANDS_HPP #define MPI_COMMANDS_HPP 1 #ifdef RICH_MPI #include <vector> #include <mpi.h> #include "../newtonian/two_dimensional/computational_cell_2d.hpp" #include "../newtonian/two_dimensional/extensive.hpp" #include "../tessellation/tessellation.hpp" #include "../misc/serializable.hpp" #include "../misc/utils.hpp" using std::vector; /*! \brief Sends and revs data \param tess The tessellation \param cells The data to send/recv \param ghost_or_sent True for ghost cells false for sent cells. */ template<class T> void MPI_exchange_data(const Tessellation& tess, vector<T>& cells,bool ghost_or_sent) { if (cells.empty()) throw UniversalError("Empty cell vector in MPI_exchange_data"); T example_cell = cells[0]; vector<int> correspondents; vector<vector<int> > duplicated_points; if (ghost_or_sent) { correspondents = tess.GetDuplicatedProcs(); duplicated_points = tess.GetDuplicatedPoints(); } else { correspondents = tess.GetSentProcs(); duplicated_points = tess.GetSentPoints(); } vector<MPI_Request> req(correspondents.size()); vector<vector<double> > tempsend(correspondents.size()); vector<double> temprecv; double temp = 0; for (size_t i = 0; i < correspondents.size(); ++i) { bool isempty = duplicated_points[i].empty(); if(!isempty) tempsend[i] = list_serialize(VectorValues(cells, duplicated_points[i])); int size = static_cast<int>(tempsend[i].size()); if (size == 0) MPI_Isend(&temp, 1, MPI_DOUBLE, correspondents[i], 4, MPI_COMM_WORLD, &req[i]); else MPI_Isend(&tempsend[i][0], size, MPI_DOUBLE, correspondents[i], 5, MPI_COMM_WORLD, &req[i]); } const vector<vector<int> >& ghost_indices = tess.GetGhostIndeces(); if (ghost_or_sent) cells.resize(tess.GetTotalPointNumber(),cells[0]); else cells = VectorValues(cells, tess.GetSelfPoint()); vector<vector<T> > torecv(correspondents.size()); for (size_t i = 0; i < correspondents.size(); ++i) { MPI_Status status; MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int count; MPI_Get_count(&status, MPI_DOUBLE, &count); temprecv.resize(static_cast<size_t>(count)); MPI_Recv(&temprecv[0], count, MPI_DOUBLE, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if (status.MPI_TAG == 5) { size_t location = static_cast<size_t>(std::find(correspondents.begin(), correspondents.end(), status.MPI_SOURCE) - correspondents.begin()); if (location >= correspondents.size()) throw UniversalError("Bad location in mpi exchange"); torecv[location] = list_unserialize(temprecv, example_cell); } else { if (status.MPI_TAG != 4) throw UniversalError("Recv bad mpi tag"); } } for (size_t i = 0; i < correspondents.size(); ++i) { if (ghost_or_sent) { for (size_t j = 0; j < torecv[i].size(); ++j) cells.at(ghost_indices.at(i).at(j)) = torecv[i][j]; } else { for (size_t j = 0; j < torecv[i].size(); ++j) cells.push_back(torecv[i][j]); } } if(req.size()>0) MPI_Waitall(static_cast<int>(correspondents.size()), &req[0], MPI_STATUSES_IGNORE); MPI_Barrier(MPI_COMM_WORLD); } /*! \brief Sends and revs data \param totalkwith The cpus to talk with \param tosend The indeces in data to send ordered by cpu \param cells The data to send \return Th recv data ordered by cpu */ template <class T> vector<vector<T> > MPI_exchange_data(const vector<int>& totalkwith,vector<vector<int> > const& tosend, vector<T>const& cells) { vector<MPI_Request> req(totalkwith.size()); vector<vector<double> > tempsend(totalkwith.size()); vector<double> temprecv; double temp = 0; for (size_t i = 0; i < totalkwith.size(); ++i) { bool isempty = tosend[i].empty(); if (!isempty) tempsend[i] = list_serialize(VectorValues(cells, tosend[i])); int size = static_cast<int>(tempsend[i].size()); if (size == 0) MPI_Isend(&temp, 1, MPI_DOUBLE, totalkwith[i], 4, MPI_COMM_WORLD, &req[i]); else MPI_Isend(&tempsend[i][0], size, MPI_DOUBLE, totalkwith[i], 5, MPI_COMM_WORLD, &req[i]); } vector<vector<T> > torecv(totalkwith.size()); for (size_t i = 0; i < totalkwith.size(); ++i) { MPI_Status status; MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int count; MPI_Get_count(&status, MPI_DOUBLE, &count); temprecv.resize(static_cast<size_t>(count)); MPI_Recv(&temprecv[0], count, MPI_DOUBLE, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if (status.MPI_TAG == 5) { size_t location = static_cast<size_t>(std::find(totalkwith.begin(), totalkwith.end(), status.MPI_SOURCE) - totalkwith.begin()); if (location >= totalkwith.size()) throw UniversalError("Bad location in mpi exchange"); torecv[location] = list_unserialize(temprecv, cells[0]); } else { if (status.MPI_TAG != 4) throw UniversalError("Recv bad mpi tag"); } } if(req.size()>0) MPI_Waitall(static_cast<int>(totalkwith.size()), &req[0], MPI_STATUSES_IGNORE); MPI_Barrier(MPI_COMM_WORLD); return torecv; } /*! \brief Sends and revs data \param totalkwith The cpus to talk with \param cells The data to send ordered bys cpu \param example An example cell for serialization \return The recv data ordered by cpu */ template <class T> vector<vector<T> > MPI_exchange_data(const vector<int>& totalkwith, vector<vector<T> > const& cells,T const& example) { vector<MPI_Request> req(totalkwith.size()); vector<vector<double> > tempsend(totalkwith.size()); vector<double> temprecv; double temp = 0; for (size_t i = 0; i < totalkwith.size(); ++i) { bool isempty = cells[i].empty(); if (!isempty) tempsend[i] = list_serialize(cells[i]); int size = static_cast<int>(tempsend[i].size()); if (size == 0) MPI_Isend(&temp, 1, MPI_DOUBLE, totalkwith[i], 4, MPI_COMM_WORLD, &req[i]); else MPI_Isend(&tempsend[i][0], size, MPI_DOUBLE, totalkwith[i], 5, MPI_COMM_WORLD, &req[i]); } vector<vector<T> > torecv(totalkwith.size()); for (size_t i = 0; i < totalkwith.size(); ++i) { MPI_Status status; MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int count; MPI_Get_count(&status, MPI_DOUBLE, &count); temprecv.resize(static_cast<size_t>(count)); MPI_Recv(&temprecv[0], count, MPI_DOUBLE, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); if (status.MPI_TAG == 5) { size_t location = static_cast<size_t>(std::find(totalkwith.begin(), totalkwith.end(), status.MPI_SOURCE) - totalkwith.begin()); if (location >= totalkwith.size()) throw UniversalError("Bad location in mpi exchange"); torecv[location] = list_unserialize(temprecv, example); } else { if (status.MPI_TAG != 4) throw UniversalError("Recv bad mpi tag"); } } MPI_Waitall(static_cast<int>(totalkwith.size()), &req[0], MPI_STATUSES_IGNORE); MPI_Barrier(MPI_COMM_WORLD); return torecv; } /*! \brief Sends and recvs data \param tess The tessellation \param cells The data to send/recv outermost vector defines the processors. \param example An example type T, used in order to serialize. \return The recv data ordered by cpu */ template<class T> vector<vector<vector<T> > > MPI_exchange_data(const Tessellation& tess, vector<vector<vector<T> > > const& cells, T const& example) { vector<int> correspondents = tess.GetDuplicatedProcs(); vector<vector<vector<T> > > res(correspondents.size()); vector<MPI_Request> req(2*correspondents.size()); vector<vector<double> > tempsend(correspondents.size()); vector<vector<int> > send_sizes(tempsend.size()); // vector<double> temprecv; // vector<int> tempirecv; double temp = 0; for (size_t i = 0; i < correspondents.size(); ++i) { bool isempty = cells[i].empty(); if (!isempty) { send_sizes[i].reserve(cells[i].size()); tempsend[i].reserve(cells[i].size()*cells[i][0][0].getChunkSize()); for (size_t j = 0; j < cells[i].size(); ++j) { send_sizes[i].push_back(static_cast<int>(cells[i][j].size())); vector<double> dtemp = list_serialize(cells[i][j]); tempsend[i].insert(tempsend[i].end(), dtemp.begin(), dtemp.end()); } } else send_sizes[i].push_back(-1); int size = static_cast<int>(tempsend[i].size()); if (size == 0) { MPI_Isend(&temp, 1, MPI_DOUBLE, correspondents[i], 4, MPI_COMM_WORLD, &req[2 * i]); MPI_Isend(&send_sizes[i][0], 1, MPI_INT, correspondents[i], 5, MPI_COMM_WORLD, &req[2 * i + 1]); } else { MPI_Isend(&tempsend[i][0], size, MPI_DOUBLE, correspondents[i], 6, MPI_COMM_WORLD, &req[2 * i]); MPI_Isend(&send_sizes[i][0], static_cast<int>(send_sizes[i].size()), MPI_INT, correspondents[i], 7, MPI_COMM_WORLD, &req[2 * i + 1]); } } vector<vector<double> > drecv(correspondents.size()); vector<vector<int> > irecv(correspondents.size()); for (size_t i = 0; i < 2*correspondents.size(); ++i) { MPI_Status status; MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status); int count; if (status.MPI_TAG % 2 == 0) { MPI_Get_count(&status, MPI_DOUBLE, &count); size_t location = static_cast<size_t>(std::find(correspondents.begin(), correspondents.end(), status.MPI_SOURCE) - correspondents.begin()); if (location >= correspondents.size()) throw UniversalError("Bad location in mpi exchange"); drecv[location].resize(static_cast<size_t>(count)); MPI_Recv(&drecv[location][0], count, MPI_DOUBLE, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } else { MPI_Get_count(&status, MPI_INT, &count); size_t location = static_cast<size_t>(std::find(correspondents.begin(), correspondents.end(), status.MPI_SOURCE) - correspondents.begin()); if (location >= correspondents.size()) throw UniversalError("Bad location in mpi exchange"); irecv[location].resize(static_cast<size_t>(count)); MPI_Recv(&irecv[location][0], count, MPI_INT, status.MPI_SOURCE, status.MPI_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } } for (size_t i = 0; i < correspondents.size(); ++i) { size_t counter = 0; for (size_t j = 0; j < irecv[i].size(); ++j) { if (irecv[i][j] > 0) { size_t to_read = static_cast<size_t>(irecv[i][j] * example.getChunkSize()); vector<double> dtemp(drecv[i].begin() + counter, drecv[i].begin() + counter + to_read); counter += to_read; res[i].push_back(list_unserialize(dtemp, example)); } } } MPI_Waitall(static_cast<int>(2*correspondents.size()), &req[0], MPI_STATUSES_IGNORE); MPI_Barrier(MPI_COMM_WORLD); return res; } /*! \brief Sends and recvs data \param tess The tessellation \param cells The data to send/recv outermost vector defines the processors. \return The recv data ordered by cpu */ vector<vector<vector<int> > > MPI_exchange_data(const Tessellation& tess, vector<vector<vector<int> > > const& cells); vector<vector<double> > MPI_exchange_data(const vector<int>& totalkwith, vector<vector<double> > &tosend); vector<vector<int> > MPI_exchange_data(const vector<int>& totalkwith, vector<vector<int> > &tosend); #endif //RICH_MPI #endif // MPI_COMMANDS_HPP
0d1d82887908c53d5c6a48d21dfeb101f0f35b13
0cf5d5bb15e448df7a2f30395af53c362055b97a
/camera.cpp
0efa0546629de956c0bca7c93d9a833ed5fe8170
[]
no_license
guilhermevmelo/TrabalhoDeCg
323ebed207238915922deb3598e356f4820ffa1f
1262c54b346b07766eced6cef016b7bc967a9a06
refs/heads/master
2021-01-10T11:00:03.565069
2016-02-16T14:06:46
2016-02-16T14:06:46
51,665,397
2
0
null
null
null
null
UTF-8
C++
false
false
773
cpp
camera.cpp
#include "camera.h" Camera::Camera(Vector position, Vector look_at, Vector up):camera_position(position), camera_direction(look_at) { Vector diff_btw (camera_position.x() - look_at.x(), camera_position.y() - look_at.y(), camera_position.z() - look_at.z()); camera_direction = diff_btw.negative().normalize(); camera_right = camera_direction.crossProduct(up).normalize(); camera_down = camera_right.crossProduct(camera_direction); } Ray Camera::createRay(double xamnt, double yamnt) { Vector camera_ray_direction = camera_direction.add(camera_right.multiply(xamnt - 0.5).add(camera_down.multiply(yamnt - 0.5))).normalize(); Ray camera_ray(camera_position, camera_ray_direction); return camera_ray; }
cca5aee45736a52d6dca5a44ee6e15f47a5dff00
50c10d3a89cbad20ace5c1fcda6ac2996753a365
/NNIE_BOARD/MT_O_NET.cpp
e9756360e032eee90b0fdb4bea6a20aa365e0a1e
[]
no_license
pighead1016/NNIE_BOARD
e0e472ebf98fd11f775f20adf5f9b4056063cf78
d3f685b5de91c6e5cff8c4ffc25903b29a5a1041
refs/heads/master
2021-05-20T14:45:43.088178
2020-04-02T02:45:43
2020-04-02T02:45:43
252,337,521
1
0
null
null
null
null
UTF-8
C++
false
false
3,596
cpp
MT_O_NET.cpp
#include "MT_O_NET.h" MT_O_NET::MT_O_NET() { } MT_O_NET::~MT_O_NET() { } HI_S32 MT_O_NET::INIT(HI_CHAR * pszModelFile) { HI_S32 s32Ret = NNIE_NET_INIT(pszModelFile); return s32Ret; } HI_S32 MT_O_NET::INIT(HI_CHAR * pszModelFile, HI_CHAR * matFile) { HI_S32 s32Ret = NNIE_NET_INIT(pszModelFile); this->Read_weight_bias(matFile); return s32Ret; } HI_S32 MT_O_NET::INIT(HI_CHAR * buffer, HI_U64 size) { HI_S32 s32Ret = NNIE_NET_INIT(buffer,size); return s32Ret; } HI_S32 MT_O_NET::Confirm_bboxes(const cv::Mat core_img, const cv::Rect in_bbox, cv::Rect & out_bbox, float & socer, const float thres, float pad, HI_U8 Seg) { int padding_width = pad * core_img.cols; int padding_height = pad * core_img.rows; cv::Mat pading_img(padding_height * 2 + core_img.rows, padding_width * 2 + core_img.cols, core_img.type()); core_img.copyTo(pading_img(cv::Rect(padding_width, padding_height, core_img.cols, core_img.rows))); cv::Rect pad_rect(padding_width + in_bbox.x, padding_height + in_bbox.y, in_bbox.width, in_bbox.height); if (pad_rect.x < 0 || pad_rect.x + pad_rect.width >= pading_img.cols || pad_rect.y < 0 || pad_rect.y + pad_rect.height >= pading_img.rows) { socer = -1; return HI_FAILURE; } HI_S32 *data; cv::Mat temp = pading_img(pad_rect); SAMPLE_SVP_NNIE_INPUT_DATA_INDEX_S input_index = { 0,0 }; SAMPLE_SVP_NNIE_PROCESS_SEG_INDEX_S process_index = { 0,0 }; SVP_FillSrcData_Mat(&input_index, temp); SAMPLE_SVP_NNIE_Forward(&input_index, &process_index); data = (HI_S32 *)(astSegData[process_index.u32SegIdx].astDst[process_index.u32NodeIdx].u64VirAddr); if (!this->weight_matrix.empty() || !bias_matrix.empty()) { //cv::Mat seg1_in = Inner(data, true); input_index = { 1,0 }; process_index = { 1,0 }; Inner(data, (void*)astSegData[input_index.u32SegIdx].astSrc[input_index.u32NodeIdx].u64VirAddr, true); //memcpy((void*)astSegData[input_index.u32SegIdx].astSrc[input_index.u32NodeIdx].u64VirAddr,(void*)seg1_in.data,astSegData[input_index.u32SegIdx].astSrc[input_index.u32NodeIdx].u32Stride); SAMPLE_SVP_CHECK_EXPR_TRACE(astSegData[input_index.u32SegIdx].astSrc[input_index.u32NodeIdx].u32Stride != 4* astSegData[input_index.u32SegIdx].astSrc[input_index.u32NodeIdx].unShape.stWhc.u32Width, SAMPLE_SVP_ERR_LEVEL_FATAL,"Error,seg input width failed!\n"); #if ((defined __arm__) || (defined __aarch64__)) && defined HISI_CHIP HI_MPI_SYS_MmzFlushCache(astSegData[input_index.u32SegIdx].astSrc[input_index.u32NodeIdx].u64PhyAddr, SAMPLE_SVP_NNIE_CONVERT_64BIT_ADDR(HI_VOID, astSegData[input_index.u32SegIdx].astSrc[input_index.u32NodeIdx].u64VirAddr),astSegData[input_index.u32SegIdx].astSrc[input_index.u32NodeIdx].u32Stride); #endif SAMPLE_SVP_NNIE_Forward(&input_index, &process_index); data = (HI_S32 *)(astSegData[process_index.u32SegIdx].astDst[process_index.u32NodeIdx].u64VirAddr); } if (data[1] > thres * 4096 && data[1] <= 4096) { float sn = data[2] / 4096.f; float xn = data[3] / 4096.f; float yn = data[4] / 4096.f; int crop_x = pad_rect.x; int crop_y = pad_rect.y; int crop_w = pad_rect.width; int rw = int(sn * crop_w); int rx = int(crop_x - 0.5 * sn * crop_w + crop_w * sn * xn + 0.5 * crop_w); int ry = int(crop_y - 0.5 * sn * crop_w + crop_w * sn * yn + 0.5 * crop_w); if (rx >= 0 && rx + rw < pading_img.cols && ry >= 0 && ry + rw < pading_img.rows) { out_bbox.x = rx - padding_width; out_bbox.y = ry - padding_height; out_bbox.width = rw; out_bbox.height = rw; socer = data[1] / 4096.f; } else { socer = -1; } } else { socer = 0; } return HI_SUCCESS; }
4710ce204e02c326d1b81365b5f165c0230e3de0
f04ceb0d2d99968874d3c4b88870fac6966d95eb
/ProjectSolver.h
f7dd1f1e644b4e70821a95f94438096a104ffba5
[]
no_license
QuentinLisack/Stable-Fluid
c8942bec134a29b394281764c018be2032bd302a
44cc74dac3838c93f6e77db82967d377bbf9bdb3
refs/heads/master
2021-01-10T16:08:20.230795
2015-11-24T15:21:53
2015-11-24T15:21:53
45,927,454
0
0
null
null
null
null
UTF-8
C++
false
false
501
h
ProjectSolver.h
// // Created by Paul VANHAESEBROUCK on 17/11/2015. // #ifndef STABLE_FLUIDS_PROJECTSOLVER_H #define STABLE_FLUIDS_PROJECTSOLVER_H #include <gsl/gsl_vector.h> #include <gsl/gsl_spmatrix.h> #include "main.h" class ProjectSolver { const double h; gsl_spmatrix *UV, *C; public: ProjectSolver(const double h); ~ProjectSolver(); void div(gsl_vector *UV, gsl_vector **U); void project(gsl_vector *U1[NDIM], gsl_vector *U0[NDIM]); }; #endif //STABLE_FLUIDS_PROJECTSOLVER_H
5453444b2d1c836781eaafae3edfde341278f88c
2f4ecef9bb43a9f8468ddd08842124fb64aa7035
/Source/Game/Game/EnemyTestScene.cpp
fcd3cddda22d7bf63a31744e5ff88c9d7b8b390b
[]
no_license
sandcastle-studios/GameEngine
f745849a087b488d1302666190679253daa3ea9b
4feee60bfe7ab414346e5453cf593b521ae6e605
refs/heads/master
2020-02-26T15:32:50.033865
2016-10-01T18:49:11
2016-10-01T18:49:11
68,903,862
2
0
null
null
null
null
UTF-8
C++
false
false
1,436
cpp
EnemyTestScene.cpp
#include "stdafx.h" #include "EnemyTestScene.h" #include <Engine\Component\Factory\ComponentFactory.h> #include <Engine/Model/ModelInstance.h> #include <Engine\Component\ModelComponent.h> #include <Engine\Component\LightComponent.h> #include <Engine\GameObject\GameObject.h> #include <Engine\Model\AssimpModel.h> #include <Engine/Effect/StandardEffect.h> #include <Engine\Camera/Camera.h> #include <Engine/Scripting/ScriptFile.h> EnemyTestScene::EnemyTestScene() { CreateFactories(); myScript = SB::Engine::GetResourceManager().Get<SB::ScriptFile>("Assets/Scripts/Components/TestComponent.lua")->Execute(); } EnemyTestScene::~EnemyTestScene() { } void EnemyTestScene::Update(const SB::Time & aDeltaTime) { SB::Scene::Update(aDeltaTime); } void EnemyTestScene::Render() { SB::Scene::Render(); } void EnemyTestScene::CreateFactories() { std::shared_ptr<SB::GameObject> enemy = CreateGameObject(); //GetComponentFactory<ModelComponent>()->CreateComponent(); SB::SharedPtrComponent<SB::ModelComponent> prettyModel (GetComponentFactory<SB::ModelComponent>()->CreateComponent()); std::shared_ptr<SB::AssimpModel> model = std::make_shared<SB::AssimpModel>("models/Modelviewer_Exempelmodell/K11_1415.fbx"); prettyModel->SetModel(model); SetCameraOrientation(model->GetBoundingBox().GetCenter() + SB::Vector3f(0.f, 0.f, -model->GetBoundingBox().GetSize().z * 1.5f)); enemy->AddComponent<SB::ModelComponent>(prettyModel); }
76323d82ae71c709cdc581957c22078a77d269db
863f203cfb256f5a3e99ab4956b744dcc2cc25f7
/PyMRFLSSVM/ssvm/Checkboard/Checkboard.cpp
4630a6c76fc7d6e4246161e41429be154d72973b
[ "MIT" ]
permissive
yirencaifu/sample_python_trading_algo
46153ca8939dc7477bc3a547e03254268b1744d4
2a39862c10c054bcbce73e75b3d6c719254d2515
refs/heads/master
2021-01-16T19:08:35.676146
2017-08-13T02:24:41
2017-08-13T02:24:41
100,145,544
0
1
null
null
null
null
UTF-8
C++
false
false
5,690
cpp
Checkboard.cpp
#include "Checkboard.h" #include <iostream> #include <iomanip> Checkboard::Checkboard() : cliques(options.H, options.W), y(options.H, options.W), unary(options.H, options.W, options.dimUnary) { checkboardHelper(); } void Checkboard::checkboardHelper() { bool _black = true; int cliqueID = 1; //generate ground-truth checkboard for (int row = 0; row < options.H; row += options.gridStep) { for (int col = 0; col < options.W; col += options.gridStep) { cliques(span(row, row + options.gridStep - 1), span(col, col + options.gridStep - 1)).fill(cliqueID); cliqueID++; y(span(row, row + options.gridStep - 1), span(col, col + options.gridStep - 1)).fill(_black ? 0 : 1); _black = !_black; } } // generate observed labels double eta1 = 0.1; double eta2 = 0.1; unary.slice(0).fill(0); unary.slice(1) = 2 * (randomMatrix(options.H, options.W) - 0.5) + eta1 * (1 - y) - eta2 * y; // generate pairwise labels; if (options.hasPairwise) { // if this options is false, dimPairwise = 0 int pairwiseLength = options.H * options.W * 2 - options.H - options.W; pairwise = (float **) malloc(pairwiseLength * sizeof(float *)); int counter = 0; for (int i = 0; i < pairwiseLength / 2; ++i) { if (((counter + 1) % 128) == 0) { counter++; } pairwise[i] = (float *) malloc(options.dimPairwise * sizeof(float)); // todo: magic number pairwise[i][0] = counter; pairwise[i][1] = counter + 1; pairwise[i][2] = 0; counter++; } counter = 0; for (int i = pairwiseLength / 2; i < pairwiseLength; ++i) { pairwise[i] = (float *) malloc(options.dimPairwise * sizeof(float)); // todo: magic number pairwise[i][0] = counter; pairwise[i][1] = counter + options.H; pairwise[i][2] = 0; counter++; } } else { options.dimPairwise = 0; } } int **Checkboard::mat_to_std_vec(Mat<int> &A) { int **V = (int **) malloc(sizeof(int *) * A.n_rows); for (size_t i = 0; i < A.n_rows; i++) { int *temp = (int *) malloc(sizeof(int) * A.n_cols); for (int j = 0; j < A.n_cols; ++j) { temp[j] = A(i, j); } V[i] = temp; }; return V; } double **Checkboard::mat_to_std_vec(mat &A) { double **V = (double **) malloc(sizeof(double *) * A.n_rows); for (size_t i = 0; i < A.n_rows; i++) { double *temp = (double *) malloc(sizeof(double) * A.n_cols); for (int j = 0; j < A.n_cols; ++j) { temp[j] = A(i, j); } V[i] = temp; }; return V; } float **Checkboard::mat_to_float_vec(mat &A) { float **V = (float **) malloc(sizeof(float *) * A.n_rows); for (size_t i = 0; i < A.n_rows; i++) { float *temp = (float *) malloc(sizeof(float) * A.n_cols); for (int j = 0; j < A.n_cols; ++j) { temp[j] = (float) A(i, j); } V[i] = temp; }; return V; } double ***Checkboard::cube_to_std_vec(cube &A) { double ***VVV = (double ***) malloc(sizeof(double **) * A.n_rows); for (size_t i = 0; i < A.n_rows; i++) { double **VV = (double **) malloc(sizeof(double *) * A.n_cols); for (size_t j = 0; j < A.n_cols; j++) { double *V = (double *) malloc(sizeof(double) * A.n_rows); for (int k = 0; k < A.n_slices; ++k) { V[k] = A(i, j, k); } VV[j] = V; } VVV[i] = VV; } return VVV; } float ***Checkboard::cube_to_float(cube &A) { float ***VVV = (float ***) malloc(sizeof(float **) * A.n_rows); for (size_t i = 0; i < A.n_rows; i++) { float **VV = (float **) malloc(sizeof(float *) * A.n_cols); for (size_t j = 0; j < A.n_cols; j++) { float *V = (float *) malloc(sizeof(float) * A.n_slices); for (int k = 0; k < A.n_slices; ++k) { V[k] = (float) A(i, j, k); } VV[j] = V; } VVV[i] = VV; } return VVV; } mat Checkboard::randomMatrix(int rows, int cols) { std::random_device rd; std::mt19937 e2(rd()); std::uniform_real_distribution<> dist(0, 1); mat A(rows, cols); for (auto &a : A) { a = dist(e2); } return A; } void Checkboard::printVector(int **vec) { for (int i = 0; i < options.H; i++) { for (int j = 0; j < options.W; j++) { std::cout << vec[i][j] << " "; } std::cout << "\n"; } } void Checkboard::printVector(double **vec) { for (int i = 0; i < options.H; i++) { for (int j = 0; j < options.W; j++) { std::cout << vec[i][j] << " "; } std::cout << "\n"; } } void Checkboard::printCube(float ***cube) { for (int i = 0; i < options.H; i++) { for (int j = 0; j < options.W; j++) { for (int k = 0; k < options.dimUnary; ++k) { std::cout << std::setprecision(2) << cube[i][j][k] << ";"; } std::cout << " "; } std::cout << "\n"; } } //int main(int argc, char **argv) { // Checkboard checkboard; //// checkboard.printStdVector( //// checkboard.mat_to_std_vec(checkboard.cliques)); //// checkboard.printStdCube( //// checkboard.cube_to_std_vec(checkboard.unary)); // checkboard.printCube(checkboard.cube_to_float(checkboard.unary)); // // return 0; //}
f1621bc6ba90a1e165892c6f8bfdcb8393f7c153
e0d2699cf0c9e831cbcd37d1c5e61bf266c4aca8
/1. Introduction To C++/CharacterArray/PrintSubstringOfLengthK.cpp
69d2fd6096226ae2d68b3774ac68fac4b7ba179e
[]
no_license
tastaslim/Cplusplus
6972ed3ff1ff724667512a84d5667baf96370d30
f518705f1991b65f0044dc3e332fa178593ecabc
refs/heads/master
2023-08-07T02:00:02.323052
2021-10-03T10:07:49
2021-10-03T10:07:49
290,798,163
2
1
null
null
null
null
UTF-8
C++
false
false
425
cpp
PrintSubstringOfLengthK.cpp
#include <iostream> #include <algorithm> #include <cstring> using namespace std; void PrintSubstring(char input[],int k){ for(int i=0;input[i]!='\0';i++){ for(int j=i;input[j]!='\0';j++){ for(int k=i;k<=j;k++){ if(j-i==k-1) cout<<input[k]; } if(j-i==k-1) cout<<endl; } } } int main() { char input[1000000]; cin.getline(input,1000000); int k; cin>>k; PrintSubstring(input,k); }
ad87d47f0d0c595680d99fd3c8b1865ea9dad973
0088486ce01f74f8fda297c6077a4a62be772cbb
/tests/cpp/test_atomic.cpp
0ea8ab66d4efc97ea996f5b7051ae2aaa0a10b8c
[ "MIT" ]
permissive
CyberZHG/MIXAL
46c010fead1869fa846d5262f719cb7b6519fdc1
06ebe91bb5abcc1ed4ff4af71809a1a41272c4f3
refs/heads/master
2023-02-13T21:53:08.664447
2021-01-04T11:07:40
2021-01-04T11:08:06
194,983,871
6
2
MIT
2020-07-10T15:50:43
2019-07-03T05:13:59
C++
UTF-8
C++
false
false
856
cpp
test_atomic.cpp
#include <iostream> #include "test.h" #include "expression.h" namespace test { class TestAtomic : public UnitTest { }; __TEST_U(TestAtomic, test_equal) { __ASSERT_EQ(mixal::Atomic(mixal::AtomicType::INTEGER, 12, true), mixal::Atomic(mixal::AtomicType::INTEGER, 12, true)); __ASSERT_EQ(mixal::Atomic(mixal::AtomicType::SYMBOL, "sym"), mixal::Atomic(mixal::AtomicType::SYMBOL, "sym")); __ASSERT_EQ(mixal::Atomic(mixal::AtomicType::ASTERISK, "sym"), mixal::Atomic(mixal::AtomicType::ASTERISK, "sym")); __ASSERT_NE(mixal::Atomic(mixal::AtomicType::SYMBOL, "sym"), mixal::Atomic(mixal::AtomicType::ASTERISK, "sym")); } __TEST_U(TestAtomic, test_is_local_symbol) { __ASSERT_FALSE(mixal::Atomic(mixal::AtomicType::INTEGER, 12, true).isLocalSymbol()); } } // namespace test
648f65d6997b4712d01e12e82f22d0667742ac62
44147b92cfc409164288fda1a5d36a2715838fa7
/XSmilAgent/SMILObjects.cpp
162f524d512a00dc700ad83472f11d9c28db6da6
[]
no_license
bestdpf/xface-new
43d6c85fdf5fc4e44629dd24ef5232142c2f28b7
6870fea0cf49c7e185fbee31cff1b04e49b33dd6
refs/heads/master
2021-01-22T04:36:43.050943
2014-05-25T06:44:31
2014-05-25T06:44:31
20,047,812
3
0
null
null
null
null
UTF-8
C++
false
false
12,177
cpp
SMILObjects.cpp
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.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 XSmilAgent. * * The Initial Developer of the Original Code is * ITC-irst, TCC Division (http://tcc.fbk.eu) Trento / ITALY. * For info, contact: xface-info@fbk.eu or http://xface.fbk.eu * Portions created by the Initial Developer are Copyright (C) 2004 - 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * - Koray Balci (koraybalci@gmail.com) * ***** END LICENSE BLOCK ***** */ #include "SMILObjects.h" #include <iostream> #include "XercesString.h" void SMILReferencedBlock::print() const { std::cerr << "content-id: " << content_id << std::endl; std::cerr << "content-begin: " << content_begin << std::endl; std::cerr << "content-end: " << content_end << std::endl; SMILBlock::print(); } void SMILSpeechAnimation::print() const { std::cerr << "*****Dumping speech-animation object contents:*****\n"; SMILReferencedBlock::print(); std::cerr << "fill: " << fill << std::endl; std::cerr << "intensity: " << intensity << std::endl; std::cerr << "******************************************\n"; } void SMILBlock::print() const { synch.print(); performance.print(); } void SMILSpeech::print() const { std::cerr << "*****Dumping speech object contents:*****\n"; SMILBlock::print(); std::cerr << "Filename: " << filename << std::endl; std::cerr << "Content:\n"; for(size_t i = 0; i < content.size(); ++i) { if(content.at(i).type == SMILSpeechContent::kMark) std::cerr << "\tMark id: " << content.at(i).value << std::endl; else std::cerr << "\tText: " << content.at(i).value << " begins: " << content.at(i).beginVal << " ends: " << content.at(i).endVal << std::endl; } std::cerr << "******************************************\n"; } void SMILSynchronizationAttributes::print() const { std::cerr << "begin: " << begin << std::endl; std::cerr << "end: " << end << std::endl; std::cerr << "beginVal: " << beginVal << std::endl; std::cerr << "endVal: " << endVal << std::endl; std::cerr << "dur: " << dur << std::endl; std::cerr << "repeat: " << repeat << std::endl; } void SMILSystemAttributes::print() const { std::cerr << "system-language: " << language << std::endl; std::cerr << "system-required: " << required << std::endl; std::cerr << "system-screen-size: " << screen_size << std::endl; std::cerr << "system-screen-depth: "<< screen_depth << std::endl; } void SMILTestAttributes::print() const { system.print(); } void SMILPerformanceAttributes::print() const { std::cerr << "channel: " << channel << std::endl; std::cerr << "id: " << id << std::endl; std::cerr << "affect: " << affect << std::endl; std::cerr << "title: " << title << std::endl; tests.print(); } void SMILAction::print() const { std::cerr << "*****Dumping action object contents:*****\n"; SMILReferencedBlock::print(); std::cerr << "action-type: " << action_type << std::endl; std::cerr << "fill: " << fill << std::endl; std::cerr << "intensity: " << intensity << std::endl; std::cerr << "There are " << params.size() << " parameters." << std::endl; for(size_t i = 0; i < params.size(); ++i) std::cerr << "\t" << i + 1 << ". " << params[i] << std::endl; std::cerr << "******************************************\n"; } void SMILSynchronizationAttributes::read(DOMNode* pNode) { // get the attributes DOMNamedNodeMap* outputAttr = pNode->getAttributes(); DOMNode* attr = outputAttr->getNamedItem(XercesString("begin")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); begin = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("end")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); end = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("dur")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); dur = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("repeat")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); repeat = atoi(dummy); XMLString::release(&dummy); } } void SMILSystemAttributes::read(DOMNode* pNode) { // get the attributes DOMNamedNodeMap* outputAttr = pNode->getAttributes(); DOMNode* attr = outputAttr->getNamedItem(XercesString("system-language")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); language = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("system-required")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); required = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("system-screen-size")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); screen_size = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("system-screen-depth")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); screen_depth = dummy; XMLString::release(&dummy); } } void SMILTestAttributes::read(DOMNode* pNode) { system.read(pNode); } void SMILPerformanceAttributes::read(DOMNode* pNode) { // get the attributes DOMNamedNodeMap* outputAttr = pNode->getAttributes(); DOMNode* attr = outputAttr->getNamedItem(XercesString("channel")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); channel = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("affect")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); affect = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("id")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); id = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("title")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); title = dummy; XMLString::release(&dummy); } tests.read(pNode); } void SMILAction::read(DOMNode* pAction) { DOMNamedNodeMap* outputAttr = pAction->getAttributes(); DOMNode* attr = outputAttr->getNamedItem(XercesString("content-id")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); content_id = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("action-type")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); action_type = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("content-begin")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); content_begin = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("content-end")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); content_end = dummy; XMLString::release(&dummy); } performance.read(pAction); synch.read(pAction); attr = outputAttr->getNamedItem(XercesString("intensity")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); intensity = (float)atof(dummy); XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("fill")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); fill = dummy; XMLString::release(&dummy); } // now process the children DOMNodeList* pTest = pAction->getChildNodes(); for(XMLSize_t j = 0; j < pTest->getLength(); ++j) { std::string param; if(pTest->item(j)->getNodeType() == DOMNode::ELEMENT_NODE) { char* dummy = XMLString::transcode(pTest->item(j)->getNodeName()); std::string nodeName = dummy; XMLString::release(&dummy); if(nodeName == "parameter") { DOMNodeList* pParam = pTest->item(j)->getChildNodes(); for(XMLSize_t k = 0; k < pParam->getLength(); ++k) { if(pParam->item(k)->getNodeType() == DOMNode::TEXT_NODE) { if(((DOMText*)pParam->item(k))->isIgnorableWhitespace()) continue; XMLCh* data = const_cast<XMLCh*>(pParam->item(k)->getNodeValue()); //dangerous, naah!! if(XMLString::isAllWhiteSpace(data)) continue; XMLString::collapseWS(data); char* dummy = XMLString::transcode(data); param = dummy; XMLString::release(&dummy); params.push_back(param); } } } } } } void SMILSpeechAnimation::read(DOMNode* pAnim) { // get the attributes DOMNamedNodeMap* outputAttr = pAnim->getAttributes(); DOMNode* attr = outputAttr->getNamedItem(XercesString("content-id")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); content_id = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("content-begin")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); content_begin = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("content-end")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); content_end = dummy; XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("content")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); content = dummy; XMLString::release(&dummy); } performance.read(pAnim); synch.read(pAnim); attr = outputAttr->getNamedItem(XercesString("intensity")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); intensity = (float)atof(dummy); XMLString::release(&dummy); } attr = outputAttr->getNamedItem(XercesString("fill")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); fill = dummy; XMLString::release(&dummy); } } void SMILSpeech::read(DOMNode* pSpeech) { DOMNode* attr = 0; DOMNamedNodeMap* outputAttr = pSpeech->getAttributes(); performance.read(pSpeech); synch.read(pSpeech); attr = outputAttr->getNamedItem(XercesString("file")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); filename = dummy; XMLString::release(&dummy); } // now process the children DOMNodeList* pTest = pSpeech->getChildNodes(); for(XMLSize_t j = 0; j < pTest->getLength(); ++j) { SMILSpeechContent cont; if(pTest->item(j)->getNodeType() == DOMNode::TEXT_NODE) { if(((DOMText*)pTest->item(j))->isIgnorableWhitespace()) continue; XMLCh* data = const_cast<XMLCh*>(pTest->item(j)->getNodeValue()); //dangerous, naah!! if(XMLString::isAllWhiteSpace(data)) continue; XMLString::collapseWS(data); char* dummy = XMLString::transcode(data); cont.value = dummy; cont.type = SMILSpeechContent::kText; XMLString::release(&dummy); } else if(pTest->item(j)->getNodeType() == DOMNode::ELEMENT_NODE) { outputAttr = pTest->item(j)->getAttributes(); attr = outputAttr->getNamedItem(XercesString("id")); if(attr) { char* dummy = XMLString::transcode(attr->getNodeValue()); cont.value = dummy; cont.type = SMILSpeechContent::kMark; XMLString::release(&dummy); } } if(cont.value.size() == 0 ) // delay push continue; content.push_back(cont); } } void SMILBlock::read(DOMNode* pBlock) { synch.read(pBlock); performance.read(pBlock); }
5d28818fd41d3487a9cd81b71da2dc1d60e7e696
d657d42eba1a5cf80f39719859cb6944e28f0aa0
/Exercícios Aulas Práticas Resolvidos/Exercícios While Saul Delabrida/65.cpp
617bd9ffc7edf602f14b4b2619f23b2369dd15a5
[]
no_license
fonte-nele/BCC201-Introducao-Programacao
ef6b700f2caea2806d57901d9eace1fac85d29a5
18383ae82b49595c25add46bfa2e8fcef83afdf1
refs/heads/master
2020-06-08T16:17:37.457370
2019-06-22T17:29:53
2019-06-22T17:29:53
193,261,398
0
0
null
null
null
null
UTF-8
C++
false
false
355
cpp
65.cpp
#include <iostream> #include <cmath> using namespace std; int main() { int num; cout<<"Digite um numero:\n"; cin>>num; while (num %6!=0) { cout<<"O quadrado deste numero eh: "<<pow(num,2)<<endl; cout<<"Digite um numero:\n"; cin>>num; } cout<<"O quadrado deste numero eh: "<<pow(num,2); return 0; }
cace89b0242712af4a4603ea0efcaca356e9d3e6
e3f6a6225e923f9e3302c06ddfc0d2370fdfd56f
/hcpe_uniq2/hcpe_uniq2.cpp
359bb50dc0b58983c49c5c1765c4c4fe9567f2e5
[]
no_license
TadaoYamaoka/ElmoTeacherDecoder
d9cbeea4ab52196484dae6e41f23f51b76b35268
2a395ccd1d71817e356d3ca7c3968f6fea761f7f
refs/heads/master
2021-06-05T23:35:00.323216
2021-04-11T04:12:07
2021-04-11T04:12:07
92,166,651
1
2
null
null
null
null
UTF-8
C++
false
false
2,764
cpp
hcpe_uniq2.cpp
#include "position.hpp" bool operator <(const HuffmanCodedPosAndEval& l, const HuffmanCodedPosAndEval& r) { const long long* lhcp = (const long long*)&l.hcp; const long long* rhcp = (const long long*)&r.hcp; for (int i = 0; i < 4; i++) { if (lhcp[i] < rhcp[i]) return true; else if (lhcp[i] > rhcp[i]) return false; } return false; } bool operator ==(const HuffmanCodedPosAndEval& l, const HuffmanCodedPosAndEval& r) { const long long* lhcp = (const long long*)&l.hcp; const long long* rhcp = (const long long*)&r.hcp; for (int i = 0; i < 4; i++) { if (lhcp[i] != rhcp[i]) return false; } return true; } int main(int argc, char** argv) { if (argc < 4) { std::cout << "hcpe_uniq2 infile comparefile outfile" << std::endl; return 1; } char* infile = argv[1]; char* comparefile = argv[2]; char* outfile = argv[3]; // 入力ファイル std::ifstream ifs(infile, std::ifstream::in | std::ifstream::binary | std::ios::ate); if (!ifs) { std::cerr << "Error: cannot open " << infile << std::endl; exit(EXIT_FAILURE); } const s64 entryNum = ifs.tellg() / sizeof(HuffmanCodedPosAndEval); std::cout << entryNum << std::endl; // 全て読む ifs.seekg(std::ios_base::beg); HuffmanCodedPosAndEval *hcpevec = new HuffmanCodedPosAndEval[entryNum]; ifs.read(reinterpret_cast<char*>(hcpevec), sizeof(HuffmanCodedPosAndEval) * entryNum); ifs.close(); // ソート std::sort(hcpevec, hcpevec + entryNum); // uniq HuffmanCodedPosAndEval* end = std::unique(hcpevec, hcpevec + entryNum); const s64 uniqNum = end - hcpevec; std::cout << uniqNum << std::endl; // 比較ファイル std::ifstream ifs_comp(comparefile, std::ifstream::in | std::ifstream::binary | std::ios::ate); if (!ifs_comp) { std::cerr << "Error: cannot open " << comparefile << std::endl; exit(EXIT_FAILURE); } const s64 entryNumComp = ifs_comp.tellg() / sizeof(HuffmanCodedPosAndEval); std::cout << entryNumComp << std::endl; // 全て読む ifs_comp.seekg(std::ios_base::beg); HuffmanCodedPosAndEval *hcpevecComp = new HuffmanCodedPosAndEval[entryNumComp]; ifs_comp.read(reinterpret_cast<char*>(hcpevecComp), sizeof(HuffmanCodedPosAndEval) * entryNumComp); ifs_comp.close(); // ソート std::sort(hcpevecComp, hcpevecComp + entryNumComp); // 出力 std::ofstream ofs(outfile, std::ios::binary); if (!ofs) { std::cerr << "Error: cannot open " << outfile << std::endl; exit(EXIT_FAILURE); } s64 count = 0; for (s64 i = 0, j = 0; i < uniqNum; i++) { while (hcpevecComp[j] < hcpevec[i] && j < entryNumComp - 1) j++; if (!(hcpevec[i] == hcpevecComp[j])) { ofs.write(reinterpret_cast<char*>(hcpevec + i), sizeof(HuffmanCodedPosAndEval)); count++; } } std::cout << count << std::endl; return 0; }
d09d91002603d06330b04c59fb2ddafe166a27d6
a074bb216be2d9516e6290b4037e85e69683d266
/src/loader/load.cpp
067dd939b8610366a81a77f411918f46fb29c12c
[ "Apache-2.0" ]
permissive
gesucca-official/pastablaster
c7d997960374fce7b21092aa6ed542392c0271db
5bb95fe432daf7d68c59b918c1264d916d724899
refs/heads/master
2021-09-07T16:47:38.101436
2018-02-26T08:59:56
2018-02-26T08:59:56
91,077,688
1
0
null
null
null
null
UTF-8
C++
false
false
1,242
cpp
load.cpp
#include <stdlib.h> #include <string.h> #include "load.h" //#define WINDOWS //#define DEBUG #ifdef DEBUG #include <stdio.h> #endif #ifdef WINDOWS #define EXPORT_DLL extern "C" __declspec(dllexport) #else #define EXPORT_DLL #endif EXPORT_DLL void DatFile::read(char key[], char res[]) { #ifdef DEBUG printf("Loader module, reading string...\n"); #endif char line[256]; char readKey[5]; //4 chars to name stuff is hardcoded in dat file while (fgets(line, sizeof(line), file)) { strncpy(readKey, line, 4); readKey[4] = (char) 0; if (!strcmp(readKey, key)) { strcpy(res, line+5); res[strcspn(res, "\n")] = (char) 0; break; } } rewind(file); #ifdef DEBUG printf("...read into buffer: %s\n", res); #endif } EXPORT_DLL float DatFile::read(char key[]) { #ifdef DEBUG printf("Loader module, reading float...\n"); #endif char line[256]; char readKey[5]; //4 chars to name stuff is hardcoded in dat file char res[32]; while (fgets(line, sizeof(line), file)) { strncpy(readKey, line, 4); readKey[4] = (char) 0; if (!strcmp(readKey, key)) { strcpy(res, line+5); break; } } rewind(file); #ifdef DEBUG printf("...returning %f\n", atof(res)); #endif return atof(res); }
6346fc5dce116371a56a0528c40c353f9dff50cb
aa1847d55e46771f5591631872f1d4dd4923de23
/Universities/zhonghaiyang04.cpp
ae2e951f6f080f84b37e3dd879bfdf8f38dfde95
[]
no_license
Gongyihang/Daily
8cd224e2122c2e2abd7def3058865f1511c5e3a3
952b74605e965859efaac21e3c29ede9289b5107
refs/heads/master
2023-01-19T20:12:59.718452
2020-12-05T14:40:11
2020-12-05T14:40:11
256,097,511
0
0
null
null
null
null
UTF-8
C++
false
false
844
cpp
zhonghaiyang04.cpp
#include <algorithm> #include <iostream> #include <math.h> #include <string> #include <vector> using namespace std; //公众号:一航代码 int main() { int n, m; cin >> n >> m; vector<int> v; for (int i = 1; i <= n; i++) { v.push_back(i); } for (int i = 0; i < m; i++) { int t, move; cin >> t >> move; vector<int>::iterator it; for (it = v.begin(); it != v.end(); it++) { if (*it == t) { break; } } v.erase(it); //vector的erase真正把这个元素从容器中删除,后面的元素会前移。end表示当前容器末尾 v.insert(it + move, t); } for (int i = 0; i < (int)v.size() - 1; i++) { cout << v[i] << " "; } cout << v[v.size() - 1] << endl; system("pause"); return 0; }
9e725c3689fae328a074aecaecebac1748ad08c3
c6eaad09db0ffa798e66d6486b0a9dc46e8a9256
/WorldPackets/Responses/UpdateExperienceResponsePacket.h
23c429de8cb348107e4ee801e95a8ef6c77f22c0
[]
no_license
DerBasti/JBROSE_World
8afbb0d8ce8cad611ccb716f30146ed5913c40f2
f63aca7518377e4c72b29baabb9d1e053dd4db6a
refs/heads/master
2022-02-06T11:02:05.277912
2022-01-24T21:23:06
2022-01-24T21:23:06
138,166,965
0
0
null
null
null
null
UTF-8
C++
false
false
638
h
UpdateExperienceResponsePacket.h
#ifndef __ROSE_UPDATE_EXPERIENCE_RESPONSEPACKET__ #define __ROSE_UPDATE_EXPERIENCE_RESPONSEPACKET__ #include "../../../JBROSE_Common/Packet.h" class UpdateExperienceResponsePacket : public ResponsePacket { private: const static uint16_t DEFAULT_PACKET_LENGTH = 14; uint32_t experience; uint16_t stamina; uint16_t unknown; protected: void appendContentToSendable(SendablePacket& packet) const; public: const static uint16_t ID = 0x79B; UpdateExperienceResponsePacket(class Player* player); virtual ~UpdateExperienceResponsePacket(); virtual std::string toPrintable() const; }; #endif //__ROSE_UPDATE_EXPERIENCE_RESPONSEPACKET__
f8a9482255b41df3ffbc38b0cd60dd683df5bb1b
fe6bc2c414661a72215e2990e9b11d6ddb35485d
/source/action_initialization/AnalysisManager.cpp
6373b730614fc06c7f3cf6d082d80d5fe989c48c
[ "MIT" ]
permissive
goroyabu/sim4py
b0be880ba41a3d7406852f3d25aad5aac375352a
44ae2a6a4adfe347a7ae899c849936ae6fe7caf3
refs/heads/master
2023-08-04T22:03:12.983731
2021-09-21T04:45:27
2021-09-21T04:45:27
277,063,001
0
0
null
null
null
null
UTF-8
C++
false
false
7,460
cpp
AnalysisManager.cpp
/** @file AnalysisManager.cpp @author Goro Yabu @date 2020/02/04 **/ #include "AnalysisManager.hpp" #include <algorithm> #include <string> using std::cout; using std::endl; AnalysisManager * AnalysisManager::AnalysisManagerInstance = 0; AnalysisManager * AnalysisManager::Instance() { if ( AnalysisManagerInstance == 0 ) { AnalysisManagerInstance = new AnalysisManager(); } return AnalysisManagerInstance; } AnalysisManager::AnalysisManager() : G4RootAnalysisManager() { AnalysisManagerInstance = this; } AnalysisManager::~AnalysisManager() { AnalysisManagerInstance = 0; } AnalysisManager::column_index AnalysisManager::GetColumnIndex(const G4String& name) { auto itr = ColumnIndex.find(name); if ( itr == ColumnIndex.end() ) return column_index(); return itr->second; } G4int AnalysisManager::AddColumnIndex(const G4String& name, const column_index& column) { if ( this->GetColumnIndex(name).ntupleId != -1 ) return -1; ColumnIndex[name] = column; return 0; } G4bool AnalysisManager::ClearNtupleVector() { for ( auto&& column : IColumn ) column = 0; for ( auto&& column : DColumn ) column = 0.0; for ( auto&& column : SColumn ) column = ""; for ( auto&& column : IColumnV ) column->clear(); for ( auto&& column : DColumnV ) column->clear(); return true; } G4int AnalysisManager::CreateNtupleIColumn(const G4String& name) { auto index = column_index( 0, ColumnIndex.size(), 1, this->int_number, IColumn.size() ); if ( this->AddColumnIndex( name, index ) < 0 ) return -1; IColumn.emplace_back(0); return G4RootAnalysisManager::CreateNtupleIColumn(name); } G4int AnalysisManager::CreateNtupleDColumn(const G4String& name) { auto index = column_index( 0, ColumnIndex.size(), 1, this->double_number, DColumn.size() ); if ( this->AddColumnIndex( name, index ) < 0 ) return -1; DColumn.emplace_back( 0.0 ); return G4RootAnalysisManager::CreateNtupleDColumn(name); } G4int AnalysisManager::CreateNtupleSColumn(const G4String& name) { auto index = column_index( 0, ColumnIndex.size(), 1, this->string_number, SColumn.size() ); if ( this->AddColumnIndex( name, index ) < 0 ) return -1; SColumn.emplace_back( "" ); return G4RootAnalysisManager::CreateNtupleSColumn(name); } G4int AnalysisManager::CreateNtupleIColumnV(const G4String& name, G4int maxSize) { auto index = column_index( 0, ColumnIndex.size(), maxSize, this->int_number, IColumnV.size() ); if ( this->AddColumnIndex( name, index ) < 0 ) return -1; auto column = new std::vector<G4int>; column->reserve(maxSize); IColumnV.emplace_back( column ); return this->G4RootAnalysisManager::CreateNtupleIColumn(name, *column); } G4int AnalysisManager::CreateNtupleDColumnV(const G4String& name, G4int maxSize) { auto index = column_index( 0, ColumnIndex.size(), maxSize, this->double_number, DColumnV.size() ); if ( this->AddColumnIndex( name, index ) < 0 ) return -1; auto column = new std::vector<G4double>; column->reserve(maxSize); DColumnV.emplace_back( column ); return this->G4RootAnalysisManager::CreateNtupleDColumn(name, *column); } G4bool AnalysisManager::FillNtupleIColumnName(const G4String& name, G4int value) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->int_number ) return false; if ( index.isVector!=false || index.isVariable!=false ) return false; return G4RootAnalysisManager::FillNtupleIColumn(index.columnId, value); } G4bool AnalysisManager::FillNtupleDColumnName(const G4String& name, G4double value) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->double_number ) return false; if ( index.isVector!=false || index.isVariable!=false ) return false; DColumn[ index.indexInType ] = value; return G4RootAnalysisManager::FillNtupleDColumn(index.columnId, value); } G4bool AnalysisManager::FillNtupleSColumnName(const G4String& name, const G4String& value) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->string_number ) return false; if ( index.isVector!=false || index.isVariable!=false ) return false; SColumn[ index.indexInType ] = value; return G4RootAnalysisManager::FillNtupleSColumn(index.columnId, value); } G4bool AnalysisManager::FillNtupleIColumnVName(const G4String& name, G4int value) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->int_number ) return false; if ( index.maxSize <= (int)IColumnV[ index.indexInType ]->size() ) return false; IColumnV[ index.indexInType ]->emplace_back( value ); return true; } G4bool AnalysisManager::FillNtupleDColumnVName(const G4String& name, G4double value) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->double_number ) return false; if ( index.maxSize <= (int)DColumnV[ index.indexInType ]->size() ) return false; DColumnV[ index.indexInType ]->emplace_back( value ); return true; } G4bool AnalysisManager::FillNtupleIColumnV(G4int columnId, G4int elementId, G4int value) { if ( (int)IColumnV.size()<=columnId ) return false; if ( (int)IColumnV[columnId]->size()<=elementId ) return false; IColumnV[columnId]->at(elementId) = value; return true; } G4bool AnalysisManager::FillNtupleDColumnV(G4int columnId, G4int elementId, G4double value) { if ( (int)DColumnV.size()<=columnId ) return false; if ( (int)DColumnV[columnId]->size()<=elementId ) return false; DColumnV[columnId]->at(elementId) = value; return true; } G4bool AnalysisManager::AddNtupleIColumnName(const G4String& name, G4int value) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->int_number ) return false; if ( index.isVector!=false || index.isVariable!=false ) return false; IColumn[ index.indexInType ] += value; return G4RootAnalysisManager::FillNtupleIColumn(index.columnId, IColumn[index.indexInType] ); } G4bool AnalysisManager::AddNtupleDColumnName(const G4String& name, G4double value) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->double_number ) return false; if ( index.isVector!=false || index.isVariable!=false ) return false; DColumn[ index.indexInType ] += value; return G4RootAnalysisManager::FillNtupleDColumn(index.columnId, DColumn[index.indexInType] ); } G4bool AnalysisManager::AddNtupleSColumnName(const G4String& name, const G4String& value) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->string_number ) return false; if ( index.isVector!=false || index.isVariable!=false ) return false; // SColumn[ index.indexInType ] += value+":"; // auto str = std::string(value); SColumn[ index.indexInType ] = SColumn[ index.indexInType ]+":"+value; // cout << SColumn[ index.indexInType ] << endl; // G4RootAnalysisManager::FillNtupleSColumn( index.columnId, "" ); return G4RootAnalysisManager::FillNtupleSColumn ( index.columnId, (G4String)SColumn[index.indexInType] ); } G4int AnalysisManager::GetNtupleIColumn(const G4String& name) { auto index = this->GetColumnIndex( name ); if ( index.typeNumber != this->int_number ) return -1; if ( index.isVector!=false || index.isVariable!=false ) return -1; return IColumn[ index.indexInType ]; }
2d836f432e9255daa9e8f79999e38360c17c8383
a9be7d02028936cfdb82e492d2cc3a9384bdc437
/LuminousPassage2/audio.cpp
80735edddf108e144004a33993c5dfe7a87a8eb4
[]
no_license
dshobbes13/LuminousPassage2
c1f9529c33d551ec986b23eead93d9a7b5b206eb
5ab315295fff20044b6c86d926c295c8c60ebcec
refs/heads/master
2016-09-05T12:38:46.937406
2012-12-11T01:43:12
2012-12-11T01:43:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,133
cpp
audio.cpp
// File: audio.cpp //***************** // INCLUDES //***************** #include "audio.h" #ifndef SOFTWARE #include <Arduino.h> #include <EEPROM.h> #include "config.h" #include "typedefs.h" #else #endif #include "global.h" //***************** // DEFINITIONS //***************** //#define DEBUG //***************** // VARIABLES //***************** static quint16 mBuckets[GLOBAL_NUM_BUCKETS] = {0}; static quint8 mLo[GLOBAL_NUM_BUCKETS] = {0}; static quint8 mHi[GLOBAL_NUM_BUCKETS] = {0}; static quint8 mFreqAverages[GLOBAL_NUM_FREQ] = {0}; static quint16 mBucketAverages[GLOBAL_NUM_BUCKETS] = {0}; static quint8 mThreshold= 0; static float mAveraging = 0; //***************** // PRIVATE PROTOTYPES //***************** //***************** // PUBLIC //***************** void AudioInit( void ) { mThreshold = 8; mAveraging = 0.9; mLo[0] = 1; mHi[0] = 2; mLo[1] = 3; mHi[1] = 4; mLo[2] = 5; mHi[2] = 8; mLo[3] = 9; mHi[3] = 16; mLo[4] = 17; mHi[4] = 32; mLo[5] = 33; mHi[5] = 63; } void AudioSave( void ) { #ifdef FIRMWARE cli(); EEPROM.write( EEPROM_AUDIO_THRESHOLD, mThreshold ); EEPROM.write( EEPROM_AUDIO_AVERAGING, (quint8)( 255 * mAveraging ) ); EEPROM.write( EEPROM_AUDIO_BUCKETS_LO_0, mLo[0] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_HI_0, mHi[0] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_LO_1, mLo[1] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_HI_1, mHi[1] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_LO_2, mLo[2] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_HI_2, mHi[2] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_LO_3, mLo[3] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_HI_3, mHi[3] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_LO_4, mLo[4] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_HI_4, mHi[4] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_LO_5, mLo[5] ); EEPROM.write( EEPROM_AUDIO_BUCKETS_HI_5, mHi[5] ); sei(); #endif } void AudioLoad( void ) { #ifdef FIRMWARE cli(); mThreshold = EEPROM.read( EEPROM_AUDIO_THRESHOLD ); mAveraging = ( (float)EEPROM.read( EEPROM_AUDIO_AVERAGING ) ) / 255; mLo[0] = EEPROM.read( EEPROM_AUDIO_BUCKETS_LO_0 ); mHi[0] = EEPROM.read( EEPROM_AUDIO_BUCKETS_HI_0 ); mLo[1] = EEPROM.read( EEPROM_AUDIO_BUCKETS_LO_1 ); mHi[1] = EEPROM.read( EEPROM_AUDIO_BUCKETS_HI_1 ); mLo[2] = EEPROM.read( EEPROM_AUDIO_BUCKETS_LO_2 ); mHi[2] = EEPROM.read( EEPROM_AUDIO_BUCKETS_HI_2 ); mLo[3] = EEPROM.read( EEPROM_AUDIO_BUCKETS_LO_3 ); mHi[3] = EEPROM.read( EEPROM_AUDIO_BUCKETS_HI_3 ); mLo[4] = EEPROM.read( EEPROM_AUDIO_BUCKETS_LO_4 ); mHi[4] = EEPROM.read( EEPROM_AUDIO_BUCKETS_HI_4 ); mLo[5] = EEPROM.read( EEPROM_AUDIO_BUCKETS_LO_5 ); mHi[5] = EEPROM.read( EEPROM_AUDIO_BUCKETS_HI_5 ); sei(); #endif } void AudioSetParameters( quint8 threshold, float averaging, quint8* lo, quint8* hi ) { mThreshold = threshold; mAveraging = averaging; memcpy( mLo, lo, GLOBAL_NUM_BUCKETS ); memcpy( mHi, hi, GLOBAL_NUM_BUCKETS ); } void AudioUpdateFreq( quint8* newFrequencies ) { for( quint8 i=0; i<GLOBAL_NUM_BUCKETS; i++ ) { mBuckets[i] = 0; for( quint8 j=0; j<GLOBAL_NUM_FREQ; j++ ) { if( ( j >= mLo[i] ) && ( j <= mHi[i] ) ) { quint8 value = newFrequencies[j]; mBuckets[i] += ( value > mThreshold ) ? value : 0; } } } for( quint8 i=0; i<GLOBAL_NUM_FREQ; i++ ) { float oldValue = (float)(mFreqAverages[i]) * mAveraging; float newValue = (float)(newFrequencies[i]) * ( 1.0 - mAveraging ); mFreqAverages[i] = (quint8)( oldValue + newValue ); } for( quint8 i=0; i<GLOBAL_NUM_BUCKETS; i++ ) { float oldValue = (float)(mBucketAverages[i]) * mAveraging; float newValue = (float)(mBuckets[i]) * ( 1.0 - mAveraging ); mBucketAverages[i] = (quint16)( oldValue + newValue ); } } quint16* AudioBuckets( void ) { return mBuckets; } quint8* AudioFreqAverages( void ) { return mFreqAverages; } quint16* AudioBucketAverages( void ) { return mBucketAverages; }
2b0f78a918f8d54558828edb4a589cb5cdb2e3de
37659bfb7dfc0892115b3160d2dd40d2edb76c76
/ParticleQuadTree.h
b0e82b2d34b4365d9411ba8b9001adc8b807e35f
[]
no_license
amdreallyfast/render_particles_2D_CPU_p_on_p_collisions
10f65e3da5e226bc348cd0432efb1422d9d75f2b
9ebd8fe30ba56fdd9b8714ccdb56d069293856dc
refs/heads/master
2021-01-13T14:10:03.750646
2017-01-03T15:45:57
2017-01-03T15:45:57
76,145,207
0
0
null
null
null
null
UTF-8
C++
false
false
2,399
h
ParticleQuadTree.h
#pragma once #include <vector> #include "Particle.h" #include "glm\vec2.hpp" #include "ParticleQuadTreeNode.h" #include "GeometryData.h" /*----------------------------------------------------------------------------------------------- Description: Responsible for generating a quad tree that can contain all the currently active particles. Creator: John Cox (12-17-2016) -----------------------------------------------------------------------------------------------*/ class ParticleQuadTree { public: ParticleQuadTree(); void InitializeTree(const glm::vec2 &particleRegionCenter, float particleRegionRadius); void ResetTree(); void AddParticlestoTree(std::vector<Particle> &particleCollection); void DoTheParticleParticleCollisions(float deltaTimeSec, std::vector<Particle> &particleCollection) const; void GenerateGeometry(GeometryData *putDataHere, bool firstTime = false); int NumNodesInUse() const; private: bool AddParticleToNode(int particleIndex, int nodeIndex, std::vector<Particle> &particleCollection); bool SubdivideNode(int nodeIndex, std::vector<Particle> &particleCollection); //int NodeLookUp(const glm::vec2 &position); void ParticleCollisionsWithinNode(int nodeIndex, float deltaTimeSec, std::vector<Particle> &particleCollection) const; void ParticleCollisionsWithNeighboringNode(int particleIndex, int nodeIndex, float deltaTimeSec, std::vector<Particle> &particleCollection) const; void ParticleCollisionP1WithP2(int thisParticleIndex, int otherParticleIndex, float deltaTimeSec, std::vector<Particle> &particleCollection) const; // increase the number of additional nodes as necessary to handle more subdivision // Note: This algorithm was built with the compute shader's implementation in mind. These // structures are meant to be used as if a compute shader was running it, hence all the // arrays and a complete lack of runtime memory reallocation. static const int _NUM_ROWS_IN_TREE_INITIAL = 8; static const int _NUM_COLUMNS_IN_TREE_INITIAL = 8; static const int _NUM_STARTING_NODES = _NUM_ROWS_IN_TREE_INITIAL * _NUM_COLUMNS_IN_TREE_INITIAL; static const int _MAX_NODES = _NUM_STARTING_NODES * 8; QuadTreeNode _allQuadTreeNodes[_MAX_NODES]; int _numNodesInUse = _NUM_STARTING_NODES; glm::vec2 _particleRegionCenter; float _particleRegionRadius; };
6c9e8da8b17893d6b6594d5a39bc46fe93c09842
db5faa187eacebd8be27bdd971bba455aa30cd55
/cpp/algo/dp/permute.cpp
120a4398e88fc1cbee194629f3fbf97c90cdb966
[]
no_license
ajaygh/go
7a9eb303b28770778993c91df8e62f32d0ee65cb
6057017eb38fea669396832a15dd2aa43f652e2e
refs/heads/master
2020-12-30T16:14:29.603814
2017-12-12T07:49:35
2017-12-12T07:49:35
90,964,485
0
0
null
null
null
null
UTF-8
C++
false
false
809
cpp
permute.cpp
#include <iostream> #include <vector> using namespace std; void permute(string s); vector<string> permutePos(vector<string> &prev, char ch); int main() { string in; cin >> in; permute(in); cout << endl; return 0; } void permute(string s){ vector<string> res; //base case string tmp; tmp.push_back(s[0]); res.push_back(tmp); for(int i = 1; i < s.length(); i++){ res = permutePos(res, s[i]); } for(auto str: res) cout << str <<" "; } vector<string> permutePos(vector<string> &prev, char ch){ vector<string> res; for(auto str: prev){ for(int i = 0; i < str.length()+1; i++){ string tmp; for(int j = 0; j < i; j++) tmp.push_back(str[j]); tmp.push_back(ch); for(int j = i; j < str.length();j++) tmp.push_back(str[j]); res.push_back(tmp); } } return res; }
eb90b79eab657df72d6d95aecef4392388642e0c
f13ef18abfb61d983040f83249bd19c6f55c29c9
/models/AI-Model-Zoo/caffe-xilinx/examples/yolo/yolo_detect.cpp
c8469beb470af8e25d9ff1fe823068e6a618f6f7
[ "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
AEW2015/Vitis-AI
5487b6474924e57dbdf54f66517d1c604fc2c480
84798c76e6ebb93300bf384cb56397f214676330
refs/heads/master
2023-06-24T11:02:20.049076
2021-07-27T05:41:52
2021-07-27T05:41:52
390,221,916
1
0
Apache-2.0
2021-07-28T05:12:07
2021-07-28T05:12:06
null
UTF-8
C++
false
false
14,536
cpp
yolo_detect.cpp
// This is a demo code for using a Yolo model to do detection. // The code is modified from examples/cpp_classification/classification.cpp. // Usage: // ssd_detect [FLAGS] model_file weights_file list_file // // where model_file is the .prototxt file defining the network architecture, and // weights_file is the .caffemodel file containing the network parameters, and // list_file contains a list of image files with the format as follows: // folder/img1.JPEG // folder/img2.JPEG #include <caffe/caffe.hpp> #ifdef USE_OPENCV #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #endif // USE_OPENCV #include "caffe/transformers/yolo_transformer.hpp" #include <string> #include <iostream> #include <vector> #ifdef USE_OPENCV using namespace caffe; // NOLINT(build/namespaces) using namespace std; float sigmoid(float p){ return 1.0 / (1 + exp(-p * 1.0)); } float overlap(float x1, float w1, float x2, float w2) { float left = max(x1 - w1 / 2.0,x2 - w2 / 2.0); float right = min(x1 + w1 / 2.0,x2 + w2 / 2.0); return right - left; } float cal_iou(vector<float> box, vector<float> truth) { float w = overlap(box[0], box[2], truth[0], truth[2]); float h = overlap(box[1], box[3], truth[1], truth[3]); if (w<0 || h<0) return 0; float inter_area = w * h; float union_area = box[2] * box[3] + truth[2] * truth[3] - inter_area; return inter_area * 1.0 / union_area; } vector<string> InitLabelfile(const string& labels) { vector<string> new_labels; if(labels != "") { size_t start = 0; size_t index = labels.find(",", start); while (index != std::string::npos) { new_labels.push_back(labels.substr(start, index - start)); start = index + 1; index = labels.find(",", start); } new_labels.push_back(labels.substr(start)); } else { new_labels = {"aeroplane","bicycle","bird","boat","bottle", "bus","car","cat","chair","cow","diningtable", "dog","horse","motorbike","person","pottedplant", "sheep","sofa","train","tvmonitor"}; } //for (auto it = 0; it < new_labels.size(); it ++) { // LOG(INFO) << "new_labels List:" << new_labels[it] ; //} return new_labels; } vector<float> InitBiases(const string& biases) { vector<float> new_biases; if(biases != "") { size_t start = 0; size_t index = biases.find(",", start); while (index != std::string::npos) { new_biases.push_back(atof(biases.substr(start, index - start).c_str())); start = index + 1; index = biases.find(",", start); } new_biases.push_back(atof(biases.substr(start).c_str())); } else { new_biases = {10,13,16,30,33,23, 30,61,62,45,59,119, 116,90,156,198,373,326}; } //for (auto it = 0; it < new_biases.size(); it ++) { // LOG(INFO) << "new_biases List:" << new_biases[it] ; //} return new_biases; } vector<vector<float>> apply_nms(vector<vector<float>>boxes , int classes ,float thres) { vector<pair<int, float>> order(boxes.size()); vector<vector<float>> result; for( int k = 0; k <classes; k++){ for(size_t i = 0; i < boxes.size(); ++i){ order[i].first = i; boxes[i][4] = k; order[i].second = boxes[i][6+k]; } sort(order.begin(), order.end(),[](const pair<int, float>& ls, const pair<int, float>& rs) {return ls.second > rs.second;}); vector<bool> exist_box(boxes.size(), true); for(size_t _i = 0; _i < boxes.size(); ++_i){ size_t i = order[_i].first; if(!exist_box[i]) continue; if(boxes[i][6 + k] < 0.005) { exist_box[i] = false; continue; } result.push_back(boxes[i]); for(size_t _j = _i+1; _j < boxes.size(); ++_j){ size_t j = order[_j].first; if(!exist_box[j]) continue; float ovr = cal_iou(boxes[j], boxes[i]); if(ovr >= thres) exist_box[j] = false; } } } return result; } vector<vector<float>> correct_region_boxes( vector<vector<float>> boxes, int n, int w, int h, int netw, int neth) { int new_w = 0; int new_h = 0; if (((float)netw / w) < ((float)neth / h)){ new_w = netw; new_h = (h * netw) / w; } else { new_w = (w * neth) / h; new_h = neth; } for(int i =0; i < boxes.size() ; i++) { boxes[i][0] = (boxes[i][0] - (netw - new_w) / 2.0 / netw) / ((float)new_w / netw); boxes[i][1] = (boxes[i][1] - (neth - new_h) / 2.0 / neth) / ((float)new_h / neth); boxes[i][2] *= (float)netw / new_w; boxes[i][3] *= (float)neth / new_h; } return boxes; } class Detector { public: Detector(const string& model_file, const string& weights_file); vector<vector<float>> Detectv3(string file, int classes, vector<float> biases ,int anchorCnt, int w, int h); vector<vector<float>> Detectv2(string file, int classes, vector<float> biases ,int anchorCnt, int w, int h); private: boost::shared_ptr<Net<float>> net_; cv::Size input_geometry_; int num_channels_; }; Detector::Detector(const string& model_file, const string& weights_file){ #ifdef CPU_ONLY Caffe::set_mode(Caffe::CPU); #else Caffe::set_mode(Caffe::GPU); Caffe::SetDevice(0); #endif /* Load the network. */ net_.reset(new Net<float>(model_file, TEST)); net_->CopyTrainedLayersFrom(weights_file); Blob<float>* input_layer = net_->input_blobs()[0]; num_channels_ = input_layer->channels(); CHECK(num_channels_ == 3 || num_channels_ == 1) << "Input layer should have 1 or 3 channels."; input_geometry_ = cv::Size(input_layer->width(), input_layer->height()); } vector<vector<float> > Detector::Detectv2(string file ,int classes ,vector<float>biases, int anchorCnt, int img_width , int img_height) { Blob<float>* input_layer = net_->input_blobs()[0]; image img = load_image_yolo(file.c_str(), input_layer->width(), input_layer->height(), input_layer->channels()); input_layer->set_cpu_data(img.data); net_->Forward(); free_image(img); /* Copy the output layer to a std::vector */ Blob<float>* result_blob = net_->output_blobs()[0]; const float* result = result_blob->cpu_data(); int height = net_->output_blobs()[0]->height(); int width = net_->output_blobs()[0]->width(); float swap[height*width][anchorCnt][classes + 5]; for(int h =0; h < height; h++) for(int w =0; w < width; w++) for(int c =0 ; c < anchorCnt*(classes + 5);c++) swap[h * width + w][c / (classes + 5)][c % (classes + 5)] = result[c * height * width + h * width + w]; vector<vector<float> > boxes; for(int h =0; h < height; h++){ for(int w =0; w < width; w++){ for(int n =0 ; n < anchorCnt; n++){ vector<float>box , cls; float s = 0.0; float x = (w + sigmoid(swap[h * width + w][n][0])) / static_cast<float>(width); float y = (h + sigmoid(swap[h * width + w][n][1])) / static_cast<float>(height); float ww = (exp(swap[h * width + w][n][2])* biases[2 * n]) / static_cast<float>(width); float hh = (exp(swap[h * width + w][n][3])* biases[2 * n+1]) / static_cast<float>(height); float obj_score = sigmoid(swap[h * width + w][n][4]); for(int p =0; p < classes; p++) cls.push_back(swap[h * width + w][n][5 + p]); float large = *max_element(cls.begin(),cls.end()); for(int p =0; p <cls.size() ;p++){ cls[p] = exp(cls[p] -large); s += cls[p]; } vector<float>::iterator biggest = max_element(cls.begin(),cls.end()); large = * biggest; for(int p =0; p < cls.size() ; p++) cls[p] = cls[p] / s; box.push_back(x); box.push_back(y); box.push_back(ww); box.push_back(hh); box.push_back(-1); box.push_back(obj_score); for (int p =0; p < cls.size(); p ++) {box.push_back(obj_score * cls[p]); } boxes.push_back(box); } } } boxes = correct_region_boxes(boxes, boxes.size() ,img_width ,img_height ,input_geometry_.width ,input_geometry_.height); vector<vector<float> > res = apply_nms(boxes ,classes ,0.45); return res; } vector<vector<float>> Detector::Detectv3(string file, int classes, vector<float> biases ,int anchorCnt, int img_width, int img_height) { Blob<float>* input_layer = net_->input_blobs()[0]; image img = load_image_yolo(file.c_str(), input_layer->width(), input_layer->height(), input_layer->channels()); input_layer->set_cpu_data(img.data); net_->Forward(); free_image(img); /* Copy the output layer to a std::vector */ vector<vector<float>> boxes; vector<int> scale_feature; for (int iter = 0; iter < net_->num_outputs(); iter++){ int width = net_->output_blobs()[iter]->width(); scale_feature.push_back(width); } sort(scale_feature.begin(), scale_feature.end(), [](int a, int b){return a > b;}); for (int iter = 0; iter < net_->num_outputs(); iter++) { Blob<float>* result_blob = net_->output_blobs()[iter]; const float* result = result_blob->cpu_data(); int height = net_->output_blobs()[iter]->height(); int width = net_->output_blobs()[iter]->width(); int channles = net_->output_blobs()[iter]->channels(); int index = 0; for (int i = 0; i < net_->num_outputs(); i++) { if(width == scale_feature[i]) { index = i; break; } } // swap the network's result to a new sequence float swap[width*height][anchorCnt][5+classes]; for(int h =0; h < height; h++) for(int w =0; w < width; w++) for(int c =0 ; c < channles; c++) swap[h * width + w][c / (5 + classes)][c % (5 + classes)] = result[c * height * width + h * width + w]; // compute the coordinate of each primary box for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { for (int n = 0 ; n < anchorCnt; n++) { float obj_score = sigmoid(swap[h * width + w][n][4]); if(obj_score < 0.005) continue; vector<float>box,cls; float x = (w + sigmoid(swap[h * width + w][n][0])) / width; float y = (h + sigmoid(swap[h * width + w][n][1])) / height; float ww = exp(swap[h * width + w][n][2]) * biases[2 * n + 2 * anchorCnt * index] / input_geometry_.width; float hh = exp(swap[h * width + w][n][3]) * biases[2 * n + 2 * anchorCnt * index + 1] / input_geometry_.height; box.push_back(x); box.push_back(y); box.push_back(ww); box.push_back(hh); box.push_back(-1); box.push_back(obj_score); for(int p =0; p < classes; p++) box.push_back(obj_score * sigmoid(swap[h * width + w][n][5 + p])); boxes.push_back(box); } } } } boxes = correct_region_boxes(boxes,boxes.size(), img_width,img_height, input_geometry_.width, input_geometry_.height); vector<vector<float>> res = apply_nms(boxes, classes, 0.45); return res; } DEFINE_string(file_type, "image", "Default support for image"); DEFINE_string(out_file, "", "If provided, store the detection results in the out_file."); DEFINE_string(labels, "", "If not provided, the defult support for VOC."); DEFINE_string(biases, "", "If not provided, the defult support for VOC."); DEFINE_string(model_type, "yolov3", "If not provided, the defult support yolov3 model.model-type for detection {yolov2,yolov3}."); DEFINE_double(confidence_threshold, 0.005, "If not provided, the threshold for testing mAP is used by default."); DEFINE_int32(classes, 80, "If not provided, the category of the COCO dataset is used by default."); DEFINE_int32(anchorCnt,3, "If not provided, the number of anchors using yolov3 is used by default."); int main(int argc, char** argv) { ::google::InitGoogleLogging(argv[0]); // Print output to stderr (while still logging) FLAGS_alsologtostderr = 1; #ifndef GFLAGS_GFLAGS_H_ namespace gflags = google; #endif gflags::SetUsageMessage("Do detection using Yolo mode.\n" "Usage:\n" " yolo_detect [FLAGS] model_file weights_file list_file\n"); gflags::ParseCommandLineFlags(&argc, &argv, true); if (argc < 4) { gflags::ShowUsageWithFlagsRestrict(argv[0], "examples/yolo/yolo_detect"); return 1; } const string& model_file = argv[1]; const string& weights_file = argv[2]; const string& file_type = FLAGS_file_type; const string& output_filename = FLAGS_out_file; const string& model_type = FLAGS_model_type; const float confidence = FLAGS_confidence_threshold; const int classes = FLAGS_classes; const int anchorCnt = FLAGS_anchorCnt; ofstream fout; fout.open(output_filename.c_str()); // Initialize the network. Detector detector(model_file, weights_file); // Initialize the label,biases. vector<string> labels = InitLabelfile(FLAGS_labels); vector<float> biases = InitBiases(FLAGS_biases); // Process image one by one. ifstream infile(argv[3]); string file; while (infile >> file) { if (file_type == "image") { // CHECK(img) << "Unable to decode image " << file; cv::Mat img = cv::imread(file, -1); int w = img.cols; int h = img.rows; vector<vector<float>> results; if(model_type == "yolov3") results = detector.Detectv3(file, classes,biases, anchorCnt, w, h); else results = detector.Detectv2(file, classes,biases, anchorCnt, w, h); for(int i = 0; i < results.size(); i++) { float xmin = (results[i][0] - results[i][2] / 2.0) * w + 1; float ymin = (results[i][1] - results[i][3] / 2.0) * h + 1; float xmax = (results[i][0] + results[i][2] / 2.0) * w + 1; float ymax = (results[i][1] + results[i][3] / 2.0) * h + 1; if (xmin < 0) xmin = 1; if (ymin < 0) ymin = 1; if (xmax > w) xmax = w; if (ymax > h) ymax = h; if (results[i][results[i][4] + 6] > confidence) { fout << file <<" "<<labels[results[i][4]]<<" " << results[i][6 + results[i][4]] << " " << xmin << " " << ymin << " " << xmax << " " << ymax << endl; cv::rectangle(img,cvPoint(xmin,ymin), cvPoint(xmax,ymax), cv::Scalar(255,0,255), 2, 1, 0); LOG(INFO) << file << " " << labels[results[i][4]] << " " << results[i][6 + results[i][4]] << " " << xmin << " " << ymin << " " << xmax << " " << ymax << endl; } } cv::imwrite("detection.jpg", img); results.clear(); } else { LOG(FATAL) << "Unknown file_type: " << file_type; } } return 0; } #else int main(int argc, char** argv) { LOG(FATAL) << "This example requires OpenCV; compile with USE_OPENCV."; } #endif // USE_OPENCV
63d0ecbd001fd26bf9cd0afd6097c306dd57016c
b12c00f297b7a5ffddf60d8bdca2eaa8129ed631
/src/comm/HashMap.h
abc6c1eb5e21935bed301aa96b5e545f87152959
[]
no_license
ben-xue/server_add
29541cdb74da95f9e988eb6dbf5f69f87997dd57
62a95f20dc196fb21f31be717ab0e938144dab23
refs/heads/master
2023-04-18T05:48:08.846411
2021-04-30T09:37:51
2021-04-30T09:37:51
362,110,958
1
0
null
null
null
null
UTF-8
C++
false
false
4,703
h
HashMap.h
// // Created by jianghz on 2020/10/24. // #ifndef KGAME_SERVER_HASHMAP_H #define KGAME_SERVER_HASHMAP_H //class HashFunc //{ //public: // int operator()(const string & key ) // { // int hash = 0; // for(int i = 0; i < key.length(); ++i) // { // hash = hash << 7 ^ key[i]; // } // return (hash & 0x7FFFFFFF); // } //}; //class EqualKey //{ //public: // bool operator()(const string & A, const string & B) // { // if (A.compare(B) == 0) // return true; // else // return false; // } //}; #include <iostream> #include <string> using namespace std; template<class Key, class Value> class HashNode { public: Key _key; Value _value; HashNode *next; HashNode(Key key, Value value) { _key = key; _value = value; next = NULL; } ~HashNode() { } HashNode& operator=(const HashNode& node) { _key = node.key; _value = node.key; next = node.next; return *this; } }; template <class Key, class Value, class HashFunc, class EqualKey> class HashMap { public: HashMap(int size = 1024); ~HashMap(); bool Insert(const Key& key, const Value& value); bool Del(const Key& key); bool Exist(const Key& key); Value& Find(const Key& key); Value& operator [](const Key& key); private: HashFunc hash; EqualKey equal; HashNode<Key, Value> **table; unsigned int _size; Value ValueNULL; }; template <class Key, class Value, class HashFunc, class EqualKey> HashMap<Key, Value, HashFunc, EqualKey>::HashMap(int size) : _size(size) { hash = HashFunc(); equal = EqualKey(); table = new HashNode<Key, Value> *[_size]; for (unsigned i = 0; i < _size; i++) table[i] = NULL; } template <class Key, class Value, class HashFunc, class EqualKey> HashMap<Key, Value, HashFunc, EqualKey>::~HashMap() { for (unsigned i = 0; i < _size; i++) { HashNode<Key, Value> *currentNode = table[i]; while (currentNode) { HashNode<Key, Value> *temp = currentNode; currentNode = currentNode->next; delete temp; } } delete table; } template <class Key, class Value, class HashFunc, class EqualKey> bool HashMap<Key, Value, HashFunc, EqualKey>::Insert(const Key& key, const Value& value) { int index = hash(key) % _size; HashNode<Key, Value> *node = new HashNode<Key, Value>(key,value); node->next = table[index]; table[index] = node; return true; } template <class Key, class Value, class HashFunc, class EqualKey> bool HashMap<Key, Value, HashFunc, EqualKey>::Del(const Key& key) { unsigned index = hash(key) % _size; HashNode<Key, Value> * node = table[index]; HashNode<Key, Value> * prev = NULL; while (node) { if (node->_key == key) { if (prev == NULL) { table[index] = node->next; } else { prev->next = node->next; } delete node; return true; } prev = node; node = node->next; } return false; } template <class Key, class Value, class HashFunc, class EqualKey> bool HashMap<Key, Value, HashFunc, EqualKey>::Exist(const Key& key) { unsigned index = hash(key) % _size; if (table[index] == NULL) return false; else { HashNode<Key, Value> * node = table[index]; while (node) { if (node->_key == key) return true; node = node->next; } } return false; } template <class Key, class Value, class HashFunc, class EqualKey> Value& HashMap<Key, Value, HashFunc, EqualKey>::Find(const Key& key) { unsigned index = hash(key) % _size; if (table[index] == NULL) return ValueNULL; else { HashNode<Key, Value> * node = table[index]; while (node) { // cout << "node->_key = " << node->_key << endl; if (node->_key == key) return node->_value; node = node->next; } // cout << "key is not find!" << endl; return ValueNULL; } } template <class Key, class Value, class HashFunc, class EqualKey> Value& HashMap<Key, Value, HashFunc, EqualKey>::operator [](const Key& key) { return Find(key); } #endif //KGAME_SERVER_HASHMAP_H
a9dcfafc324179d84155d7c9e27214f9010b7de6
ca43c232f60ca55437c9f204402f11000e805b14
/MathLibrary/Vector_Matrix.h
064897d645304fccf5e4d69c9a7c7fffbee2689c
[]
no_license
Kurowoomy/Math-Library
a2a4e48b2c20c5b7f2925f0c34c0dcb185f47999
daa9d251856a7a677ee3af605f71d2c16a4d7977
refs/heads/master
2020-07-23T09:34:06.698927
2019-09-10T09:11:29
2019-09-10T09:11:29
206,348,522
0
0
null
null
null
null
UTF-8
C++
false
false
14,795
h
Vector_Matrix.h
#pragma once #include <math.h> /// has no use so far, can ignore this class class MyVector3 { public: float x, y, z; MyVector3() { } MyVector3(float x, float y, float z) { this->x = x; this->y = y; this->z = z; } MyVector3 operator+(const MyVector3& v) { MyVector3 vect; vect.x = this->x + v.x; vect.y = this->y + v.y; vect.z = this->z + v.z; return vect; } MyVector3 operator-(const MyVector3& v) { MyVector3 vect; vect.x = this->x - v.x; vect.y = this->y - v.y; vect.z = this->z - v.z; return vect; } MyVector3 operator*(const float scalar) { MyVector3 vect; vect.x = this->x * scalar; vect.y = this->y * scalar; vect.z = this->z * scalar; return vect; } MyVector3& operator=(const MyVector3& v) { x = v.x; y = v.y; z = v.z; return *this; } float length() { return sqrt(this->x * this->x + this->y * this->y + this->z * this->z); } MyVector3 normalize() { MyVector3 vect; vect.x = this->x / this->length(); vect.y = this->y / this->length(); vect.z = this->z / this->length(); return vect; } float dotProduct(MyVector3 v) { return this->x * v.x + this->y * v.y + this->z * v.z; } MyVector3 crossProduct(MyVector3 v) { MyVector3 vect; vect.x = this->y * v.z - this->z * v.y; vect.y = this->z * v.x - this->x * v.z; vect.z = this->x * v.y - this->y * v.x; return vect; } ~MyVector3() { } }; class MyVector4 { public: float x, y, z, w; MyVector4() { } ///assigns values to x, y, z, and w MyVector4(float x, float y, float z, float w) { this->x = x; this->y = y; this->z = z; this->w = w; } ///vector + vector operator MyVector4 operator+(const MyVector4& v) { MyVector4 vect; vect.x = this->x + v.x; vect.y = this->y + v.y; vect.z = this->z + v.z; vect.w = this->w + v.w; return vect; } ///vector - vector operator MyVector4 operator-(const MyVector4& v) { MyVector4 vect; vect.x = this->x - v.x; vect.y = this->y - v.y; vect.z = this->z - v.z; vect.w = this->w - v.w; return vect; } ///vector * float operator MyVector4 operator*(const float scalar) { MyVector4 vect; vect.x = this->x * scalar; vect.y = this->y * scalar; vect.z = this->z * scalar; vect.w = this->w * scalar; return vect; } ///vector = vector operator MyVector4& operator=(const MyVector4& v) { x = v.x; y = v.y; z = v.z; w = v.w; return *this; } ///returns length of vector float length() { return sqrt(this->x * this->x + this->y * this->y + this->z * this->z); } ///uses length(), normalizes vector MyVector4 normalize() { MyVector4 vect; vect.x = this->x / this->length(); vect.y = this->y / this->length(); vect.z = this->z / this->length(); return vect; } ///computes dot product of vector float dotProduct(MyVector4 v) { return this->x * v.x + this->y * v.y + this->z * v.z; } ///computes cross product of vector MyVector4 crossProduct(MyVector4 v) { MyVector4 vect; vect.x = this->y * v.z - this->z * v.y; vect.y = this->z * v.x - this->x * v.z; vect.z = this->x * v.y - this->y * v.x; return vect; } ~MyVector4() { } }; class MyMatrix4 { public: float matrix[16]; MyMatrix4() { } ///sets diagonal to given float, other numbers to 0 MyMatrix4(float diagonal) { matrix[0] = diagonal; matrix[5] = diagonal; matrix[10] = diagonal; matrix[15] = diagonal; matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0; matrix[6] = matrix[7] = matrix[8] = matrix[9] = 0; matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0; } ///makes it so one doesn't have to type matrix whenever referencing a position with [] float& operator[](int index) { return matrix[index]; } ///matrix x matrix computation MyMatrix4 operator*(const MyMatrix4& m) { MyMatrix4 mat; mat[0] = this->matrix[0] * m.matrix[0] + this->matrix[1] * m.matrix[4] + this->matrix[2] * m.matrix[8] + this->matrix[3] * m.matrix[12]; //row 1, column 1 mat[1] = this->matrix[0] * m.matrix[1] + this->matrix[1] * m.matrix[5] + this->matrix[2] * m.matrix[9] + this->matrix[3] * m.matrix[13]; //row 1, column 2 mat[2] = this->matrix[0] * m.matrix[2] + this->matrix[1] * m.matrix[6] + this->matrix[2] * m.matrix[10] + this->matrix[3] * m.matrix[14]; //row 1, column 3 mat[3] = this->matrix[0] * m.matrix[3] + this->matrix[1] * m.matrix[7] + this->matrix[2] * m.matrix[11] + this->matrix[3] * m.matrix[15]; //row 1, column 4 mat[4] = this->matrix[4] * m.matrix[0] + this->matrix[5] * m.matrix[4] + this->matrix[6] * m.matrix[8] + this->matrix[7] * m.matrix[12]; //row 2, column 1 mat[5] = this->matrix[4] * m.matrix[1] + this->matrix[5] * m.matrix[5] + this->matrix[6] * m.matrix[9] + this->matrix[7] * m.matrix[13]; //row 2, column 2 mat[6] = this->matrix[4] * m.matrix[2] + this->matrix[5] * m.matrix[6] + this->matrix[6] * m.matrix[10] + this->matrix[7] * m.matrix[14]; //row 2, column 3 mat[7] = this->matrix[4] * m.matrix[3] + this->matrix[5] * m.matrix[7] + this->matrix[6] * m.matrix[11] + this->matrix[7] * m.matrix[15]; //row 2, column 4 mat[8] = this->matrix[8] * m.matrix[0] + this->matrix[9] * m.matrix[4] + this->matrix[10] * m.matrix[8] + this->matrix[11] * m.matrix[12]; //row 3, column 1 mat[9] = this->matrix[8] * m.matrix[1] + this->matrix[9] * m.matrix[5] + this->matrix[10] * m.matrix[9] + this->matrix[11] * m.matrix[13]; //row 3, column 2 mat[10] = this->matrix[8] * m.matrix[2] + this->matrix[9] * m.matrix[6] + this->matrix[10] * m.matrix[10] + this->matrix[11] * m.matrix[14]; //row 3, column 3 mat[11] = this->matrix[8] * m.matrix[3] + this->matrix[9] * m.matrix[7] + this->matrix[10] * m.matrix[11] + this->matrix[11] * m.matrix[15]; //row 3, column 4 mat[12] = this->matrix[12] * m.matrix[0] + this->matrix[13] * m.matrix[4] + this->matrix[14] * m.matrix[8] + this->matrix[15] * m.matrix[12]; //row 4, column 1 mat[13] = this->matrix[12] * m.matrix[1] + this->matrix[13] * m.matrix[5] + this->matrix[14] * m.matrix[9] + this->matrix[15] * m.matrix[13]; //row 4, column 2 mat[14] = this->matrix[12] * m.matrix[2] + this->matrix[13] * m.matrix[6] + this->matrix[14] * m.matrix[10] + this->matrix[15] * m.matrix[14]; //row 4, column 3 mat[15] = this->matrix[12] * m.matrix[3] + this->matrix[13] * m.matrix[7] + this->matrix[14] * m.matrix[11] + this->matrix[15] * m.matrix[15]; //row 4, column 4 return mat; } ///matrix x vector computation MyVector4 operator*(const MyVector4& v) { MyVector4 vect; vect.x = this->matrix[0] * v.x + this->matrix[1] * v.y + this->matrix[2] * v.z + this->matrix[3] * v.w; //row 1 vect.y = this->matrix[4] * v.x + this->matrix[5] * v.y + this->matrix[6] * v.z + this->matrix[7] * v.w; //row 2 vect.z = this->matrix[8] * v.x + this->matrix[9] * v.y + this->matrix[10] * v.z + this->matrix[11] * v.w; //row 3 vect.w = this->matrix[12] * v.x + this->matrix[13] * v.y + this->matrix[14] * v.z + this->matrix[15] * v.w; //row 4 return vect; } ///rotate v around x axis MyVector4 rotateX(MyVector4 v, float radians) { MyMatrix4 m(1); m[5] = cos(radians); m[6] = -sin(radians); m[9] = sin(radians); m[10] = cos(radians); return m * v; } ///rotate v around y axis MyVector4 rotateY(MyVector4 v, float radians) { MyMatrix4 m(1); m[0] = cos(radians); m[2] = sin(radians); m[8] = -sin(radians); m[10] = cos(radians); return m * v; } ///rotate v around z axis MyVector4 rotateZ(MyVector4 v, float radians) { MyMatrix4 m(1); m[0] = cos(radians); m[1] = -sin(radians); m[4] = sin(radians); m[5] = cos(radians); return m * v; } ///rotate vect around v vector MyVector4 rotateVector(MyVector4 v, MyVector4 vect, float r) { MyMatrix4 m(1); m[0] = cos(r) + v.x * v.x * (1 - cos(r)); m[1] = v.x * v.y * (1 - cos(r)) - v.z * sin(r); m[2] = v.x * v.z * (1 - cos(r)) + v.y * sin(r); m[4] = v.y * v.x * (1 - cos(r)) + v.z * sin(r); m[5] = cos(r) + v.y * v.y * (1 - cos(r)); m[6] = v.y * v.z * (1 - cos(r)) - v.x * sin(r); m[8] = v.z * v.x * (1 - cos(r)) - v.y * sin(r); m[9] = v.z * v.y * (1 - cos(r)) + v.x * sin(r); m[10] = cos(r) + v.z * v.z * (1 - cos(r)); return m * vect; } ///make rows and columns switch place MyMatrix4 transpose() { MyMatrix4 m; //row 1 to column 1 m[0] = this->matrix[0]; m[1] = this->matrix[4]; m[2] = this->matrix[8]; m[3] = this->matrix[12]; //row 2 to column 2 m[4] = this->matrix[1]; m[5] = this->matrix[5]; m[6] = this->matrix[9]; m[7] = this->matrix[13]; //row 3 to column 3 m[8] = this->matrix[2]; m[9] = this->matrix[6]; m[10] = this->matrix[10]; m[11] = this->matrix[14]; //row 4 to column 4 m[12] = this->matrix[3]; m[13] = this->matrix[7]; m[14] = this->matrix[11]; m[15] = this->matrix[15]; return m; } ///inverse computation MyMatrix4 inverse() { MyMatrix4 mat; float det, m[16]; m[0] = this->matrix[5] * this->matrix[10] * this->matrix[15] - this->matrix[5] * this->matrix[11] * this->matrix[14] - this->matrix[9] * this->matrix[6] * this->matrix[15] + this->matrix[9] * this->matrix[7] * this->matrix[14] + this->matrix[13] * this->matrix[6] * this->matrix[11] - this->matrix[13] * this->matrix[7] * this->matrix[10]; m[4] = -this->matrix[4] * this->matrix[10] * this->matrix[15] + this->matrix[4] * this->matrix[11] * this->matrix[14] + this->matrix[8] * this->matrix[6] * this->matrix[15] - this->matrix[8] * this->matrix[7] * this->matrix[14] - this->matrix[12] * this->matrix[6] * this->matrix[11] + this->matrix[12] * this->matrix[7] * this->matrix[10]; m[8] = this->matrix[4] * this->matrix[9] * this->matrix[15] - this->matrix[4] * this->matrix[11] * this->matrix[13] - this->matrix[8] * this->matrix[5] * this->matrix[15] + this->matrix[8] * this->matrix[7] * this->matrix[13] + this->matrix[12] * this->matrix[5] * this->matrix[11] - this->matrix[12] * this->matrix[7] * this->matrix[9]; m[12] = -this->matrix[4] * this->matrix[9] * this->matrix[14] + this->matrix[4] * this->matrix[10] * this->matrix[13] + this->matrix[8] * this->matrix[5] * this->matrix[14] - this->matrix[8] * this->matrix[6] * this->matrix[13] - this->matrix[12] * this->matrix[5] * this->matrix[10] + this->matrix[12] * this->matrix[6] * this->matrix[9]; m[1] = -this->matrix[1] * this->matrix[10] * this->matrix[15] + this->matrix[1] * this->matrix[11] * this->matrix[14] + this->matrix[9] * this->matrix[2] * this->matrix[15] - this->matrix[9] * this->matrix[3] * this->matrix[14] - this->matrix[13] * this->matrix[2] * this->matrix[11] + this->matrix[13] * this->matrix[3] * this->matrix[10]; m[5] = this->matrix[0] * this->matrix[10] * this->matrix[15] - this->matrix[0] * this->matrix[11] * this->matrix[14] - this->matrix[8] * this->matrix[2] * this->matrix[15] + this->matrix[8] * this->matrix[3] * this->matrix[14] + this->matrix[12] * this->matrix[2] * this->matrix[11] - this->matrix[12] * this->matrix[3] * this->matrix[10]; m[9] = -this->matrix[0] * this->matrix[9] * this->matrix[15] + this->matrix[0] * this->matrix[11] * this->matrix[13] + this->matrix[8] * this->matrix[1] * this->matrix[15] - this->matrix[8] * this->matrix[3] * this->matrix[13] - this->matrix[12] * this->matrix[1] * this->matrix[11] + this->matrix[12] * this->matrix[3] * this->matrix[9]; m[13] = this->matrix[0] * this->matrix[9] * this->matrix[14] - this->matrix[0] * this->matrix[10] * this->matrix[13] - this->matrix[8] * this->matrix[1] * this->matrix[14] + this->matrix[8] * this->matrix[2] * this->matrix[13] + this->matrix[12] * this->matrix[1] * this->matrix[10] - this->matrix[12] * this->matrix[2] * this->matrix[9]; m[2] = this->matrix[1] * this->matrix[6] * this->matrix[15] - this->matrix[1] * this->matrix[7] * this->matrix[14] - this->matrix[5] * this->matrix[2] * this->matrix[15] + this->matrix[5] * this->matrix[3] * this->matrix[14] + this->matrix[13] * this->matrix[2] * this->matrix[7] - this->matrix[13] * this->matrix[3] * this->matrix[6]; m[6] = -this->matrix[0] * this->matrix[6] * this->matrix[15] + this->matrix[0] * this->matrix[7] * this->matrix[14] + this->matrix[4] * this->matrix[2] * this->matrix[15] - this->matrix[4] * this->matrix[3] * this->matrix[14] - this->matrix[12] * this->matrix[2] * this->matrix[7] + this->matrix[12] * this->matrix[3] * this->matrix[6]; m[10] = this->matrix[0] * this->matrix[5] * this->matrix[15] - this->matrix[0] * this->matrix[7] * this->matrix[13] - this->matrix[4] * this->matrix[1] * this->matrix[15] + this->matrix[4] * this->matrix[3] * this->matrix[13] + this->matrix[12] * this->matrix[1] * this->matrix[7] - this->matrix[12] * this->matrix[3] * this->matrix[5]; m[14] = -this->matrix[0] * this->matrix[5] * this->matrix[14] + this->matrix[0] * this->matrix[6] * this->matrix[13] + this->matrix[4] * this->matrix[1] * this->matrix[14] - this->matrix[4] * this->matrix[2] * this->matrix[13] - this->matrix[12] * this->matrix[1] * this->matrix[6] + this->matrix[12] * this->matrix[2] * this->matrix[5]; m[3] = -this->matrix[1] * this->matrix[6] * this->matrix[11] + this->matrix[1] * this->matrix[7] * this->matrix[10] + this->matrix[5] * this->matrix[2] * this->matrix[11] - this->matrix[5] * this->matrix[3] * this->matrix[10] - this->matrix[9] * this->matrix[2] * this->matrix[7] + this->matrix[9] * this->matrix[3] * this->matrix[6]; m[7] = this->matrix[0] * this->matrix[6] * this->matrix[11] - this->matrix[0] * this->matrix[7] * this->matrix[10] - this->matrix[4] * this->matrix[2] * this->matrix[11] + this->matrix[4] * this->matrix[3] * this->matrix[10] + this->matrix[8] * this->matrix[2] * this->matrix[7] - this->matrix[8] * this->matrix[3] * this->matrix[6]; m[11] = -this->matrix[0] * this->matrix[5] * this->matrix[11] + this->matrix[0] * this->matrix[7] * this->matrix[9] + this->matrix[4] * this->matrix[1] * this->matrix[11] - this->matrix[4] * this->matrix[3] * this->matrix[9] - this->matrix[8] * this->matrix[1] * this->matrix[7] + this->matrix[8] * this->matrix[3] * this->matrix[5]; m[15] = this->matrix[0] * this->matrix[5] * this->matrix[10] - this->matrix[0] * this->matrix[6] * this->matrix[9] - this->matrix[4] * this->matrix[1] * this->matrix[10] + this->matrix[4] * this->matrix[2] * this->matrix[9] + this->matrix[8] * this->matrix[1] * this->matrix[6] - this->matrix[8] * this->matrix[2] * this->matrix[5]; det = this->matrix[0] * m[0] + this->matrix[1] * m[4] + this->matrix[2] * m[8] + this->matrix[3] * m[12]; for (int i = 0; i < 16; i++) { mat[i] = m[i] / det; if (mat[i] == -0) mat[i] = 0; } return mat; } ~MyMatrix4() { } };
81856dbae6558b55c65c6c9e537d9240f3f276db
341f61df4841409719462de654dcacfebce89784
/sudao-smsp/01_trunk/source/smsp_c2s/direct/CMPPDeliverResp.h
9448c9919ae27dff688561a1bd603ffb3d499d30
[]
no_license
jarven-zhang/paas_smsp
ebc0bbec8d3296d56a1adc6b49846b60237539a8
5bb8f59a54fa5013e144e91187781a487a767dca
refs/heads/master
2020-05-15T18:31:48.082722
2019-05-07T12:35:33
2019-05-07T12:35:33
182,426,035
0
0
null
null
null
null
UTF-8
C++
false
false
481
h
CMPPDeliverResp.h
#ifndef CMPPDELIVERRESP_H_ #define CMPPDELIVERRESP_H_ #include "CMPPBase.h" namespace smsp { class CMPPDeliverResp : public CMPPBase { public: CMPPDeliverResp(); virtual ~CMPPDeliverResp(); public: virtual UInt32 bodySize() const; virtual bool Pack(Writer &writer) const; virtual bool Unpack(Reader& reader); public: UInt64 _msgId; UInt8 _result; }; } /* namespace smsp */ #endif /* CMPPDELIVERRESP_H_ */
8f7b7ddac312654bb1e60c432f59bc823badd9f5
af0117d0f151dfbb27abd2b28c51640ea7a482fe
/CatPaws/CPCore/Src/CPStackAllocator.cpp
85e47ec818ee541fdaf984dd670bfbdddf4bb88d
[ "MIT" ]
permissive
gingercat-studio/GingerCats_Paws
ac5d526cfeb8544dc56c1a8b3f40cc448d921684
c6d8e8999c27cd032a68630b87c7f506488ac92f
refs/heads/master
2020-06-10T12:02:29.696575
2019-09-10T08:02:10
2019-09-10T08:02:10
193,643,349
0
0
null
null
null
null
UTF-8
C++
false
false
1,773
cpp
CPStackAllocator.cpp
#include "CPCore.h" CPStackAllocator::CPStackAllocator(std::size_t size, void* start) :CPAllocator(size, start) , current_position_{start} { assert(size > 0); #if _DEBUG prev_position_ = nullptr; #endif } CPStackAllocator::~CPStackAllocator() { #if _DEBUG prev_position_ = nullptr; #endif current_position_ = nullptr; } void* CPStackAllocator::Allocate(std::size_t size, uint8_t alignment) { assert(size != 0); uintptr_t adjustment = PtrMath::AlignFowardAdjustmentWithHeader (current_position_, alignment, sizeof(CPAllocationHeader)); if (used_memory_ + adjustment + size > size_) return nullptr; void* aligned_address = PtrMath::Move(current_position_, adjustment); CPAllocationHeader* header = (CPAllocationHeader*) (PtrMath::Move(aligned_address, -static_cast<int64_t>(sizeof(CPAllocationHeader)))); header->adjustment_ = adjustment; #if _DEBUG header->prev_address_ = prev_position_; prev_position_ = aligned_address; #endif current_position_ = PtrMath::Move(aligned_address, size); used_memory_ += size + adjustment; num_allocations_++; return aligned_address; } void CPStackAllocator::Deallocate(void* p) { #if _DEBUG assert(p == prev_position_); #endif // Access the allocation header CPAllocationHeader* header = (CPAllocationHeader*) (PtrMath::Move(p, -static_cast<int64_t>(sizeof(CPAllocationHeader)))); used_memory_ -= (uintptr_t)current_position_ - (uintptr_t)p + header->adjustment_; current_position_ = PtrMath::Move(p, -static_cast<int64_t>((header->adjustment_))); #if _DEBUG prev_position_ = header->prev_address_; #endif num_allocations_--; }
265382e60e4eb8af4993c9016f4afce31058cc1b
77bacab54e77422c815dbc59dd08e77a5ca09293
/aoj/volume0/n0049/Main.cpp
ba2b1211a6773e2be5c7842019d26baf02a95760
[ "MIT" ]
permissive
KoKumagai/exercises
7819f0199efa99a2321cd8b83cdad76958a49911
256b226d3e094f9f67352d75619b392a168eb4d1
refs/heads/master
2020-05-21T20:46:57.599713
2018-01-15T10:46:56
2018-01-15T10:46:56
60,871,560
0
0
null
null
null
null
UTF-8
C++
false
false
552
cpp
Main.cpp
#include <iostream> using namespace std; int main() { int id; char comma; string bloodType; int a = 0, b = 0, ab = 0, o = 0; while (cin >> id >> comma >> bloodType) { if (bloodType == "A") { a++; } if (bloodType == "B") { b++; } if (bloodType == "AB") { ab++; } if (bloodType == "O") { o++; } } cout << a << endl; cout << b << endl; cout << ab << endl; cout << o << endl; return 0; }
3b70e8a75cd604f24f27d6a536dcc0fefcfd27b7
0da4fb313b9ac09b0091754d2f3b187b40a9efb0
/Classes/Singletons/Helpers.h
70bbfc32725266e937f55126ef13012a564dcb37
[ "MIT" ]
permissive
alexkangbiao/ChickenRunningII
ae97a36f678418053220557deb7ec6e5da47cbb1
4ef55d21d5871a24746d2b85019512497197a3de
refs/heads/master
2020-06-23T15:11:19.109113
2019-07-24T15:04:09
2019-07-24T15:04:09
198,657,831
0
1
null
null
null
null
UTF-8
C++
false
false
496
h
Helpers.h
#ifndef __Helpers_H__ #define __Helpers_H__ #include "cocos2d.h" USING_NS_CC; // directions typedef enum GameDirs : unsigned int{ GameDirNone = 0, GameDirUp = 1, GameDirDown = 2, GameDirLeft = 3, GameDirRight = 4 } GameDirs; class Helpers { public: static int swipeDirection(Point start, Point end); static std::vector<std::string> explodeString(std::string delimiter, std::string str); static bool to_bool(std::string const& s); }; #endif // __Helpers_H__
82865d7d45b99208e56da34fb888085764c3d2d3
fc55df3cbed39b6b6b0bca937c055de7b25da51d
/src/lightSrc.cpp
464dd99d7277d3f73e892c6ed662dab00ceddd56
[]
no_license
piotrfutymski/Maze_2
dbd7f258358a66c624ea0c56bc1b786866cc2c4b
61e014f71cf935b96eb0864e2c26694276c51258
refs/heads/master
2023-03-08T10:32:34.796180
2021-02-11T18:42:10
2021-02-11T18:42:10
285,009,693
0
0
null
null
null
null
UTF-8
C++
false
false
2,603
cpp
lightSrc.cpp
#include "LightSrc.h" LightSrc::LightSrc(ShaderProgram* p, Model* m, glm::mat4 M, const glm::vec3& pos,const glm::vec3& color) : Entity(p), _mod(m), _M(M), envID(Environment::lightsCount++) { Environment::lights[envID].color = color; Environment::lights[envID].strength = 1.f; this->changePos(pos); // Creating Depth Textures for (int i = 0; i < 6; i++) { unsigned int depthMap; glGenTextures(1, &depthMap); glBindTexture(GL_TEXTURE_2D, depthMap); glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, Environment::smapWidth, Environment::smapHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); float borderColor[] = { 1.0, 1.0, 1.0, 1.0 }; glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor); Environment::lights[envID].depthMap[i] = depthMap; } } void LightSrc::changePos(const glm::vec3& pos) { static glm::mat4 lightProjection, lightView; static float near_plane = .1f, far_plane = 50.f; static glm::vec3 directions[] = { glm::vec3(1.f,0.f,0.f), glm::vec3(0.f, 1.f, 0.f), glm::vec3(0.f,0.f,1.f), // x, y, z glm::vec3(-1.f,0.f,0.f), glm::vec3(0.f, -1.f, 0.f), glm::vec3(0.f,0.f,-1.f) // -x, -y, -z }; lightProjection = glm::perspective(glm::radians(90.f), (GLfloat)Environment::smapWidth / (GLfloat)Environment::smapHeight, near_plane, far_plane); for (int i = 0; i < 6; i++) { lightView = glm::lookAt(pos, pos + directions[i], directions[(i + 1) % 6]); Environment::lights[envID].lightSpaceMatrix[i] = lightProjection * lightView; } Environment::lights[envID].position = pos; } void LightSrc::changeColor(const glm::vec3& color) { Environment::lights[envID].color = color; } void LightSrc::setStrength(float scale) { Environment::lights[envID].strength = scale; } void LightSrc::draw() { glUseProgram(_shaderProgram->get()); glUniformMatrix4fv(_shaderProgram->u("P"), 1, false, glm::value_ptr(Environment::P)); glUniformMatrix4fv(_shaderProgram->u("V"), 1, false, glm::value_ptr(Environment::V)); glUniformMatrix4fv(_shaderProgram->u("M"), 1, false, glm::value_ptr(_M)); glBindVertexArray(_mod->get()); glDrawArrays(GL_TRIANGLES, 0, _mod->count()); } void LightSrc::update(float dt) { }
fa9fca84d90a57e05617a7b89d9ba22740a05356
eabfaf54d50dfa9544604f4c74a7d734e4ee914e
/software/ESP01/R2ESP01/R2ESP01.ino
529f79bb50ccfd1126de8625d2ebe89ff5354f8a
[]
no_license
inggunny/Laboratorio_de_robotica_movil_en_Cloud
5bf91bf62cc42dc0f8a5e3a72c63c448dd45469d
1292a21da1205ab7d7e5aea67d93cab1e3cba917
refs/heads/master
2020-07-02T23:35:51.352537
2019-08-24T21:07:27
2019-08-24T21:07:27
201,707,564
0
0
null
null
null
null
UTF-8
C++
false
false
5,963
ino
R2ESP01.ino
/* */ String W =" "; char w =' '; int robot = 2;//numero de robot #include <ESP8266WiFi.h> #include <PubSubClient.h> const char* ssid = "GunnY"; const char* password = "abcde12345"; const char* mqtt_server = "192.168.1.200"; //ip del server 192.168.1.200 IPAddress ip(192, 168, 1, 102); // IP ROBOT IPAddress gateway(192, 168, 1, 1);// GATEWAY IPAddress subnet(255, 255, 255, 0); //AVERIGUAR int timeout=2500; WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; void setup() { Serial.begin(9600); setup_wifi(); client.setServer(mqtt_server, 1883); //PUERTO client.setCallback(callback); } void setup_wifi() { delay(10); WiFi.begin(ssid, password); WiFi.config(ip, gateway, subnet); while (WiFi.status() != WL_CONNECTED) { delay(500); } } void callback(char* topic, byte* payload, unsigned int length) { for (int i = 0; i < length; i++) { }//cambiar //---------------------------------------- if ((char)payload[0] == 'Q') { snprintf (msg, 75, "IZQUIERDAQ&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,doblando,izquierda,abierto",robot); client.publish("control", msg); } if ((char)payload[0] == 'A'){ snprintf (msg, 75, "IZQUIERDAA&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,doblando,izquierda,medio",robot); client.publish("control", msg); } if ((char)payload[0] == 'Z'){ snprintf (msg, 75, "IZQUIERDAZ&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,doblando,izquierda,cerrado",robot); client.publish("control", msg); } //---------------------------------------- if ((char)payload[0] == 'W') { snprintf (msg, 75, "ADELANTEW&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,avanzando,rapido,0",robot); client.publish("control", msg); } if ((char)payload[0] == 'S'){ snprintf (msg, 75, "ADELANTES&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,avanzando,medio,0",robot); client.publish("control", msg); } if ((char)payload[0] == 'X'){ snprintf (msg, 75, "ADELANTEX&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,avanzando,lento,0",robot); client.publish("control", msg); } //---------------------------------------- if ((char)payload[0] == 'E') { snprintf (msg, 75, "DERECHAE&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,doblando,derecha,abierto",robot); client.publish("control", msg); } if ((char)payload[0] == 'D'){ snprintf (msg, 75, "DERECHAD&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,doblando,derecha,medio",robot); client.publish("control", msg); } if ((char)payload[0] == 'C'){ snprintf (msg, 75, "DERECHAC&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,doblando,derecha,cerrado",robot); client.publish("control", msg); } //---------------------------------------- if ((char)payload[0] == 'F'){ snprintf (msg, 75, "DETENER&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,detenido,0,0",robot); client.publish("control", msg); } if ((char)payload[0] == 'R'){ snprintf (msg, 75, "ATRAS&"); Serial.println(msg); snprintf (msg, 75, "robot%d,desplazamiento,retrocediendo,0,0",robot); client.publish("control", msg); } //---------------------------------------- if ((char)payload[0] == 'P'){ Serial.println("POSICION&"); leerserial(); float lat = W.toFloat(); W = "" ; w = ' ' ; leerserial(); float lon = W.toFloat(); snprintf (msg, 75, "robot%d,sensor,posicion,%f,%f",robot,lat,lon); client.publish("control", msg); W = "" ; w = ' ' ; Serial.println(""); } //---------------------------------------- if ((char)payload[0] == 'V'){ Serial.println("VELOCIDAD&"); leerserial(); float vel = W.toFloat(); snprintf (msg, 75, "robot%d,sensor,velocidad,%f,0",robot,vel); client.publish("control", msg); W = "" ; w = ' ' ; Serial.println(""); } //--------------------------------------- if ((char)payload[0] == 'H'){ Serial.println("ALTITUD&"); leerserial(); float alt = W.toFloat(); snprintf (msg, 75, "robot%d,sensor,altitud,%f,0",robot,alt); client.publish("control", msg); W = "" ; w = ' ' ; Serial.println(""); } //--------------------------------------- if ((char)payload[0] == 'N'){ Serial.println("SATELITE&"); leerserial(); int sat = W.toInt(); snprintf (msg, 75, "robot%d,sensor,satelite,%d,0",robot, sat); client.publish("control", msg); W = "" ; w = ' ' ; Serial.println(""); } //--------------------------------------- if ((char)payload[0] == 'U'){ Serial.println("ULTRA&"); leerserial(); int ultra = W.toInt(); snprintf (msg, 75, "robot%d,sensor,ultrasonico,%d,0",robot, ultra); client.publish("control", msg); W = "" ; w = ' ' ; Serial.println(""); } } //--------------------------------------- //--------------------------------------- void reconnect() { while (!client.connected()) { if (client.connect("ROBOT2")) { client.publish("control", "robot2,enlinea,,"); client.subscribe("campo/desplazamiento/robot2"); } else { delay(1000); } } } //---------------------------------------- void leerserial(){ long int time1 = millis(); while(1){ if (Serial.available()) { w = Serial.read() ; if(w == '\n'){ return ; } W = W + w ; } long int time2=millis()-time1; if(time2 >= timeout){ W="99";return ;}//agregar timeout }} //------------------------------ void loop() { if (!client.connected()) { reconnect(); } client.loop(); }
5edabc15e3f8759f91f3dffb4f4682a74ef8c95e
f5ca13449a9c38b9ccb7cabfad55c0fb70b64795
/MyScript/CLisp.h
2f657a742126a029d3e95ba14273e82d3393b9cd
[]
no_license
bajdcc/MyScript
f167e3ad91b6d11099d19814e51a0f279df60782
f51007a9852a0be5a1486a78ae993c9f8023f59c
refs/heads/master
2021-01-19T13:39:22.959428
2017-08-24T02:35:45
2017-08-24T02:35:45
100,853,308
3
1
null
null
null
null
GB18030
C++
false
false
5,059
h
CLisp.h
#pragma once #include "clib_memory.h" #include "MyScriptBaseVisitor.h" // Refer: http://piumarta.com/software/lysp/lysp-1.1/lysp.c class CLisp : public MyScriptBaseVisitor { public: CLisp(); ~CLisp(); public: typedef enum { None, Number, String, Symbol, Cons, Subr, Fsubr, Expr, Fexpr } Tag; // 由于需要GC,那么所有的对象就表为Cell同一结构 struct Cell { Tag tag; union { int number; const char *string; const char *symbol; struct { Cell *a; Cell *d; } cons; struct { Cell *expr; Cell *env; } expr; typedef Cell *(CLisp::*subr_t)(Cell *args, Cell *env); subr_t subr; }; }; using Subr_t = Cell *(CLisp::*)(Cell *args, Cell *env); private: clib::memory::memory_pool<> gc; clib::memory::memory_pool<> strings; const char *__strdup(const char *); void mark(Cell *); void unmark(Cell *); static void fatal(const char *); void init(); void init_fsubr(const char *, Subr_t); void init_subr(const char *, Subr_t); Cell *_S_t = nullptr; Cell *_S_quote = nullptr; Cell *_S_qquote = nullptr; Cell *_S_uquote = nullptr; Cell *_S_uquotes = nullptr; Cell *syntaxTable = nullptr; Cell* interns = nullptr; Cell *globals = nullptr; using apply_t = void(*)(void); using arglist_t = union { char *argp; } *; Cell* cell(); Cell* cell_num(int n); Cell* cell_str(const char* s); Cell* cell_sym(const char* s); Cell* cell_cons(Cell* a, Cell* d); Cell* cell_subr(Subr_t fn); Cell* cell_fsubr(Subr_t fn); Cell* cell_expr(Cell* x, Cell* e); Cell* cell_fexpr(Cell* x, Cell* e); int nilP(Cell* self); int numberP(Cell* self); int stringP(Cell* self); int symbolP(Cell* self); int consP(Cell* self); int subrP(Cell* self); int fsubrP(Cell* self); int exprP(Cell* self); int fexprP(Cell* self); int number(Cell* self); const char* string(Cell* self); const char* symbol(Cell* self); Subr_t subr(Cell* self); Subr_t fsubr(Cell* self); Cell* expr(Cell* self); Cell* exprenv(Cell* self); Cell* fexpr(Cell* self); Cell* fexprenv(Cell* self); Cell* car(Cell* self); Cell* cdr(Cell* self); Cell* rplaca(Cell* self, Cell* c); Cell* rplacd(Cell* self, Cell* c); Cell* caar(Cell* self); Cell* cadr(Cell* self); Cell* cdar(Cell* self); Cell* caddr(Cell* self); Cell* cadar(Cell* self); Cell* intern(const char* s); Cell* assq(Cell* key, Cell* list); Cell* undefined(Cell* sym); Cell* evargs(Cell* self, Cell* env); Cell* evbind(Cell* expr, Cell* args, Cell* env); Cell* evlist(Cell* expr, Cell* env); Cell* apply(Cell* fn, Cell* args, Cell* env); Cell* eval(Cell* expr, Cell* env); Cell* defineFsubr(Cell* args, Cell* env); Cell* setqFsubr(Cell* args, Cell* env); Cell* lambdaFsubr(Cell* args, Cell* env); Cell* flambdaFsubr(Cell* args, Cell* env); Cell* letFsubr(Cell* args, Cell* env); Cell* orFsubr(Cell* args, Cell* env); Cell* andFsubr(Cell* args, Cell* env); Cell* ifFsubr(Cell* args, Cell* env); Cell* whileFsubr(Cell* args, Cell* env); Cell* mapArgs(Cell* args); Cell* mapSubr(Cell* args, Cell* env); Cell* evalSubr(Cell* args, Cell* env); Cell* applySubr(Cell* args, Cell* env); Cell* consSubr(Cell* args, Cell* env); Cell* rplacaSubr(Cell* args, Cell* env); Cell* rplacdSubr(Cell* args, Cell* env); Cell* carSubr(Cell* args, Cell* env); Cell* cdrSubr(Cell* args, Cell* env); Cell* assqSubr(Cell* args, Cell* env); Cell* printSubr(Cell* args, Cell* env); Cell* printlnSubr(Cell* args, Cell* env); Cell* addSubr(Cell* args, Cell* env); Cell* subtractSubr(Cell* args, Cell* env); Cell* multiplySubr(Cell* args, Cell* env); Cell* divideSubr(Cell* args, Cell* env); Cell* modulusSubr(Cell* args, Cell* env); Cell* lessSubr(Cell* args, Cell* env); Cell* lessEqualSubr(Cell* args, Cell* env); Cell* equalSubr(Cell* args, Cell* env); Cell* notEqualSubr(Cell* args, Cell* env); Cell* greaterEqualSubr(Cell* args, Cell* env); Cell* greaterSubr(Cell* args, Cell* env); public: Cell* run(std::string str); Cell* repl(Cell* expr); Cell* print(Cell* self, std::ostream& stream); Cell* println(Cell* self, std::ostream& stream); antlrcpp::Any visitStart(MyScriptParser::StartContext* ctx) override; antlrcpp::Any visitExprs(MyScriptParser::ExprsContext* ctx) override; antlrcpp::Any visitExpr(MyScriptParser::ExprContext* ctx) override; antlrcpp::Any visitQuote(MyScriptParser::QuoteContext* ctx) override; antlrcpp::Any visitList(MyScriptParser::ListContext* ctx) override; antlrcpp::Any visitAtom(MyScriptParser::AtomContext* ctx) override; };
fef71f2785cf8f7d4b186612d81cfb5c318840ca
3f3a42f429f8bcd769644148b24c3b0e6e2589ed
/GameProjectCopy/GameEngine/GameApp/GameObject.h
7f87d5dc740557ffe7eb50a007ae939031447ca7
[]
no_license
DanielNeander/my-3d-engine
d10ad3e57a205f6148357f47467b550c7e0e0f33
7f0babbfdf0b719ea4b114a89997d3e52bcb2b6c
refs/heads/master
2021-01-10T17:58:25.691360
2013-04-24T07:37:31
2013-04-24T07:37:31
53,236,587
3
0
null
null
null
null
UTF-8
C++
false
false
5,720
h
GameObject.h
#pragma once #include <EngineCore/RefCount.h> #include "WeakPointer.h" #include "FSM.h" #include "AI/AICommon.h" MSmartPointer(ITransformComponent); MSmartPointer(IGameObjectComponent); MSmartPointer(SceneNode); class IGameObjectComponent; MSmartPointer(IGameObjectAttribute); //Add new object types here (bitfield mask - objects can be combinations of types) #define OBJECT_Ignore_Type (0) #define OBJECT_Gameflow (1<<1) #define OBJECT_Character (1<<2) #define OBJECT_NPC (1<<3) #define OBJECT_Player (1<<4) #define OBJECT_Enemy (1<<5) #define OBJECT_Weapon (1<<6) #define OBJECT_Item (1<<7) #define OBJECT_Projectile (1<<8) enum StateMachineChange { NO_STATE_MACHINE_CHANGE, STATE_MACHINE_RESET, STATE_MACHINE_REPLACE, STATE_MACHINE_QUEUE, STATE_MACHINE_REQUEUE, STATE_MACHINE_PUSH, STATE_MACHINE_POP }; class StateMachine; class IGameObjectMessage { public: virtual ~IGameObjectMessage() {} virtual uint32 GetId()=0; }; class GameObject : public FSMObject, public RefCounter { public: noDeclareRootRTTI(GameObject); GameObject(const std::string& filename); //GameObject(M2Loader* pLoader); virtual ~GameObject(); void AttachComponent(IGameObjectComponent *pkComponent); void AttachAttribute(IGameObjectAttribute *pkAttribute); void RemoveAttribute(IGameObjectAttribute *pkAttribute); void RemoveComponent(IGameObjectComponent *pkComponent); virtual void PreUpdate() { } virtual bool Update(float fDelta); virtual void PostUpdate() { } virtual bool ProcessInput(); WeakPointerData* GetWeakPointerData() { return m_weakPointer.GetWeakPointerData(); } virtual noVec3 GetTranslation(); virtual noMat3 GetRotation(); virtual float GetScale(); virtual noVec3 GetVelocity(); virtual void SetRotation(const noMat3 &rotation); virtual void SetTranslation(const noVec3 &translation); virtual void SetHeight(float height); virtual void SetScale(float fScale); virtual void SetVelocity(const noVec3 &velocity); /*void Hide(); void Show(); bool IsHidden(); void Pause(); void Resume(); void TogglePause();*/ IGameObjectComponent *GetComponentOfType(const noRTTI &type); IGameObjectAttribute *GetAttributeOfType(const noRTTI &type); const char* GetName(); void SetName(const std::string &name); virtual bool HandleMessage(IGameObjectMessage *pkMessage) { return false; } virtual float GetUpdateTime(); void AttachGameObject(GameObject *pkGameObject, const noVec3 &offset = vec3_zero, bool bRotation=true); void DetachGameObject(GameObject *pkGameObject); virtual void ResetTranslation(const noVec3 &position); virtual void CreateTransformComponent(); ITransformComponent *GetTransformComponent(); //virtual bool OnCollision(const GameObjectCollision &collisionArray); SceneNode *GetNode() { return m_spNode; } void SetID(objectID id) { m_id = id; } objectID GetID( void ) { return( m_id ); } void SetType(unsigned int type) { m_type = type; } unsigned int GetType( void ) { return( m_type ); } //State Machine access StateMachine* GetStateMachine( void ) { if( m_stateMachineList.empty() ) { return( 0 ); } else { return( m_stateMachineList.back() ); } } void RequestStateMachineChange( StateMachine * mch, StateMachineChange change ); void ResetStateMachine( void ); void ReplaceStateMachine( StateMachine & mch ); void QueueStateMachine( StateMachine & mch ); void RequeueStateMachine( void ); void PushStateMachine( StateMachine & mch ); void PopStateMachine( void ); void DestroyStateMachineList( void ); int GetHealth( void ) { return( m_health ); } void SetHealth( int health ) { if( health > 0 ) { m_health = health; } else { m_health = 0; } } bool IsAlive( void ) { return( m_health > 0 ); } protected: virtual void Initialize(); virtual void AttachComponents() { } // convenient place for subclasses to attach components virtual bool UpdateComponents(float fDelta); virtual bool PostUpdateComponents(float fDelta); virtual void UpdateInternal(float fDelta); virtual void LoadModel() {} void InitNewComponents(); virtual void UpdateAttachments(); void RemoveDeadComponents(); // remove unwanted components void SetTransformComponent(ITransformComponent *pkComponent); virtual void OnTeleported(); protected: WeakPointerMaster m_weakPointer; bool m_bPaused; ITransformComponentPtr m_spTransformComponent; std::vector<IGameObjectComponentPtr> m_components; std::vector<IGameObjectComponentPtr> m_newComponents; std::vector<IGameObjectAttributePtr> m_attributes; std::vector<class GameObjectAttachment*> m_attachedObjects; std::string m_name; std::string m_filename; noVec3 m_velocity; int m_health; SceneNodePtr m_spNode; friend class GameObjectManager; private: typedef std::list<StateMachine*> stateMachineListContainer; objectID m_id; //Unique id of object (safer than a pointer). unsigned int m_type; //Type of object (can be combination). stateMachineListContainer m_stateMachineList; //List of state machines. Top one is active. StateMachineChange m_stateMachineChange; //Directions for any pending state machine changes StateMachine * m_newStateMachine; //A state machine that will be added to the queue later void ProcessStateMachineChangeRequests( void ); }; noWeakPointer(GameObject);
2764a84f76e126d01c0a7dcf9349477fea6e755a
e097ca136d17ff092e89b3b54214ec09f347604f
/include/amtrs/lang/java/class/android/view/SurfaceHolder.hpp
27f19ba655fb93308e387f609d727be65e6cd399
[ "BSD-2-Clause" ]
permissive
isaponsoft/libamtrs
1c02063c06613cc43091d5341c132b45d3051ee0
0c5d4ebe7e0f23d260bf091a4ab73ab9809daa50
refs/heads/master
2023-01-14T16:48:23.908727
2022-12-28T02:27:46
2022-12-28T02:27:46
189,788,925
2
0
null
null
null
null
UTF-8
C++
false
false
2,542
hpp
SurfaceHolder.hpp
/* Copyright (c) 2019, isaponsoft (Isao Shibuya) All rights reserved. * * Use of this source code is governed by a BSD-style license that * * can be found in the LICENSE file. */ #ifndef __libamtrs__android__java_classes__android_view__SurfaceHolder__hpp #define __libamtrs__android__java_classes__android_view__SurfaceHolder__hpp #include "../../java/lang/Object.hpp" AMTRS_JAVA_CLASSES_NAMESPACE_BEGIN namespace android::graphics { struct Canvas; struct Rect; } namespace android::view { struct Surface; AMTRS_JAVA_DEFINE_CLASS(SurfaceHolder, java::lang::Object) { using Canvas = android::graphics::Canvas; using Rect = android::graphics::Rect; AMTRS_JAVA_CLASS_SIGNATURE("android/view/SurfaceHolder"); AMTRS_JAVA_DEFINE_CLASS(Callback, java::lang::Object) { AMTRS_JAVA_CLASS_SIGNATURE("android/view/SurfaceHolder$Callback"); // クラスメソッドとクラスフィールド AMTRS_JAVA_DEFINE_STATIC_MEMBER { AMTRS_JAVA_STATICS_BASIC; }; // 動的メソッドと動的フィールド AMTRS_JAVA_DEFINE_DYNAMICS_MEMBER { AMTRS_JAVA_DYNAMICS_BASIC; }; }; // クラスメソッドとクラスフィールド AMTRS_JAVA_DEFINE_STATIC_MEMBER { AMTRS_JAVA_STATICS_BASIC; AMTRS_JAVA_DEFINE_FIELD(jint, SURFACE_TYPE_GPU) AMTRS_JAVA_DEFINE_FIELD(jint, SURFACE_TYPE_HARDWARE) AMTRS_JAVA_DEFINE_FIELD(jint, SURFACE_TYPE_NORMAL) AMTRS_JAVA_DEFINE_FIELD(jint, SURFACE_TYPE_PUSH_BUFFERS) }; // 動的メソッドと動的フィールド AMTRS_JAVA_DEFINE_DYNAMICS_MEMBER { AMTRS_JAVA_DYNAMICS_BASIC; AMTRS_JAVA_DEFINE_METHOD(addCallback , void(Callback callback) ) AMTRS_JAVA_DEFINE_METHOD(getSurface , Surface() ) AMTRS_JAVA_DEFINE_METHOD(getSurfaceFrame , Rect() ) AMTRS_JAVA_DEFINE_METHOD(isCreating , jboolean() ) AMTRS_JAVA_DEFINE_METHOD(lockCanvas , Canvas() , Canvas(Rect dirty) ) AMTRS_JAVA_DEFINE_METHOD(lockHardwareCanvas , Canvas() ) AMTRS_JAVA_DEFINE_METHOD(removeCallback , void(Callback callback) ) AMTRS_JAVA_DEFINE_METHOD(setFixedSize , void(jint width, jint height) ) AMTRS_JAVA_DEFINE_METHOD(setFormat , void(jint format) ) AMTRS_JAVA_DEFINE_METHOD(setKeepScreenOn , void(jboolean screenOn) ) AMTRS_JAVA_DEFINE_METHOD(setSizeFromLayout , void() ) AMTRS_JAVA_DEFINE_METHOD(setType , void(jint type) ) AMTRS_JAVA_DEFINE_METHOD(unlockCanvasAndPost , void(Canvas canvas) ) }; }; } AMTRS_JAVA_CLASSES_NAMESPACE_END #endif
62c7d8d298bc2207e4256e8daf0a447ca8c5f3ee
934c14082fed25d8161079d8615b11b3ef84f088
/EasyButton/EasyButton.h
1868a750c1b92ad109544e523c0aa02637cbd43d
[ "MIT" ]
permissive
blackhack/ArduLibraries
5bc25ce2df7af75e700fcbb45b755496c0bed3ea
2f26ef7b1fbe91303e599e0171d18d78f026c2ef
refs/heads/master
2021-01-17T14:51:34.097533
2017-11-23T12:55:20
2017-11-23T12:55:20
7,395,763
25
34
MIT
2018-10-30T14:42:20
2013-01-01T13:55:42
C++
ISO-8859-2
C++
false
false
1,426
h
EasyButton.h
/* #name: EasyButton.cpp #version: 1.0 #author: José Aristizábal #nick: Blackhack #contact: davidaristi.0504@gmail.com */ #ifndef _EASYBUTTON_h #define _EASYBUTTON_h #if defined(ARDUINO) && ARDUINO >= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #define DEFAULT_PUSH_THRESHOLD 1000 #define DEBOUNCE_DELAY 50 enum FunctionCallOptions { CALL_NONE = 0, CALL_IN_PUSHED = 1, CALL_IN_PUSH = 2, CALL_IN_HOLD = 4, CALL_IN_RELEASE = 8, CALL_IN_ALL = (CALL_IN_PUSHED | CALL_IN_PUSH | CALL_IN_HOLD | CALL_IN_RELEASE) }; class EasyButton { private: bool m_current_state; bool m_press_notifier; bool m_release_notifier; bool m_hold; bool m_pullup_mode; unsigned long m_hold_time; unsigned long m_release_time; int m_pin; unsigned int m_push_Threshold; void (*m_function)(); FunctionCallOptions m_call_option; public: EasyButton(int buttonPin, void (*function)() = NULL, FunctionCallOptions call_option = CALL_NONE, bool pullup = false); void update(unsigned long millisec = NULL); bool IsPushed(); bool InPush() { return m_current_state; } bool IsHold(); bool IsRelease(); void SetThreshold(unsigned int ms) { m_push_Threshold = ms; } void SetCallFunction(void (*function)() = NULL, FunctionCallOptions call_option = CALL_NONE); }; #endif // _EASYBUTTON_h
1e0e822be779d6c284e579a69cdc762492c7eb97
4a87f5e7372f7d0312f8e08ac58274cd500008bd
/hashmap&heaps/pairSumDivisibility.cc
9479b03b62aa6281ece347031632a2aeae1a8606
[]
no_license
mahimahans111/cpp_codes
b025c214ab3ce6a8c34bf0e23384edb74afb1818
fe6f88aca79cb8366107f3dcd08cff7f532c2242
refs/heads/master
2021-06-28T07:48:35.400033
2020-10-31T17:34:12
2020-10-31T17:34:12
211,819,858
1
4
null
2021-02-02T13:15:02
2019-09-30T09:05:21
C++
UTF-8
C++
false
false
862
cc
pairSumDivisibility.cc
#include<bits/stdc++.h> using namespace std; map<int, int> m; bool pairSumDivisibility(int arr[], int n, int k){ for(int i = 0; i < n; i++){ if(arr[i]<0){ int no = (k-(arr[i]%k))%k; if(m.count(no))m[no]++; else m[no] = 1; } else if(m.count(arr[i]%k)) m[arr[i]%k]++; else m[arr[i]%k] = 1; } if(k%2 == 0){ if(m.count(k/2) && m[k/2]%2 != 0) return false; } if(m.count(0) && m[0]%2!= 0) return false; for(int i = 1; i <= k/2; i++){ if(m[i]!=m[k-i]) return false; } return true; } int main(){ int n; cin >> n; int arr[n]; for(int i = 0; i < n; i++){ cin >> arr[i]; } int k; cin >> k; bool ans = pairSumDivisibility(arr, n, k); // cout <<-402%100; // for(int i = 0; i < k; i++){ // // cout << "i wanna"; // if(m.count(i))cout << i << " " << m[i] << " "; // } ans==1?cout << "Yes" : cout << "No"; }
9f71c40c34dcc261bac72a5d8dfd88ac4c61a61f
a9dfddf283ce56acfb211066fd96fc741944d4c4
/328.cpp
6cd1b41f97fe5bfe1317210b5bf539bd617da16d
[]
no_license
UladzislauB/algo-acmp
b0c6392eb56d92f9dff21455ef07416e46e32a7e
5c9d493a8fd93b2616e2d471f57518e314a56cd6
refs/heads/master
2021-07-14T21:24:25.787058
2020-06-10T12:37:16
2020-06-10T12:37:16
167,836,709
0
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
328.cpp
#include <fstream> #include <iostream> using namespace std; int main() { ifstream fin("input.txt"); ofstream fout("output.txt"); long long n,s=0; fin>>n; for(int i=1; i<=n; i++) s=s+i*(n+2); fout<<s; return 0; }
3f9d5ed4bfcdf9b0f5e81463b86bbbdf7f09d62b
6f30ac85e1b02e2d314d17ff8b0b185350cd6519
/code/elements/threaded_runner.h
b6cbd9f824ca52bcfe9e23ec00fac270eeecb766
[]
no_license
egrois/my_events_stuff
06f4a84958a90dbc432f58182f4a974554d8f1c8
9a2142b5e726e9686e985ea692a428b2d772d6c3
refs/heads/master
2021-01-19T02:31:32.208913
2016-07-19T15:46:40
2016-07-19T15:46:40
63,707,043
0
1
null
null
null
null
UTF-8
C++
false
false
1,086
h
threaded_runner.h
#ifndef ELEMENTS_THREADED_RUNNER_H #define ELEMENTS_THREADED_RUNNER_H #include <thread> namespace elements { class threaded_runner { public: threaded_runner() {} threaded_runner( int affinity ) { _affinity = affinity; } virtual ~threaded_runner() {} void run() { _is_running = true; using namespace std; _thread = new std::thread( bind( &elements::threaded_runner::_run, this ) ); } void stop() { _is_running = false; _thread->join(); delete _thread; } protected: bool _is_running = false; std::thread * _thread; int _affinity = -1; void _run() { if(_affinity >= 0 ) { cpu_set_t mask; CPU_ZERO(&mask); CPU_SET((unsigned int)_affinity, &mask); sched_setaffinity(0,sizeof(mask), &mask); } while(true) { _process(); if(_is_running == false) break; } } virtual void _process() { } }; } #endif //ELEMENTS_THREADED_RUNNER_H
589f250aa63e4a650b8714195167d27c108072d6
6f75b8771085d4809611c1a6d8981bc86afa533f
/CodeChef/Aprillong/first.cpp
c342916457e515c4cec44e02f8d4ae091cd26307
[]
no_license
ohil17yo36/CodeChef-Long
507ba9ce398294876eb563f940417b327917f6be
688a03858c6d9787aaec0e0ac3187be752eb7d11
refs/heads/master
2021-01-13T02:08:11.572643
2015-09-03T12:31:31
2015-09-03T12:31:31
41,857,237
1
0
null
null
null
null
UTF-8
C++
false
false
641
cpp
first.cpp
#include <bits/stdc++.h> #define lli long long int using namespace std; inline lli scan( ) { lli n = 0; char c; for( c = getchar_unlocked(); c==' ' || c=='\n' || c == '\t'; c = getchar_unlocked()); for( ; c > 0x2f && c < 0x3a; c = getchar_unlocked()) n = (n * 10) + (c & 0x0f); return n; } lli a[100005],n,counti,t; int main(int argc, char const *argv[]) { t=scan(); while(t--) { counti=0; n=scan(); for(lli i=1;i<=n;i++) a[i]=scan(); if(a[1]!=a[2]) counti++; if(a[n-1]!=a[n]) counti++; for(lli i=2;i<n;i++) { if((a[i]!=a[i-1]) || (a[i]!=a[i+1])) { counti++; } } cout<<counti<<endl; } return 0; }
c49e8b6cc581c75d0de6adda7e1ec5c6344e307c
50d3840d705264f2aaff34c82d00b06730939090
/buildmenu.cpp
edebab93eac91d28d33cdcbf6d99b5ce5a151ccf
[]
no_license
Polladin/Factory
c9e9463a65ac44e69c42579795c0dd7f76b6cd07
64f325a3224b73dc401c8a5c2b0fa5e25d1b84d3
refs/heads/master
2021-01-20T19:39:24.477901
2016-08-04T22:41:25
2016-08-04T22:41:25
64,684,981
0
0
null
null
null
null
UTF-8
C++
false
false
346
cpp
buildmenu.cpp
#include "buildmenu.h" BuildMenu::BuildMenu() { } t_menuButtons BuildMenu::get_available_menus() const { t_menuButtons listOfAvailableMenus; for (const auto& menuItem : allMenuButtons) { if (menuItem->is_available()) listOfAvailableMenus.push_back(menuItem.get()); } return listOfAvailableMenus; }
f7f4ed865d353d41c0b50834e9a8be3f5737568a
d1cd0e61a0d5ed2b5341bc9e996625fb677f4f23
/lib/phy/physical_channel/physical_channel.h
45ca36eba3858f36861bfc0a78c6c7bb39582082
[ "Apache-2.0" ]
permissive
soumyadeepbi/free5GRAN
251bff61bfd30628f0861a285086ac94368de34f
4e92458e955f59d86463ce65ea08c5c06cc8a48e
refs/heads/master
2023-07-28T20:23:42.404672
2021-10-06T16:32:47
2021-10-06T16:32:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,836
h
physical_channel.h
/* * Copyright 2020-2021 Telecom Paris 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 <complex> #include <vector> #include "../../variables/common_structures/common_structures.h" using namespace std; namespace free5GRAN::phy::physical_channel { void decode_pdcch(vector<complex<float>> pdcch_symbols, int* dci_bits, int agg_level, int* reg_index, int* reg_index_sorted, int pdcch_DMRS_ScrambingID); void decode_pdsch(vector<complex<float>> pdsch_samples, double* unscrambled_soft_bits, int pci); void decode_pbch(vector<complex<float>> pbch_symbols, int i_ssb, int pci, int* bch_bits); void compute_pbch_indexes(vector<vector<vector<int>>>& ref, int pci); void compute_pdcch_indexes(vector<vector<vector<int>>>& ref, int n_symb_coreset, int agg_level, int* reg_bundles, int height_reg_rb); void compute_pdsch_indexes(vector<vector<vector<int>>>& ref, bool dmrs_symbol_array[], int L, int lrb); } // namespace free5GRAN::phy::physical_channel
08116a9c8579b64433738922543ea5cdde950ab7
af03ac4c9b602a5e9a0e3bde6e1d0d67b7b79875
/alarme/alarme.ino
0c6b0ef5cd9ff82be50d3dd5965b957511b43608
[]
no_license
MikeSquall/arduino
e618017bc7bd5c851cf5f2fa445da09b61268831
0bd0a3efe72e1d45237608acddc536349a63b575
refs/heads/master
2020-09-24T06:57:20.328005
2019-12-03T19:02:25
2019-12-03T19:02:25
225,694,733
0
0
null
null
null
null
UTF-8
C++
false
false
787
ino
alarme.ino
int ledPin = 5; int inputPin = 2; int pinSpeaker = 6; int pirState = LOW; int val = 0; void setup() { // put your setup code here, to run once: pinMode(ledPin, OUTPUT); pinMode(inputPin, INPUT); pinMode(pinSpeaker, OUTPUT); } void joueSon(long duree, int frequence){ duree *= 1000; int period = (1.0 / frequence) * 1000000; long temps_passe = 0; while(temps_passe < duree) { digitalWrite(pinSpeaker, HIGH); delayMicroseconds(period/2); digitalWrite(pinSpeaker, LOW); delayMicroseconds(period/2); temps_passe += (period); } } void loop() { val = digitalRead(inputPin); if(val == HIGH){ digitalWrite(ledPin, HIGH); joueSon(300, 160); delay(150); } else { digitalWrite(ledPin, LOW); joueSon(0, 0); delay(300); } }
cf0be03c625d411ae701cb9b7428943f648bb7c9
da28ab796633564c3892669b713aa07ae56b0061
/Prog5.cpp
3e2d8ffc250792caefd3f22e50ae51f762ca2f3c
[]
no_license
Soumyadeep-Chakraborty/labassignment4-B
def2edd4d6681e5034a3aec3d58d228a8ce793b2
d2526a1ca33d4f734fe60a42005b2e1b8940d7c3
refs/heads/master
2021-07-06T14:29:26.396490
2017-09-29T15:23:52
2017-09-29T15:23:52
105,287,559
0
0
null
null
null
null
UTF-8
C++
false
false
793
cpp
Prog5.cpp
#include <iostream> using namespace std; int print(int,int,int); int main() {int num1,num2,sum; char exp; cout<<"Enter The Lower Limit : "; cin>>num1; cout<<"Enter The Upper Limit : "; cin>>num2; cout<<"Choose To Print Sum Of Odd Or Even Number ,Enter 'o' for Odd And 'e' for Even : "; cin>>exp; if(exp=='e') { if ((num1%2)==0) { sum=print(num2,num1,0); } else { sum=print(num2,(num1+1),0); } } else if(exp=='o') { if((num1%2)==0) { sum=print(num2,(num1+1),0); } else { sum=print(num2,num1,0); } } cout<<"The Required Sum Is : "<<endl<<sum; return 0; } int print(int num2,int num1,int k){ if(num1<=num2) { k+=num1; return print(num2,(num1+2),k); } else {return k; } }
b5244e0da75fb667dcf4dd4e61ffbec07b9b7cb1
7b30f7cb971a3c2260ef37110cce6c8c3237d3cc
/hexwalk2016.ino
591ed6b3aab2d4353285e469e9bb67695875c84a
[]
no_license
cemot/Hexapodv2
f09a0767b6acd06a0b850dfc78617f56ffb42113
58d13237fcc49bc2e1440aac5306e9e3a837fc88
refs/heads/master
2020-04-19T12:21:22.626086
2018-06-03T16:07:43
2018-06-03T16:07:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,424
ino
hexwalk2016.ino
/* This code drives a hexapod with 2 DOF legs and a SRF04 ultrasonic range finder. It was written for an Arduino Mega, and utilizes an Adafruit 16 channel servo driver (see text below) and an SRF04 ultrasonic range finder. Written by Josh Herrala. www.networkoracle.com BSD license, all text above must be included in any redistribution. */ /*************************************************** This is an example for our Adafruit 16-channel PWM & Servo driver Servo test - this will drive 16 servos, one after the other Pick one up today in the adafruit shop! ------> http://www.adafruit.com/products/815 These displays use I2C to communicate, 2 pins are required to interface. For Arduino UNOs, thats SCL -> Analog 5, SDA -> Analog 4 Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. BSD license, all text above must be included in any redistribution ****************************************************/ #include <Wire.h> #include <Adafruit_PWMServoDriver.h> // called this way, it uses the default address 0x40 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(); #define SERVOMIN 100 // this is the 'minimum' pulse length count (out of 4096) #define SERVOMAX 600 // this is the 'maximum' pulse length count (out of 4096) //******Rotation servo matches leg number********** //Legs are numbered 1-6 starting with front left, 1-3 on left side, 4-6 on right. 4 is right front. //Triangle Left int leglift1 = 0; int leglift3 = 3; int leglift5 = 4; int legrot1 = 1; int legrot3 = 2; //425bb servo int legrot5 = 5; //Triangle Right int leglift4 = 6; int leglift6 = 8; int leglift2 = 14; int legrot4 = 7; int legrot6 = 9; int legrot2 = 13; //head rotation servo # int headrot = 15; int led = 13; /*Initial leg position variables. Variations in servo type and mechanical differences require each servo to be tuned to an initial neutral position.*/ int frontleftliftpos = 375; int frontleftrotpos = 470; //-- makes it go forward more int midleftliftpos = 500; //425bb servo int midleftrotpos = 350; int backleftliftpos = 400; int backleftrotpos = 500; int frontrightliftpos = 400; int frontrightrotpos = 450; int midrightliftpos = 500; int midrightrotpos = 350; int backrightliftpos = 400; int backrightrotpos = 450; int headposition = 300; //Variables used to control walking speed. int liftdelay = 1; int rotdelay = 5; //Variables used as counters in Do While loops that create walking motion. int counter = 200; int rotcounter = 200; int wavecounter = 200; int turncount = 0; //Following variables define the send/receive pins for the SRF04. const int triggerPin = 22; //pin to send pulse const int echoPin = 31; //pin to receive pulse //variables to sum distances using ping() long pingone; long pingtwo; long pingsumone; long pingsumtwo; void setup() { Serial.begin(9600); pinMode(led, OUTPUT); pwm.begin(); pwm.setPWMFreq(60); // Analog servos run at ~60 Hz updates } /*Main loop centers on using the SRF04 to determine if there are obstacles in front of the robot, and take avoidance actions if required.*/ void loop() { if (ping() > 10) //call the range finder { walk(); } else scan(); } void walk() { //IMPORTANT. reducing the rotation range (rotcounter) requires repositioning starting positions. walkpos(); servoreset(); leftlift(); locomotion(0); //rightbackleftforward(); dropleft(); liftright(); locomotion(1); //rightforwardleftback(); dropright(); } void leftturn(){ scanpos(); leftlift(); locomotion(2); //rightbackleftforward(); dropleft(); liftright(); locomotion(3); //rightforwardleftback(); dropright(); } void rightturn(){ right_turn_pos(); leftlift(); locomotion(3); dropleft(); liftright(); locomotion(2); dropright(); } void scan() { scanpos(); servoreset(); headrotate(100); delay(100); pingone = ping(); delay(500); headrotate(200); delay(100); pingtwo = ping(); delay(500); pingsumone = (pingone + pingtwo); Serial.print(pingsumone + "right!"); Serial.println(); headrotate(445); delay(100); pingone = ping(); delay(500); headrotate(555); delay(100); pingtwo = ping(); delay(500); pingsumtwo = (pingone + pingtwo); Serial.print(pingsumtwo + " left!"); Serial.println(); headrotate(headposition); if (pingsumone < pingsumtwo) { Serial.print("turning right"); Serial.println(); do { rightturn(); turncount++; } while(turncount <= 1); turncount = 0; } else { Serial.print("turning left"); Serial.println(); do { leftturn(); turncount++; } while(turncount <= 1); turncount = 0; } delay(1000); headrotate(headposition); /* do { //headrotate(320); servofrontleftlift(frontleftliftpos); servofrontrightlift(frontrightliftpos); frontleftliftpos--; frontrightliftpos++; wavecounter++; delay(liftdelay); } while (wavecounter <= 300); do { //headrotate(280); servofrontleftlift(frontleftliftpos); servofrontrightlift(frontrightliftpos); frontleftliftpos++; frontrightliftpos--; wavecounter--; delay(liftdelay); } while (wavecounter >= 200); */ } //servo moves********************************************* void locomotion(int dir) { //0=right back, left forward 1=right forward, left back //2,3=turns do { servorightfrontrot(frontrightrotpos); servorightbackrot(backrightrotpos); servoleftmidrot(midleftrotpos); if (dir == 0) { frontrightrotpos--; midleftrotpos++; backrightrotpos--; } else if (dir == 1) { frontrightrotpos++; midleftrotpos--; backrightrotpos++; } else if (dir == 2) { frontrightrotpos--; midleftrotpos--; backrightrotpos--; } else if (dir == 3) { frontrightrotpos++; midleftrotpos++; backrightrotpos++; } servoleftfrontrot(frontleftrotpos); servorightmidrot(midrightrotpos); servobackleftrot(backleftrotpos); if (dir == 0) { frontleftrotpos--; midrightrotpos++; backleftrotpos--; } else if (dir == 1) { frontleftrotpos++; midrightrotpos--; backleftrotpos++; } else if (dir == 2) { frontleftrotpos++; midrightrotpos++; backleftrotpos++; } else if (dir == 3) { frontleftrotpos--; midrightrotpos--; backleftrotpos--; } rotcounter++; delay(rotdelay); } while (rotcounter <=300); rotcounter = 200; } void leftlift() { Serial.print("Lift Left"); Serial.println(); //Lift left triangle. This includes the front and rear legs on //on the left side, and the middle leg on the right side. do { servofrontleftlift(frontleftliftpos); servobackleftlift(backleftliftpos); servomidrightlift(midrightliftpos); midrightliftpos++; frontleftliftpos--; backleftliftpos--; counter++; delay(liftdelay); } while (counter <= 300); counter = 200; } /* void rightbackleftforward() { Serial.print("Rotate Right Triangle Back, Left Forward."); Serial.println(); //Right triangle legs move back, pushing robot forward. Left legs //move forward. do { servorightfrontrot(frontrightrotpos); servorightbackrot(backrightrotpos); servoleftmidrot(midleftrotpos); frontrightrotpos--; midleftrotpos++; backrightrotpos--; servoleftfrontrot(frontleftrotpos); servorightmidrot(midrightrotpos); servobackleftrot(backleftrotpos); frontleftrotpos--; backleftrotpos--; midrightrotpos++; rotcounter++; delay(rotdelay); } while (rotcounter <=300); rotcounter = 200; } */ void dropleft() { Serial.print("Drop Left"); Serial.println(); //Drop left triangle legs do { servofrontleftlift(frontleftliftpos); servomidrightlift(midrightliftpos); servobackleftlift(backleftliftpos); midrightliftpos--; frontleftliftpos++; backleftliftpos++; counter++; delay(liftdelay); } while (counter <= 300); counter = 200; } void liftright() { Serial.print("Lift Right"); Serial.println(); //Lift right triangle legs do { servofrontrightlift(frontrightliftpos); servomidleftlift(midleftliftpos); servobackrightlift(backrightliftpos); midleftliftpos--; backrightliftpos++; frontrightliftpos++; counter++; delay(liftdelay); } while (counter <= 300); counter = 200; } /* void rightforwardleftback() { Serial.print("Rotate Right Forward, Left Backward"); Serial.println(); //Rotate right triangle forward, left triangle legs move backward //pushing the robot forward. do { servorightfrontrot(frontrightrotpos); servorightbackrot(backrightrotpos); servoleftmidrot(midleftrotpos); frontrightrotpos++; backrightrotpos++; midleftrotpos--; servoleftfrontrot(frontleftrotpos); servorightmidrot(midrightrotpos); servobackleftrot(backleftrotpos); frontleftrotpos++; midrightrotpos--; backleftrotpos++; rotcounter++; delay(rotdelay); } while (rotcounter <= 300); rotcounter = 200; } */ void dropright() { Serial.print("Drop Right"); Serial.println(); //Drop right triangle do { servofrontrightlift(frontrightliftpos); servomidleftlift(midleftliftpos); servobackrightlift(backrightliftpos); backrightliftpos--; midleftliftpos++; frontrightliftpos--; counter++; delay(liftdelay); } while (counter <= 300); counter = 200; } void servoreset() { //reset the left servofrontleftlift(frontleftliftpos); servoleftfrontrot(frontleftrotpos); servomidleftlift(midleftliftpos); servoleftmidrot(midleftrotpos); servobackleftlift(backleftliftpos); servobackleftrot(backleftrotpos); //reset the right servofrontrightlift(frontrightliftpos); servorightfrontrot(frontrightrotpos); servomidrightlift(midrightliftpos); servorightmidrot(midrightrotpos); servobackrightlift(backrightliftpos); servorightbackrot(backrightrotpos); headrotate(headposition); } /*Servo positioning functions. These functions are called with each pass through the do while loops above. */ //****************************************************************** void headrotate(int pulselen) //head position { pwm.setPWM(headrot, 0, pulselen); Serial.print("headcalled"); Serial.println(); } void servofrontleftlift(int pulselen) //Lift position of leg 1, front left lift { pwm.setPWM(leglift1, 0, pulselen); } void servobackleftlift(int pulselen) //Lift position of leg 3, back left lift { pwm.setPWM(leglift3, 0, pulselen); } void servomidrightlift(int pulselen) //Lift position of leg 5, middle right lift { pwm.setPWM(leglift5, 0, pulselen); } void servofrontrightlift(int pulselen) //Lift position of leg 4, front right lift { pwm.setPWM(leglift4, 0, pulselen); } void servobackrightlift(int pulselen) //Lift position of leg 6, back right lift { pwm.setPWM(leglift6, 0, pulselen); } void servomidleftlift(int pulselen) //Lift position of leg 2, middle left lift { pwm.setPWM(leglift2, 0, pulselen); } void servorightfrontrot(int pulselen) //Rotation position of leg 4, front right rotation { pwm.setPWM(legrot4, 0, pulselen); } void servorightbackrot(int pulselen) //Rotation position of leg 6, back right rotation { pwm.setPWM(legrot6, 0, pulselen); } void servoleftmidrot(int pulselen) //Rotation position of leg 2, middle left rotation { pwm.setPWM(legrot2, 0, pulselen); } void servoleftfrontrot(int pulselen) //Rotation position of leg 1, front left rotation { pwm.setPWM(legrot1, 0, pulselen); } void servobackleftrot(int pulselen) //Rotation position of leg 3, back left rotation { pwm.setPWM(legrot3, 0, pulselen); } void servorightmidrot(int pulselen) //Rotation position of leg 5, middle right rotation { pwm.setPWM(legrot5, 0, pulselen); } //sonic range finder functions************************************** long ping() { // establish variables for duration of the ping, // and the distance result in centimeters: long duration, cm; // The PING))) is triggered by a HIGH pulse of 2 or more microseconds. // Give a short LOW pulse beforehand to ensure a clean HIGH pulse: pinMode(triggerPin, OUTPUT); digitalWrite(triggerPin, LOW); delayMicroseconds(2); digitalWrite(triggerPin, HIGH); delayMicroseconds(5); digitalWrite(triggerPin, LOW); // The echo pin is used to read the signal from the PING))): a HIGH // pulse whose duration is the time (in microseconds) from the sending // of the ping to the reception of its echo off of an object. pinMode(echoPin, INPUT); duration = pulseIn(echoPin, HIGH); // convert the time into a distance cm = microsecondsToCentimeters(duration); //Use code below to see distance using serial monitors Serial.print(cm); Serial.print("cm"); Serial.println(); return cm; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the // object we take half of the distance travelled. return microseconds / 29 / 2; } //servo default position functions void scanpos() { /*Initial leg position variables. Variations in servo type and mechanical differences require each servo to be tuned to an initial neutral position.*/ frontleftliftpos = 380; frontleftrotpos = 400; //-- makes it go forward more midleftliftpos = 530; //425bb servo midleftrotpos = 390; backleftliftpos = 410; backleftrotpos = 465; frontrightliftpos = 400; frontrightrotpos = 400; midrightliftpos = 400; midrightrotpos = 400; backrightliftpos = 400; backrightrotpos = 400; headposition = 300; } void walkpos() { /*Initial leg position variables. Variations in servo type and mechanical differences require each servo to be tuned to an initial neutral position.*/ frontleftliftpos = 375; frontleftrotpos = 470; //-- makes it go forward more midleftliftpos = 500; //425bb servo midleftrotpos = 350; backleftliftpos = 400; backleftrotpos = 500; frontrightliftpos = 400; frontrightrotpos = 450; midrightliftpos = 400; midrightrotpos = 350; backrightliftpos = 400; backrightrotpos = 450; headposition = 300; } void right_turn_pos() { /*Initial leg position variables. Variations in servo type and mechanical differences require each servo to be tuned to an initial neutral position.*/ frontleftliftpos = 375; frontleftrotpos = 350; //-- makes it go forward more midleftliftpos = 500; //425bb servo midleftrotpos = 300; backleftliftpos = 400; backleftrotpos = 420; frontrightliftpos = 400; frontrightrotpos = 350; midrightliftpos = 400; midrightrotpos = 450; backrightliftpos = 400; backrightrotpos = 350; headposition = 300; } //testing loops using the leds void fastled(){ int ledcount = 1; do{ digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(100); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(100); ledcount++; } while(ledcount <= 30); ledcount = 1; delay(500); }
53d266c83f520f369a0463af81c8aff983ed9197
9ac6dc8e31438bc947cbf6b4ac2f7ec9d30ff1ed
/doc/src/Chapter5-programs/include/random.h
228186f7ebd27a710db866486a0585bd8e2413ae
[ "CC0-1.0" ]
permissive
ManyBodyPhysics/LectureNotesPhysics
65ed7cf87a58942406362b0c00313d80a2ccba11
40483747002575bf0f8c206ef3ad5a8374a7e05a
refs/heads/master
2021-05-22T05:28:03.213633
2020-07-06T22:09:26
2020-07-06T22:09:26
42,460,345
29
26
null
2016-12-21T13:11:43
2015-09-14T16:10:02
C++
UTF-8
C++
false
false
401
h
random.h
#include "arg.h" #include "uniform_deviates.h" #ifndef INCLUDED_RANDOM #define INCLUDED_RANDOM class Random // Random number generator base class { private: UniformDeviate* r; RandomType random_type; public: Random(RandomArg); ~Random(); double Uniform(); double Gauss(double); int Z(int); void ReadState(const char*); void WriteState(const char*); }; #endif
69efbea04ec6978a00b5a199653f296dc055f122
b66b9f3b36acabd2b9c68e0261c53cbf9b1196c6
/ThomasTheTankEngine/Components/CameraComponent.hpp
bbbe0510adad2b2584d9d0d3953c6e35b857a72f
[]
no_license
JamesHovet/ThomasTheTankEngine
715edcad807cf2d8f96262e5dcf3a41c854f49a6
6e334808215492097e7788447822e6e003f8586c
refs/heads/master
2023-02-07T14:40:44.271654
2020-12-28T21:36:17
2020-12-28T21:36:17
283,554,733
0
0
null
null
null
null
UTF-8
C++
false
false
1,093
hpp
CameraComponent.hpp
// CameraComponent.hpp // generated at: 2020-07-24 10:40:50.122297 #pragma once #ifndef CameraComponent_hpp #define CameraComponent_hpp #include "Component.hpp" struct CameraComponent : public ECSComponent { static constexpr int componentIndex{ 2 }; componentID getComponentIndex(){return componentIndex;} float m_FOV = 45.0f; bool m_enabled = true; //to add: render surface? ortho vs perspective? void imDisplay(EntityAdmin* m_admin){ // ImGui::PushID(this); if(ImGui::TreeNode("CameraComponent")){ ImGui::InputFloat("m_FOV", &m_FOV); ImGui::Checkbox("m_enabled", &m_enabled); ImGui::TreePop(); } // ImGui::PopID(); } json::object_t serialize(){ json::object_t obj = json::object(); obj["m_FOV"] = m_FOV; obj["m_enabled"] = m_enabled; return obj; } static CameraComponent deserialize(json::object_t obj){ CameraComponent out; out.m_FOV = obj["m_FOV"]; out.m_enabled = obj["m_enabled"]; return out; } }; #endif
43b5c01230550edc5e00d750fca5844267d5947e
badf25deddbb2f71a5251632d61f46a493189408
/dataloggerT1TH2AIR.ino
405fcc2a65316ce7e4374c72af3967f83503dd5e
[]
no_license
makerwelt/Firmware-Datalogger03
52e9cf9980a1bb1b608db1601fdfccb0e1998327
169ad0ec192123a91085963de09924faeeeaed5f
refs/heads/master
2020-03-13T02:42:10.424194
2018-04-25T00:42:41
2018-04-25T00:42:41
130,929,661
0
0
null
null
null
null
UTF-8
C++
false
false
6,449
ino
dataloggerT1TH2AIR.ino
#include <Wire.h> #include <DHT11.h> #include <SPI.h> #include <SD.h> #include "RTClib.h" RTC_DS1307 rtc; DHT11 dht11(3); int s_analogica_mq135 = 0; const int chipSelect = 10; // En nuestra shield el pin SD es el 10. char daysOfTheWeek[7][12] = {"Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"}; int temp = 1; // Pin analógico A1 del Arduino donde conectaremos el pin de datos del sensor TMP36 float maxC = 0, minC = 100, maxF = 0, minF = 500, maxV = 0, minV = 5; //Variables para ir comprobando maximos y minimos int UVOUT = A5; // Output from the sensor int REF_3V3 = A4; // 3.3V power on the Arduino board int T2 = 0; int TH1 = 0; int AIR = 0; void setup() { pinMode(UVOUT, INPUT); pinMode(REF_3V3, INPUT); pinMode(4, INPUT); pinMode(7, INPUT); pinMode(8, INPUT); T2 = digitalRead (4); TH1 = digitalRead (7); AIR = digitalRead (8); Serial.begin(9600); Wire.begin(); //rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); // auto update from computer time //rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0)); // to set the time manualy pinMode(2, OUTPUT); // Pin para led de confirmacion de lectura escritura pinMode(3, INPUT_PULLUP) ; // DHT11 pin de lectura delay (500); Serial.print("Inicializando memoria SD..."); // Comprobamos que la SD esta preparada para realizar la copia de datos: pinMode(10, OUTPUT); // visualiza si existe SD y si esta bien inicializada: if (!SD.begin(chipSelect)) { Serial.println("Memoria Fallada, o no insertada"); // Si responde con fallo el programa no haria nada mas: return; } Serial.println("Memoria Inicializada."); } void loop() { digitalWrite(2, LOW) ; float voltaje, gradosC, gradosF; // Declaramos estas variables tipo float para guardar los valores de lectura // del sensor, así como las conversiones a realizar para convertir a grados // centígrados y a grados Fahrenheit voltaje = analogRead(1) * 0.004882814; // Con esta operación lo que hacemos es convertir el valor que nos devuelve // el analogRead(1) que va a estar comprendido entre 0 y 1023 a un valor // comprendido entre los 0.0 y los 5.0 voltios gradosC = (voltaje - 0.5) * 100.0; // Gracias a esta fórmula que viene en el datasheet del sensor podemos convertir // el valor del voltaje a grados centigrados gradosF = ((voltaje - 0.5) * 100.0) * (9.0 / 5.0) + 32.0; // Gracias a esta fórmula que viene en el datasheet del sensor podemos convertir // el valor del voltaje a grados Fahrenheit delay(9450); Serial.println(); DateTime now = rtc.now(); Serial.print(daysOfTheWeek[now.dayOfTheWeek()]); Serial.print(", "); Serial.print(now.day()); Serial.print('/'); Serial.print(now.month()); Serial.print('/'); Serial.print(now.year()); Serial.print(", "); Serial.print(now.hour()); Serial.print(':'); Serial.print(now.minute()); Serial.print(':'); Serial.print(now.second()); Serial.println(" "); if (T2 == 1){ Serial.print ("Temp. Sensor de Contacto: "); Serial.print (gradosC); Serial.println (" ºC. "); } int err; float temp, hum; if ( TH1 == 1){ if ((err = dht11.read(hum, temp)) == 0) { // Si devuelve 0 es que ha leido bien Serial.print("Temperatura Ambiente: "); Serial.print(temp); Serial.print (" ºC., "); Serial.print(" Humedad Ambiente: "); Serial.print(hum); Serial.println(" %."); } else { Serial.println(); Serial.print("Error Num :"); Serial.print(err); Serial.println(); } } if ( AIR == 1 ) { s_analogica_mq135 = analogRead(0); Serial.print(s_analogica_mq135, DEC); Serial.print(" ppm."); delay(250); if (s_analogica_mq135 <= 50) { Serial.println(" Calidad de Aire Buena."); delay(50); } if (s_analogica_mq135 >= 51 && s_analogica_mq135 <= 100) { Serial.println(" Calidad de Aire Regular."); delay(50); } if (s_analogica_mq135 >= 101 && s_analogica_mq135 <= 150) { Serial.println(" Calidad de Aire Mala."); delay(50); } if (s_analogica_mq135 >= 151 && s_analogica_mq135 <= 200) { Serial.println(" Calidad de Aire Muy mala."); delay(50); } if (s_analogica_mq135 >= 201) { Serial.println(" Calidad de Aire Extremadamente mala"); } } delay(1000); //Recordad que solo lee una vez por segundo // Abrimos el fichero. Nota: solo se puede abrir un fichero a la vez. Para abrir un segundo fichero hay que cerrar el anterior. File dataFile = SD.open("test.txt", FILE_WRITE); if (dataFile) { Serial.print(" Escribiendo en test.txt..."); dataFile.print(now.day()); dataFile.print('/'); dataFile.print(now.month()); dataFile.print('/'); dataFile.print(now.year()); dataFile.print(", "); dataFile.print(now.hour()); dataFile.print(':'); dataFile.print(now.minute()); dataFile.print(':'); dataFile.print(now.second()); dataFile.print(", "); if ( TH1 == 1){ dataFile.print("Temperatura: "); dataFile.print(temp); dataFile.print(" ºC. ,"); dataFile.print(" Humedad: "); dataFile.print(hum); dataFile.print(" %. "); } if ( T2 == 1){ dataFile.print("temperatura: "); dataFile.println(gradosC); } if ( AIR == 1 ) { s_analogica_mq135 = analogRead(0); dataFile.print(s_analogica_mq135, DEC); dataFile.print(" ppm. "); delay(250); if (s_analogica_mq135 <= 50) { dataFile.println(" Calidad de Aire Buena."); delay(50); } if (s_analogica_mq135 >= 51 && s_analogica_mq135 <= 100) { dataFile.println(" Calidad de Aire Regular."); delay(50); } if (s_analogica_mq135 >= 101 && s_analogica_mq135 <= 150) { dataFile.println(" Calidad de Aire Mala."); delay(50); } if (s_analogica_mq135 >= 151 && s_analogica_mq135 <= 200) { dataFile.println(" Calidad de Aire Muy mala."); delay(50); } if (s_analogica_mq135 >= 201) { dataFile.println(" Calidad de Aire Extremadamente mala"); delay(50); } } digitalWrite(2, HIGH) ; delay(50); // close the file: dataFile.close(); } }
229f2bf1b5b2c9533cbbcf623dcb15f9395f53ae
239cb6da14686db3d3e795f7a6f5e9706f0e63fc
/C++/动态规划/完全背包.cpp
415b6451b4ff89d274f927267247a4929b620994
[]
no_license
zcTresure/Note
d508cb0064b30d2cbe9f726f6f7d481c5684a808
47de9b80766b08c7e0cc6b32c48fe84eb6102c95
refs/heads/master
2021-10-26T04:18:00.994992
2019-04-10T09:03:26
2019-04-10T09:03:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
572
cpp
完全背包.cpp
#include <iostream> using namespace std; int sub_set[100][1000]; int rec_subset(int arr[],int i,int S) { if(S==0)return 1; else if(i==0) return arr[i] == S ? 1 : 0; else if(arr[i]>S)return rec_subset(arr,i-1,S); else { if(rec_subset(arr,i-1,S-arr[i])==1){ return 1; } else{ rec_subset(arr,i-1,S); } } return 0; } int main() { int S; int n; int arr[100]; cin>>S>>n; for(int i=0;i<n;i++){ cin>>arr[i]; } cout<<rec_subset(arr,n,S)<<endl; return 0; }
6727a260782a4362bea805d0b371c830c7673476
a7ff96e37278abb16d03890cae1e6c932b4c9705
/Design pattern/State Design Pattern/TCP/TCPOpen.h
96a8db625d9d0d590f8c2be8658ef732243f2748
[]
no_license
vectormars/CPP
c42b2b4812b44935bd02cc2c0e22be1777b45228
20e8347a1ec50f75acead3d55bf1209dd01714cf
refs/heads/master
2021-09-18T20:39:52.055912
2018-07-19T17:45:02
2018-07-19T17:45:02
106,834,183
0
3
null
null
null
null
UTF-8
C++
false
false
457
h
TCPOpen.h
#ifndef TCPOPEN_H_INCLUDED #define TCPOPEN_H_INCLUDED #include <iostream> #include "TCPConnection.h" class TCPOpen : public TCPState { public: static TCPOpen* Instance(); virtual void Listen(TCPConnection *tc); virtual string CurrentState(){return m_currState;} private: TCPOpen():m_currState("Open"){} static TCPOpen* m_ti; string m_currState; }; #endif // TCPOPEN_H_INCLUDED
792a415b5282f185a36917683300348b9c37ce98
6365c01954ef8f1451276a71447ed0dcecbbc28c
/map.cpp
a08c9a09a32ac4ba1307b29beaed084e3ab685f0
[]
no_license
Urthawen/Urthawin
fc59b587e3ccde71ed5fefd767981eb5173ff031
7d771573a8b48c77d987234cf1d7d97c0cb5be1e
refs/heads/master
2021-01-13T07:22:47.542578
2016-11-08T13:30:41
2016-11-08T13:30:41
71,343,517
0
0
null
null
null
null
UTF-8
C++
false
false
3,010
cpp
map.cpp
#include "map.h" Map::Map(){ int nbDeadCell=0; int nbLifeCell=0; srand(time(NULL)); for(size_t x=0; x<MAP_LENGHT;x++) { for(size_t y=0; y<MAP_LENGHT;y++) { Desk[x][y].setX(x); Desk[x][y].setY(y); int nbgen=rand()%4+0; switch(nbgen){ case 0: Desk[x][y].setState(Cellule::WALKABLE); break; case 1: Desk[x][y].setState(Cellule::UNWALKABLE); break; case 2: if(nbLifeCell<LIFE_CELL) {Desk[x][y].setState(Cellule::LIFECELL);nbLifeCell++;} else {Desk[x][y].setState(Cellule::WALKABLE);} break; case 3: if(nbDeadCell<DEAD_CELL) {Desk[x][y].setState(Cellule::DEADCELL);nbDeadCell++;} else {Desk[x][y].setState(Cellule::WALKABLE);} break; default: std::cerr<<"Error"<<std::endl; } } } std::cout<<"Function "<<__FUNCTION__<<" (LINE "<<__LINE__<<") "<<"LENGHT ("<<MAP_LENGHT<<","<<MAP_LENGHT<<") created"<<std::endl; } size_t Map::nb_cells(Cellule::Statment etat) const{ size_t cpt=0; for(size_t x=0; x<MAP_LENGHT;x++) { for(size_t y=0; y<MAP_LENGHT;y++) { if(celluleIsState(Desk[x][y], etat)) { cpt++; } } } return cpt; } void Map::printMap(){ //TOP_MAP for(size_t x=0;x<MAP_LENGHT*2+5;x++) { std::cout<<"\033[2;37m__\033[0m"; } std::cout<<std::endl<<"|"<<std::endl; for(size_t x=0;x<MAP_LENGHT;x++) { std::cout<<"\033[2;37m|\033[0m "; for(size_t y=0;y<MAP_LENGHT;y++) { std::cout<<readCell(Desk[x][y]); if(y==MAP_LENGHT-1) { std::cout<<"|"<<std::endl<<"| "; for(size_t i=0;i<MAP_LENGHT;i++) { std::cout<<" "; if(i==MAP_LENGHT-1) std::cout<<"|"; } std::cout<<std::endl; } } } //BOT OF THE MAP for(size_t x=0;x<MAP_LENGHT*2+5;x++) { std::cout<<"\033[2;37m__\033[0m"; } std::cout<<std::endl<<std::endl; return; } void Map::addEntity(){ int x=0; bool cellFoundMonster = false; bool cellFoundPlayer = false; while(cellFoundMonster==false && x<MAP_LENGHT) { if(celluleIsState(Desk[1][x], Cellule::WALKABLE)) { std::cout<<"Cell Spawn monster found at [1,"<<x<<"]"<<std::endl; cellFoundMonster=true; Desk[1][x].setState(Cellule::MONSTER); } x++; } x=0; while(cellFoundPlayer==false && x<MAP_LENGHT) { if(celluleIsState(Desk[MAP_LENGHT-2][x], Cellule::WALKABLE)) { std::cout<<"Cell Spawn player found at ["<<MAP_LENGHT-2<<","<<x<<"]"<<std::endl; cellFoundPlayer=true; Desk[MAP_LENGHT-2][x].setState(Cellule::PLAYER); PlayerPos[MAP_LENGHT-2][x].setY(x); } x++; } return; } void Map::readMap() const{ int x=0, y=0; for(x=0;x<MAP_LENGHT;x++) { for(y=0;y<MAP_LENGHT;y++) { std::cout<<"Cellule ["<<x<<","<<y<<"] = "; testCell(Desk[x][y]); } } return; } void Map::movePlayer(Move position){ /*std::cout<<"PLAYER_POS["<<PlayerPos.getX()<<","<<PlayerPos.getY()<<"]"<<std::endl;*/ return; }
dce99b35a1bd0cb8ff3d7c44228f9d1e49ed8e39
029fdba41004a613d9273aa51a5bbb481385b163
/get-out/EffectReplaceEntity.h
3c78164fa86fdc80d4e9a389d520a0d838fb5650
[ "MIT" ]
permissive
BrunoAOR/get-out
5c7df6de52b8a255b032dde831947609181ceec7
ae10585d5f2127db498e12232632bbb1a4b31b83
refs/heads/master
2021-07-12T14:14:46.450081
2018-09-11T17:59:18
2018-09-11T17:59:18
106,185,519
0
0
null
null
null
null
UTF-8
C++
false
false
490
h
EffectReplaceEntity.h
#ifndef H_EFFECT_REPLACE_ENTITY #define H_EFFECT_REPLACE_ENTITY #include "ActionEffect.h" class Entity; class EffectReplaceEntity : public ActionEffect { public: EffectReplaceEntity(const std::string& effectDescription, Entity* entityToRemove, Entity* entityToAdd); ~EffectReplaceEntity(); // Inherited via ActionEffect virtual void doEffect() const override; private: Entity* m_entityToRemove = nullptr; Entity* m_entityToAdd = nullptr; }; #endif // !H_EFFECT_REPLACE_ENTITY
cfed4a8ec0ce9db93c13c1add1517d792782b9dc
5c1328a271a8607e59be87244068ab46fd24c893
/cpp/134-Gas-Station.cpp
ff4c7468c56b7671c1507a847898fac738642549
[ "MIT" ]
permissive
ErdemOzgen/leetcode
32d0f2fae605caf33655db38d8dc701062dd773c
c50d6fa482a608a2556e92e6f629e9c29089efd6
refs/heads/main
2022-11-06T06:22:10.322894
2022-10-02T23:20:09
2022-10-02T23:20:09
514,034,071
1
0
null
null
null
null
UTF-8
C++
false
false
949
cpp
134-Gas-Station.cpp
/* Gas stations along circular route, return where to start to complete 1 trip Ex. gas = [1,2,3,4,5] cost = [3,4,5,1,2] -> index 3 (station 4), tank = 4,8,7,6,5 At a start station, if total ever becomes negative won't work, try next station Time: O(n) Space: O(1) */ class Solution { public: int canCompleteCircuit(vector<int>& gas, vector<int>& cost) { int n = gas.size(); int totalGas = 0; int totalCost = 0; for (int i = 0; i < n; i++) { totalGas += gas[i]; totalCost += cost[i]; } if (totalGas < totalCost) { return -1; } int total = 0; int result = 0; for (int i = 0; i < n; i++) { total += gas[i] - cost[i]; if (total < 0) { total = 0; result = i + 1; } } return result; } };
fe49be2c088d89771b3eb244cce338fc7ddfb4dd
f026c72ee5d7dd948db480f6bf0bf6255fe1ea00
/CADPhysics/src/CADPhysicsAtomicDeexcitation.cc
8682ac2ef58b63b4805ce722a38a651e75a42848
[]
no_license
eScatter/lowe-g4
53290d3eab3daccb410b9dce3015fa0cfce01209
67a29209688cf8b9a83640408b83daa88cd1c4a5
refs/heads/master
2021-01-17T02:48:46.095019
2017-06-08T14:06:03
2017-06-08T14:06:03
57,113,496
2
3
null
2017-06-08T14:06:04
2016-04-26T09:00:43
C++
UTF-8
C++
false
false
14,814
cc
CADPhysicsAtomicDeexcitation.cc
// CADPhysicsAtomicDeexcitation.cc // // A general note on shell indices versus shell IDs. The shell IDs are those used in the // Lawrence Livermore Evaluated Atomic Data Libraries, EADL, to designate subshells of atoms. // These IDs are described in table VI, on page 7, of the document // 'ENDL Type Formats for the Livermore Evaluated Atomic Data Library, EADL' which can be found // (a.o.) at http://www.nea.fr/html/dbdata/data/nds_eval_eadl.pdf. // Shell indices, on the other hand, are an internal Geant4 designation of shells per element. The // shell index starts at zero, and is for each element just a counter over all shells that appear in the file // G4EMLOW/fluor/binding.dat . In general, this leads to the following designations: // // Name ID index // K 1 0 // L1 3 1 // L2 5 2 // L3 6 3 // M1 8 4 // M2 10 5 // (...) // M5 14 8 // N1 16 9 // etcetera. // // The highest valid number for the index of course depends on the element (Z number). For instance, for hydrogen the // highest index is 0, while for silicon (Z=14) it is 6 (shells defined up to the M3 shell, ID=11) and for gold (Z=79) it's // 21 (highest shell is P1, ID=41). #include "CADPhysicsAtomicDeexcitation.hh" #include "Randomize.hh" #include "G4Gamma.hh" #include "G4Electron.hh" #include "G4FluoTransition.hh" CADPhysicsAtomicDeexcitation::CADPhysicsAtomicDeexcitation(): minGammaEnergy(100.*eV), minElectronEnergy(100.*eV), fAuger(false), transitionManager(G4AtomicTransitionManager::Instance()) {} CADPhysicsAtomicDeexcitation::~CADPhysicsAtomicDeexcitation() {} std::vector<G4DynamicParticle*>* CADPhysicsAtomicDeexcitation::GenerateParticles(G4int Z,G4int givenShellId) { // Some initialization VacancyEnergies.clear(); ShellIdstobeprocessed.clear(); std::vector<G4DynamicParticle*>* vectorOfParticles = new std::vector<G4DynamicParticle*>; ShellIdstobeprocessed.push_back(givenShellId); G4DynamicParticle* aParticle; G4int currentShellId = 0;// ID of the current shell under investigation (in which a vacancy is present) G4int provShellId = 0;// ID of a higher shell, i.e. the 'starting point' for the transition do {// Repeat the Fluorescence/Auger process as long as there are any shell vacancies to be processed currentShellId = ShellIdstobeprocessed.back(); ShellIdstobeprocessed.pop_back(); provShellId = SelectTypeOfTransition(Z, currentShellId);// First find out if a radiative transition // should take place and if so, determine the ID of the upper shell ('starting point' of the transition) if (provShellId >0)// Radiative transition between the already-known shells { aParticle = GenerateFluorescence(Z,currentShellId,provShellId); } else if (provShellId == -1)// Non-radiative transition { aParticle = GenerateAuger(Z, currentShellId); } else { G4Exception("CADPhysicsAtomicDeexcitation::GenerateParticles()","errorCADPhysicsAtomicDeexcitation01",FatalException,"CADPhysicsAtomicDeexcitation: starting shell uncorrect: check it"); } if (aParticle != 0) {vectorOfParticles->push_back(aParticle);} } while (ShellIdstobeprocessed.size()>0); return vectorOfParticles; } G4int CADPhysicsAtomicDeexcitation::SelectTypeOfTransition(G4int Z, G4int shellId) { if (shellId <=0 ) G4Exception("CADPhysicsAtomicDeexcitation::SelectTypeOfTransition()","errorCADPhysicsAtomicDeexcitation02",FatalException,"CADPhysicsAtomicDeexcitation: zero or negative shellId"); G4bool fluoTransitionFoundFlag = false; G4int provShellId = -1;// ID of the upper shell G4int shellNum = 0;// INDEX corresponding to shellId (lower shell) in a list of shells that can serve as // lower shells in a fluorescent transition G4int maxNumOfShells = transitionManager->NumberOfReachableShells(Z); const G4FluoTransition* refShell = transitionManager->ReachableShell(Z,maxNumOfShells-1); // refShell corresponds to the highest shell that can still serve as a final state for a fluorescent transition. if ( shellId <= refShell->FinalShellId())// If shellId is larger than the ID of refShell, // then it means that there can be NO fluorescent transition that has shellId as the lower shell. // Hence, we can save us the trouble looking for one. { // Now find the index of shellId in the list of shells that can get a fluorescent transition. while (shellId != transitionManager->ReachableShell(Z,shellNum)->FinalShellId()) { if(shellNum==maxNumOfShells-1) break; shellNum++; } G4int transProb = 1; G4double partialProb = G4UniformRand(); G4double partSum = 0; const G4FluoTransition* aShell = transitionManager->ReachableShell(Z,shellNum); G4int trSize = (aShell->TransitionProbabilities()).size(); // Loop over the shells wich can provide an electron for a radiative transition towards shellId: // in every run of the loop the partial sum of probabilities of the first transProb shells // is calculated and compared with a random number [0,1]. // If the partial sum is greater, the shell whose index is transProb // is chosen as the starting shell for a radiative transition // and its ID is returned. // Note that the sum of all radiative probabilities can be lower than unity, due to competition // with Auger transitions. Hence, the loop may be terminated without finding // a radiative transition, and in that case -1 is returned and control is handed over to // the GenerateAuger routine. while(transProb < trSize){ partSum += aShell->TransitionProbability(transProb); if(partialProb <= partSum) { provShellId = aShell->OriginatingShellId(transProb); fluoTransitionFoundFlag = true; break; } transProb++; } } // If a radiative transition was found, the ID of the 'upper shell' is returned. If not, an Auger transition may take place. return provShellId; } G4DynamicParticle* CADPhysicsAtomicDeexcitation::GenerateFluorescence(G4int Z, G4int shellId, G4int provShellId ) { // Isotropic angular distribution for the photon G4double newcosTh = 1.-2.*G4UniformRand(); G4double newsinTh = std::sqrt(1.-newcosTh*newcosTh); G4double newPhi = twopi*G4UniformRand(); G4double xDir = newsinTh*std::sin(newPhi); G4double yDir = newsinTh*std::cos(newPhi); G4double zDir = newcosTh; G4ThreeVector newGammaDirection(xDir,yDir,zDir); // Again, find the index of shellId G4int shellNum = 0; G4int maxNumOfShells = transitionManager->NumberOfReachableShells(Z); while (shellId != transitionManager-> ReachableShell(Z,shellNum)->FinalShellId()) { if(shellNum == maxNumOfShells-1) { break; } shellNum++; } // Find the index of provShellId const G4FluoTransition* aShell = transitionManager->ReachableShell(Z,shellNum); size_t transitionSize = aShell->OriginatingShellIds().size(); size_t index = 0; while (provShellId != aShell->OriginatingShellId(index)) { if(index == transitionSize-1) { break; } index++; } // Energy of the gamma leaving provShellId for shellId G4double transitionEnergy = aShell->TransitionEnergy(index); // This is the shell where the new vacancy is: it is the same // shell where the electron came from. It is stored to the // vector of shells to be processed. ShellIdstobeprocessed.push_back(aShell->OriginatingShellId(index)); // Return the photon as a new particle G4DynamicParticle* newPart = new G4DynamicParticle(G4Gamma::Gamma(), newGammaDirection, transitionEnergy); return newPart; } G4DynamicParticle* CADPhysicsAtomicDeexcitation::GenerateAuger(G4int Z, G4int shellId) { // If Auger production was disabled, then simply push the binding energy of the // current shell to the VacancyEnergies vector and return if(!fAuger) { PushEnergy(Z,shellId); return 0; } if (shellId <=0 ) G4Exception("CADPhysicsAtomicDeexcitation::GenerateAuger()","errorCADPhysicsAtomicDeexcitation03",FatalException,"CADPhysicsAtomicDeexcitation: zero or negative shellId"); G4int maxNumOfShells = transitionManager->NumberOfReachableAugerShells(Z); const G4AugerTransition* refAugerTransition = transitionManager->ReachableAugerShell(Z,maxNumOfShells-1); // refAugerTransition corresponds to the highest shell that can still serve as a final state for an Auger transition. G4int shellNum = 0;// index corresponding to shell ID if ( shellId <= refAugerTransition->FinalShellId() )// If shellId is larger than the ID of refAugerTransition, // then it means that there can be NO Auger transition that has shellId as the lower shell. // Hence, we can save us the trouble looking for one. { // Now find the index of shellId in the list of shells that can get an Auger transition. G4int pippo = transitionManager->ReachableAugerShell(Z,shellNum)->FinalShellId(); if (shellId != pippo ) { do { shellNum++; if(shellNum == maxNumOfShells)// No Auger transitions for shellId! { PushEnergy(Z,shellId);// Add this shell's energy to the VacancyEnergies vector return 0; } } while (shellId != (transitionManager->ReachableAugerShell(Z,shellNum)->FinalShellId()) ) ; } // Find the Auger transition G4int transitionLoopShellIndex = 0; G4double partSum = 0; const G4AugerTransition* anAugerTransition = transitionManager->ReachableAugerShell(Z,shellNum);// anAugerTransition contains ALL possible // Auger transitions that have shellId as the lower shell // First sum up the transition probabilities over all possible Auger transitions that have shellId as the lower shell G4int transitionSize = (anAugerTransition->TransitionOriginatingShellIds())->size(); while (transitionLoopShellIndex < transitionSize) { std::vector<G4int>::const_iterator pos = anAugerTransition->TransitionOriginatingShellIds()->begin(); G4int transitionLoopShellId = *(pos+transitionLoopShellIndex); G4int numberOfPossibleAuger = (anAugerTransition->AugerTransitionProbabilities(transitionLoopShellId))->size(); G4int augerIndex = 0; if (augerIndex < numberOfPossibleAuger) { do { G4double thisProb = anAugerTransition->AugerTransitionProbability(augerIndex, transitionLoopShellId); partSum += thisProb; augerIndex++; } while (augerIndex < numberOfPossibleAuger); } transitionLoopShellIndex++; } G4double totalVacancyAugerProbability = partSum; // Next, select a specific Auger process based on partial probabilities. // transitionRandomShellId corresponds to the shell from which an electron goes to shellId // augerId corresponds to the shell from which an electron is emitted (into vacuum) G4int transitionRandomShellIndex = 0; G4int transitionRandomShellId = 1; G4int augerIndex = 0; G4int augerId = 1; partSum = 0; G4double partialProb = G4UniformRand(); G4int numberOfPossibleAuger = 0; G4bool foundFlag = false; while (transitionRandomShellIndex < transitionSize)// Loop over the transitionRandomShellIds { std::vector<G4int>::const_iterator pos = anAugerTransition->TransitionOriginatingShellIds()->begin(); transitionRandomShellId = *(pos+transitionRandomShellIndex);// Find transitionRandomShellId //corresponding to transitionRandomShellIndex augerIndex = 0; numberOfPossibleAuger = (anAugerTransition-> AugerTransitionProbabilities(transitionRandomShellId))->size(); while (augerIndex < numberOfPossibleAuger)// Loop over the augerIds for the given transitionRandomShellId { G4double thisProb =anAugerTransition->AugerTransitionProbability(augerIndex, transitionRandomShellId);// Partial probability of this specific Auger process partSum += thisProb; // EB: original code: if (partSum >= (partialProb/totalVacancyAugerProbability) )// This specific transition is selected // EB: totalVacancyAugerProbability is the total probability of generating an Auger // EB: partSum should, in case we reach the end of the loop equal totalVacancyAugerProbability i.e. 100% of that probability // EB: partialProb is the random number we have drawn to determine which of these transitions is selected. // EB: This means that only a multiplication here makes sense. Note that in G4 9.5 this is indeed repaired with the // EB: famous comment : // was / if (partSum >= (partialProb*totalVacancyAugerProbability) )// This specific transition is selected { foundFlag = true; augerId = anAugerTransition->AugerOriginatingShellId(augerIndex,transitionRandomShellId);// Find augerId // corresponding to augerIndex break; } augerIndex++; } if (foundFlag) break; transitionRandomShellIndex++; } if (!foundFlag) {// After looping over all possible transitions, no suitable transition has been found. Note that in principle // this should never occur. PushEnergy(Z,shellId);// Simply add the binding energy corresponding to shellId to the VacancyEnergies vector return 0; } // Deal with the details of the newly emitted electron: // Isotropic angular distribution G4double newcosTh = 1.-2.*G4UniformRand(); G4double newsinTh = std::sqrt(1.-newcosTh*newcosTh); G4double newPhi = twopi*G4UniformRand(); G4double xDir = newsinTh*std::sin(newPhi); G4double yDir = newsinTh*std::cos(newPhi); G4double zDir = newcosTh; G4ThreeVector newElectronDirection(xDir,yDir,zDir); // Energy of the Auger electron emitted G4double transitionEnergy = anAugerTransition->AugerTransitionEnergy(augerIndex, transitionRandomShellId); // G4cout << "Auger electron energy: " << transitionEnergy // << " MeV for element Z=" << Z; // G4cout << G4endl; // As a result of the Auger process, we have TWO new shells with vacancies. Both are added // to the vector of shells to be processed. ShellIdstobeprocessed.push_back(transitionRandomShellId); ShellIdstobeprocessed.push_back(augerId); G4DynamicParticle* newPart = new G4DynamicParticle(G4Electron::Electron(), newElectronDirection, transitionEnergy); return newPart; } else {// No Auger transitions for this shell PushEnergy(Z,shellId); return 0; } } void CADPhysicsAtomicDeexcitation::PushEnergy(G4int Z, G4int ShellId) { // Loop over all shells of Z to find the shell index corresponding to ShellId. // Once found, immediately store the binding energy corresponding to that shell to VacancyEnergies. G4int maxNumOfShells = transitionManager->NumberOfShells(Z); G4int index = 0; while (index < maxNumOfShells) { if(ShellId == transitionManager->Shell(Z,index)->ShellId()) { VacancyEnergies.push_back(transitionManager->Shell(Z,index)->BindingEnergy()); break; } index++; } return; }
4fdcef1460294b85e238eb9f1cd8772ece3d1cd6
47799e9cfecd2e534a6f87dc98c4b2a62f63e644
/CIE205-Project-F2018-std/DSProject_Code_S2018/Castle/Castle.h
7c32b401f0786062be54904da410427c58527bfb
[]
no_license
melsayed-7/DS_Project_Fall_2018
6e670ac8fee558d2ff7cc681c84263decd17567a
e478bce99db38576b78ee4e8a8ab204846a244fc
refs/heads/master
2022-10-09T23:38:39.096208
2018-12-30T20:07:56
2018-12-30T20:07:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
631
h
Castle.h
#pragma once #include "..\Defs.h" #include "..\CMUgraphicsLib\CMUgraphics.h" #include "..\GUI\GUI.h" #include "Tower.h" class Castle { Tower Towers[NoOfRegions]; // // TODO: Add More Data Members As Needed // public: Castle(); //Castle(double TH, int no_enemies, double power); void SetTowerHealth(REGION TowerRegion, double h); double get_total_tower_health(); void set_all_towers(double health, int no_enemies, int power); void tower_act(int tower_number, Enemy* enemy,int current_tick); Tower* get_tower(int index); void reconstruct_towers(); // // TODO: Add More Member Functions As Needed // };
772c222a8f03239577e079a61898e1a50c11f8f4
b1aef802c0561f2a730ac3125c55325d9c480e45
/src/ripple/rpc/handlers/BlackList.cpp
54f92fc31c7479e11ec9465dd180941964f25cfe
[]
no_license
sgy-official/sgy
d3f388cefed7cf20513c14a2a333c839aa0d66c6
8c5c356c81b24180d8763d3bbc0763f1046871ac
refs/heads/master
2021-05-19T07:08:54.121998
2020-03-31T11:08:16
2020-03-31T11:08:16
251,577,856
6
4
null
null
null
null
UTF-8
C++
false
false
457
cpp
BlackList.cpp
#include <ripple/app/main/Application.h> #include <ripple/protocol/jss.h> #include <ripple/resource/ResourceManager.h> #include <ripple/rpc/Context.h> namespace ripple { Json::Value doBlackList (RPC::Context& context) { auto& rm = context.app.getResourceManager(); if (context.params.isMember(jss::threshold)) return rm.getJson(context.params[jss::threshold].asInt()); else return rm.getJson(); } }
eeb9c55b148cde831ba50e214e0395b6297b883b
b4d6efac4bba01bcf8aecaaa6ced8851ff84a3fc
/Source/FEngine/Renderer/GLES20/VertexBoilProgram.cpp
28d5223af4e6140f9fdbdf795d3fcbc6950b42f4
[ "MIT" ]
permissive
fakhirsh/3DShaderDemo
5715cb0a0a86347c0858b0a7d65662797b62e319
3a045b31ac3af533f109053bf9448be27b2b1c74
refs/heads/master
2020-06-06T04:33:07.343317
2015-03-01T11:57:42
2015-03-01T11:57:42
31,494,446
1
0
null
null
null
null
UTF-8
C++
false
false
1,613
cpp
VertexBoilProgram.cpp
// // VertexBoilProgram.cpp // Game // // Created by Fakhir Shaheen on 01/03/2015. // Copyright (c) 2015 Fakhir Shaheen. All rights reserved. // #include "VertexBoilProgram.h" #include "../../../../Assets/Effects/GLES20/VertexBoil.vs" #include "../../../../Assets/Effects/GLES20/VertexBoil.fs" namespace Fakhir { VertexBoilProgram::VertexBoilProgram() { _positionAttrib = GLuint(-1); _angleUniform = GLuint(-1); _normalAttrib = GLuint(-1); _PMVMatrixUniform = GLuint(-1); } VertexBoilProgram::~VertexBoilProgram() { } bool VertexBoilProgram::Init() { _name = "VertexBoilProgram"; if (!LinkProgram(std::string(VertexBoilVS), std::string(VertexBoilFS))) { return false; } _positionAttrib = glGetAttribLocation(_programID, "a_position"); _angleUniform = glGetUniformLocation(_programID, "u_angle"); _normalAttrib = glGetAttribLocation(_programID, "a_normal"); _PMVMatrixUniform = glGetUniformLocation(_programID, "PMVMatrix"); return true; } GLuint VertexBoilProgram::GetPositionAttribLocation() { return _positionAttrib; } GLuint VertexBoilProgram::GetAngleUniformLoc() { return _angleUniform; } GLuint VertexBoilProgram::GetNormalAttribLocation() { return _normalAttrib; } GLuint VertexBoilProgram::GetPVMMatrixLoc() { return _PMVMatrixUniform; } };
c4ea10f4c4281f654a31c792f4aca4938c962e1a
e232de1f42a922dc0c94d889c1f72d4f66b325d6
/archived/Editable.h
effe91518a535292295cb771018a9fbfeaef7ed5
[]
no_license
rec/slow_gold
b19fcd684e469978bf20cd0638fa83786fc5ffae
f4551785cf7f9cf45605a850d013eef5d80f4ea6
refs/heads/master
2022-10-20T06:37:00.370927
2017-02-04T11:39:59
2017-02-04T11:39:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,878
h
Editable.h
#ifndef __REC_DATA_EDITABLE__ #define __REC_DATA_EDITABLE__ #include <map> #include <set> #include "rec/data/Address.h" #include "rec/data/Value.h" #include "rec/util/Proto.h" #include "rec/util/file/VirtualFile.pb.h" namespace rec { namespace data { class Address; class AddressProto; class Editable; class UntypedEditable; class Value; class ValueProto; typedef std::map<string, UntypedEditable*> EditableMap; typedef std::set<UntypedEditable*> EditableSet; typedef std::vector<Editable*> EditableList; #if 0 // private: void setValue(const Value&, const Address& a = Address::default_instance(), bool undoable = true); public: void append(const Value& value, const Address&); string toString() const { return ptr<Message>(clone())->ShortDebugString(); } virtual void applyLater(Operations*) = 0; virtual void applyOperations(const Operations& olist, Operations* undoes = NULL) = 0; virtual void onDataChange() = 0; virtual const Value getValue(const Address&) const = 0; virtual const string getTypeName() const = 0; virtual const VirtualFile& virtualFile() const = 0; virtual bool readFromFile() const = 0; virtual bool writeToFile() const = 0; virtual bool hasValue(const Address&) const = 0; virtual void copyTo(Message*) const = 0; virtual int getSize(const Address&) const = 0; virtual Message* clone() const = 0; virtual void needsUpdate() = 0; virtual void updateClients() = 0; // Returns true if there is no actual value behind changed behind this item. virtual bool isEmpty() const = 0; }; #endif void setValue(Editable* e, const Value&, const Address& a = Address::default_instance(), bool undoable = true); // There are more setters in archived/OldEditable.h } // namespace data } // namespace rec #endif // __REC_DATA_EDITABLE__
9838be43b85e6b5f5e2e853cf3a488db4b60f235
2e85265708e5369faeaee91111865d053d7881f4
/VGMap.h
f23ff19e4e21f716a7569a6be50d1712052d1769
[]
no_license
ChiD12/New_Heaven
f0a7fa6b0c05990d4b66a7bebbfc9e5669002d6e
0a86bae00e9f2d2f834398c3e80cae91d3023455
refs/heads/master
2020-12-26T11:35:57.151556
2020-04-22T19:37:25
2020-04-22T19:37:25
237,496,099
1
1
null
2020-04-18T19:48:09
2020-01-31T18:55:58
C++
UTF-8
C++
false
false
636
h
VGMap.h
#pragma once #include "Resources.h" #include "VGMapLoader.h" #include <vector> class VGMap { int* score; int* village_number; string* village_name; //Added by Nathan bool* forest_placed; bool* wheatfield__placed; bool* meadow_placed; bool* quarry_placed; public: VGMap(); ~VGMap(); const int* width; const int* height; bool placeTile(int, int, bool, BuildingTile); void setName(string given_name); int calculateScore(); int getScore() const; int getVillageNum() const; void PrintVillageBoard(); void PrintNumRow(int num); std::vector<vector<BuildingTile*>> *map; };
58d0ede6b403f205f9d82a33e935e20c0eb589eb
305d3be9ff0391aa35cde4d27eea1b2a06390da8
/MidiFile.h
e4bd4f0cdec668f8dfb3923a5a6c07733097c2d6
[ "MIT" ]
permissive
Madsy/libmidi
190257a61a713bd34c329be933346b35d1da1e3e
c271e991e9d6f762e81a8d2dbf7a5cd63973629d
refs/heads/master
2021-01-22T22:03:15.203945
2017-03-30T15:02:22
2017-03-30T15:02:22
85,501,956
6
0
null
null
null
null
UTF-8
C++
false
false
582
h
MidiFile.h
#ifndef MIDIFILE_H_GUARD #define MIDIFILE_H_GUARD #include <string> #include <fstream> #include <memory> #include <vector> class Midi; struct MidiChunkHeader; class MidiFile { public: MidiFile(const std::string& name); ~MidiFile(); std::shared_ptr<Midi> data(); protected: void load(const std::string& name); void readChunkInfo(); void readHeader(); void readTracks(); private: std::ifstream pStrm; std::vector<std::unique_ptr<MidiChunkHeader>> pTrackChunkInfo; std::unique_ptr<MidiChunkHeader> pHeaderChunkInfo; std::shared_ptr<Midi> pMidiData; }; #endif
3a24de2205ad99141620b5350b964424bba5052b
3b8cc751018462d1a255b0954bdeab4ce91dfc59
/include/key/ck_key_mgr.h
dc1941b1d3c027f7041bff22b83359833ae212cd
[]
no_license
yui0/Kikyu
cc2683c88318544725a729437a8b57970396d4ed
b33f1bca5a664bbb2daf4e7bceee8dcaac52dde5
refs/heads/master
2020-03-22T05:29:50.628148
2018-07-14T09:30:35
2018-07-14T09:30:35
139,570,122
1
0
null
null
null
null
UTF-8
C++
false
false
9,276
h
ck_key_mgr.h
/* Copyright (c) 2007-2010 Takashi Kitao 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. */ class ckKeyDaemon; /*! @ingroup ckKey The key manager singleton. */ class CK_API ckKeyMgr { friend class ckKeyDaemon; public: //! @cond ckDefineException(ExceptionInvalidArgument); ckDefineException(ExceptionNotInitialized); //! @endcond /*! The number of the extra values. */ static const u32 EXTRA_VALUE_NUM = 16; /*! Key types. */ enum KeyType { KEY_0, KEY_1, KEY_2, KEY_3, KEY_4, KEY_5, KEY_6, KEY_7, KEY_8, KEY_9, // KEY_A, KEY_B, KEY_C, KEY_D, KEY_E, KEY_F, KEY_G, KEY_H, KEY_I, KEY_J, KEY_K, KEY_L, KEY_M, // KEY_N, KEY_O, KEY_P, KEY_Q, KEY_R, KEY_S, KEY_T, KEY_U, KEY_V, KEY_W, KEY_X, KEY_Y, KEY_Z, // KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, // KEY_LEFT, KEY_UP, KEY_RIGHT, KEY_DOWN, // KEY_SHIFT, KEY_CTRL, KEY_ALT, // KEY_BACKSPACE, KEY_TAB, KEY_ENTER, KEY_ESCAPE, KEY_SPACE, // KEY_PAGEUP, KEY_PAGEDOWN, KEY_END, KEY_HOME, KEY_INSERT, KEY_DELETE, // KEY_NUMPAD0, KEY_NUMPAD1, KEY_NUMPAD2, KEY_NUMPAD3, KEY_NUMPAD4, // KEY_NUMPAD5, KEY_NUMPAD6, KEY_NUMPAD7, KEY_NUMPAD8, KEY_NUMPAD9, // KEY_MULTIPLY, KEY_ADD, KEY_SEPARATOR, KEY_SUBTRACT, KEY_DECIMAL, KEY_DIVIDE, // KEY_LBUTTON, KEY_MBUTTON, KEY_RBUTTON, KEY_WHEELUP, KEY_WHEELDOWN, // KEY_EXT_00, KEY_EXT_01, KEY_EXT_02, KEY_EXT_03, KEY_EXT_04, KEY_EXT_05, KEY_EXT_06, KEY_EXT_07, // KEY_EXT_08, KEY_EXT_09, KEY_EXT_10, KEY_EXT_11, KEY_EXT_12, KEY_EXT_13, KEY_EXT_14, KEY_EXT_15, // KEY_ANY, KEY_NONE }; /*! Key states. */ enum KeyState { STATE_DOWN, //!< A key is on. STATE_UP //!< A key is off. }; /*! The key event handler type. @param[in] key The type of the key. @param[in] key_state The state of the key. */ typedef void (*KeyEventHandler)(KeyType key, KeyState key_state); /*! The mouse event handler type. @param[in] mouse_x The x-coordinates of the mouse. @param[in] mouse_y The y-coordinates of the mouse. */ typedef void (*MouseEventHandler)(s16 mouse_x, s16 mouse_y); /*! The extra event handler type. @param[in] val_index The index of the value. @param[in] value The value of the extra event. */ typedef void (*ExtraEventHandler)(u8 val_index, r32 value); /*! Returns whether the key manager singleton is created. @return Whether the key manager singleton is created. */ static bool isCreated(); /*! Creates the key manager singleton. */ static void createAfterTask(); /*! Destroys the key manager singleton. */ static void destroyBeforeSys(); /*! Returns the key event handler. If the key event handler doen't exist, returns NULL. @return The key event handler. */ static KeyEventHandler getKeyEventHandlerN(); /*! Sets the key event handler. @param[in] handler A key event handler. */ static void setKeyEventHandler(KeyEventHandler handler); /*! The default key event handler. @param[in] key The key type. @param[in] key_state The state of the key. */ static void defaultKeyEventHandler(KeyType key, KeyState key_state); /*! Returns the mouse event handler. If the mouse event handler doen't exit, returns NULL. @return The mouse event handler. */ static MouseEventHandler getMouseEventHandlerN(); /*! Sets the mouse event handler. @param[in] handler A mouse event handler. */ static void setMouseEventHandler(MouseEventHandler handler); /*! The default key event handler. @param[in] mouse_x The x-coordinate of the mouse. @param[in] mouse_y The y-coordinate of the mouse. */ static void defaultMouseEventHandler(s16 mouse_x, s16 mouse_y); /*! Returns the extra event handler. If the extra event handler doen't exit, return NULL. @return The extra event handler. */ static ExtraEventHandler getExtraEventHandlerN(); /*! Sets the extra event handler. @param[in] handler An extra event handler. */ static void setExtraEventHandler(ExtraEventHandler handler); /*! The default extra event handler. @param[in] val_index The index of the value. @param[in] value The value of the extra event. */ static void defaultExtraEventHandler(u8 val_index, r32 value); /*! Returns whether the specified key is on. @param[in] key A key. @return Whether the specified key is on. */ static bool isOn(KeyType key); /*! Returns whether the specified key is off. @param[in] key A key. @return Whether the specified key is off. */ static bool isOff(KeyType key); /*! Returns the specified key is pressed. @param[in] key A key. @return The specified key is pressed. */ static bool isPressed(KeyType key); /*! Returns the specified key is released. @param[in] key A key. @return The specified key is released. */ static bool isReleased(KeyType key); /*! Returns the x-coordinate of the mouse. @return The x-coordinate of the mouse. */ static s16 getMouseX(); /*! Returns the y-coordinate of the mouse. @return The y-coordinate of the mouse. */ static s16 getMouseY(); /*! Returns the wheel offset of the mouse. @return The wheel offset of the mouse. */ static s16 getMouseWheel(); /*! Sets the position of the mouse. @param[in] mouse_x The x-coordinate of the mouse. @param[in] mouse_y The y-coordinate of the mouse. */ static void setMousePos(s16 mouse_x, s16 mouse_y); /*! Returns whether the mouse is visible. @return Whether the mouse is visible. */ static bool isMouseVisible(); /*! Determines whether the mouse is visible. @param[in] is_visible Whether the mouse is visible. */ static void setMouseVisible(bool is_visible); /*! Returns the extra value as 32-bit integer number. @param[in] val_index The index of the extra value. @return The extra value. */ static s32 getExtraValue_s32(u8 val_index); /*! Returns the extra value as 32-bit floating point number. @param[in] val_index The index of the extra value. @return The extra value. */ static r32 getExtraValue_r32(u8 val_index); /*! Updates the states of the keys. This method is only for system. */ static void updateKeyStateForSystem(); /*! Resets the states of the kyes. This method is only for system. */ static void resetKeyStateForSystem(); /*! Updates the extra value. This method id only for system. */ static void updateExtraValueForSystem(); private: static const u32 KEY_TYPE_NUM = KEY_NONE + 1; enum KeyFlag { FLAG_REAL_ON = 0x01, // FLAG_DELAY_ON = 0x02, // FLAG_CUR_ON = 0x04, // FLAG_LAST_ON = 0x08 }; ckKeyMgr(); ~ckKeyMgr(); void operator=(const ckKeyMgr&); static ckKeyMgr* instance(); KeyEventHandler m_key_event_handler; MouseEventHandler m_mouse_event_handler; ExtraEventHandler m_extra_event_handler; u8 m_key_flag[KEY_TYPE_NUM]; r32 m_cur_ext_val[EXTRA_VALUE_NUM]; r32 m_real_ext_val[EXTRA_VALUE_NUM]; s16 m_mouse_x; s16 m_mouse_y; s16 m_real_mouse_wheel; s16 m_cur_mouse_wheel; ckKeyDaemon* m_key_daemon; static ckKeyMgr* m_instance; };
42e93d62ac3ef014152c4c0f5f16465e50aacb88
7f6b34428696aec2c0f7722da41b99800fb00849
/code/r3/filesystem.cpp
28cff268dc68cb9179015842a539f491f4104d5d
[]
no_license
casseveritt/r3
865f880f24fa1206b793377dee775193eaa33a70
158584b0821a57772dba6aada7b43df3da5cba84
refs/heads/master
2020-12-24T08:15:33.906205
2015-12-18T00:52:26
2015-12-18T00:52:26
5,392,165
7
2
null
null
null
null
UTF-8
C++
false
false
24,037
cpp
filesystem.cpp
/* * filesystem * */ /* Copyright (c) 2010 Cass Everitt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of contributors to this software may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Cass Everitt */ #include "r3/filesystem.h" #include "r3/command.h" #include "r3/http.h" #include "r3/md5.h" #include "r3/output.h" #include "r3/parse.h" #include "r3/thread.h" #include "r3/time.h" #include "r3/ujson.h" #include "r3/var.h" #if __APPLE__ # include <TargetConditionals.h> #endif #if __APPLE__ || ANDROID || __linux__ # include <unistd.h> # include <dirent.h> # include <sys/stat.h> #endif #if _WIN32 # include <Windows.h> #endif #include <stdio.h> #include <assert.h> #include <iostream> #include <sstream> #include <map> #include <set> #include <deque> using namespace std; using namespace r3; VarInteger f_numOpenFiles( "f_numOpenFiles", "Number of open files.", 0, 0 ); #if ANDROID // copy a file out of the apk into the cache extern bool appMaterializeFile( const char * filename ); VarString app_apkPath( "app_apkPath", "path to APK file", 0, "" ); double apkTimestamp; #endif namespace r3 { VarString f_basePath( "f_basePath", "path to the base directory", Var_ReadOnly, ""); VarString f_cachePath( "f_cachePath", "path to writable cache directory", Var_ReadOnly, "" ); VarString f_netPath( "f_netPath", "semicolon separated base urls", Var_ReadOnly, "http://home.xyzw.us/star3map/data/" ); VarBool f_cacheUpdated( "f_cacheUpdated", "tells us we need to restart at the next opportunity", Var_ReadOnly, false ); } // Try to download a the file again if it's been this long (in seconds) #define CACHE_REFRESH_INTERVAL 3600 // Wait at least this long after a cached file has been opened before refreshing it from the net (in seconds) #define CACHE_FETCH_DELAY 15 namespace { File * CachedFileOpenForPrivateRead( const string & inFileName ); string ComputeMd5Sum(File *file) { if( file == NULL || file->Size() == 0 ) { return "00000000000000000000000000000000000000"; } unsigned char buf[4096]; MD5Context ctx; MD5Init( &ctx ); int pos = file->Tell(); file->Seek( Seek_Begin, 0 ); for(;;) { int sz = file->Read( buf, 1, sizeof(buf) ); if( sz == 0 ) { break; } MD5Update( &ctx, buf, sz ); } file->Seek( Seek_Begin, pos ); MD5Final( buf, &ctx ); char hex[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; string sum; for( int i = 0; i < 16; i++ ) { sum += hex[ ( buf[i] >> 4 ) & 0xf ]; sum += hex[ ( buf[i] >> 0 ) & 0xf ]; } return sum; } struct ManifestInfo { ManifestInfo() : lastTry(0) {} string url; string md5; string etag; string lastModified; int lastTry; }; Condition filesystemCond; Mutex filesystemMutex; map<string, ManifestInfo> manifest; ManifestInfo & GetManifestInfo( const string & filename ) { ScopedMutex scm( filesystemMutex, R3_LOC ); return manifest[ filename ]; } void WriteCacheManifest() { if( f_cachePath.GetVal().size() == 0 ) { return; } File * f = FileOpenForWrite( "CacheManifest.json" ); if( f == NULL ) { return; } stringstream ss ( stringstream::out ); ss << "{ "; string sep = ""; for( map<string,ManifestInfo>::iterator it = manifest.begin(); it != manifest.end(); ++it ) { ManifestInfo &mi = it->second; ss << sep << endl; ss << " \"" << it->first.c_str() << "\": {" << endl; bool prev = false; if( mi.url.size() ) { if( prev ) { ss << "," << endl; } prev = true; ss << " \"url\": \"" << mi.url.c_str() << "\""; } if( mi.md5.size() ) { if( prev ) { ss << "," << endl; } prev = true; ss << " \"md5\": \"" << mi.md5.c_str() << "\""; } if( mi.etag.size() ) { if( prev ) { ss << "," << endl; } prev = true; ss << " \"etag\": \"" << mi.etag.c_str() << "\""; } if( mi.lastModified.size() ) { if( prev ) { ss << "," << endl; } prev = true; ss << " \"Last-Modified\": \"" << mi.lastModified.c_str() << "\""; } if( mi.lastTry != 0 ) { if( prev ) { ss << "," << endl; } prev = true; ss << " \"lastTry\": " << mi.lastTry; } if( prev ) { ss << endl; } ss << " }"; sep = ","; } ss << endl << "}" << endl; f->WriteLine( ss.str() ); delete f; } void ReadCacheManifest() { vector< unsigned char > data; bool success = FileReadToMemory( "CacheManifest.json", data ); if( !success || data.size() == 0 ) { Output( "Failed to read the CacheManifest.json file." ); return; } ujson::Json * root = ujson::Decode( reinterpret_cast<const char *>(&data[0]), int( data.size() ) ); if( root && root->GetType() == ujson::Type_Object ) { map<string, ujson::Json *> & m = root->m; for( map<string, ujson::Json *>::iterator i = m.begin(); i != m.end(); ++i ) { if( i->second == NULL || i->second->GetType() != ujson::Type_Object ) { continue; } ManifestInfo mi; map<string, ujson::Json *> & f = i->second->m; string fn = i->first; if( f.count( "url" ) && f["url"]->GetType() == ujson::Type_String ) { mi.url = f["url"]->s; } if( f.count( "md5" ) && f["md5"]->GetType() == ujson::Type_String ) { mi.md5 = f["md5"]->s; } if( f.count( "etag" ) && f["etag"]->GetType() == ujson::Type_String ) { mi.etag = f["etag"]->s; } if( f.count( "Last-Modified" ) && f["Last-Modified"]->GetType() == ujson::Type_String ) { mi.lastModified = f["Last-Modified"]->s; } if( f.count( "lastTry" ) && f["lastTry"]->GetType() == ujson::Type_Number ) { mi.lastTry = f["lastTry"]->n; } GetManifestInfo( i->first ) = mi; } } } void WriteCacheManifest_cmd( const vector< Token > & tokens ) { WriteCacheManifest(); } CommandFunc WriteCacheManifestCmd( "writecachemanifest", "write the cache manifest file", WriteCacheManifest_cmd ); string NormalizePathSeparator( const string inPath ) { string path = inPath; for ( int i = 0; i < (int)path.size(); i++ ) { if ( path[i] == '\\' ) { path[i] = '/'; } } return path; } #if ! _WIN32 double getFileTimestamp( const char *path ) { struct stat s; double ts = 0.0; if ( 0 == stat( path, &s ) ) { #if ANDROID || __linux__ ts = double( s.st_mtime ); #else ts = double( s.st_mtimespec.tv_sec ); #endif } //Output( "Timestamp is %lf for %s", ts, path ); return ts; } #endif #if _WIN32 FILE *Fopen( const char *filename, const char *mode ) { FILE *fp; fopen_s( &fp, filename, mode ); if ( fp ) { f_numOpenFiles.SetVal( f_numOpenFiles.GetVal() + 1 ); } return fp; } #else FILE *Fopen( const char *filename, const char *mode ) { FILE *fp; fp = fopen( filename, mode ); f_numOpenFiles.SetVal( f_numOpenFiles.GetVal() + 1 ); return fp; } #endif void Fclose( FILE * fp ) { f_numOpenFiles.SetVal( f_numOpenFiles.GetVal() - 1 ); fclose( fp ); } class StdCFile : public r3::File { public: FILE *fp; bool unlinkOnDestruction; bool write; bool internal; string name; StdCFile( const string & filename, bool filewrite ) : fp( 0 ) , unlinkOnDestruction( false ) , write( filewrite ) , internal( false ) , name( filename ) {} virtual ~StdCFile() { if ( fp ) { Fclose( fp ); if( unlinkOnDestruction > 0 ) { unlink( name.c_str() ); } if( write ) { size_t loc = name.find( f_cachePath.GetVal() ); if( loc != string::npos ) { string fn = name.substr( name.rfind('/') + 1 ); if( internal == false && fn != "CacheManifest.json" ) { StdCFile * file = reinterpret_cast<StdCFile *>( CachedFileOpenForPrivateRead( fn ) ); file->internal = true; string md5 = ComputeMd5Sum( file ); delete file; GetManifestInfo( fn ).md5 = md5; //Output( "md5 for %s = %s", fn.c_str(), md5.c_str() ); //WriteCacheManifest(); } } } } } virtual int Read( void *data, int size, int nitems ) { return (int)fread( data, (size_t)size, (size_t)nitems, fp ); } virtual int Write( const void *data, int size, int nitems ) { return (int)fwrite( data, size, nitems, fp ); } virtual void Seek( SeekEnum whence, int offset ) { fseek( fp, offset, (int)whence ); } virtual int Tell() { return (int)ftell( fp ); } virtual int Size() { int curPos = Tell(); Seek( Seek_End, 0 ); int size = Tell(); Seek( Seek_Begin, curPos ); return size; } virtual bool AtEnd() { return feof( fp ) != 0; } virtual double GetModifiedTime() { struct stat s; fstat( fileno( fp ), & s ); #if ANDROID || __linux__ return double( s.st_mtime ); #else return double( s.st_mtimespec.tv_sec ); #endif } }; bool FindDirectory( VarString & path, const char * dirName ) { string dirname = dirName; #if ! _WIN32 // figure out current working directory if ( path.GetVal().size() > 0 ) { DIR *dir = opendir( path.GetVal().c_str() ); if ( ! dir ) { return false; } } else { Output( "Searching for \"%s\" directory.", dirName ); char ccwd[256]; getcwd( ccwd, sizeof( ccwd )); string cwd = ccwd; for( int i = 0; i < 10; i++ ) { Output( "cwd = %s", cwd.c_str() ); DIR *dir = opendir( ( cwd + string("/") + dirname ).c_str() ); if ( dir ) { cwd += "/" + dirname + "/"; path.SetVal( cwd ); Output( "Found \"%s\": %s", dirName, cwd.c_str() ); closedir( dir ); break; } else { cwd += "/.."; } } } #else WIN32_FIND_DATAA findData; // figure out current working directory if ( path.GetVal().size() > 0 ) { HANDLE hDir = FindFirstFileA( path.GetVal().c_str(), &findData ); if ( hDir == INVALID_HANDLE_VALUE ) { return false; } } else { //Output( "Searching for base directory." ); char ccwd[256]; GetCurrentDirectoryA( sizeof( ccwd ), ccwd ); string cwd = ccwd; for( int i = 0; i < 10; i++ ) { //Output( "cwd = %s", cwd ); HANDLE hDir = FindFirstFileA( ( cwd + "/" + dirname ).c_str(), &findData ); if ( hDir != INVALID_HANDLE_VALUE ) { cwd += "/" + dirname + "/"; cwd = NormalizePathSeparator( cwd ); path.SetVal( cwd ); //Output( "Found base: %s", base.c_str() ); FindClose( hDir ); break; } else { cwd += "/.."; } } } #endif return true; } bool MakeDirectory( const char * dirName ) { assert( dirName ); vector<Token> tokens = TokenizeString( dirName, "/" ); Output( "In MakeDirectory( \"%s\" )", dirName ); string dirname = dirName[0] == '/' ? "/" : ""; for ( int i = 0; i < (int)tokens.size(); i++ ) { dirname += tokens[i].valString; //Output( "Checking dir %s", dirname.c_str() ); #if ! _WIN32 if ( getFileTimestamp( dirname.c_str() ) == 0.0 ) { Output( "Attempting to create dir %s", dirname.c_str() ); int ret = mkdir( dirname.c_str(), 0777 ); if ( ret != 0 ) { Output( "Failed to create dir %s", dirname.c_str() ); return false; } } #else WIN32_FIND_DATAA findData; // figure out current working directory HANDLE hDir = FindFirstFileA( dirname.c_str(), &findData ); if ( hDir == INVALID_HANDLE_VALUE ) { Output( "Attempting to create dir %s", dirname.c_str() ); CreateDirectoryA( dirname.c_str(), NULL ); HANDLE hDir = FindFirstFileA( dirname.c_str(), &findData ); if ( hDir == INVALID_HANDLE_VALUE ) { Output( "Failed to create dir %s", dirname.c_str() ); return false; } } #endif dirname += "/"; } //Output( "Success in MakeDirectory for %s", dirname.c_str() ); return true; } struct FileFetchEntry { FileFetchEntry() : notBefore( 0.0 ) {} FileFetchEntry( const string & file_name, double not_before ) : filename( file_name ), notBefore( not_before ) {} string filename; double notBefore; }; deque<FileFetchEntry> fetchQueue; set<string> fetchSet; void PushFileFetch( const string & filename, double notBefore = 0.0 ) { ScopedMutex scm( filesystemMutex, R3_LOC ); FileFetchEntry ffe( filename, notBefore ); if( fetchSet.count( ffe.filename ) ) { Output( "PushFileFetch: Already have %s", ffe.filename.c_str() ); return; } fetchSet.insert( filename ); fetchQueue.push_back( ffe ); } bool PopFileFetch( FileFetchEntry & ffe ) { ScopedMutex scm( filesystemMutex, R3_LOC ); if( fetchQueue.size() == 0 ) { return false; } ffe = fetchQueue.front(); fetchQueue.pop_front(); fetchSet.erase( ffe.filename ); return true; } File * CachedFileOpenForWrite( const string & inFileName, ManifestInfo & mi ) { string path = f_cachePath.GetVal(); if( path.size() == 0 ) { return NULL; } string filename = NormalizePathSeparator( inFileName ); string dir = path; if( filename.rfind('/') != string::npos ) { dir += filename.substr( 0, filename.rfind('/') ); if ( MakeDirectory( dir.c_str() ) == false ) { return NULL; } } string fn = path + filename; FILE * fp = Fopen( fn.c_str(), "wb" ); Output( "Opening file %s for write %s", fn.c_str(), fp ? "succeeded" : "failed" ); if ( fp ) { StdCFile * F = new StdCFile( fn, true ); F->fp = fp; GetManifestInfo( filename ) = mi; return F; } return NULL; } double lastCacheRefresh = 0; void RefreshCache() { map<string,ManifestInfo> m; { ScopedMutex scm( filesystemMutex, R3_LOC ); m = manifest; } double t = GetTime(); lastCacheRefresh = t; for( map<string,ManifestInfo>::iterator i = m.begin(); i != m.end(); ++i ) { PushFileFetch( i->first, t ); } } struct NetCacheThread : public Thread { NetCacheThread() : Thread( "NetCache" ) {} string UrlToFilename( const string & url ) { string s = url.substr( url.rfind('/') ).substr( 1 ); return s; } void Run() { int count = 0; while( ++count ) { filesystemCond.Wait(); FileFetchEntry ffe; double t = GetTime(); if( PopFileFetch( ffe ) == false ) { if( ( t - lastCacheRefresh ) > CACHE_REFRESH_INTERVAL ) { RefreshCache(); } continue; } string file; { if( t < ffe.notBefore ) { PushFileFetch( ffe.filename, ffe.notBefore ); continue; } file = ffe.filename; if( file.size() == 0 ) { continue; } } vector<Token> urls = TokenizeString( f_netPath.GetVal().c_str(), ";" ); ManifestInfo mi = GetManifestInfo( file ); if( mi.url == "local" ) { continue; } if( ( t - mi.lastTry ) < CACHE_REFRESH_INTERVAL ) { Output( "NetCache - skipping %s, last try only %.0lf minutes ago", file.c_str(), (t - mi.lastTry ) / 60 ); continue; } Output( "NetCache looking for %s", file.c_str() ); mi.lastTry = t; for( int i = 0; i < urls.size(); i++ ) { string url = urls[i].valString; Output( "NetCache trying %s - %s", url.c_str(), file.c_str() ); vector<uchar> data; map<string,string> header; if( url == mi.url && mi.etag.size() ) { header["etag"] = mi.etag; } if( UrlReadToMemory( url + '/' + file, data, header ) ) { mi.url = url; if( header.count( "Last-Modified" ) ) { mi.lastModified = header["Last-Modified"]; } if( header.count( "etag" ) ) { mi.etag = header["etag"]; if( mi.etag.size() && mi.etag[0] == '"' ) { mi.etag = mi.etag.substr( 1, mi.etag.size() - 2 ); } } mi.lastTry = GetTime(); File * f = CachedFileOpenForWrite( file, mi ); f->Write( &data[0], 1, (int)data.size() ); f_cacheUpdated.SetVal( true ); delete f; break; } } GetManifestInfo( file ) = mi; } } }; NetCacheThread netCacheThread; File * CachedFileOpenForPrivateRead( const string & inFileName ) { string path = f_cachePath.GetVal(); if( path.size() == 0 ) { return NULL; } string filename = NormalizePathSeparator( inFileName ); if( filename.size() && filename[0] == '/' ) { return NULL; } string dir = path; if( filename.rfind('/') != string::npos ) { dir += filename.substr( 0, filename.rfind('/') ); if ( MakeDirectory( dir.c_str() ) == false ) { return NULL; } } string fn = path + filename; FILE * fp = Fopen( fn.c_str(), "rb" ); Output( "Opening file %s for read %s", fn.c_str(), fp ? "succeeded" : "failed" ); if ( fp ) { StdCFile * F = new StdCFile( fn, true ); F->fp = fp; return F; } return NULL; } File * CachedFileOpenForRead( const string & inFileName ) { File *fp = CachedFileOpenForPrivateRead( inFileName ); if( inFileName != "CacheManifest.json" ) { string filename = NormalizePathSeparator( inFileName ); PushFileFetch( filename, GetTime() + CACHE_FETCH_DELAY ); } return fp; } } namespace r3 { void InitFilesystem() { // for debugging "missing file" resilience // if ( FindDirectory( f_basePath, "bass" ) == false ) { if ( FindDirectory( f_basePath, "base" ) == false ) { Output( "exiting due to invalid %s: %s", f_basePath.Name().Str().c_str(), f_basePath.GetVal().c_str() ); exit( 1 ); } if( f_cachePath.GetVal().size() == 0 ) { f_cachePath.SetVal( f_basePath.GetVal() + "/../cache/" ); } if( MakeDirectory( f_cachePath.GetVal().c_str() ) == false ) { exit( 1 ); } lastCacheRefresh = GetTime() + 120.0; ReadCacheManifest(); netCacheThread.Start(); } void ShutdownFilesystem() { WriteCacheManifest(); } void TickFilesystem() { filesystemCond.Broadcast(); } bool CacheUpdated() { return f_cacheUpdated.GetVal(); } File * FileOpenForWrite( const string & inFileName ) { ManifestInfo mi; mi.url = "local"; File * f = CachedFileOpenForWrite( inFileName, mi ); return f; } File * FileOpenForRead( const string & inFileName ) { string filename = NormalizePathSeparator( inFileName ); { File *F = CachedFileOpenForRead( inFileName ); if( F ) { return F; } } // then check in base { string fn = f_basePath.GetVal() + filename; FILE * fp = Fopen( fn.c_str(), "rb" ); Output( "Opening file %s for read %s", fn.c_str(), fp ? "succeeded" : "failed" ); if ( fp ) { StdCFile * F = new StdCFile( fn, false); F->fp = fp; return F; } } #if ANDROID // try to materialize the file, then look for it again in the base path... if ( f_basePath.GetVal().size() > 0 ) { if ( appMaterializeFile( filename.c_str() ) ) { Output( "Materialized file %s from apk.", filename.c_str() ); } else { Output( "Materialize failed." ); } string fn = f_basePath.GetVal() + filename; FILE * fp = Fopen( fn.c_str(), "rb" ); Output( "Opening file %s for read %s", fn.c_str(), fp ? "succeeded" : "failed" ); if ( fp ) { StdCFile * F = new StdCFile(fn, false); F->fp = fp; F->unlinkOnDestruction = true; return F; } } #endif // then give up return NULL; } void FileDelete( const string & fileName ) { string filename = NormalizePathSeparator( fileName ); vector<string> paths; if ( f_cachePath.GetVal().size() > 0 ) { paths.push_back( f_cachePath.GetVal() ); } paths.push_back( f_basePath.GetVal() ); Output( "Trying to delete file %s", fileName.c_str() ); vector<Token> tokens = TokenizeString( filename.c_str(), "/" ); for ( int i = 0; i < (int)paths.size(); i++ ) { string & path = paths[i]; if ( path.size() > 0 ) { string dir = path; for ( int j = 0; j < (int)tokens.size() - 1; j++ ) { dir += tokens[j].valString; dir += "/"; } if ( MakeDirectory( dir.c_str() ) == false ) { continue; } string fn = path + filename; FILE * fp = Fopen( fn.c_str(), "wb" ); bool found = fp != NULL; Fclose( fp ); if( found ) { Output( "Deleting file %s", fn.c_str() ); unlink( fn.c_str() ); return; } } } } bool FileReadToMemory( const string & inFileName, vector< unsigned char > & data ) { string filename = NormalizePathSeparator( inFileName ); File *f = FileOpenForRead( filename ); if ( f == NULL ) { data.clear(); return false; } int sz = f->Size(); data.resize( sz ); int bytesRead = f->Read( &data[0], 1, sz ); assert( sz == bytesRead && sz == data.size() ); delete f; return true; } string File::ReadLine() { string ret; char s[256]; int l; do { l = Read( s, 1, sizeof( s ) ); int end = l; for ( int i = 0; i < l; i++ ) { if ( s[i] == '\n' ) { // We take care not seek with a zero offset, // because it clears the eof flag. int o = i + 1 - l; if ( o != 0 ) { Seek( Seek_Curr, o ); } l = 0; end = i; break; } } ret = ret + string( s, s + end ); } while( l ); return ret; } void File::WriteLine( const string & str ) { string s = str + "\n"; Write( s.c_str(), 1, (int)s.size() ); } }
39594040934e628f15bd4af2adfce57d0e6160bf
84257c31661e43bc54de8ea33128cd4967ecf08f
/ppc_85xx/usr/include/c++/4.2.2/javax/swing/tree/DefaultTreeCellEditor.h
982e443f43e5323a94ede136db81876251242171
[]
no_license
nateurope/eldk
9c334a64d1231364980cbd7bd021d269d7058240
8895f914d192b83ab204ca9e62b61c3ce30bb212
refs/heads/master
2022-11-15T01:29:01.991476
2020-07-10T14:31:34
2020-07-10T14:31:34
278,655,691
0
0
null
null
null
null
UTF-8
C++
false
false
4,270
h
DefaultTreeCellEditor.h
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __javax_swing_tree_DefaultTreeCellEditor__ #define __javax_swing_tree_DefaultTreeCellEditor__ #pragma interface #include <java/lang/Object.h> #include <gcj/array.h> extern "Java" { namespace java { namespace awt { namespace event { class ActionEvent; } class Font; class Color; class Component; class Container; } } namespace javax { namespace swing { class Icon; class Timer; class JTree; namespace tree { class DefaultTreeCellEditor; class TreePath; class DefaultTreeCellRenderer; class TreeCellEditor; } namespace event { class TreeSelectionEvent; class CellEditorListener; class EventListenerList; } } } } class javax::swing::tree::DefaultTreeCellEditor : public ::java::lang::Object { public: DefaultTreeCellEditor (::javax::swing::JTree *, ::javax::swing::tree::DefaultTreeCellRenderer *); DefaultTreeCellEditor (::javax::swing::JTree *, ::javax::swing::tree::DefaultTreeCellRenderer *, ::javax::swing::tree::TreeCellEditor *); private: void configureEditingComponent (::javax::swing::JTree *, ::javax::swing::tree::DefaultTreeCellRenderer *, ::javax::swing::tree::TreeCellEditor *); void writeObject (::java::io::ObjectOutputStream *) { } void readObject (::java::io::ObjectInputStream *) { } public: virtual void setBorderSelectionColor (::java::awt::Color *); virtual ::java::awt::Color *getBorderSelectionColor () { return borderSelectionColor; } virtual void setFont (::java::awt::Font *); virtual ::java::awt::Font *getFont () { return font; } virtual ::java::awt::Component *getTreeCellEditorComponent (::javax::swing::JTree *, ::java::lang::Object *, jboolean, jboolean, jboolean, jint); virtual ::java::lang::Object *getCellEditorValue (); virtual jboolean isCellEditable (::java::util::EventObject *); virtual jboolean shouldSelectCell (::java::util::EventObject *); virtual jboolean stopCellEditing (); virtual void cancelCellEditing (); private: void stopEditingTimer (); public: virtual void addCellEditorListener (::javax::swing::event::CellEditorListener *); virtual void removeCellEditorListener (::javax::swing::event::CellEditorListener *); virtual JArray< ::javax::swing::event::CellEditorListener *> *getCellEditorListeners (); virtual void valueChanged (::javax::swing::event::TreeSelectionEvent *); virtual void actionPerformed (::java::awt::event::ActionEvent *) { } public: // actually protected virtual void setTree (::javax::swing::JTree *); virtual jboolean shouldStartEditingTimer (::java::util::EventObject *); virtual void startEditingTimer (); virtual jboolean canEditImmediately (::java::util::EventObject *); virtual jboolean inHitRegion (jint, jint); virtual void determineOffset (::javax::swing::JTree *, ::java::lang::Object *, jboolean, jboolean, jboolean, jint); virtual void prepareForEditing (); virtual ::java::awt::Container *createContainer (); virtual ::javax::swing::tree::TreeCellEditor *createTreeCellEditor (); public: // actually package-private static jint CLICK_COUNT_TO_START; private: ::javax::swing::event::EventListenerList * __attribute__((aligned(__alignof__( ::java::lang::Object )))) listenerList; public: // actually protected ::javax::swing::tree::TreeCellEditor *realEditor; ::javax::swing::tree::DefaultTreeCellRenderer *renderer; ::java::awt::Container *editingContainer; ::java::awt::Component *editingComponent; jboolean canEdit; jint offset; ::javax::swing::JTree *tree; ::javax::swing::tree::TreePath *lastPath; ::javax::swing::Timer *timer; jint lastRow; ::java::awt::Color *borderSelectionColor; ::javax::swing::Icon *editingIcon; ::java::awt::Font *font; private: ::javax::swing::tree::TreePath *tPath; friend class javax_swing_tree_DefaultTreeCellEditor$RealEditorListener; friend class javax_swing_tree_DefaultTreeCellEditor$DefaultTextField; friend class javax_swing_tree_DefaultTreeCellEditor$EditorContainer; public: static ::java::lang::Class class$; }; #endif /* __javax_swing_tree_DefaultTreeCellEditor__ */
2c17a4293652bba0d061ab1e8d742c4b1f86bd31
96f1314000cc6cc5b15b26832f336d651e16514c
/v8-fibjs/v8/src/base/platform/mutex.cc
829227f7d51ea628c77e1d296f49587e2c099ad7
[]
no_license
bitsuperlab/vendor
52b3454f4716c0eb5faae25a4c26265707cd5028
ec8b08a10ef22980c0ac32fdb7336a3c3be5360f
refs/heads/master
2021-01-21T07:44:52.127233
2016-03-24T06:56:46
2016-03-24T06:56:46
28,850,258
0
1
null
2015-08-19T08:07:49
2015-01-06T06:34:49
C++
UTF-8
C++
false
false
605
cc
mutex.cc
#include "mutex.h" namespace v8 { namespace base { Mutex::Mutex() : native_handle_(false) { } Mutex::~Mutex() { } void Mutex::Lock() { native_handle_.lock(); } void Mutex::Unlock() { native_handle_.unlock(); } bool Mutex::TryLock() { return native_handle_.trylock(); } RecursiveMutex::RecursiveMutex() : native_handle_(true) { } RecursiveMutex::~RecursiveMutex() { } void RecursiveMutex::Lock() { native_handle_.lock(); } void RecursiveMutex::Unlock() { native_handle_.unlock(); } bool RecursiveMutex::TryLock() { return native_handle_.trylock(); } } } // namespace v8::base
c4ec62813d3c3bc628f23bf4b062dfa14793afe8
8d0f764da10bc17675f82bde3d1801de4c2c9ff7
/Codeforces gym solutions/2017-2018 ACM-ICPC German Collegiate Programming Contest (GCPC 2017)/G.cpp
1a6c410f30b4a7a294de81a7ed2813e47344ac62
[]
no_license
AbdelrahmanElhawary/CompetitiveProgramming
f24f675ced34d75a383db03a9ffef59373b23c31
791ed4fcdefde421902f3b512414c1a49fdc21cd
refs/heads/master
2021-05-09T05:00:41.380756
2020-08-19T09:57:32
2020-08-19T09:57:32
119,295,405
1
3
null
2020-10-01T20:12:38
2018-01-28T20:33:41
C++
UTF-8
C++
false
false
659
cpp
G.cpp
#include <bits/stdc++.h> #include<complex> using namespace std; #define ll long long #define endl "\n" typedef complex<long double> point; #define cross(a,b) ((conj(a)*(b)).imag()) #define len(v) ((long double) hypot((v).imag(),(v).real())) int n; int main() { std::ios_base::sync_with_stdio(0); cin.tie(NULL); cin>>n; vector<point> v; for(int i=0;i<n;i++){ ll x,y; cin>>x>>y; point a(x,y); v.push_back(a); } long double res = 0; ll bound =0; for(int i=0;i<n;i++){ ll j = (i+1) % n; res+=cross(v[i],v[j]); point vv = v[j] - v[i]; bound +=abs(__gcd((ll)vv.real() , (ll)vv.imag())); } cout<<(ll)(fabs(res/2) - bound/2+1)<<endl; }
de7c364f2a1a5d31e50bb2b862f456e107d34cb9
3dc86dd9a7a4159406724124cb280d6f5e5bda29
/Shared/Foundation/BasicTypes/BasicTypeFuncs.h
ed2a0c2118da794d797f2268f9e17e85ee362e06
[]
no_license
hamfirst/StormBrewerEngine
3e051fb6806277c8273031f0e9ab241659fafba4
491ff8e42022e01c43d72b6d7b4f76db439d8745
refs/heads/master
2023-03-17T02:23:34.827037
2023-03-10T17:24:23
2023-03-10T17:24:23
53,809,267
0
3
null
null
null
null
UTF-8
C++
false
false
2,804
h
BasicTypeFuncs.h
#pragma once #include "Foundation/Optional/Optional.h" #include "Foundation/BasicTypes/BasicTypes.refl.h" inline Vector2 SelectVectorXY(const Vector2 & v1, const Vector2 & v2, uint32_t mask) { return Vector2( (mask & 0b01) ? v1.x : v2.x, (mask & 0b10) ? v1.y : v2.y ); } inline Vector2 MaxVectorXY(const Vector2 & v1, const Vector2 & v2) { return Vector2(std::max(v1.x, v2.x), std::max(v1.y, v2.y)); } inline Vector2 MinVectorXY(const Vector2 & v1, const Vector2 & v2) { return Vector2(std::min(v1.x, v2.x), std::min(v1.y, v2.y)); } inline RenderVec2 SelectVectorXY(const RenderVec2 & v1, const RenderVec2 & v2, uint32_t mask) { return RenderVec2{ (mask & 0b01) ? v1.x : v2.x, (mask & 0b10) ? v1.y : v2.y }; } inline RenderVec2 MaxVectorXY(const RenderVec2 & v1, const RenderVec2 & v2) { return RenderVec2{ std::max(v1.x, v2.x), std::max(v1.y, v2.y) }; } inline RenderVec2 MinVectorXY(const RenderVec2 & v1, const RenderVec2 & v2) { return RenderVec2{ std::min(v1.x, v2.x), std::min(v1.y, v2.y) }; } inline int DotVector2(const Vector2 & a, const Vector2 & b) { return a.x * b.x + a.y + b.y; } inline bool BoxIntersect(const Box & b1, const Box & b2) { return !( (b1.m_Start.x > b2.m_End.x) | (b1.m_Start.y > b2.m_End.y) | (b1.m_End.x < b2.m_Start.x) | (b1.m_End.y < b2.m_Start.y)); } inline bool PointInBox(const Box & b, const Vector2 & p) { return !( (b.m_Start.x > p.x) | (b.m_Start.y > p.y) | (b.m_End.x < p.x) | (b.m_End.y < p.y)); } inline Optional<Box> ClipBox(const Box & box, const Box & bounds) { if (!BoxIntersect(box, bounds)) { return Optional<Box>(); } Box result; result.m_Start = MaxVectorXY(box.m_Start, bounds.m_Start); result.m_End = MinVectorXY(box.m_End, bounds.m_End); return result; } inline Box MakeBoxFromStartAndSize(const Vector2 & start, const Vector2 & size) { return Box{ start, start + size }; } inline void BoxUnionInPlace(Box & a, const Box & b) { a.m_Start.x = std::min(a.m_Start.x, b.m_Start.x); a.m_Start.y = std::min(a.m_Start.y, b.m_Start.y); a.m_End.x = std::max(a.m_End.x, b.m_End.x); a.m_End.y = std::max(a.m_End.y, b.m_End.y); } inline Box BoxUnion(const Box & a, const Box & b) { Box r = a; BoxUnionInPlace(r, b); return r; } inline Optional<Box> BoxUnionList(const std::vector<Box> & box_list) { Optional<Box> result; for (auto & elem : box_list) { if (result) { BoxUnionInPlace(result.Value(), elem); } else { result = elem; } } return result; } inline Color LerpColor(const Color & a, const Color & b, float val) { auto one_minus_v = 1.0f - val; return Color( a.r * one_minus_v + b.r * val, a.g * one_minus_v + b.g * val, a.b * one_minus_v + b.b * val, a.a * one_minus_v + b.a * val); }
40b488577ba6e603ba741b5c71b62c766d61a583
dc86e3b0ef61a308e627d18207e3bd121778008b
/MusicProvider/src/AlbumArtLoader.cpp
bc817e0bf5063d8606b6b546dd07fd7a6b7eeb1a
[ "MIT" ]
permissive
jesseDtucker/Arcusical
59444fca8aa1ca0862275b0b375d238cb90fb550
f2c4245662ab43dadd147f79c6526471dea6f905
refs/heads/master
2021-01-18T22:28:46.973949
2016-04-09T19:09:25
2016-04-09T19:09:25
34,878,320
5
1
null
null
null
null
UTF-8
C++
false
false
30,481
cpp
AlbumArtLoader.cpp
#include "AlbumArtLoader.hpp" #include "boost/algorithm/string/predicate.hpp" #include <functional> #include <numeric> #include <random> #include <string> #include <unordered_map> #include <utility> #include "DefaultAlbumArt.hpp" #include "FilterProcessor.hpp" #include "IFile.hpp" #include "IFileReader.hpp" #include "IFolder.hpp" #include "ImageTypes.hpp" #include "LocalMusicCache.hpp" #include "MPEG4_Parser.hpp" #include "MusicTypes.hpp" #include "Storage.hpp" using std::accumulate; using std::any_of; using std::begin; using std::copy_if; using std::default_random_engine; using std::end; using std::function; using std::max_element; using std::pair; using std::random_device; using std::shared_ptr; using std::tuple; using std::unordered_map; using std::vector; using std::wstring; using namespace Arcusical::MusicProvider; using namespace Arcusical::Model; using namespace Arcusical::MPEG4; using namespace FileSystem; using namespace std::placeholders; using namespace Util; static const int MIN_EMBEDED_LOAD_BATCH_SIZE = 5; static const int MAX_EMBEDED_LOAD_BATCH_SIZE = 20; static const int MIN_DELAYED_LOAD_BATCH_SIZE = 5; static const int MAX_DELAYED_LOAD_BATCH_SIZE = 10; static const std::chrono::milliseconds EMBEDED_LOAD_INTERVAL{ 500}; // do not wait more than this amount of time before loading more typedef boost::uuids::uuid SongId; static vector<tuple<AlbumArtLoader::AlbumId, vector<SongId>>> GetSongIdsForAlbums( const vector<AlbumArtLoader::AlbumId>& ids, const AlbumCollection& albums); static unordered_map<AlbumArtLoader::AlbumId, wstring, boost::hash<AlbumArtLoader::AlbumId>> BuildAlbumNameLookup( const vector<AlbumArtLoader::AlbumId>& ids, const AlbumCollection& albums); static vector<tuple<AlbumArtLoader::AlbumId, vector<tuple<wstring, ContainerType>>>> GetPathsForSongIds( const vector<tuple<AlbumArtLoader::AlbumId, vector<SongId>>>& albumInfo, const SongCollection& songs); static vector<tuple<wstring, ContainerType>> GetFilePaths(const Song& song); static wstring LoadAlbumImage(const vector<tuple<wstring, ContainerType>>& songPaths, const wstring& albumName); static boost::optional<wstring> LoadAlbumImage(const tuple<wstring, ContainerType>& songPathj, const wstring& albumName); static boost::optional<tuple<vector<unsigned char>, ImageType>> GetThumbnail(const IFile& file, const ContainerType& container); static boost::optional<tuple<vector<unsigned char>, ImageType>> LoadThumbnailFromMpeg4(const IFile& file); static boost::optional<tuple<vector<unsigned char>, ImageType>> LoadThumbnailFromSystem(const IFile& file); static wstring SaveImageFile(const std::wstring& existingArtPath); static boost::optional<wstring> SaveImageFile(vector<unsigned char>& imgData, const wstring& albumName, ImageType imageType); static boost::optional<wstring> SaveImageFile(vector<unsigned char>& imgData, const wstring& albumName, const wstring& imageExtension); static vector<wstring> GetImagePaths(vector<FilePtr> files); static wstring FindArt(const wstring& albumName, const vector<tuple<wstring, ContainerType>>& albumSongInfo, const vector<wstring>& imagePaths); static wstring FindArt(const vector<wstring>& imagePaths, const wstring& songPath, const wstring& albumName); static wstring VoteOnResult(const vector<pair<wstring, wstring>>& selections, const unordered_map<wstring, size_t>& pathWeights); static size_t FindLastPathSeperator(const wstring& path); static unordered_map<wstring, size_t> BuildCounts(const vector<wstring>& strings); static bool CheckAlbum(const AlbumArtLoader::IdBoolPair&); struct CheckAlbumPath { typedef const AlbumArtLoader::IdPathPair& argument_type; bool operator()(argument_type pair) const { return pair.second.size() > 0; } }; static AlbumArtLoader::AlbumId StripId(const AlbumArtLoader::IdBoolPair&); static AlbumArtLoader::AlbumId StripIdFromPath(const AlbumArtLoader::IdPathPair&); Arcusical::MusicProvider::AlbumArtLoader::AlbumArtLoader(LocalMusicStore::LocalMusicCache* cache) : m_verifier(), m_verifyFilter(&CheckAlbum), m_verifyIdStripper(&StripId), m_embededLoader(MIN_EMBEDED_LOAD_BATCH_SIZE, MAX_EMBEDED_LOAD_BATCH_SIZE, EMBEDED_LOAD_INTERVAL), m_loadedFilter(CheckAlbumPath()), m_loadedIdStripper(&StripIdFromPath), m_delayedLoader(MIN_DELAYED_LOAD_BATCH_SIZE, MAX_DELAYED_LOAD_BATCH_SIZE, EMBEDED_LOAD_INTERVAL), m_delayedLoadedFilter(CheckAlbumPath()), m_recorder(), m_cache(cache) { m_recorder.SetBatchProcessor(std::bind(&AlbumArtLoader::RecordAlbumArt, this, _1)); m_verifier.SetBatchProcessor(std::bind(&AlbumArtLoader::VerifyAlbums, this, _1)); m_embededLoader.SetBatchProcessor(std::bind(&AlbumArtLoader::EmbededAlbumLoad, this, _1)); m_delayedLoader.SetBatchProcessor(std::bind(&AlbumArtLoader::DelayedAlbumLoad, this, _1)); m_verifier.Connect(&m_verifyFilter); m_verifyFilter.ConnectRejectBuffer(&m_verifyIdStripper); m_verifyIdStripper.ConnectBuffer(&m_embededLoader); m_embededLoader.Connect(&m_loadedFilter); m_loadedFilter.ConnectMatchingBuffer(&m_recorder); m_loadedFilter.ConnectRejectBuffer(&m_loadedIdStripper); m_loadedIdStripper.ConnectBuffer(&m_delayedLoader); m_delayedLoader.Connect(&m_delayedLoadedFilter); m_delayedLoadedFilter.ConnectMatchingBuffer(&m_recorder); m_verifier.Start(); m_embededLoader.Start(); m_imagePathFuture = std::async(std::launch::async, [this]() { return FileSystem::Storage::MusicFolder().FindFilesWithExtensions({L".bmp", L".jpg", L".jpeg", L".png", L".tiff"}); }); } Arcusical::MusicProvider::AlbumArtLoader::~AlbumArtLoader() { m_verifier.AwaitCompletion(); m_embededLoader.AwaitCompletion(); m_delayedLoader.AwaitCompletion(); m_imagePathFuture.wait(); } // // Verification // std::vector<AlbumArtLoader::IdBoolPair> AlbumArtLoader::VerifyAlbums( const std::vector<AlbumArtLoader::AlbumId>& albumIds) { std::vector<AlbumArtLoader::IdBoolPair> results; results.reserve(albumIds.size()); vector<tuple<AlbumArtLoader::AlbumId, wstring>> imageFilePaths; { auto albums = m_cache->GetLocalAlbums(); for (auto& id : albumIds) { auto album = albums->find(id); if (album != end(*albums)) { auto filePath = album->second.GetImageFilePath(); imageFilePaths.push_back(std::make_tuple(id, filePath)); } } } for (auto& idPathPair : imageFilePaths) { const auto& id = std::get<0>(idPathPair); const auto& path = std::get<1>(idPathPair); bool isVerified = !isDefaultAlbumArt(path) || FileSystem::Storage::FileExists(path); results.push_back(std::make_pair(id, isVerified)); } return results; } // // Loading // vector<AlbumArtLoader::IdPathPair> AlbumArtLoader::EmbededAlbumLoad(const vector<AlbumArtLoader::AlbumId>& albumIds) { vector<tuple<AlbumArtLoader::AlbumId, vector<SongId>>> songIdsForAlbums; vector<tuple<AlbumArtLoader::AlbumId, vector<tuple<wstring, ContainerType>>>> songPathsForAlbums; vector<AlbumArtLoader::IdPathPair> albumsWithArt; unordered_map<AlbumArtLoader::AlbumId, wstring, boost::hash<AlbumArtLoader::AlbumId>> albumNameLookup; albumsWithArt.reserve(albumIds.size()); { auto albums = m_cache->GetLocalAlbums(); songIdsForAlbums = GetSongIdsForAlbums(albumIds, *albums); albumNameLookup = BuildAlbumNameLookup(albumIds, *albums); } { auto songs = m_cache->GetLocalSongs(); songPathsForAlbums = GetPathsForSongIds(songIdsForAlbums, *songs); } transform(begin(songPathsForAlbums), end(songPathsForAlbums), back_inserter(albumsWithArt), [&albumNameLookup](const tuple<AlbumArtLoader::AlbumId, vector<tuple<wstring, ContainerType>>>& songPaths) { auto id = std::get<0>(songPaths); auto nameItr = albumNameLookup.find(id); if (nameItr != end(albumNameLookup)) { auto path = LoadAlbumImage(std::get<1>(songPaths), nameItr->second); return make_pair(id, path); } else { return make_pair(id, wstring()); } }); return albumsWithArt; } // // Recording // std::vector<int> AlbumArtLoader::RecordAlbumArt(const std::vector<AlbumArtLoader::IdPathPair>& albumArt) { m_cache->GetLocalAlbumsMutable([&albumArt](Model::AlbumCollection* albums) { for (auto& result : albumArt) { auto& id = std::get<0>(result); auto& path = std::get<1>(result); auto albumItr = albums->find(id); if (albumItr != end(*albums) && path.size() > 0) { albumItr->second.SetImageFilePath(path); } } }); m_cache->SaveAlbums(); // Notify any listeners that album art has been loaded and is ready. vector<AlbumArtLoader::AlbumId> albumIdsLoaded; albumIdsLoaded.reserve(albumArt.size()); transform(begin(albumArt), end(albumArt), back_inserter(albumIdsLoaded), [](IdPathPair res) { return std::get<0>(res); }); OnArtLoaded(albumIdsLoaded); return std::vector<int>(albumArt.size()); } // // Delayed Loading // std::vector<AlbumArtLoader::IdPathPair> AlbumArtLoader::DelayedAlbumLoad( const std::vector<AlbumArtLoader::AlbumId>& batch) { // first try to load from the songs again. The load may have failed before because not all the songs // in an album had art and the ones that were processed initially did not contain art. I've sometimes noticed // only the first few songs in an album have art, but I do not define an order for loading so these may not be // loaded initially. auto embededLoadResults = EmbededAlbumLoad(batch); decltype(embededLoadResults) missingResults; decltype(embededLoadResults) foundArt; missingResults.reserve(embededLoadResults.size()); foundArt.reserve(embededLoadResults.size()); copy_if(begin(embededLoadResults), end(embededLoadResults), back_inserter(foundArt), CheckAlbumPath()); copy_if(begin(embededLoadResults), end(embededLoadResults), back_inserter(missingResults), std::not1(CheckAlbumPath())); std::vector<AlbumArtLoader::AlbumId> idsToSearchFor; idsToSearchFor.reserve(missingResults.size()); transform(begin(missingResults), end(missingResults), back_inserter(idsToSearchFor), &StripIdFromPath); vector<tuple<AlbumArtLoader::AlbumId, vector<SongId>>> songIdsForAlbums; vector<tuple<AlbumArtLoader::AlbumId, vector<tuple<wstring, ContainerType>>>> songPathsForAlbums; unordered_map<AlbumArtLoader::AlbumId, wstring, boost::hash<AlbumArtLoader::AlbumId>> albumNameLookup; { auto albums = m_cache->GetLocalAlbums(); songIdsForAlbums = GetSongIdsForAlbums(idsToSearchFor, *albums); albumNameLookup = BuildAlbumNameLookup(idsToSearchFor, *albums); } { auto songs = m_cache->GetLocalSongs(); songPathsForAlbums = GetPathsForSongIds(songIdsForAlbums, *songs); } vector<AlbumArtLoader::IdPathPair> artPaths; artPaths.reserve(songPathsForAlbums.size()); transform(begin(songPathsForAlbums), end(songPathsForAlbums), back_inserter(artPaths), [this, &albumNameLookup]( const tuple<AlbumArtLoader::AlbumId, vector<tuple<wstring, ContainerType>>>& songPathsForAlbum) { auto id = std::get<0>(songPathsForAlbum); auto albumSongInfo = std::get<1>(songPathsForAlbum); auto albumName = albumNameLookup.at(id); auto imagePath = FindArt(albumName, albumSongInfo, m_imagePaths); return make_pair(id, imagePath); }); // now make sure to add in the ones that were loaded from embedded artPaths.reserve(artPaths.size() + foundArt.size()); std::move(begin(foundArt), end(foundArt), back_inserter(artPaths)); return artPaths; } // // Helpers // vector<tuple<AlbumArtLoader::AlbumId, vector<SongId>>> GetSongIdsForAlbums(const vector<AlbumArtLoader::AlbumId>& ids, const AlbumCollection& albums) { vector<tuple<AlbumArtLoader::AlbumId, vector<SongId>>> songIdsForAlbums; songIdsForAlbums.reserve(albums.size()); for (auto& id : ids) { auto albumItr = albums.find(id); if (albumItr != end(albums)) { auto songIds = albumItr->second.GetSongIds(); songIdsForAlbums.push_back(std::make_tuple(id, vector<SongId>{begin(songIds), end(songIds)})); } } return songIdsForAlbums; } unordered_map<AlbumArtLoader::AlbumId, wstring, boost::hash<AlbumArtLoader::AlbumId>> BuildAlbumNameLookup( const vector<AlbumArtLoader::AlbumId>& ids, const AlbumCollection& albums) { unordered_map<AlbumArtLoader::AlbumId, wstring, boost::hash<AlbumArtLoader::AlbumId>> lookup; for (auto& id : ids) { auto albumItr = albums.find(id); if (albumItr != end(albums)) { lookup[id] = albumItr->second.GetTitle(); } } return lookup; } vector<tuple<AlbumArtLoader::AlbumId, vector<tuple<wstring, ContainerType>>>> GetPathsForSongIds( const vector<tuple<AlbumArtLoader::AlbumId, vector<SongId>>>& albumInfo, const SongCollection& songs) { vector<tuple<AlbumArtLoader::AlbumId, vector<tuple<wstring, ContainerType>>>> songPathsForAlbums; songPathsForAlbums.reserve(albumInfo.size()); transform(begin(albumInfo), end(albumInfo), back_inserter(songPathsForAlbums), [&songs](const tuple<AlbumArtLoader::AlbumId, vector<SongId>>& info) { auto& ids = std::get<1>(info); vector<tuple<wstring, ContainerType>> paths; paths.reserve(ids.size()); for (auto& id : ids) { std::wstring songPath = L""; const auto& songItr = songs.find(id); // we have to check if the song still exists. It's possible it was deleted while we were doing // other work. if (songItr != end(songs)) { auto songPaths = GetFilePaths(songItr->second); std::move(begin(songPaths), end(songPaths), back_inserter(paths)); } } return make_tuple(std::get<0>(info), paths); }); return songPathsForAlbums; } wstring LoadAlbumImage(const vector<tuple<wstring, ContainerType>>& songPaths, const wstring& albumName) { wstring path; for (auto& songPath : songPaths) { auto imagePath = LoadAlbumImage(songPath, albumName); if (imagePath != boost::none) { path = *imagePath; break; } } return path; } boost::optional<wstring> LoadAlbumImage(const tuple<wstring, ContainerType>& songPath, const std::wstring& albumName) { boost::optional<wstring> imagePath = boost::none; auto& path = std::get<0>(songPath); auto& container = std::get<1>(songPath); auto songFile = FileSystem::Storage::LoadFileFromPath(path); ARC_ASSERT(songFile != nullptr); if (songFile != nullptr) { auto thumbnail = GetThumbnail(*songFile, container); if (thumbnail != boost::none) { imagePath = SaveImageFile(std::get<0>(*thumbnail), albumName, std::get<1>(*thumbnail)); } } return imagePath; } vector<wstring> GetImagePaths(vector<FilePtr> imageFiles) { vector<wstring> imagePaths; imagePaths.reserve(imageFiles.size()); transform(begin(imageFiles), end(imageFiles), back_inserter(imagePaths), [](const FilePtr& file) { return file->GetFullPath(); }); return imagePaths; } wstring GetOnlyPathToFile(const wstring& fullPath) { auto pathEnd = FindLastPathSeperator(fullPath); if (pathEnd != 0) { // we want to try and keep the separator on the end, hence the +1 return wstring(begin(fullPath), next(begin(fullPath), pathEnd + 1)); } else { return fullPath; } } wstring FindArt(const wstring& albumName, const vector<tuple<wstring, ContainerType>>& albumSongInfo, const vector<wstring>& imagePaths) { if (imagePaths.size() == 0) { return L""; } // this is gonna get messy... // will find art for a song by simply: // 1) determining the number of identical characters in the song path and art path // 2) determine the average number of characters in common // 3) filter out any image paths that are less than or equal to the average // 4) select the max length of what remains, if more than one select all max // 5a) select any with the album name in their title, if at least 1 go to 6 // 5b) select any with the word 'cover' in their title, if at least 1 go to 6 // 5c) select any with the words 'art', 'album', 'front' or 'back', if at least 1 go to 6 // 5d) select them all // 6) randomly select one of the available options produced by step 5s selection // // The above steps will get the art for a single song. The kicker is we have no guarantee that all the songs // are in the same folder and will give the same result. As such the above procedure will be repeated for each // song. Yes this will be slow and has a fair bit of time complexity. However, this process should run in the // background // and only for a handful of songs so I'm not too worried about this operation being a tad pricey. To improve the // efficiency // songs in the same folder will be grouped together as they should all produce the same result anyways. // // Once each song has some art selected aggregate them and select the most common song file. If a tie choose randomly // first break the albumSongInfo down into only paths vector<wstring> songPaths; songPaths.reserve(albumSongInfo.size()); transform(begin(albumSongInfo), end(albumSongInfo), back_inserter(songPaths), [](const tuple<wstring, ContainerType>& info) { auto fullPath = std::get<0>(info); return GetOnlyPathToFile(fullPath); }); // now we only really care about searching for the unique folders, no point doing the work twice. // However, because of the voting mechanism the number of songs in each location must be maintained // otherwise a single song in another directory may be enough to outvote many other songs located // in the album directory. While this is unlikely I would rather the system was fairly comprehensive // in its search capabilities and behaved in a 'manner of least surprise' for a typical end user. auto pathWeights = BuildCounts(songPaths); decltype(songPaths) uniqueSongPaths; uniqueSongPaths.reserve(pathWeights.size()); transform(begin(pathWeights), end(pathWeights), back_inserter(uniqueSongPaths), [](const unordered_map<wstring, size_t>::value_type& pair) { return pair.first; }); vector<pair<wstring, wstring>> selections; selections.reserve(uniqueSongPaths.size()); transform(begin(uniqueSongPaths), end(uniqueSongPaths), back_inserter(selections), [&imagePaths, &albumName](const wstring& songPath) { auto imagePath = FindArt(imagePaths, songPath, albumName); return make_pair(songPath, imagePath); }); auto imgPath = VoteOnResult(selections, pathWeights); return SaveImageFile(imgPath); } wstring VoteOnResult(const vector<pair<wstring, wstring>>& selections, const unordered_map<wstring, size_t>& pathWeights) { // now convert the selections to votes taking into account the weights of each path vector<pair<size_t, wstring>> votes; votes.reserve(selections.size()); transform(begin(selections), end(selections), back_inserter(votes), [&pathWeights](const pair<wstring, wstring>& selection) { ARC_ASSERT(end(pathWeights) != pathWeights.find(selection.first)); auto weight = pathWeights.at(selection.first); return make_pair(weight, selection.second); }); // finally it is possible that an image was selected twice by two different paths, its votes should be merged together unordered_map<wstring, size_t> uniqueVotes; for (auto& vote : votes) { if (vote.second.size() > 0) // don't vote on empty paths { auto itr = uniqueVotes.find(vote.second); if (itr == end(uniqueVotes)) { uniqueVotes[vote.second] = vote.first; } else { uniqueVotes[vote.second] += vote.first; } } } if (uniqueVotes.size() > 0) { auto maxItr = max_element(begin(uniqueVotes), end(uniqueVotes), [](const unordered_map<wstring, size_t>::value_type& a, const unordered_map<wstring, size_t>::value_type& b) { return a.second < b.second; }); return maxItr->first; } else { // there are no options return L""; } } size_t NumberOfCommonAncestors(const wstring& a, const wstring& b) { // requiring that a is the shorter string if (a.size() > b.size()) { return NumberOfCommonAncestors(b, a); } auto aItr = begin(a); auto bItr = begin(b); size_t commonCount = 0; while (aItr != end(a) && *aItr == *bItr) { ARC_ASSERT(bItr != end(b)); // a should be shorter, so we can't run over b. assert just in case // basically we only care about the depth matching, not the actual length of the path that is common if (*aItr == '\\' || *aItr == '/') { ++commonCount; } ++aItr; ++bItr; } return commonCount; } wstring SelectCandidate(const wstring& albumName, const vector<wstring>& fullImagePaths) { // this is a series of selection passes // first pass is for any that have the album name is the title of the file // second pass is for any with the word 'cover' or 'art' 'album' in the title // third pass is for any with the word 'front' or 'back' in the title // final pass selects them all // given that we only care about the titles at this point lets first strip the rest of the path out ARC_ASSERT(fullImagePaths.size() > 0); vector<pair<wstring, const wstring*>> imagePaths; imagePaths.reserve(fullImagePaths.size()); transform(begin(fullImagePaths), end(fullImagePaths), back_inserter(imagePaths), [](const wstring& fullPath) { auto nameStart = FindLastPathSeperator(fullPath); auto name = wstring(std::next(begin(fullPath), nameStart + 1), end(fullPath)); return make_pair(name, &fullPath); }); vector<vector<wstring>> namesToCheck = {{albumName}, {L"front"}, {L"cover", L"albumart"}, {L"album", L"art"}, {L"inlay"}, {L"back", L"rear"}}; vector<pair<wstring, const wstring*>> possiblePaths; for (auto& keywords : namesToCheck) { copy_if(begin(imagePaths), end(imagePaths), back_inserter(possiblePaths), [&keywords](const pair<wstring, const wstring*>& title) { return any_of(begin(keywords), end(keywords), [&title](const wstring& keyword) { return boost::icontains(title.first, keyword); }); }); if (possiblePaths.size() > 0) { break; } } const wstring* selection = nullptr; static random_device rd; static default_random_engine rand(rd()); auto r = rand(); if (possiblePaths.size() == 0) { // no possible paths, just pick any path at random auto offset = r % imagePaths.size(); selection = imagePaths[offset].second; } else { auto offset = r % possiblePaths.size(); selection = possiblePaths[offset].second; } ARC_ASSERT(selection != nullptr); ARC_ASSERT(selection->size() != 0); ARC_ASSERT(FileSystem::Storage::FileExists(*selection)); return *selection; } wstring FindArt(const vector<wstring>& imagePaths, const wstring& songPath, const wstring& albumName) { wstring selectedImagePath; ARC_ASSERT(imagePaths.size() > 0); // Note see the other FindArt function for details of the process, makes more sense to read all pieces in one go to // understand the process vector<pair<wstring, size_t>> imagePathsWithLengths; imagePathsWithLengths.reserve(imagePaths.size()); transform(begin(imagePaths), end(imagePaths), back_inserter(imagePathsWithLengths), [&songPath](const wstring& path) { auto length = NumberOfCommonAncestors(path, songPath); return make_pair(path, length); }); size_t total = accumulate(begin(imagePathsWithLengths), end(imagePathsWithLengths), size_t(0), [](const size_t& c, const pair<wstring, size_t>& p) { return c + p.second; }); // rounding matters! auto avg = (float)(total) / (float)(imagePathsWithLengths.size()); vector<pair<wstring, size_t>> candidatePairs; copy_if(begin(imagePathsWithLengths), end(imagePathsWithLengths), back_inserter(candidatePairs), [&avg](const pair<wstring, size_t> pair) { return pair.second > avg; }); if (candidatePairs.size() > 0) { auto max = max_element(begin(candidatePairs), end(candidatePairs), [](const pair<wstring, size_t>& a, const pair<wstring, size_t>& b) { return a.second < b.second; }); ARC_ASSERT(max != end(candidatePairs)); auto last = remove_if(begin(candidatePairs), end(candidatePairs), [&max](const pair<wstring, size_t>& pair) { return pair.second != max->second; }); candidatePairs.erase(last, end(candidatePairs)); vector<wstring> candidates; candidates.reserve(candidatePairs.size()); ARC_ASSERT(candidatePairs.size() > 0); transform(begin(candidatePairs), end(candidatePairs), back_inserter(candidates), [](const pair<wstring, size_t>& pair) { return pair.first; }); selectedImagePath = SelectCandidate(albumName, candidates); } return selectedImagePath; } InputBuffer<AlbumArtLoader::AlbumId>* AlbumArtLoader::AlbumsNeedingArt() { return &m_embededLoader; } InputBuffer<AlbumArtLoader::AlbumId>* AlbumArtLoader::AlbumsToVerify() { return &m_verifier; } void AlbumArtLoader::NotifyLoadingComplete() { auto imageFiles = m_imagePathFuture.get(); m_imagePaths = GetImagePaths(imageFiles->GetAll()); m_delayedLoader.Start(); m_verifier.Complete(); m_embededLoader.Complete(); } vector<tuple<wstring, ContainerType>> GetFilePaths(const Song& song) { vector<tuple<wstring, ContainerType>> paths; auto& filesWithFormats = song.GetFiles(); paths.reserve(filesWithFormats.size()); for (auto& format : filesWithFormats) { for (auto& songFile : format.second) { paths.push_back(std::make_tuple(songFile.filePath, songFile.container)); } } return paths; } boost::optional<tuple<vector<unsigned char>, ImageType>> GetThumbnail(const IFile& file, const ContainerType& container) { boost::optional<tuple<vector<unsigned char>, ImageType>> thumb = boost::none; switch (container) { case ContainerType::MP4: thumb = LoadThumbnailFromMpeg4(file); break; default: // fall back to system if we can't get it ourselves thumb = LoadThumbnailFromSystem(file); } return thumb; } boost::optional<tuple<vector<unsigned char>, ImageType>> LoadThumbnailFromMpeg4(const IFile& file) { boost::optional<tuple<vector<unsigned char>, ImageType>> thumb = boost::none; MPEG4_Parser mpegParser; auto reader = Storage::GetReader(&file); auto mpegTree = mpegParser.ReadAndParseFromStream(*reader); auto imageData = mpegTree->GetImageData(); if (imageData != nullptr && imageData->size() > 0) { auto imageType = mpegTree->GetImageType(); thumb = tuple<vector<unsigned char>, ImageType>(std::move(*imageData), imageType); } return thumb; } boost::optional<tuple<vector<unsigned char>, ImageType>> LoadThumbnailFromSystem(const IFile& file) { auto thumbnail = file.GetThumbnail( false); // hopefully the thumbnail is the album art, probably won't work well for .wav or .flac... if (thumbnail.size() > 0) { return make_tuple(thumbnail, ImageType::BMP); } else { return boost::none; } } boost::optional<wstring> SaveImageFile(vector<unsigned char>& imgData, const wstring& albumName, ImageType imageType) { auto ext = ImageTypeToWString.at(imageType); return SaveImageFile(imgData, albumName, ext); } boost::optional<wstring> SaveImageFile(vector<unsigned char>& imgData, const wstring& albumName, const wstring& imageExtension) { using namespace FileSystem; auto fileName = albumName + L"." + imageExtension; Storage::RemoveIllegalCharacters(fileName); replace(begin(fileName), end(fileName), '\\', '_'); replace(begin(fileName), end(fileName), '/', '_'); fileName = L"albumImgs\\" + fileName; auto imgFile = Storage::ApplicationFolder().CreateNewFile(fileName); if (nullptr != imgFile) { imgFile->WriteToFile(imgData); return imgFile->GetFullPath(); } else { return boost::none; } } wstring SaveImageFile(const std::wstring& existingArtPath) { if (existingArtPath.size() == 0) { return existingArtPath; } // For some reason we can't load the image in its default location, move to local folder first auto hash = std::hash<wstring>()(existingArtPath); auto albumArtFile = FileSystem::Storage::LoadFileFromPath(existingArtPath); vector<unsigned char> buffer; albumArtFile->ReadFromFile(buffer); auto ext = albumArtFile->GetExtension(); // including the hash of the path incase there is a collision with file names // for instance 2 separate images both names cover.png auto newFileName = albumArtFile->GetName() + L"_" + std::to_wstring(hash); auto path = SaveImageFile(buffer, newFileName, ext); ARC_ASSERT(path); ARC_ASSERT(path->size() > 0); return *path; } size_t FindLastPathSeperator(const wstring& path) { auto nameStart = path.find_last_of('/'); if (nameStart == wstring::npos) { nameStart = path.find_last_of('\\'); } if (nameStart == wstring::npos) { nameStart = 0; } return nameStart; } unordered_map<wstring, size_t> BuildCounts(const vector<wstring>& strings) { unordered_map<wstring, size_t> counts; for (auto& str : strings) { auto itr = counts.find(str); if (itr == end(counts)) { counts[str] = 1; } else { ++counts[str]; } } return counts; } // New Stuff // functional bool CheckAlbum(const AlbumArtLoader::IdBoolPair& pair) { return pair.second; } AlbumArtLoader::AlbumId StripId(const AlbumArtLoader::IdBoolPair& pair) { return pair.first; } AlbumArtLoader::AlbumId StripIdFromPath(const AlbumArtLoader::IdPathPair& pair) { return pair.first; }
dec987ba1a8fd509a10aa56f8a25ac8ae97d6429
69821ab0c5cab53c717756b598d84eab40ff261d
/solutions/uri-onlinejudge/1016.cpp
a6f645638f2ff7d6f102ab906159d0849438464e
[ "MIT" ]
permissive
gregoriobenatti/playground
6c2048b6d570b91569b335b18e70c70fef9f759a
4d3968b3b6ab1ec37a198406480073523079a09d
refs/heads/master
2020-09-15T00:35:23.313194
2018-10-23T09:08:13
2018-10-23T09:08:13
67,713,445
0
0
null
null
null
null
UTF-8
C++
false
false
240
cpp
1016.cpp
#include <iostream> using namespace std; int main() { const int VY = 90, VX = 60, HOUR_TO_MIN = 60; float d, t; cin >> d; t = (d / (VY - VX)) * HOUR_TO_MIN; cout << "" << t << " minutos" << endl; return 0; }