text
string
size
int64
token_count
int64
#include "gl/context.h" #include "gl/environment.h" #include "gl/mockglfw.h" #include "gl/mockglxw.h" #include <gmock/gmock.h> using namespace gxy; using testing::_; using testing::InSequence; using testing::NiceMock; using testing::Return; struct Fixture : public testing::Test { const int width{42}; const int height{89}; const std::string title{"badger"}; NiceMock<gl::mockglfw> mockglfw{}; NiceMock<gl::mockglxw> mockglxw{}; ::GLFWwindow window{}; Fixture() { ON_CALL(mockglfw, Init()) .WillByDefault(Return(GL_TRUE)); ON_CALL(mockglxw, Init()) .WillByDefault(Return(0)); ON_CALL(mockglfw, CreateWindow(_, _, _, _, _)) .WillByDefault(Return(&window)); } }; struct EnvironmentFixture : public Fixture { gl::environment env{}; }; TEST_F(EnvironmentFixture, CreateContext_CreatesWindow) { EXPECT_CALL(mockglfw, CreateWindow(width, height, title.c_str(), nullptr, nullptr)) .Times(1); gl::context ctx{env, width, height, title.c_str()}; } TEST_F(EnvironmentFixture, CreateContext_SetsWindowHintsBefore) { InSequence s; EXPECT_CALL(mockglfw, WindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4)) .Times(1); EXPECT_CALL(mockglfw, WindowHint(GLFW_CONTEXT_VERSION_MINOR, 1)) .Times(1); EXPECT_CALL(mockglfw, WindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE)) .Times(1); EXPECT_CALL(mockglfw, WindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE)) .Times(1); EXPECT_CALL(mockglfw, CreateWindow(_, _, _, _, _)) .Times(1); gl::context ctx{env, width, height, title.c_str()}; } TEST_F(EnvironmentFixture, CreateContext_ResetWindowHintsAfter) { InSequence s; EXPECT_CALL(mockglfw, CreateWindow(_, _, _, _, _)) .Times(1); EXPECT_CALL(mockglfw, DefaultWindowHints()) .Times(1); gl::context ctx{env, width, height, title.c_str()}; } TEST_F(EnvironmentFixture, CreateContext_MakesContextCurrent) { EXPECT_CALL(mockglfw, MakeContextCurrent(&window)) .Times(1); gl::context ctx{env, width, height, title.c_str()}; } TEST_F(EnvironmentFixture, DestructContext_CallsDestroyWindow) { gl::context ctx{env, width, height, title.c_str()}; EXPECT_CALL(mockglfw, DestroyWindow(&window)) .Times(1); } using EnvironmentFixtureDeathTest = EnvironmentFixture; TEST_F(EnvironmentFixtureDeathTest, CreateWindowReturnsNullptr_Death) { ASSERT_DEATH({ ON_CALL(mockglfw, CreateWindow(_, _, _, _, _)) .WillByDefault(Return(nullptr)); gl::context ctx(env, width, height, title.c_str()); }, ""); } struct ContextFixture : public EnvironmentFixture { gl::context uut{env, width, height, title.c_str()}; }; TEST_F(ContextFixture, RunOneWindowShouldCloseTrue_ReturnsFalse) { EXPECT_CALL(mockglfw, WindowShouldClose(&window)) .WillOnce(Return(true)); ASSERT_FALSE(uut.run_one()); } struct ContextFixtureWindowShouldntClose : public ContextFixture { ContextFixtureWindowShouldntClose() { ON_CALL(mockglfw, WindowShouldClose(&window)) .WillByDefault(Return(false)); } }; TEST_F(ContextFixtureWindowShouldntClose, RunOne_ReturnsTrue) { ASSERT_TRUE(uut.run_one()); } TEST_F(ContextFixtureWindowShouldntClose, RunOne_CallsSwapBuffersThenPollEvents) { InSequence s; EXPECT_CALL(mockglfw, SwapBuffers(&window)) .Times(1); EXPECT_CALL(mockglfw, PollEvents()) .Times(1); uut.run_one(); }
3,357
1,304
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <arrayfire.h> #include <stdio.h> #include <vector> #include <string> #include <af/util.h> #include <math.h> #include "mnist_common.h" using namespace af; float accuracy(const array& predicted, const array& target) { array val, plabels, tlabels; max(val, tlabels, target, 1); max(val, plabels, predicted, 1); return 100 * count<float>(plabels == tlabels) / tlabels.elements(); } float abserr(const array& predicted, const array& target) { return 100 * sum<float>(abs(predicted - target)) / predicted.elements(); } // Activation function array sigmoid(const array &val) { return 1 / (1 + exp(-val)); } // Predict based on given parameters array predict(const array &X, const array &Weights) { array Z = matmul(X, Weights); return sigmoid(Z); } void cost(array &J, array &dJ, const array &Weights, const array &X, const array &Y, double lambda = 1.0) { // Number of samples int m = Y.dims(0); // Make the lambda corresponding to Weights(0) == 0 array lambdat = constant(lambda, Weights.dims()); // No regularization for bias weights lambdat(0, span) = 0; // Get the prediction array H = predict(X, Weights); // Cost of misprediction array Jerr = -sum(Y * log(H) + (1 - Y) * log(1 - H)); // Regularization cost array Jreg = 0.5 * sum(lambdat * Weights * Weights); // Total cost J = (Jerr + Jreg) / m; // Find the gradient of cost array D = (H - Y); dJ = (matmulTN(X, D) + lambdat * Weights) / m; } array train(const array &X, const array &Y, double alpha = 0.1, double lambda = 1.0, double maxerr = 0.01, int maxiter = 1000, bool verbose = false) { // Initialize parameters to 0 array Weights = constant(0, X.dims(1), Y.dims(1)); array J, dJ; float err = 0; for (int i = 0; i < maxiter; i++) { // Get the cost and gradient cost(J, dJ, Weights, X, Y, lambda); err = max<float>(abs(J)); if (err < maxerr) { printf("Iteration %4d Err: %.4f\n", i + 1, err); printf("Training converged\n"); return Weights; } if (verbose && ((i + 1) % 10 == 0)) { printf("Iteration %4d Err: %.4f\n", i + 1, err); } // Update the parameters via gradient descent Weights = Weights - alpha * dJ; } printf("Training stopped after %d iterations\n", maxiter); return Weights; } void benchmark_logistic_regression(const array &train_feats, const array &train_targets, const array test_feats) { timer::start(); array Weights = train(train_feats, train_targets, 0.1, 1.0, 0.01, 1000); af::sync(); printf("Training time: %4.4lf s\n", timer::stop()); timer::start(); const int iter = 100; for (int i = 0; i < iter; i++) { array test_outputs = predict(test_feats , Weights); test_outputs.eval(); } af::sync(); printf("Prediction time: %4.4lf s\n", timer::stop() / iter); } // Demo of one vs all logistic regression int logit_demo(bool console, int perc) { array train_images, train_targets; array test_images, test_targets; int num_train, num_test, num_classes; // Load mnist data float frac = (float)(perc) / 100.0; setup_mnist<true>(&num_classes, &num_train, &num_test, train_images, test_images, train_targets, test_targets, frac); // Reshape images into feature vectors int feature_length = train_images.elements() / num_train; array train_feats = moddims(train_images, feature_length, num_train).T(); array test_feats = moddims(test_images , feature_length, num_test ).T(); train_targets = train_targets.T(); test_targets = test_targets.T(); // Add a bias that is always 1 train_feats = join(1, constant(1, num_train, 1), train_feats); test_feats = join(1, constant(1, num_test , 1), test_feats ); // Train logistic regression parameters array Weights = train(train_feats, train_targets, 0.1, // learning rate (aka alpha) 1.0, // regularization constant (aka weight decay, aka lamdba) 0.01, // maximum error 1000, // maximum iterations true);// verbose // Predict the results array train_outputs = predict(train_feats, Weights); array test_outputs = predict(test_feats , Weights); printf("Accuracy on training data: %2.2f\n", accuracy(train_outputs, train_targets )); printf("Accuracy on testing data: %2.2f\n", accuracy(test_outputs , test_targets )); printf("Maximum error on testing data: %2.2f\n", abserr(test_outputs , test_targets )); benchmark_logistic_regression(train_feats, train_targets, test_feats); if (!console) { test_outputs = test_outputs.T(); // Get 20 random test images. display_results<true>(test_images, test_outputs, test_targets.T(), 20); } return 0; } int main(int argc, char** argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; int perc = argc > 3 ? atoi(argv[3]) : 60; try { af::setDevice(device); af::info(); return logit_demo(console, perc); } catch (af::exception &ae) { std::cerr << ae.what() << std::endl; } }
5,904
2,014
#include<iostream> using namespace std; int main(){ int n; cin>>n; int b[100]; //static cout<<sizeof(b)<<endl; cout<<b<<endl; //symbol table int * a=new int[n]; //dynamic cout<<sizeof(a)<<endl; cout<<a<<endl; for(int i=0;i<n;i++){ cin>>a[i]; cout<<a[i]<<" "; } cout<<endl; delete [] a; }
325
147
#ifdef CH_LANG_CC /* * _______ __ * / ___/ / ___ __ _ / / ___ * / /__/ _ \/ _ \/ V \/ _ \/ _ \ * \___/_//_/\___/_/_/_/_.__/\___/ * Please refer to Copyright.txt, in Chombo's root directory. */ #endif #include "CoarseAverageFace.H" #include "AverageFaceF_F.H" #include "NamespaceHeader.H" // ---------------------------------------------------------- CoarseAverageFace::CoarseAverageFace() : m_isDefined(false), m_isAveraged(false) { } // ---------------------------------------------------------- CoarseAverageFace::~CoarseAverageFace() { } // ---------------------------------------------------------- CoarseAverageFace::CoarseAverageFace(const DisjointBoxLayout& a_fineGrids, int a_nComp, int a_nRef) : m_isDefined(false), m_isAveraged(false) { define(a_fineGrids, a_nComp, a_nRef); } // ---------------------------------------------------------- void CoarseAverageFace::define(const DisjointBoxLayout& a_fineGrids, int a_nComp, int a_nRef) { m_nRef = a_nRef; DisjointBoxLayout coarsened_fine_domain; coarsen(coarsened_fine_domain, a_fineGrids, m_nRef); m_coarsenedFineData.define(coarsened_fine_domain, a_nComp); m_isDefined = true; m_isAveraged = false; } // ---------------------------------------------------------- bool CoarseAverageFace::isDefined() const { return m_isDefined; } // ---------------------------------------------------------- void CoarseAverageFace::average(const LevelData<FluxBox>& a_fineData) { average(a_fineData, arithmetic, m_nRef); } // ---------------------------------------------------------- void CoarseAverageFace::averageHarmonic(const LevelData<FluxBox>& a_fineData) { average(a_fineData, harmonic, m_nRef); } // ---------------------------------------------------------- /** \param[in] a_refFactor * Sum of fine values is divided by * a_refFactor^(CH_SPACEDIM-1). For * sums this should be set to one * (default). */ void CoarseAverageFace::sum(const LevelData<FluxBox>& a_fineData, const int a_refFactor) { average(a_fineData, arithmetic, a_refFactor); } // ---------------------------------------------------------- void CoarseAverageFace::copyTo(LevelData<FluxBox>& a_coarseData) { CH_assert(m_isAveraged); // if coarseData's DisjointBoxLayout is not a simple coarsenening of // the fine one, then it needs to have at least one ghost cell in // order to ensure that this copyTo is done correctly. In // particular, this is required in order to ensure that we handle // the case where the coarse-fine interface is coincident with a // coarse-coarse boundary. The other solution to this would be to // build a specialized Copier for LevelData<FluxBox>, but we're // hoping to avoid that for now... if ((a_coarseData.ghostVect() == IntVect::Zero) && !(a_coarseData.getBoxes().compatible(m_coarsenedFineData.getBoxes()))) { MayDay::Error("CoarseAverageFace requires that coarse data which is not a coarsenening of the fine grids have at least one ghost cell"); } m_coarsenedFineData.copyTo(m_coarsenedFineData.interval(), a_coarseData, a_coarseData.interval()); } // ---------------------------------------------------------- // this function is shamelessly based on the ANAG CoarseAverage // (cell-centered) version void CoarseAverageFace::averageToCoarse(LevelData<FluxBox>& a_coarseData, const LevelData<FluxBox>& a_fineData) { computeAverages(a_coarseData, a_fineData, arithmetic); } // ---------------------------------------------------------- // this function is shamelessly based on the ANAG CoarseAverage // (cell-centered) version void CoarseAverageFace::averageToCoarseHarmonic(LevelData<FluxBox>& a_coarseData, const LevelData<FluxBox>& a_fineData) { computeAverages(a_coarseData, a_fineData, harmonic); } // ---------------------------------------------------------- void CoarseAverageFace::computeAverages(LevelData<FluxBox>& a_coarseData, const LevelData<FluxBox>& a_fineData, int a_averageType) { average(a_fineData, a_averageType, m_nRef); copyTo(a_coarseData); } // ---------------------------------------------------------- /** \param[in] a_refFactor * Sum of fine values is divided by * a_refFactor^(CH_SPACEDIM-1). * Normally this is the refinement ratio */ void CoarseAverageFace::average(const LevelData<FluxBox>& a_fineData, const int a_averageType, const int a_refFactor) { CH_assert(isDefined()); DataIterator dit = a_fineData.dataIterator(); for (dit.reset(); dit.ok(); ++dit) { FluxBox& coarsenedFine = m_coarsenedFineData[dit()]; const FluxBox& fine = a_fineData[dit()]; // coarsen from the entire fine grid onto the entire coarse grid averageGridData(coarsenedFine, fine, a_averageType, a_refFactor); } m_isAveraged = true; } // ---------------------------------------------------------- /** \param[in] a_refFactor * Sum of fine values is divided by * a_refFactor^(CH_SPACEDIM-1). * Normally this is the refinement ratio */ void CoarseAverageFace::averageGridData(FluxBox& a_coarsenedFine, const FluxBox& a_fine, int a_averageType, const int a_refFactor) const { for (int dir=0; dir<SpaceDim; dir++) { FArrayBox& coarseFab = a_coarsenedFine[dir]; const FArrayBox& fineFab = a_fine[dir]; const Box& coarseBox = coarseFab.box(); // set up refinement box int boxHi = m_nRef-1; IntVect hiVect(D_DECL6(boxHi,boxHi,boxHi, boxHi,boxHi,boxHi)); // don't want to index at all in dir direction -- // instead, want to just march along face. hiVect.setVal(dir,0); IntVect loVect(D_DECL6(0,0,0,0,0,0)); Box refBox(loVect, hiVect); if (a_averageType == arithmetic) { FORT_AVERAGEFACE( CHF_FRA(coarseFab), CHF_CONST_FRA(fineFab), CHF_BOX(coarseBox), CHF_CONST_INT(dir), CHF_CONST_INT(m_nRef), CHF_CONST_INT(a_refFactor), CHF_BOX(refBox)); } else if (a_averageType == harmonic) { FORT_AVERAGEFACEHARMONIC( CHF_FRA(coarseFab), CHF_CONST_FRA(fineFab), CHF_BOX(coarseBox), CHF_CONST_INT(dir), CHF_CONST_INT(m_nRef), CHF_CONST_INT(a_refFactor), CHF_BOX(refBox)); } else { MayDay::Error("CoarseAverageFace::averageGridData -- bad averageType"); } } } #include "NamespaceFooter.H"
7,355
2,344
// PX2BeamEmitter.inl //---------------------------------------------------------------------------- inline void BeamEmitter::SetEmitRate (float rate) { mEmitRate = rate; } //---------------------------------------------------------------------------- inline float BeamEmitter::GetEmitRate () const { return mEmitRate; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetEmitStartPos (const APoint &startPos) { mEmitStartPos = startPos; } //---------------------------------------------------------------------------- inline const APoint &BeamEmitter::GetEmitStartPos () const { return mEmitStartPos; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetEmitEndPos (const APoint &endPos) { mEmitEndPos = endPos; } //---------------------------------------------------------------------------- inline const APoint &BeamEmitter::GetEmitEndPos () const { return mEmitEndPos; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetStartPosUseLocal (bool startUseLocal) { mIsStartUseLocal = startUseLocal; } //---------------------------------------------------------------------------- inline bool BeamEmitter::IsStartPosUseLocal () const { return mIsStartUseLocal; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetSimpleLineWave (bool simpleLineWave) { mIsSimpleLineWave = simpleLineWave; } //---------------------------------------------------------------------------- inline bool BeamEmitter::IsSimpleLineWave () const { return mIsSimpleLineWave; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetSimpleLineDoAlphaDisAfterStopSpeed (float speed) { mDoAlphaDisAfterStopSpeed = speed; } //---------------------------------------------------------------------------- inline float BeamEmitter::GetSimpleLineDoAlphaDisAfterStopSpeed () const { return mDoAlphaDisAfterStopSpeed; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetWaveTypeUp (WaveType type) { mWaveTypeUp = type; } //---------------------------------------------------------------------------- inline BeamEmitter::WaveType BeamEmitter::GetWaveTypeUp () const { return mWaveTypeUp; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetWaveTypeExtend (WaveType type) { mWaveTypeExtend = type; } //---------------------------------------------------------------------------- inline BeamEmitter::WaveType BeamEmitter::GetWaveTypeExtend () const { return mWaveTypeExtend; } //---------------------------------------------------------------------------- inline int BeamEmitter::GetNumMaxBeams () const { return mNumMaxBeams; } //---------------------------------------------------------------------------- inline int BeamEmitter::GetNumLowFrequency () const { return mNumLowFrequency; } //---------------------------------------------------------------------------- inline int BeamEmitter::GetNumHighFrequency () const { return mNumHighFrequency; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetLowFrequencyRangeUp (const Float2 &range) { mLowRangeUp = range; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetLowFrequencyRangeExtend (const Float2 &range) { mLowRangeExtend = range; } //---------------------------------------------------------------------------- inline const Float2 &BeamEmitter::GetLowFrequencyRangeUp () const { return mLowRangeUp; } //---------------------------------------------------------------------------- inline const Float2 &BeamEmitter::GetLowFrequencyRangeExtend () const { return mLowRangeExtend; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetHighFrequencyRangeUp (const Float2 &range) { mHighRangeUp = range; } //---------------------------------------------------------------------------- inline void BeamEmitter::SetHighFrequencyRangeExtend (const Float2 &range) { mHighRangeExtend = range; } //---------------------------------------------------------------------------- inline const Float2 &BeamEmitter::GetHighFrequencyRangeUp () const { return mHighRangeUp; } //---------------------------------------------------------------------------- inline const Float2 &BeamEmitter::GetHighFrequencyRangeExtend () const { return mHighRangeExtend; } //----------------------------------------------------------------------------
4,721
1,132
// SPDX-License-Identifier: Apache-2.0 #include "gtest/gtest.h" #include "kompute/Kompute.hpp" #include "kompute_test/Shader.hpp" TEST(TestSpecializationConstants, TestTwoConstants) { { std::string shader(R"( #version 450 layout (constant_id = 0) const float cOne = 1; layout (constant_id = 1) const float cTwo = 1; layout (local_size_x = 1) in; layout(set = 0, binding = 0) buffer a { float pa[]; }; layout(set = 0, binding = 1) buffer b { float pb[]; }; void main() { uint index = gl_GlobalInvocationID.x; pa[index] = cOne; pb[index] = cTwo; })"); std::vector<uint32_t> spirv = compileSource(shader); std::shared_ptr<kp::Sequence> sq = nullptr; { kp::Manager mgr; std::shared_ptr<kp::TensorT<float>> tensorA = mgr.tensor({ 0, 0, 0 }); std::shared_ptr<kp::TensorT<float>> tensorB = mgr.tensor({ 0, 0, 0 }); std::vector<std::shared_ptr<kp::Tensor>> params = { tensorA, tensorB }; std::vector<float> spec = std::vector<float>({ 5.0, 0.3 }); std::shared_ptr<kp::Algorithm> algo = mgr.algorithm(params, spirv, {}, spec); sq = mgr.sequence() ->record<kp::OpTensorSyncDevice>(params) ->record<kp::OpAlgoDispatch>(algo) ->record<kp::OpTensorSyncLocal>(params) ->eval(); EXPECT_EQ(tensorA->vector(), std::vector<float>({ 5, 5, 5 })); EXPECT_EQ(tensorB->vector(), std::vector<float>({ 0.3, 0.3, 0.3 })); } } } TEST(TestSpecializationConstants, TestConstantsInt) { { std::string shader(R"( #version 450 layout (constant_id = 0) const int cOne = 1; layout (constant_id = 1) const int cTwo = 1; layout (local_size_x = 1) in; layout(set = 0, binding = 0) buffer a { int pa[]; }; layout(set = 0, binding = 1) buffer b { int pb[]; }; void main() { uint index = gl_GlobalInvocationID.x; pa[index] = cOne; pb[index] = cTwo; })"); std::vector<uint32_t> spirv = compileSource(shader); std::shared_ptr<kp::Sequence> sq = nullptr; { kp::Manager mgr; std::shared_ptr<kp::TensorT<int32_t>> tensorA = mgr.tensorT<int32_t>({ 0, 0, 0 }); std::shared_ptr<kp::TensorT<int32_t>> tensorB = mgr.tensorT<int32_t>({ 0, 0, 0 }); std::vector<std::shared_ptr<kp::Tensor>> params = { tensorA, tensorB }; std::vector<int32_t> spec({ -1, -2 }); std::shared_ptr<kp::Algorithm> algo = mgr.algorithm(params, spirv, {}, spec, {}); sq = mgr.sequence() ->record<kp::OpTensorSyncDevice>(params) ->record<kp::OpAlgoDispatch>(algo) ->record<kp::OpTensorSyncLocal>(params) ->eval(); EXPECT_EQ(tensorA->vector(), std::vector<int32_t>({ -1, -1, -1 })); EXPECT_EQ(tensorB->vector(), std::vector<int32_t>({ -2, -2, -2 })); } } }
3,420
1,166
#pragma once // libJSON lib #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4100) // unreferenced formal parameter. #pragma warning(disable : 4127) // conditional expression is constant. #endif #include "libjson_7.6.1/libjson.h" #ifdef _MSC_VER #pragma warning(pop) #endif #include <string> #include <stack> #include "IJSONReader.hpp" namespace ke { /** \class JSONReader A IJSONReader implementation which itself wraps around libjson. */ class JSONReader : public IJSONReader { public: using JSONResourceType = JSONNode; using ArrayType = JSONResourceType; using NodeType = JSONResourceType; /** \class tree_record A record of a parent JSON member & child JSON member relationship. */ struct tree_record { const JSONResourceType & parent_member; JSONNode::const_iterator iterator; tree_record(const JSONResourceType & p_rParentNode, JSONNode::const_iterator p_It) : parent_member(p_rParentNode), iterator(p_It) {}; tree_record(const tree_record & p_rRecord) : tree_record(p_rRecord.parent_member, p_rRecord.iterator) {}; JSONReader & operator = (const tree_record & p_rRecord) = delete; }; // tree_record struct private: bool m_Loaded = false; // loaded json code. JSONResourceType m_Node; bool m_AtRoot = true; std::stack<tree_record> m_TreeITStack; public: // omit ctor & dtor declaration because default versions will work. /** load & parse json file at path. @return false if failure. */ virtual bool load(const std::string & p_rPath) final; /** load string with json code int it. @return false if failure. */ virtual bool parse(const std::string & p_rJSONDoc) final; /** @return a string dump of all the contents from the json doc.*/ virtual std::string dumpToString(void) final; /** @return true if current pointered to member value is a string. */ virtual bool isTypeString(void) final; /** @return true if current pointered to member value is a number. */ virtual bool isTypeNumber(void) final; /** @return true if current pointered to member value is a boolean. */ virtual bool isTypeBoolean(void) final; /** @return true if current pointered to member value is an array. */ virtual bool isTypeArray(void) final; /** @return true if current pointered to member value is a JSON node. */ virtual bool isTypeNode(void) final; /** @return true if current pointered to member value is null/blank. */ virtual bool isTypeNull(void) final; /** @return the number of child elements the current element has. */ virtual SizeType getChildrenCount(void) const final; /** @return true if the current pointed to element has any children elements. */ virtual bool hasChildren(void) const final; /** @return current pointed to json node as a string. */ virtual StringType getValueAsString(void) const final; /** @return current pointed to json node as a number. */ virtual NumberType getValueAsNumber(void) const final; /** @return current pointed to json node as an integer. */ virtual IntegerType getValueAsInt(void) const final; /** @return current pointed to json node as a double. */ virtual FloatType getValueAsDouble(void) const final; /** @return current pointed to json node as a boolean. */ virtual BooleanType getValueAsBoolean(void) const final; /** @return true if cursor is point to the root object. */ virtual bool atRoot(void) const final; /** point cursor to the first Member/child of this member. @return true if this member contains multiple members or the value is an non-empty array. */ virtual bool traverseThisMember(void) final; /** point cursor to the parent member's next child member from this member if the parent is an array or member. @return false if there's no more. */ virtual bool pointToNextMember(void) final; /** point cursor to the parent member's previous child member from this member if the parent is an array or member. @return false if there's no more. */ virtual bool pointToPreviousMember(void) final; /** point cursor to the parent node of the currently pointed to json member. @return false if current pointed to node is the parent. */ virtual bool pointToParentMember(void) final; /** find the child element with the specified key name, and point the cursor to it. @return true if found.*/ virtual bool pointToChildElement(const std::string p_NameKey) final; /** @return name of the current element. */ virtual StringType getElementName(void) const final; }; // JSONReader class } // KE ns
4,859
1,284
// // Created by Jakub Gert on 20/06/2020. // #include <QObject> #include <QTest> #include "tests/TestSuite.h" #include "ResponseMessageParser.h" class ResponseMessageParserTests : public TestSuite { Q_OBJECT private slots: void testInvalid() { ResponseMessageParser parser; auto result = parser.parse("o"); QCOMPARE(result, false); result = parser.parse("error"); QCOMPARE(result, false); result = parser.parse("error:"); QCOMPARE(result, false); result = parser.parse("error:a"); QCOMPARE(result, false); } void testValid() { ResponseMessageParser parser; auto result = parser.parse("ok"); QCOMPARE(result, true); QCOMPARE(parser.getError(), 0); result = parser.parse("error:0"); QCOMPARE(result, true); QCOMPARE(parser.getError(), 0); } }; static ResponseMessageParserTests T_ResponseMessageParserTests; #include "ResponseMessageParser.test.moc"
1,005
322
#pragma once #include <math.h> #include <napi.h> #include <webp/encode.h> #include "format.hpp" #include "image.hpp" namespace nodeWebp { class Encoder : public Napi::AsyncWorker { private: uint8_t* buffer = nullptr; Napi::Promise::Deferred promise; float_t quality = 0; uint64_t size = 0; Image* image = nullptr; public: Encoder( Napi::Env environment, Napi::Object source, float_t quality ); ~Encoder() override; void Execute() override; void OnError(const Napi::Error& error) override; void OnOK() override; Napi::Promise getPromise(); }; }
619
273
/* Copyright (c) 2008, 2021, Oracle and/or its affiliates. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License, version 2.0, for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ /** @file storage/perfschema/table_file_summary_by_event_name.cc Table FILE_SUMMARY_BY_EVENT_NAME(implementation). */ #include "my_global.h" #include "my_thread.h" #include "pfs_instr_class.h" #include "pfs_column_types.h" #include "pfs_column_values.h" #include "table_file_summary_by_event_name.h" #include "pfs_global.h" #include "pfs_visitor.h" #include "field.h" THR_LOCK table_file_summary_by_event_name::m_table_lock; PFS_engine_table_share table_file_summary_by_event_name::m_share= { { C_STRING_WITH_LEN("file_summary_by_event_name") }, &pfs_truncatable_acl, table_file_summary_by_event_name::create, NULL, /* write_row */ table_file_summary_by_event_name::delete_all_rows, table_file_summary_by_event_name::get_row_count, sizeof(PFS_simple_index), &m_table_lock, { C_STRING_WITH_LEN("CREATE TABLE file_summary_by_event_name(" "EVENT_NAME VARCHAR(128) not null comment 'Event name.'," "COUNT_STAR BIGINT unsigned not null comment 'Number of summarized events'," "SUM_TIMER_WAIT BIGINT unsigned not null comment 'Total wait time of the summarized events that are timed.'," "MIN_TIMER_WAIT BIGINT unsigned not null comment 'Minimum wait time of the summarized events that are timed.'," "AVG_TIMER_WAIT BIGINT unsigned not null comment 'Average wait time of the summarized events that are timed.'," "MAX_TIMER_WAIT BIGINT unsigned not null comment 'Maximum wait time of the summarized events that are timed.'," "COUNT_READ BIGINT unsigned not null comment 'Number of all read operations, including FGETS, FGETC, FREAD, and READ.'," "SUM_TIMER_READ BIGINT unsigned not null comment 'Total wait time of all read operations that are timed.'," "MIN_TIMER_READ BIGINT unsigned not null comment 'Minimum wait time of all read operations that are timed.'," "AVG_TIMER_READ BIGINT unsigned not null comment 'Average wait time of all read operations that are timed.'," "MAX_TIMER_READ BIGINT unsigned not null comment 'Maximum wait time of all read operations that are timed.'," "SUM_NUMBER_OF_BYTES_READ BIGINT not null comment 'Bytes read by read operations.'," "COUNT_WRITE BIGINT unsigned not null comment 'Number of all write operations, including FPUTS, FPUTC, FPRINTF, VFPRINTF, FWRITE, and PWRITE.'," "SUM_TIMER_WRITE BIGINT unsigned not null comment 'Total wait time of all write operations that are timed.'," "MIN_TIMER_WRITE BIGINT unsigned not null comment 'Minimum wait time of all write operations that are timed.'," "AVG_TIMER_WRITE BIGINT unsigned not null comment 'Average wait time of all write operations that are timed.'," "MAX_TIMER_WRITE BIGINT unsigned not null comment 'Maximum wait time of all write operations that are timed.'," "SUM_NUMBER_OF_BYTES_WRITE BIGINT not null comment 'Bytes written by write operations.'," "COUNT_MISC BIGINT unsigned not null comment 'Number of all miscellaneous operations not counted above, including CREATE, DELETE, OPEN, CLOSE, STREAM_OPEN, STREAM_CLOSE, SEEK, TELL, FLUSH, STAT, FSTAT, CHSIZE, RENAME, and SYNC.'," "SUM_TIMER_MISC BIGINT unsigned not null comment 'Total wait time of all miscellaneous operations that are timed.'," "MIN_TIMER_MISC BIGINT unsigned not null comment 'Minimum wait time of all miscellaneous operations that are timed.'," "AVG_TIMER_MISC BIGINT unsigned not null comment 'Average wait time of all miscellaneous operations that are timed.'," "MAX_TIMER_MISC BIGINT unsigned not null comment 'Maximum wait time of all miscellaneous operations that are timed.')") }, false /* perpetual */ }; PFS_engine_table* table_file_summary_by_event_name::create(void) { return new table_file_summary_by_event_name(); } int table_file_summary_by_event_name::delete_all_rows(void) { reset_file_instance_io(); reset_file_class_io(); return 0; } ha_rows table_file_summary_by_event_name::get_row_count(void) { return file_class_max; } table_file_summary_by_event_name::table_file_summary_by_event_name() : PFS_engine_table(&m_share, &m_pos), m_pos(1), m_next_pos(1) {} void table_file_summary_by_event_name::reset_position(void) { m_pos.m_index= 1; m_next_pos.m_index= 1; } int table_file_summary_by_event_name::rnd_next(void) { PFS_file_class *file_class; m_pos.set_at(&m_next_pos); file_class= find_file_class(m_pos.m_index); if (file_class) { make_row(file_class); m_next_pos.set_after(&m_pos); return 0; } return HA_ERR_END_OF_FILE; } int table_file_summary_by_event_name::rnd_pos(const void *pos) { PFS_file_class *file_class; set_position(pos); file_class= find_file_class(m_pos.m_index); if (file_class) { make_row(file_class); return 0; } return HA_ERR_RECORD_DELETED; } /** Build a row. @param file_class the file class the cursor is reading */ void table_file_summary_by_event_name::make_row(PFS_file_class *file_class) { m_row.m_event_name.make_row(file_class); PFS_instance_file_io_stat_visitor visitor; PFS_instance_iterator::visit_file_instances(file_class, &visitor); time_normalizer *normalizer= time_normalizer::get(wait_timer); /* Collect timer and byte count stats */ m_row.m_io_stat.set(normalizer, &visitor.m_file_io_stat); m_row_exists= true; } int table_file_summary_by_event_name::read_row_values(TABLE *table, unsigned char *, Field **fields, bool read_all) { Field *f; if (unlikely(!m_row_exists)) return HA_ERR_RECORD_DELETED; /* Set the null bits */ assert(table->s->null_bytes == 0); for (; (f= *fields) ; fields++) { if (read_all || bitmap_is_set(table->read_set, f->field_index)) { switch(f->field_index) { case 0: /* EVENT_NAME */ m_row.m_event_name.set_field(f); break; case 1: /* COUNT_STAR */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_count); break; case 2: /* SUM_TIMER_WAIT */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_sum); break; case 3: /* MIN_TIMER_WAIT */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_min); break; case 4: /* AVG_TIMER_WAIT */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_avg); break; case 5: /* MAX_TIMER_WAIT */ set_field_ulonglong(f, m_row.m_io_stat.m_all.m_waits.m_max); break; case 6: /* COUNT_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_count); break; case 7: /* SUM_TIMER_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_sum); break; case 8: /* MIN_TIMER_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_min); break; case 9: /* AVG_TIMER_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_avg); break; case 10: /* MAX_TIMER_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_waits.m_max); break; case 11: /* SUM_NUMBER_OF_BYTES_READ */ set_field_ulonglong(f, m_row.m_io_stat.m_read.m_bytes); break; case 12: /* COUNT_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_count); break; case 13: /* SUM_TIMER_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_sum); break; case 14: /* MIN_TIMER_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_min); break; case 15: /* AVG_TIMER_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_avg); break; case 16: /* MAX_TIMER_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_waits.m_max); break; case 17: /* SUM_NUMBER_OF_BYTES_WRITE */ set_field_ulonglong(f, m_row.m_io_stat.m_write.m_bytes); break; case 18: /* COUNT_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_count); break; case 19: /* SUM_TIMER_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_sum); break; case 20: /* MIN_TIMER_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_min); break; case 21: /* AVG_TIMER_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_avg); break; case 22: /* MAX_TIMER_MISC */ set_field_ulonglong(f, m_row.m_io_stat.m_misc.m_waits.m_max); break; default: assert(false); break; } } // if } // for return 0; }
10,245
3,697
//$Id: TDRSSTwoWayRange.hpp 1398 2011-04-21 20:39:37Z $ //------------------------------------------------------------------------------ // TDRSSTwoWayRange //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under FDSS Task 28 // // Author: Darrel J. Conway, Thinking Systems, Inc. // Created: 2010/05/10 // /** * The TDRSS 2-way range core measurement model. */ //------------------------------------------------------------------------------ #ifndef TDRSSTwoWayRange_hpp #define TDRSSTwoWayRange_hpp #include "estimation_defs.hpp" #include "TwoWayRange.hpp" /** * TDRSS 2-Way Range Measurement Model */ class ESTIMATION_API TDRSSTwoWayRange: public TwoWayRange { public: TDRSSTwoWayRange(const std::string nomme = ""); virtual ~TDRSSTwoWayRange(); TDRSSTwoWayRange(const TDRSSTwoWayRange& usn); TDRSSTwoWayRange& operator=(const TDRSSTwoWayRange& usn); virtual GmatBase* Clone() const; bool SetRefObject(GmatBase *obj, const Gmat::ObjectType type, const std::string &name); bool SetRefObject(GmatBase *obj, const Gmat::ObjectType type, const std::string &name, const Integer index); virtual bool Initialize(); virtual const std::vector<RealArray>& CalculateMeasurementDerivatives( GmatBase *obj, Integer id); virtual Event* GetEvent(UnsignedInt whichOne); virtual bool SetEventData(Event *locatedEvent); protected: /// Turnaround time at the TDRSS (aka transponder delay) on way to the s/c Real tdrssUplinkDelay; /// Turnaround time at the TDRSS (aka transponder delay) on way to the ground Real tdrssDownlinkDelay; /// Light transit time for the forward link Real forwardlinkTime; /// Light transit time for the return link Real backlinkTime; /// The event used to model the uplink LightTimeCorrection forwardlinkLeg; /// The event used to model the downlink LightTimeCorrection backlinkLeg; /// The distance covered during the uplink Real forwardlinkRange; /// The distance covered during the downlink Real backlinkRange; virtual bool Evaluate(bool withEvents = false); void SetHardwareDelays(bool loadEvents); virtual void InitializeMeasurement(); }; #endif /* TDRSSTwoWayRange_hpp */
3,252
968
// // group.cc: // #include <stdio.h> #include <stdlib.h> #include <math.h> #include <limits.h> #include <X11/Xlib.h> #include <local_types.h> #include <list.h> #include <eedefs.h> #include <shape.h> #include <shapeset.h> #include <frame.h> #include <xcontext.h> #include <board.h> #include <group.h> #include <misc.h> #include <geometry.h> #include <xfig.h> // // コンストラクタ // Group::Group( Board* board ): Shape( board ) { shape_type = ST_GROUP; _x = _y = _w = _h = 0; } // // コピーコンストラクタ // Group::Group( Group* group ): Shape( group ) { _x = group->_x, _y = group->_y; _w = group->_w, _h = group->_h; for( int i = 0 ; i < group->shape_slot.count() ; i++ ) shape_slot.append( group->shape_slot.get(i)->duplicate() ); } // // draw(): // void Group::draw( Window window, int x, int y ) { Display* dpy = board->xcontext->get_dpy(); GC gc = board->gc; int save_gp_draw_f = board->grip_disp; board->grip_disp = False; for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->draw( window, ROUND(_x)+x, ROUND(_y)+y ); board->grip_disp = save_gp_draw_f; int left = ROUND(_x) + x - 3; int right = ROUND(_x) + ROUND(_w) + x - 3; int up = ROUND(_y) + y - 3; int down = ROUND(_y) + ROUND(_h) + y - 3; XDrawRectangle( dpy, window, gc, left, up, 5, 5 ); XDrawRectangle( dpy, window, gc, right, up, 5, 5 ); XDrawRectangle( dpy, window, gc, left, down, 5, 5 ); XDrawRectangle( dpy, window, gc, right, down, 5, 5 ); } // // hit(): // Boolean Group::hit( int x, int y, int hw ) { int left = ROUND(_x); int right = ROUND(_x) + ROUND(_w); int up = ROUND(_y); int down = ROUND(_y) + ROUND(_h); if( contain_chk( left, up, x, y, hw ) ) return True; if( contain_chk( right, up, x, y, hw ) ) return True; if(contain_chk( right, down, x, y, hw ) ) return True; if( contain_chk( left, down, x, y, hw ) ) return True; return False; } // // layout(): // EditResult Group::layout( XEvent* event ) { Display* dpy = event->xany.display; XSetFunction( dpy, board->gc, GXset ); XSetPlaneMask( dpy, board->gc, board->layout_mask ); static int last_x = -1, last_y; if( event->type == MotionNotify && proc_phase > 0 ){ int mx = event->xmotion.x, my = event->xmotion.y; board->quontize( mx, my ); if( last_x != mx || last_y != my ){ if( last_x >= 0 ){ XSetFunction( dpy, board->gc, GXclear ); int x1 = ROUND(_x), y1 = ROUND(_y), x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xmotion.window, board->gc, x1, y1, x2-x1, y2-y1 ); XSetFunction( dpy, board->gc, GXset ); } int x1 = ROUND(_x), y1 = ROUND(_y), x2 = mx, y2 = my; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xmotion.window, board->gc, x1, y1, x2-x1, y2-y1 ); last_x = mx, last_y = my; } XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } switch( proc_phase ){ case 0: // 一回目のクリック。 if( event->type != ButtonPress && event->xbutton.button != 1 ) return EDIT_CONTINUE; Window window = event->xbutton.window; int mx = event->xbutton.x, my = event->xbutton.y; board->quontize( mx, my ); _x = (double)mx, _y = (double)my; last_x = -1; proc_phase = 1; return EDIT_CONTINUE; break; case 1: // 二回目のクリック。 if( event->type != ButtonPress ) return EDIT_CONTINUE; window = event->xbutton.window; switch( event->xbutton.button ){ case 1: // 左ボタン矩形の確定。 mx = event->xbutton.x, my = event->xbutton.y; board->quontize( mx, my ); if( ROUND(_x) == mx && ROUND(_y) == my ){ XBell( dpy, 0 ); XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } if( last_x >= 0 ){ XSetFunction( dpy, board->gc, GXclear ); int x1 = ROUND(_x), y1 = ROUND(_y), x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xmotion.window, board->gc, x1, y1, x2-x1, y2-y1 ); XSetFunction( dpy, board->gc, GXset ); } int x1, x2, y1, y2; x1 = ROUND(_x), y1 = ROUND(_y), x2 = mx, y2 = my; normal_rect( x1, y1, x2, y2 ); _x = x1, _y = y1, _w = x2 - x1 - 1, _h = y2 - y1 - 1; for( int i = board->shapeset.count_shape()-1 ; i >= 0 ; i-- ){ Shape* shape = board->shapeset.get_shape(i); if( shape->contain( ROUND(_x), ROUND(_y), ROUND(_w), ROUND(_h) ) ){ shape_slot.append( shape->duplicate() ); XSetFunction( dpy, board->gc, GXclear ); XSetPlaneMask( dpy, board->gc, board->shape_mask ); shape->draw( event->xbutton.window, 0, 0 ); board->shapeset.unlink_shape( LIST_TOP, i, 1 ); } } if( shape_slot.count() == 0 ){ last_x = -1; proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CANCEL; } double min_x=INT_MAX, min_y=INT_MAX, max_x=INT_MIN, max_y=INT_MIN; for( i = 0 ; i < shape_slot.count() ; i++ ){ Shape* shape = shape_slot.get(i); double x, y, w, h; shape->bound( x, y, w, h ); if( x < min_x ) min_x = x; if( x+w > max_x ) max_x = x+w; if( y < min_y ) min_y = y; if( y+h > max_y ) max_y = y+h; } _x = min_x, _y = min_y, _w = max_x - min_x, _h = max_y - min_y; for( i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->translate( -_x, -_y ); XSetFunction( dpy, board->gc, GXset ); XSetPlaneMask( dpy, board->gc, board->shape_mask ); draw( window, 0, 0 ); last_x = -1; proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_COMPLETE; break; case 3: // 右ボタン(キャンセル) if( last_x >= 0 ){ XSetFunction( dpy, board->gc, GXclear ); XSetPlaneMask( dpy, board->gc, board->layout_mask ); int x1 = ROUND(_x), y1 = ROUND(_y), x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xmotion.window, board->gc, x1, y1, x2-x1, y2-y1 ); } last_x = -1; proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CANCEL; break; } break; } return EDIT_CONTINUE; } // // save(): // void Group::save( FILE* fp ) { fprintf( fp, "group{\n" ); fprintf( fp, " geom = (%g,%g,%g,%g);\n", _x, _y, _w, _h ); for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->save( fp ); fprintf( fp, "}\n" ); } // // tex(): // void Group::tex( FILE* fp, double h, double x, double y ) { for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->tex( fp, h, _x+x, _y+y ); } // // bound(): // void Group::bound( double& x, double& y, double& w, double& h ) { double min_x = INT_MAX, min_y = INT_MAX, max_x = INT_MIN, max_y = INT_MIN; for( int i = 0 ; i < shape_slot.count() ; i++ ){ Shape* shape = shape_slot.get(i); double x, y, w, h; shape->bound( x, y, w, h ); if( x < min_x ) min_x = x; if( x+w > max_x ) max_x = x+w; if( y < min_y ) min_y = y; if( y+h > max_y ) max_y = y+h; } _w = max_x - min_x, _h = max_y - min_y; x = _x, y = _y; w = _w, h = _h; } // // translate(): // void Group::translate( double x, double y ) { _x += x, _y += y; } // // duplicate(): // Shape* Group::duplicate() { return new Group( this ); } // // contain(): // Boolean Group::contain( int x, int y, int w, int h ) { if( ROUND(_x) < x || ROUND(_x+_w) >= x+w ) return False; if( ROUND(_y) < y || ROUND(_y+_h) >= y+h ) return False; return True; } // // scale(): // void Group::scale( double rx, double ry ) { _x *= rx, _y *= ry; _w *= rx, _h *= ry; for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->scale( rx, ry ); } // // リサイズ // EditResult Group::resize( XEvent* event ) { Display* dpy = event->xany.display; XSetFunction( dpy, board->gc, GXset ); XSetPlaneMask( dpy, board->gc, board->layout_mask ); static int last_x = -1, last_y; static int xx, yy; if( proc_phase == 1 && event->type == MotionNotify ){ int mx = event->xmotion.x, my = event->xmotion.y; board->quontize( mx, my ); if( last_x == mx && last_y == my ){ XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } int x1 = xx, y1 = yy, x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); if( last_x > 0 ){ XSetFunction( dpy, board->gc, GXclear ); XDrawRectangle( dpy, event->xbutton.window, board->gc, x1, y1, x2-x1-1, y2-y1-1 ); XSetFunction( dpy, board->gc, GXset ); } x1 = xx, y1 = yy, x2 = mx, y2 = my; normal_rect( x1, y1, x2, y2 ); XDrawRectangle( dpy, event->xbutton.window, board->gc, x1, y1, x2-x1-1, y2-y1-1 ); last_x = mx, last_y = my; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } switch( proc_phase ){ case 0: int mx = event->xbutton.x, my = event->xbutton.y; board->quontize( mx, my ); xx = ROUND(_x), yy = ROUND(_y+_h)-1; if( contain_chk( ROUND(_x+_w)-1, ROUND(_y+_h)-1, mx, my, 4 ) ) xx = ROUND(_x), yy = ROUND(_y); if( contain_chk( ROUND(_x), ROUND(_y+_h)-1, mx, my, 4 ) ) xx = ROUND(_x+_w)-1, yy = ROUND(_y); if( contain_chk( ROUND(_x), ROUND(_y), mx, my, 4 ) ) xx = ROUND(_x+_w)-1, yy = ROUND(_y+_h)-1; last_x = -1; proc_phase = 1; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; break; case 1: if( event->type != ButtonPress ){ XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } mx = event->xbutton.x, my = event->xbutton.y; board->quontize( mx, my ); switch( event->xbutton.button ){ case 1: // 左ボタン(決定) if( last_x < 0 || ( xx == last_x && yy == last_y ) ){ XBell( dpy, 0 ); XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CONTINUE; } int x1 = xx, y1 = yy, x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XSetFunction( dpy, board->gc, GXclear ); XDrawRectangle( dpy, event->xbutton.window, board->gc, x1, y1, x2-x1-1, y2-y1-1 ); XSetPlaneMask( dpy, board->gc, board->shape_mask ); draw( event->xbutton.window, 0, 0 ); scale( (double)(x2-x1-1)/_w, (double)(y2-y1-1)/_h ); _x = (double)x1, _y = (double)y1; XSetFunction( dpy, board->gc, GXset ); draw( event->xbutton.window, 0, 0 ); proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_COMPLETE; break; case 3: // 右ボタン(キャンセル) if( last_x > 0 ){ XSetFunction( dpy, board->gc, GXxor ); x1 = xx, y1 = yy, x2 = last_x, y2 = last_y; normal_rect( x1, y1, x2, y2 ); XSetFunction( dpy, board->gc, GXclear ); XDrawRectangle( dpy, event->xbutton.window, board->gc, x1, y1, x2-x1-1, y2-y1-1 ); } proc_phase = 0; XSetFunction( dpy, board->gc, GXcopy ); XSetPlaneMask( dpy, board->gc, ~0 ); return EDIT_CANCEL; break; } } return EDIT_CONTINUE; } // // reversx(): // void Group::reversx() { double bx, by, bw, bh; bound( bx, by, bw, bh ); for( int i = 0 ; i < shape_slot.count() ; i++ ){ double sx, sy, sw, sh; Shape* shape = shape_slot.get(i); shape->bound( sx, sy, sw, sh ); shape->translate( -sx, 0 ); shape->translate( bw, 0 ); shape->translate( -(sx+sw), 0 ); shape->reversx(); } } // // reversy(): // void Group::reversy() { double bx, by, bw, bh; bound( bx, by, bw, bh ); for( int i = 0 ; i < shape_slot.count() ; i++ ){ double sx, sy, sw, sh; Shape* shape = shape_slot.get(i); shape->bound( sx, sy, sw, sh ); shape->translate( 0, -sy ); shape->translate( 0, bh ); shape->translate( 0, -(sy+sh) ); shape->reversy(); } } // // update(): // void Group::update() { for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->update(); double x, y, w, h; bound( x, y, w, h ); _w = w, _h = h; } // // xfig(): // void Group::xfig( FILE* fp, double x, double y ) { fprintf( fp, "%d %d %d %d %d\n", O_COMPOUND, ROUND(XFS(_x+x)), ROUND(XFS(_y+y)), ROUND(XFS(_x+_w+x)), ROUND(XFS(_y+_h+y)) ); for( int i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->xfig( fp, _x+x, _y+y ); fprintf( fp, "%d\n", O_END_COMPOUND ); } // // ungroup(): // void Group::ungroup( Window window ) { XSetPlaneMask( board->xcontext->get_dpy(), board->gc, board->shape_mask ); XSetFunction( board->xcontext->get_dpy(), board->gc, GXclear ); draw( window, 0, 0 ); XSetFunction( board->xcontext->get_dpy(), board->gc, GXset ); for( int j = 0 ; j < shape_slot.count() ; j++ ){ Shape* dup_shape = shape_slot.get(j)->duplicate(); dup_shape->translate( _x, _y ); dup_shape->draw( window, 0, 0 ); board->shapeset.append_shape( dup_shape ); } XSetFunction( board->xcontext->get_dpy(), board->gc, GXcopy ); XSetPlaneMask( board->xcontext->get_dpy(), board->gc, ~0 ); } // // rotate(): // void Group::rotate( XEvent* event ) { for( int i = 0 ; i < shape_slot.count() ; i++ ){ Shape* shape = shape_slot.get(i); shape->translate( _x, _y ); shape->rotate( event ); shape->translate( -_x, -_y ); } double min_x = INT_MAX, min_y = INT_MAX, max_x = INT_MIN, max_y = INT_MIN; for( i = 0 ; i < shape_slot.count() ; i++ ){ Shape* shape = shape_slot.get(i); double x, y, w, h; shape->bound( x, y, w, h ); if( x < min_x ) min_x = x; if( x+w > max_x ) max_x = x+w; if( y < min_y ) min_y = y; if( y+h > max_y ) max_y = y+h; } _x += min_x, _y += min_y; _w = max_x-min_x, _h = max_y-min_y; if( min_x != 0 || min_y != 0 ) for( i = 0 ; i < shape_slot.count() ; i++ ) shape_slot.get(i)->translate( -min_x, -min_y ); }
14,017
6,342
#include <iostream> #include <thread> #include "elemental.hpp" #include "sparse_matrix.hpp" #include "matrix_generator.hpp" #include "delimited_file.hpp" #include "index_set.hpp" #include "random.hpp" #include "timer.hpp" using std::cout; using std::cerr; using std::endl; // For the NMF formulation A~WH, we need the products AH' and W'A. bool SimpleTest(Random& rng); bool TestSparseGemmIndexedABt_Rank2 (Random& rng); bool TestSparseGemmIndexedBtA_Rank2 (Random& rng); namespace GemmIndexedTest { const unsigned int NUM_RUNS = 64; const double MAX_ACCEPTABLE_FNORM = 1.0e-10; const unsigned int MAX_DIM = 8192; } //----------------------------------------------------------------------------- bool TestSparseGemmIndexed() { Random rng; rng.SeedFromTime(); bool result0 = SimpleTest(rng); //bool result1 = TestSparseGemmIndexedAB(rng); bool result2 = TestSparseGemmIndexedABt_Rank2(rng); //bool result3 = TestSparseGemmIndexedBA(rng); bool result4 = TestSparseGemmIndexedBtA_Rank2(rng); return (result0 && result2 && result4); } //----------------------------------------------------------------------------- bool SimpleTest(Random& rng) { cout << "Running SimpleTest..."; cout.flush(); // A = 1 0 0 0 H = 1 2 3 4 == W' // 0 2 0 0 5 6 7 8 // 0 0 3 0 // 1 2 3 4 SparseMatrix<double> A(4, 4, 7); A.BeginLoad(); A.Load(0, 0, 1.0); A.Load(3, 0, 1.0); A.Load(1, 1, 2.0); A.Load(3, 1, 2.0); A.Load(2, 2, 3.0); A.Load(3, 2, 3.0); A.Load(3, 3, 4.0); A.EndLoad(); elem::Matrix<double> H(2, 4); H.Set(0, 0, 1.0); H.Set(0, 1, 2.0); H.Set(0, 2, 3.0); H.Set(0, 3, 4.0); H.Set(1, 0, 5.0); H.Set(1, 1, 6.0); H.Set(1, 2, 7.0); H.Set(1, 3, 8.0); elem::Matrix<double> W(4, 2); W.Set(0, 0, 1.0); W.Set(0, 1, 5.0); W.Set(1, 0, 2.0); W.Set(1, 1, 6.0); W.Set(2, 0, 3.0); W.Set(2, 1, 7.0); W.Set(3, 0, 4.0); W.Set(3, 1, 8.0); elem::Matrix<double> C1(2, 2), C2(2, 2); std::vector<unsigned int> col_indices = {1, 3}; std::vector<unsigned int> old_to_new_rows = {0xFFFFFFFF, 0, 0xFFFFFFFF, 1}; std::vector<unsigned int> new_to_old_rows = {1, 3}; unsigned int max_threads = 1; elem::Matrix<double> Hsubset(2, 2); Hsubset.Set(0, 0, H.Get(0, col_indices[0])); Hsubset.Set(0, 1, H.Get(0, col_indices[1])); Hsubset.Set(1, 0, H.Get(1, col_indices[0])); Hsubset.Set(1, 1, H.Get(1, col_indices[1])); //cout << "\nHsubset: " << endl; //elem::Print(Hsubset); elem::Matrix<double> Wsubset(2, 2); Wsubset.Set(0, 0, W.Get(new_to_old_rows[0], 0)); Wsubset.Set(0, 1, W.Get(new_to_old_rows[0], 1)); Wsubset.Set(1, 0, W.Get(new_to_old_rows[1], 0)); Wsubset.Set(1, 1, W.Get(new_to_old_rows[1], 1)); //cout << "\nWsubset: " << endl; //elem::Print(Wsubset); // compute the product C1 = AHsubset' = 4 12 // 20 44 GemmIndexed(NORMAL, TRANSPOSE, 1.0, A, Hsubset, 0.0, C1, max_threads, new_to_old_rows.size(), old_to_new_rows, col_indices); //cout << "\nC1: " << endl; //elem::Print(C1); bool ok1 = (4.0 == C1.Get(0, 0)) && (12.0 == C1.Get(0, 1)) && (20.0 == C1.Get(1, 0)) && (44.0 == C1.Get(1, 1)); // compute the product C2 = Wsubset'A = 5 12 // 13 24 GemmIndexed(TRANSPOSE, NORMAL, 1.0, Wsubset, A, 0.0, C2, max_threads, new_to_old_rows.size(), old_to_new_rows, col_indices); //cout << "\nC2: " << endl; //elem::Print(C2); bool ok2 = (12.0 == C2.Get(0, 0)) && (16.0 == C2.Get(0, 1)) && (28.0 == C2.Get(1, 0)) && (32.0 == C2.Get(1, 1)); cout << ( (ok1 && ok2) ? "passed." : "failed.") << endl; return (ok1 && ok2); } //----------------------------------------------------------------------------- bool TestSparseGemmIndexedABt_Rank2(Random& rng) { // C = alpha*A*B' + beta*C // // Matrix A is sparse and is mxn, but use s cols from col index set S. // Matrix B has 2 rows; matrix C has 2 cols. Timer timer; unsigned int max_threads = 2; SparseMatrix<double> A, Asubset; elem::Matrix<double> B, Bsubset, C1, C2, C1subset, C2subset; double min_sparsity = 1.0, max_sparsity = 0.0; double max_norm = 0.0, elapsed_subset = 0.0, elapsed_indexed = 0.0; cout << "Running indexed GEMM rank2 AB' test..." << endl; for (unsigned int i=0; i<GemmIndexedTest::NUM_RUNS; ++i) { unsigned int height_a = rng.RandomRangeInt(512, GemmIndexedTest::MAX_DIM); unsigned int width_a = rng.RandomRangeInt(512, GemmIndexedTest::MAX_DIM); // sparse_fraction ranges from (0.1 - 0.09, 0.1 + 0.09) double sparse_fraction = rng.RandomDouble(0.1, 0.09); unsigned int nonzeros_per_col = sparse_fraction * height_a; if (0 == nonzeros_per_col) nonzeros_per_col = 1; if (sparse_fraction < min_sparsity) min_sparsity = sparse_fraction; if (sparse_fraction > max_sparsity) max_sparsity = sparse_fraction; // generate a random alpha and beta on [-1, 1] double alpha = rng.RandomDouble(0.0, 1.0); double beta = rng.RandomDouble(0.0, 1.0); RandomSparseMatrix(A, nonzeros_per_col, rng, height_a, width_a); // set the dimensions of B and randomly initialize B.ResizeTo(2, width_a); RandomMatrix(B, rng); // set the dimensions of C1 and C2 and randomly initialize C1.ResizeTo(height_a, 2); RandomMatrix(C1, rng); C2 = C1; // generate a random set of column indices of A size_t index_set_size = rng.RandomRangeInt(1, width_a/2); std::vector<unsigned int> col_indices(index_set_size); RandomIndexSet(rng, width_a, index_set_size, col_indices); // compute the height of the most compact submatrix of A std::vector<unsigned int> old_to_new_rows, new_to_old_rows; A.SubMatrixRowsCompact(col_indices, old_to_new_rows, new_to_old_rows); unsigned int new_height = new_to_old_rows.size(); // resize Bsubset and Csubset to match Bsubset.ResizeTo(2, index_set_size); C1subset.ResizeTo(new_height, 2); C2subset = C1subset; // extract Bsubset from B (cols of B from index set) for (unsigned int c=0; c<index_set_size; ++c) { for (int r=0; r<Bsubset.Height(); ++r) { double val = B.Get(r, col_indices[c]); Bsubset.Set(r, c, val); } } old_to_new_rows.clear(); new_to_old_rows.clear(); timer.Start(); // extract a compact submatrix of A using the columns in col_indices A.SubMatrixColsCompact(Asubset, col_indices, old_to_new_rows, new_to_old_rows); assert(Asubset.Height() == new_height); // perform sparse Gemm on the subset Gemm(NORMAL, TRANSPOSE, alpha, Asubset, Bsubset, beta, C1subset, max_threads); timer.Stop(); elapsed_subset += timer.ReportMicroseconds(); timer.Start(); // perform indexed Gemm on the original matrix GemmIndexed(NORMAL, TRANSPOSE, alpha, A, Bsubset, beta, C2subset, max_threads, new_height, old_to_new_rows, col_indices); timer.Stop(); elapsed_indexed += timer.ReportMicroseconds(); // check residuals // C2 = -C1 + C2 elem::Axpy(-1.0, C1subset, C2subset); double fnorm = elem::Norm(C2subset, elem::FROBENIUS_NORM); cout << "\t[" << (i+1) << "/" << GemmIndexedTest::NUM_RUNS << "]: fnorm of residual: " << fnorm << endl; if (fnorm > max_norm) max_norm = fnorm; if (max_norm > GemmIndexedTest::MAX_ACCEPTABLE_FNORM) { cerr << "*** ERROR ***" << endl; //WriteDelimitedFile(D.LockedBuffer(), D.LDim(), D.Height(), D.Width(), "Derror.csv", 6); //WriteDelimitedFile(B.LockedBuffer(), B.LDim(), B.Height(), B.Width(), "Berror.csv", 6); break; } } // compute average runtimes per loop double t_copying = elapsed_subset * 0.001 / GemmIndexedTest::NUM_RUNS; double t_indexed = elapsed_indexed * 0.001 / GemmIndexedTest::NUM_RUNS; cout << endl; cout << "\t**** Results for Rank2 Indexed Sparse Gemm AB' Test ****" << endl; cout << endl; cout << "\t\t" << GemmIndexedTest::NUM_RUNS << " runs " << endl; cout << "\t\tMax residual Frobenius norm: " << max_norm << endl; cout << "\t\tElapsed time with data copying:\t" << t_copying << " ms." << endl; cout << "\t\tElapsed time with indexing:\t" << t_indexed << " ms." << endl; cout << endl; cout << "\t********************************************************" << endl; cout << endl; return (max_norm < GemmIndexedTest::MAX_ACCEPTABLE_FNORM); } //----------------------------------------------------------------------------- bool TestSparseGemmIndexedBtA_Rank2(Random& rng) { // C = alpha*B'*A + beta*C // // Matrix A is sparse and is mxn, but use s cols from col index set S. // Matrix B has 2 cols; matrix C has 2 rows. Timer timer; unsigned int hw_max_threads = std::thread::hardware_concurrency(); SparseMatrix<double> A, Asubset; elem::Matrix<double> B, Bsubset, C1, C2, C1subset, C2subset, D; // this variant of indexed gemm requires beta == 0 double beta = 0.0; double min_sparsity = 1.0, max_sparsity = 0.0; double max_norm = 0.0, elapsed_subset = 0.0, elapsed_indexed = 0.0; cout << "Running indexed GEMM rank2 B'A test..." << endl; for (unsigned int i=0; i<GemmIndexedTest::NUM_RUNS; ++i) { unsigned int height_a = rng.RandomRangeInt(512, GemmIndexedTest::MAX_DIM); unsigned int width_a = rng.RandomRangeInt(512, GemmIndexedTest::MAX_DIM); unsigned int max_threads = 1 + (rng.RandomInt() % hw_max_threads); // sparse_fraction ranges from (0.1 - 0.09, 0.1 + 0.09) double sparse_fraction = rng.RandomDouble(0.1, 0.09); unsigned int nonzeros_per_col = sparse_fraction * height_a; if (0 == nonzeros_per_col) nonzeros_per_col = 1; if (sparse_fraction < min_sparsity) min_sparsity = sparse_fraction; if (sparse_fraction > max_sparsity) max_sparsity = sparse_fraction; // generate a random alpha on [-1, 1] double alpha = rng.RandomDouble(0.0, 1.0); RandomSparseMatrix(A, nonzeros_per_col, rng, height_a, width_a); // set the dimensions of B and randomly initialize B.ResizeTo(height_a, 2); RandomMatrix(B, rng); // set the dimensions of C1 and C2 and randomly initialize C1.ResizeTo(2, width_a); RandomMatrix(C1, rng); C2 = C1; // generate a random set of column indices of A size_t index_set_size = rng.RandomRangeInt(1, width_a/2); // force rank2 some of the time if (0 == (i % 3)) index_set_size = 2; std::vector<unsigned int> col_indices(index_set_size); RandomIndexSet(rng, width_a, index_set_size, col_indices); // compute the height of the most compact submatrix of A std::vector<unsigned int> old_to_new_rows, new_to_old_rows; A.SubMatrixRowsCompact(col_indices, old_to_new_rows, new_to_old_rows); unsigned int new_height = new_to_old_rows.size(); // resize Bsubset and Csubset to match Bsubset.ResizeTo(new_height, 2); C1subset.ResizeTo(2, index_set_size); C2subset = C1subset; // extract B subset from B for (int c=0; c != Bsubset.Width(); ++c) { for (int r=0; r != Bsubset.Height(); ++r) { double val = B.Get(new_to_old_rows[r], c); Bsubset.Set(r, c, val); } } old_to_new_rows.clear(); new_to_old_rows.clear(); timer.Start(); // extract a submatrix of A using the columns in col_indices A.SubMatrixColsCompact(Asubset, col_indices, old_to_new_rows, new_to_old_rows); assert(Asubset.Height() == new_height); // perform sparse Gemm on the subset Gemm(TRANSPOSE, NORMAL, alpha, Bsubset, Asubset, beta, C1subset, max_threads); timer.Stop(); elapsed_subset += timer.ReportMicroseconds(); timer.Start(); // perform indexed Gemm GemmIndexed(TRANSPOSE, NORMAL, alpha, Bsubset, A, beta, C2subset, max_threads, new_height, old_to_new_rows, col_indices); timer.Stop(); elapsed_indexed += timer.ReportMicroseconds(); // check residuals // C2 = -C1 + C2 elem::Axpy(-1.0, C1subset, C2subset); double fnorm = elem::Norm(C2subset, elem::FROBENIUS_NORM); cout << "\t[" << (i+1) << "/" << GemmIndexedTest::NUM_RUNS << "]: fnorm of residual: " << fnorm << endl; if (fnorm > max_norm) max_norm = fnorm; if (max_norm > GemmIndexedTest::MAX_ACCEPTABLE_FNORM) { cerr << "*** ERROR ***" << endl; //WriteDelimitedFile(D.LockedBuffer(), D.LDim(), D.Height(), D.Width(), "Derror.csv", 6); //WriteDelimitedFile(B.LockedBuffer(), B.LDim(), B.Height(), B.Width(), "Berror.csv", 6); break; } } // compute average runtimes per loop double t_copying = elapsed_subset * 0.001 / GemmIndexedTest::NUM_RUNS; double t_indexed = elapsed_indexed * 0.001 / GemmIndexedTest::NUM_RUNS; cout << endl; cout << "\t**** Results for Rank2 Indexed Sparse Gemm B'A Test ****" << endl; cout << endl; cout << "\t\t" << GemmIndexedTest::NUM_RUNS << " runs " << endl; cout << "\t\tMax residual Frobenius norm: " << max_norm << endl; cout << "\t\tElapsed time with data copying:\t" << t_copying << " ms." << endl; cout << "\t\tElapsed time with indexing:\t" << t_indexed << " ms." << endl; cout << endl; cout << "\t********************************************************" << endl; cout << endl; return (max_norm < GemmIndexedTest::MAX_ACCEPTABLE_FNORM); }
14,525
5,447
/* Copyright (c) 2014-2016 DataStax 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 "testing.hpp" #include "address.hpp" #include "get_time.hpp" #include "logger.hpp" #include "metadata.hpp" #include "murmur3.hpp" #include "result_response.hpp" #include "external_types.hpp" namespace cass { std::string get_host_from_future(CassFuture* future) { if (future->type() != cass::CASS_FUTURE_TYPE_RESPONSE) { return ""; } cass::ResponseFuture* response_future = static_cast<cass::ResponseFuture*>(future->from()); return response_future->get_host_address().to_string(); } unsigned get_connect_timeout_from_cluster(CassCluster* cluster) { return cluster->config().connect_timeout_ms(); } int get_port_from_cluster(CassCluster* cluster) { return cluster->config().port(); } std::string get_contact_points_from_cluster(CassCluster* cluster) { std::string str; const ContactPointList& contact_points = cluster->config().contact_points(); for (ContactPointList::const_iterator it = contact_points.begin(), end = contact_points.end(); it != end; ++it) { if (str.size() > 0) { str.push_back(','); } str.append(*it); } return str; } std::vector<std::string> get_user_data_type_field_names(const CassSchemaMeta* schema_meta, const std::string& keyspace, const std::string& udt_name) { std::vector<std::string> udt_field_names; if (schema_meta) { const cass::UserType* udt = schema_meta->get_user_type(keyspace, udt_name); if (udt) { for (cass::UserType::FieldVec::const_iterator it = udt->fields().begin(); it != udt->fields().end(); ++it) { udt_field_names.push_back((*it).name); } } } return udt_field_names; } int64_t create_murmur3_hash_from_string(const std::string &value) { return MurmurHash3_x64_128(value.data(), value.size(), 0); } uint64_t get_time_since_epoch_in_ms() { return cass::get_time_since_epoch_ms(); } uint64_t get_host_latency_average(CassSession* session, std::string ip_address, int port) { Address address; if (Address::from_string(ip_address, port, &address)) { return session->get_host(address)->get_current_average().average; } return 0; } } // namespace cass
2,722
955
/* MIT License Android remote Viewer, GUI ADB tools Android Viewer developed to view and control your android device from a PC. ADB exchange Android Viewer, support scale view, input tap from mouse, input swipe from keyboard, save/copy screenshot, etc.. Copyright (c) 2016-2019 PS GitHub: https://github.com/ClnViewer/ADB-Android-Viewer GitHub: https://github.com/ClnViewer/ADB-Android-Viewer/ADBSCEditDLL/ADBSCEdit 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, sub license, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "../../SCEditInternal.h" #include <commctrl.h> namespace Editor { struct TBChangeButton { int32_t btnidx, cmdcur, cmdnew, imgidx, state; }; ToolBar::ToolBar() { Base::m_data = data(); } void ToolBar::show() { if (!Base::m_data.window) return; // Base::refresh(m_rebar.gethandle()); Base::refresh(Base::m_data.window); } MDIWin::WinData ToolBar::data() { MDIWin::WinData d( MDIWin::BaseData::MDIWinType::MWTYPE_TOOLBAR, // MDIWinType group MDIWin::BaseData::MDIWinType::MWTYPE_TOOLBAR, // MDIWinType type MDIWin::BaseData::MDIWinStyle::MWSTYLE_NONE, // MDIWinStyle std::string(), // Class name std::string(), // Title 0, 0 ); d.irdefault.set<int32_t>(0, 0, 0, 0); // % from main widow return d; } bool ToolBar::event_sizeinitBegin(ImageLite::IRECT<int32_t> const & ir) { do { if ((!Base::m_data.window) || (ir.w <= 0)) break; Base::m_data.irsize.set<int32_t>( 0, 0, ir.w - 150, (getsizebtn_() + 4) ); if (Base::m_data.irsize.empty()) break; Base::refresh(SWP_NOMOVE); } while (0); return true; } void ToolBar::event_size(ImageLite::IRECT<int32_t> const & irc, ImageLite::IRECT<int32_t> const &) { Base::m_data.irsize.set<int32_t>( 0, 0, ((irc.w <= 0) ? Base::m_data.irsize.w : irc.w), Base::m_data.irsize.h ); Base::resize(); } void ToolBar::event_resize() { RECT rc{}; HWND hwnd = m_rebar.gethandle(); if (!hwnd) hwnd = Base::m_data.window; if (!::GetClientRect(hwnd, &rc)) return; Base::m_data.irsize.set<int32_t>( 0, 0, rc.right, rc.bottom ); } std::tuple<bool, bool> ToolBar::event_initBegin() { try { Base::m_data.irsize = {}; do { if (!m_rebar.init(Base::m_data.wparent)) break; if (!m_search.init( m_rebar.gethandle(), Base::m_data.wparent )) break; if (!m_menu.init( m_rebar.gethandle(), Base::m_data.wparent )) break; Base::m_data.window = ::CreateWindowExA( WS_EX_COMPOSITED, TOOLBARCLASSNAME, "", WS_VISIBLE | WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | TBSTYLE_FLAT | TBSTYLE_WRAPABLE | TBSTYLE_TRANSPARENT | CCS_NORESIZE | CCS_NODIVIDER | CCS_NOPARENTALIGN, 0, 0, 1, 1, Base::m_data.wparent, (HMENU)ID_REBAR_TOOLBAR, MDIWin::Config::instance().gethinstance(), nullptr ); if (!Base::m_data.window) break; if (!setup_()) break; m_rebar.addband(Base::m_data.window, getsizebtn_() + 4); m_rebar.addband(m_search.gethandle(), 0); m_rebar.addband(m_menu.gethandle(), 0); m_rebar.showband(0); // MDIWin::Config::instance() .setclass<MDIWin::Config::HandleType::CLASS_TBAR>(this); // return { true, true }; } while (0); } catch (...) {} return { true, false }; } int32_t ToolBar::getsizebtn_() { if (!Base::m_data.window) return -1; LRESULT ret = ::SendMessage(Base::m_data.window, TB_GETBUTTONSIZE, 0, 0); auto p = MAKEPOINTS(ret); if (p.x != p.y) return -1; return p.y; } bool ToolBar::setup_() { ::SetLastError(0); const TBBUTTON tbb[] = { # define TB_ITEM(A,B,C,...) TB_ITEM_ ## B (A,B,C) # define TB_ITEM_TBSTYLE_BUTTON(A,B,C) \ { .iBitmap = __COUNTER__, .idCommand = C, .fsState = A, .fsStyle = B, .bReserved = {}, .dwData = 0, .iString = 0 }, # define TB_ITEM_TBSTYLE_SEP(A,B,C) \ { .iBitmap = 0, .idCommand = C, .fsState = A, .fsStyle = B, .bReserved = {}, .dwData = 0, .iString = 0 }, # define TB_CHANGE(...) # include "ToolBarItems.h" }; //int32_t imgcnt = (__COUNTER__ + 3); ImageLite::IPOINT<int32_t> ip{}; MDIWin::Config::instance().getiml( MDIWin::Config::ImageButtonList::IMLBTN_TITLEBAR_CTRL, ip ); if (ip.empty()) return false; ip.x += 2; ip.y += 2; ::SendMessage(Base::m_data.window, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0); ::SendMessage(Base::m_data.window, TB_SETEXTENDEDSTYLE, 0, TBSTYLE_EX_DRAWDDARROWS); ::SendMessage(Base::m_data.window, TB_SETIMAGELIST, (WPARAM)0, (LPARAM) MDIWin::Config::instance().getiml(MDIWin::Config::ImageButtonList::IMLBTN_TOOLBAR_CTRL) ); ::SendMessage(Base::m_data.window, TB_SETBUTTONSIZE, 0, MAKELPARAM(ip.x, ip.y)); ::SendMessage(Base::m_data.window, TB_ADDBUTTONS, __NELE(tbb), (LPARAM)&tbb); ::SendMessage(Base::m_data.window, TB_SETPADDING, 0, MAKELPARAM(0, 0)); ::SendMessage(Base::m_data.window, TB_AUTOSIZE, 0, 0); ::SendMessage(Base::m_data.window, WM_SETFONT, (WPARAM)MDIWin::Config::instance().getfont(), (LPARAM)1); // return true; } // get search text std::string ToolBar::event() { return m_search.gettext(); } // change button void ToolBar::event(int32_t bidx, int32_t bcmd, int32_t bset, int32_t bimg) { static const TBChangeButton l_chbtn[] = { # define TB_CHANGE(A,B,C,D,E) \ { .btnidx = A, .cmdcur = B, .cmdnew = C, .imgidx = D, .state = E }, # define TB_ITEM(...) # include "ToolBarItems.h" }; do { if (bidx > ::SendMessage(Base::m_data.window, TB_BUTTONCOUNT, 0, 0)) break; TBBUTTON tbb{}; if (!::SendMessage(Base::m_data.window, TB_GETBUTTON, bidx, reinterpret_cast<LPARAM>(&tbb))) break; if (tbb.fsStyle == TBSTYLE_SEP) break; for (uint32_t i = 0U; i < __NELE(l_chbtn); i++) { if ((l_chbtn[i].btnidx == bidx) && ( ((bcmd == -1) && (l_chbtn[i].cmdcur == tbb.idCommand)) || ((bcmd != -1) && (l_chbtn[i].cmdnew == bcmd)) )) { // TBChangeButton btn{}; btn.cmdcur = tbb.idCommand; btn.cmdnew = ((bcmd == -1) ? l_chbtn[i].cmdnew : bcmd); btn.state = ((bset == -1) ? l_chbtn[i].state : bset); btn.imgidx = ((bimg == -1) ? l_chbtn[i].imgidx : bimg); // if ((btn.state != -1) && (btn.state != tbb.fsState)) ::SendMessage(Base::m_data.window, TB_SETSTATE, btn.cmdcur, (LPARAM)btn.state); // if ((btn.imgidx != -1) && (btn.imgidx != tbb.iBitmap)) ::SendMessage(Base::m_data.window, TB_CHANGEBITMAP, btn.cmdcur, btn.imgidx); // if ((btn.cmdnew != -1) && (btn.cmdnew != tbb.idCommand)) ::SendMessage(Base::m_data.window, TB_SETCMDID, btn.cmdcur, btn.cmdnew); // break; } } } while (0); } // set plugins toolBar menu void ToolBar::event(uint32_t mid, uint32_t off, std::vector<MDIWin::BaseData::dataMap> & v) { m_menu.add( static_cast<MenuBar::MainMenuId>(mid), off, v ); } // set style toolBar button (image/enable/disable) void ToolBar::event(int32_t id, bool isenable) { switch (id) { case IDM_EVENT_SCRUN_START: { event(TB_BTN_CHECK, -1, 0); event(TB_BTN_START, -1, 0); event(TB_BTN_EXIT, -1, 0); event(TB_BTN_STOP, -1, TBSTATE_ENABLED); m_menu.setenable(IDM_BTN_SCRUN_TEST, false); m_menu.setenable(IDM_BTN_SCRUN_START, false); m_menu.setenable(IDM_BTN_EXIT, false); m_menu.setenable(IDM_BTN_SCRUN_STOP, true); if (isenable) { event(TB_BTN_MODE, IDM_BTN_DBGDUMP); event(TB_BTN_NAVIGATTE, IDM_EDIT_SHOW_NAVIGATE, -1, 21); // m_menu.setcheck(IDM_BTN_DBGSTEP, true); m_menu.setcheck(IDM_BTN_DBGCYCLE, false); // m_menu.setenable(IDM_BTN_DBGDUMP, true); m_menu.setenable(IDM_BTN_DBGNEXT, true); } else { m_menu.setcheck(IDM_BTN_DBGSTEP, false); m_menu.setcheck(IDM_BTN_DBGCYCLE, true); // m_menu.setenable(IDM_BTN_DBGDUMP, false); m_menu.setenable(IDM_BTN_DBGNEXT, false); } break; } case IDM_EVENT_SCRUN_STOP: { event(TB_BTN_MODE, IDM_BTN_DBGCYCLE); event(TB_BTN_CHECK, -1, TBSTATE_ENABLED); event(TB_BTN_START, -1, TBSTATE_ENABLED); event(TB_BTN_EXIT, -1, TBSTATE_ENABLED); event(TB_BTN_STOP, -1, 0); event(TB_BTN_NAVIGATTE, IDM_EDIT_SHOW_NAVIGATE); // m_menu.setenable(IDM_BTN_SCRUN_TEST, true); m_menu.setenable(IDM_BTN_SCRUN_START, true); m_menu.setenable(IDM_BTN_EXIT, true); m_menu.setenable(IDM_BTN_SCRUN_STOP, false); // m_menu.setenable(IDM_BTN_DBGDUMP, false); m_menu.setenable(IDM_BTN_DBGNEXT, false); // m_menu.setcheck(IDM_BTN_DBGSTEP, false); m_menu.setcheck(IDM_BTN_DBGCYCLE, true); break; } case IDM_BTN_DBGMODE: { event(TB_BTN_MODE, ((isenable) ? IDM_BTN_DBGSTEP : IDM_BTN_DBGCYCLE) ); m_menu.setcheck(IDM_BTN_DBGSTEP, isenable); m_menu.setcheck(IDM_BTN_DBGCYCLE, !isenable); break; } case IDM_BTN_DBGSTEP: { event(TB_BTN_MODE, IDM_BTN_DBGSTEP); m_menu.setcheck(IDM_BTN_DBGSTEP, true); m_menu.setcheck(IDM_BTN_DBGCYCLE, false); break; } case IDM_BTN_DBGCYCLE: { event(TB_BTN_MODE, IDM_BTN_DBGCYCLE); m_menu.setcheck(IDM_BTN_DBGSTEP, false); m_menu.setcheck(IDM_BTN_DBGCYCLE, true); break; } case IDM_EVENT_EDIT_FINDTEXT: { if (isenable) event(TB_BTN_NAVIGATTE, IDM_EDIT_SHOW_NAVIGATE, -1, 21); else event(TB_BTN_NAVIGATTE, IDM_EDIT_SHOW_NAVIGATE); break; } case IDM_BTN_WINTOP: case IDM_BTN_EXTDBGV: case IDM_BTN_DBGMUTE: case IDM_EDIT_SHOW_ENDLINE: case IDM_EDIT_SHOW_INDENTG: { m_menu.setcheck(id, isenable); break; } default: break; } } };
14,895
5,029
#include "System.h" #include <winuser.h> #include <iostream> #include <fstream> System::System() : m_initializationFailed(false), m_applicationName(nullptr), m_hInstance(nullptr), m_hwnd(nullptr), m_input(nullptr), m_graphics(nullptr) { auto screenWidth = 0; auto screenHeight = 0; //Initialize the Windows API InitializeWindows(screenWidth, screenHeight); //Create our input object for reading keyboard inputs m_input = new InputManager(); if (!m_input) { m_initializationFailed = true; return; } //Create our graphics object for handling the rendering of all the graphics m_graphics = new GraphicsRenderer(screenWidth, screenHeight, m_hwnd); if (m_graphics->GetInitializationState()) { m_initializationFailed = true; } m_screenWidth = screenWidth; m_screenHeight = screenHeight; }; // We don't need a copy/ move constructor for this class but it's best to have it defined so the compiler doesn't generate it for us System::System(const System& other) = default; System::System(System&& other) noexcept = default; System::~System() { //Release graphics object if (m_graphics) { delete m_graphics; m_graphics = nullptr; } if (m_input) { delete m_input; m_input = nullptr; } // Shutdown window ShutdownWindows(); } System& System::operator=(const System& other) = default; System& System::operator=(System&& other) noexcept = default; //This is the main application loop where we do all the application processing through the frame function until we quit. The frame function is called each loop. void System::Run() { MSG message; auto done = false; //Initialize message structure by filling a block of memory with zeros ZeroMemory(&message, sizeof(message)); //Loop until we get a quit message from the window or the user while (!done) { //Handle windows messages if (PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&message); DispatchMessage(&message); } //If windows ends the application then we exit out if (message.message == WM_QUIT) { done = true; } else { //Else we do the frame processing auto const result = Frame(); if (!result) { done = true; } } } } bool System::GetInitializationState() const { return m_initializationFailed; } //This is where all the application processing happens, we check to see if the user wants to quit the application, if not then we call the graphics objects frame function which will render the graphics. //More code will be added here as we add more functionality to the framework/ application. bool System::Frame() { //Check if user wants to quit the application if (m_input->IsKeyDown(VK_ESCAPE)) { return false; } if (m_input->IsKeyUp(0x31) && m_input->IsKeyUp(0x32) && m_input->IsKeyUp(0x52) && m_input->IsKeyUp(0x50) && m_input->IsKeyUp(0x55) && m_input->IsKeyUp(0x4A) && m_input->IsKeyUp(0x49) && m_input->IsKeyUp(0x4B) && m_input->IsKeyUp(0x4F) && m_input->IsKeyUp(0x4C) && m_input->IsKeyUp(0x54) && m_input->IsKeyUp(0x42) && m_input->IsKeyUp(VK_SPACE)) { m_input->ToggleDoOnce(true); } //Add Balls if (m_input->IsKeyDown(0x31) && m_input->DoOnce()) { m_graphics->AddNumberOfSpheres(m_hwnd); m_input->ToggleDoOnce(false); } //Add Cube if (m_input->IsKeyDown(0x32) && m_input->DoOnce()) { m_graphics->AddCube(m_hwnd); m_input->ToggleDoOnce(false); } //Reset System if (m_input->IsKeyDown(0x52) && m_input->DoOnce()) { m_graphics->ClearMoveableGameObjects(); m_input->ToggleDoOnce(false); } //Pause Simulation if (m_input->IsKeyDown(0x50) && m_input->DoOnce()) { m_graphics->TogglePauseSimulation(); m_input->ToggleDoOnce(false); } //Increase/Decrease TimeScale if (m_input->IsKeyDown(0x55) && m_input->DoOnce()) { m_graphics->AddTimeScale(1); m_input->ToggleDoOnce(false); } if (m_input->IsKeyDown(0x4A) && m_input->DoOnce()) { m_graphics->AddTimeScale(-1); m_input->ToggleDoOnce(false); } //Increase/Decrease Friction if (m_input->IsKeyDown(0x49) && m_input->DoOnce()) { m_graphics->AddFriction(0.1f); m_input->ToggleDoOnce(false); } if (m_input->IsKeyDown(0x4B) && m_input->DoOnce()) { m_graphics->AddFriction(-0.1f); m_input->ToggleDoOnce(false); } //Increase/Decrease Restitution if (m_input->IsKeyDown(0x4F) && m_input->DoOnce()) { m_graphics->AddRestitution(0.1f); m_input->ToggleDoOnce(false); } if (m_input->IsKeyDown(0x4C) && m_input->DoOnce()) { m_graphics->AddRestitution(-0.1f); m_input->ToggleDoOnce(false); } //Increase/Decrease Sphere Diameter if (m_input->IsKeyDown(0x54) && m_input->DoOnce()) { m_graphics->AddSphereDiameter(0.1f); m_input->ToggleDoOnce(false); } if (m_input->IsKeyDown(0x42) && m_input->DoOnce()) { m_graphics->AddSphereDiameter(-0.1f); m_input->ToggleDoOnce(false); } //Increase/Decrease Number Of Spheres if (m_input->IsKeyDown(VK_OEM_6)) { m_graphics->AddNumberOfSpheres(1); } if (m_input->IsKeyDown(VK_OEM_4)) { m_graphics->AddNumberOfSpheres(-1); } //Toggle Random Texture if (m_input->IsKeyDown(VK_SPACE) && m_input->DoOnce()) { m_graphics->ToggleRandomTexture(); m_input->ToggleDoOnce(false); } //Camera Controls if (m_input->IsKeyDown(0x57)) { m_graphics->GetCamera()->AddPositionY(1.0f); } if (m_input->IsKeyDown(0x53)) { m_graphics->GetCamera()->AddPositionY(-1.0f); } if (m_input->IsKeyDown(0x44)) { m_graphics->GetCamera()->AddPositionX(1.0f); } if (m_input->IsKeyDown(0x41)) { m_graphics->GetCamera()->AddPositionX(-1.0f); } if (m_input->IsKeyDown(VK_UP)) { m_graphics->GetCamera()->AddPositionZ(1.0f); } if (m_input->IsKeyDown(VK_DOWN)) { m_graphics->GetCamera()->AddPositionZ(-1.0f); } //Call graphics objects frame processing function auto const result = m_graphics->Frame(); return result; } //Our MessageHandler where we direct the windows system messages into. With this we can listen for certain information. //For now we just read key presses and key releases and notifiy our input object, all other information we just pass back to the default windows message handler. LRESULT CALLBACK System::MessageHandler(HWND hwnd, UINT const umsg, WPARAM const wparam, LPARAM const lparam) { switch(umsg) { //Check if a key has been pressed case WM_KEYDOWN: { // If a key is pressed then send it to our input object m_input->KeyDown(static_cast<unsigned int>(wparam)); return 0; } //Check if a key has been released case WM_KEYUP: { //If a key is released then send it to our input object m_input->KeyUp(static_cast<unsigned int>(wparam)); return 0; } //Send any other messages back to the default windows message handler default: { return DefWindowProc(hwnd, umsg, wparam, lparam); } } } //This is where we build the window we are rendering to. We start by initializing a default window which can be full screen or a set size, depending on the global variable FULL_SCREEN in the GraphicsClass.h void System::InitializeWindows(int& screenWidth, int& screenHeight) { //The windows class structure where we define the window information and register it WNDCLASSEX windowClass; //The device mode structure about the initialization and environment of our display device DEVMODE deviceEnvironment; int positionX; int positionY; //Get an external pointer to our object applicationHandle = this; //Get the instance of our application m_hInstance = GetModuleHandle(nullptr); //Name our application m_applicationName = "Real Time Graphics FrameWork ACW"; //Define our windows class with default settings windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; //To do with redrawing the window if a movement or size adjustment occurs (CS_OWNDC allocates a unique device context) windowClass.lpfnWndProc = WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = m_hInstance; windowClass.hIcon = LoadIcon(nullptr, IDI_WINLOGO); windowClass.hCursor = LoadCursor(nullptr, IDC_ARROW); windowClass.hbrBackground = static_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)); windowClass.lpszMenuName = nullptr; windowClass.lpszClassName = m_applicationName; windowClass.hIconSm = windowClass.hIcon; //Register our windows class RegisterClassEx(&windowClass); //Get the resolution of the users screen screenWidth = GetSystemMetrics(SM_CXSCREEN); screenHeight = GetSystemMetrics(SM_CYSCREEN); //Setup the display device depending on whether we are in full screen mode or windowed, if it's fullscreen we set the screen to the max size and 32bit, else to a defined resolution if (FULL_SCREEN) { //Can we just do ZeroMemory? //Initialize device structure by filling a block of memory with zeros ZeroMemory(&deviceEnvironment, sizeof(deviceEnvironment)); //memset(&deviceEnvironment, 0, sizeof(deviceEnvironment)); deviceEnvironment.dmSize = sizeof(deviceEnvironment); deviceEnvironment.dmPelsWidth = static_cast<unsigned long>(screenWidth); deviceEnvironment.dmPelsHeight = static_cast<unsigned long>(screenHeight); deviceEnvironment.dmBitsPerPel = 32; deviceEnvironment.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; //Change display settings to fullscreen using device environment ChangeDisplaySettings(&deviceEnvironment, CDS_FULLSCREEN); //Set the position of the window to the top left corner positionX = 0; positionY = 0; } else { screenWidth = 1360; screenHeight = 720; //Place window in the centre of the screen positionX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2; positionY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2; } //Create the window with the screen settings and get the handle to it m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, positionX, positionY, screenWidth, screenHeight, nullptr, nullptr, m_hInstance, nullptr); //Show the window and bring it to the front of the applications ShowWindow(m_hwnd, SW_SHOW); SetForegroundWindow(m_hwnd); SetFocus(m_hwnd); //Hide the cursor ShowCursor(false); } //Reverts the screen settings and releases the window class and any handles associated with it void System::ShutdownWindows() { //Show the cursor ShowCursor(true); //Fix display settings if we're in full screen mode if (FULL_SCREEN) { ChangeDisplaySettings(nullptr, 0); } //Remove the window DestroyWindow(m_hwnd); m_hwnd = nullptr; //Remove the application instance by un-registering our window class UnregisterClass(m_applicationName, m_hInstance); m_hInstance = nullptr; //Release the pointer to this object applicationHandle = nullptr; } //This is where windows will sends its message to for us to intercept and use with our message handler, if we can't use it then we just return it back to the main windows message handler inside the MessageHandler function //We intercept this by giving this prototype function to the window procedure when we defined the window class structure for our window class (WNDCLASSEX), this way we hook into the messaging functionality and intercept messages LRESULT CALLBACK WndProc(HWND hwnd, UINT const umsg, WPARAM const wparam, LPARAM const lparam) { switch(umsg) { //Check if the window is being destroyed case WM_DESTROY: { PostQuitMessage(0); return 0; } //Check if the window is being closed case WM_CLOSE: { PostQuitMessage(0); return 0; } //All other messages pass to our message handler default: { return applicationHandle->MessageHandler(hwnd, umsg, wparam, lparam); } } }
11,629
4,229
#include <cmath> #include <cstdio> #include <cstring> #include <cassert> #include <algorithm> using namespace std; typedef long long LL; typedef long double DB; const int maxn = 201, maxm = maxn * maxn, maxs = 13; const DB eps = 1e-8, INF = 1e4; inline int sgn(DB x) { assert(!std::isnan(x)); return (x > eps) - (x < -eps); } inline DB readDB() { static char buf[maxs]; scanf("%s", buf); LL ret = 0, base = 1; char *pat = buf; for( ; *pat && *pat != '.'; ++pat) ret = (ret << 3) + (ret << 1) + (*pat - '0'); if(*pat == '.') for(++pat; *pat; ++pat) { ret = (ret << 3) + (ret << 1) + (*pat - '0'); base = (base << 3) + (base << 1); } for( ; !(ret & 1) && !(base & 1); ret >>= 1, base >>= 1); for( ; !(ret % 5) && !(base % 5); ret /= 5, base /= 5); return (DB)ret / base; } inline void writeDB(DB x, char endc = '\0') { printf("%.20f", (double)x); endc && putchar(endc); } int N, M, S, T, lev[maxn], lnk[maxn], cur[maxn]; struct Edge { int nxt, v; DB w; } e[maxm << 2 | 1]; void addEdge(int u, int v, DB w) { e[M] = (Edge){lnk[u], v, w}; lnk[u] = M++; e[M] = (Edge){lnk[v], u, 0}; lnk[v] = M++; } bool bfs() { int L = 0, R = 0; static int que[maxn]; memset(lev, -1, N * sizeof(int)); lev[S] = 0; que[R++] = S; while(L < R) for(int u = que[L++], it = lnk[u]; it != -1; it = e[it].nxt) if(sgn(e[it].w) > 0 && lev[e[it].v] == -1) { lev[e[it].v] = lev[u] + 1; que[R++] = e[it].v; } return lev[T] != -1; } DB dfs(int u, DB upp) { if(u == T) return upp; DB ret = 0, tmp; for(int &it = cur[u]; ~it; it = e[it].nxt) if(lev[e[it].v] == lev[u] + 1 && sgn(e[it].w) > 0 && sgn(tmp = dfs(e[it].v, min(upp - ret, e[it].w))) > 0) { e[it].w -= tmp; e[it ^ 1].w += tmp; if(sgn((ret += tmp) - upp) >= 0) break; } if(!sgn(ret)) lev[u] = -1; return ret; } DB dinic(int s, int t, DB lim = INF) { DB flow = 0, tmp; for(S = s, T = t; bfs() && sgn(lim - flow) > 0; ) for(memcpy(cur, lnk, N * sizeof(int)); sgn(lim - flow) > 0 && sgn(tmp = dfs(S, lim - flow)) > 0; flow += tmp); return flow; } int n, m; DB v, a, fmx, wmx, zmx, cap[2][maxm], ans; int main() { scanf("%d%d", &n, &m); v = readDB(); a = readDB(); N = n; M = 0; memset(lnk, -1, N * sizeof(int)); for(int i = 0; i < m; ++i) { int u, v, w; scanf("%d%d%d", &u, &v, &w); --u; --v; addEdge(u, v, w); addEdge(v, u, w); } // M = 4 m fmx = dinic(0, 2); zmx = fmx + dinic(1, 2); for(int i = 0; i < M; i += 2) { if((i >> 1) & 1) cap[0][i >> 2] -= e[i ^ 1].w; else cap[0][i >> 2] += e[i ^ 1].w; e[i].w += e[i ^ 1].w; e[i ^ 1].w = 0; } wmx = dinic(1, 2, zmx); dinic(0, 2, zmx - wmx); for(int i = 0; i < M; i += 2) { if((i >> 1) & 1) cap[1][i >> 2] -= e[i ^ 1].w; else cap[1][i >> 2] += e[i ^ 1].w; e[i].w += e[i ^ 1].w; e[i ^ 1].w = 0; } ans = min(max((1 - a) * zmx, zmx - fmx), wmx); DB dt = sgn(fmx + wmx - zmx) > 0 ? (wmx - ans) / (fmx + wmx - zmx) : 0; for(int i = 0; i < m; ++i) { DB cc = dt * cap[0][i] + (1 - dt) * cap[1][i]; e[i << 2].w = sgn(cc) > 0 ? cc : 0; e[i << 2 | 2].w = sgn(cc) < 0 ? -cc : 0; } dinic(1, 2, ans); for(int i = 0; i < m; ++i) { DB cc = dt * cap[0][i] + (1 - dt) * cap[1][i], ww = e[i << 2 | 1].w - e[i << 2 | 3].w; writeDB((cc - ww) / v, ' '); writeDB(ww, '\n'); } writeDB(pow((zmx - ans) / v, a) * pow(ans, 1 - a), '\n'); return 0; }
3,353
1,891
#include "../mainwindow.h" #include "pinwidget.h" #include "ui_pinwidget.h" #include <QMessageBox> using namespace Vipster; PinWidget::PinWidget(QWidget *parent) : BaseWidget(parent), ui(new Ui::PinWidget) { ui->setupUi(this); } PinWidget::~PinWidget() { delete ui; } void PinWidget::updateWidget(GUI::change_t change) { if(change & (GUI::Change::atoms | GUI::Change::trajec | GUI::Change::cell | GUI::Change::settings)){ // set gui-state on_stepList_currentRowChanged(ui->stepList->currentRow()); // update GPU data for(auto &dat: pinnedSteps){ const auto& settings = master->settings; dat->update(dat->curStep, settings.atRadVdW.val, settings.atRadFac.val, settings.bondRad.val); } } if((change & GUI::stepChanged) == GUI::stepChanged){ // disable add-button when already pinned for(auto &dat: pinnedSteps){ if(dat->curStep == master->curStep){ ui->addStep->setDisabled(true); return; } } ui->addStep->setEnabled(true); } } PinWidget::PinnedStep::PinnedStep(Step *step, const std::string& name, GUI::PBCVec mult) : GUI::StepData{step}, name{name}, mult{mult} {} void PinWidget::PinnedStep::draw(const Vec &off, const GUI::PBCVec &m, const Mat &cv, bool drawCell, void *context) { Vec off_loc = off + this->offset; Mat cv_loc = curStep->getCellVec() * curStep->getCellDim(AtomFmt::Bohr); auto mult_loc = curStep->hasCell() ? mult : GUI::PBCVec{{1,1,1}}; if(repeat){ for(int x=0; x<m[0]; ++x){ for(int y=0; y<m[1]; ++y){ for(int z=0; z<m[2]; ++z){ StepData::draw(off_loc + x*cv[0] + y*cv[1] + z*cv[2], mult_loc, cv_loc, drawCell & this->cell, context); } } } }else{ StepData::draw(off_loc, mult_loc, cv_loc, drawCell & this->cell, context); } } void PinWidget::setMult(int i) { if (!curPin) return; auto &mult = curPin->mult; if(sender() == ui->xMultBox){ mult[0] = static_cast<uint8_t>(i); }else if(sender() == ui->yMultBox){ mult[1] = static_cast<uint8_t>(i); }else if(sender() == ui->zMultBox){ mult[2] = static_cast<uint8_t>(i); } triggerUpdate(GUI::Change::extra); } void PinWidget::setOffset(double d) { if (!curPin) return; auto &off = curPin->offset; if(sender() == ui->xOffset){ off[0] = d; }else if(sender() == ui->yOffset){ off[1] = d; }else if(sender() == ui->zOffset){ off[2] = d; } triggerUpdate(GUI::Change::extra); } void PinWidget::on_showCell_toggled(bool checked) { if (!curPin) return; curPin->cell = checked; triggerUpdate(GUI::Change::extra); } void PinWidget::on_repeatStep_toggled(bool checked) { if (!curPin) return; curPin->repeat = checked; triggerUpdate(GUI::Change::extra); } void PinWidget::on_delStep_clicked() { // remove local infos ui->insertStep->setDisabled(true); if(curPin->curStep == master->curStep){ ui->addStep->setEnabled(true); } auto pos2 = std::find(pinnedSteps.begin(), pinnedSteps.end(), curPin); pinnedSteps.erase(pos2); delete ui->stepList->takeItem(ui->stepList->currentRow()); triggerUpdate(GUI::Change::extra); } void PinWidget::on_addStep_clicked() { ui->addStep->setDisabled(true); // add to list of steps pinnedSteps.push_back(std::make_shared<PinnedStep>(master->curStep, master->curMol->name + " (Step " + std::to_string(master->curVP->moldata[master->curMol].curStep) + ')', GUI::PBCVec{1,1,1})); pinnedSteps.back()->update(pinnedSteps.back()->curStep, master->settings.atRadVdW.val, master->settings.atRadFac.val, master->settings.bondRad.val); ui->stepList->addItem(QString::fromStdString(pinnedSteps.back()->name)); // enable in current viewport master->curVP->addExtraData(pinnedSteps.back(), true); triggerUpdate(GUI::Change::extra); } void PinWidget::on_stepList_currentRowChanged(int currentRow) { curPin = currentRow < 0 ? nullptr : pinnedSteps[currentRow]; auto hasPin = static_cast<bool>(curPin); auto hasCell = hasPin ? curPin->curStep->hasCell() : false; ui->insertStep->setEnabled(hasPin ? curPin->curStep != master->curStep : false); ui->delStep->setEnabled(hasPin); ui->showStep->setEnabled(hasPin); ui->repeatStep->setEnabled(hasPin); ui->xOffset->setEnabled(hasPin); ui->yOffset->setEnabled(hasPin); ui->zOffset->setEnabled(hasPin); ui->showCell->setEnabled(hasCell); ui->xMultBox->setEnabled(hasCell); ui->yMultBox->setEnabled(hasCell); ui->zMultBox->setEnabled(hasCell); ui->xFit->setEnabled(hasCell); ui->yFit->setEnabled(hasCell); ui->zFit->setEnabled(hasCell); if(hasPin){ QSignalBlocker block{ui->showStep}; ui->showStep->setChecked(master->curVP->hasExtraData(curPin, true)); QSignalBlocker block1{ui->showCell}; ui->showCell->setChecked(curPin->cell); QSignalBlocker block2{ui->repeatStep}; ui->repeatStep->setChecked(curPin->repeat); QSignalBlocker blockx{ui->xMultBox}; ui->xMultBox->setValue(curPin->mult[0]); QSignalBlocker blocky{ui->yMultBox}; ui->yMultBox->setValue(curPin->mult[1]); QSignalBlocker blockz{ui->zMultBox}; ui->zMultBox->setValue(curPin->mult[2]); QSignalBlocker blockox{ui->xOffset}; ui->xOffset->setValue(curPin->offset[0]); QSignalBlocker blockoy{ui->yOffset}; ui->yOffset->setValue(curPin->offset[1]); QSignalBlocker blockoz{ui->zOffset}; ui->zOffset->setValue(curPin->offset[2]); } } void PinWidget::on_insertStep_clicked() { if (!curPin || (curPin->curStep == master->curStep)) return; Step s = *curPin->curStep; s.asFmt(AtomFmt::Bohr).modShift(curPin->offset); std::array<bool,3> fit = {ui->xFit->isChecked(), ui->yFit->isChecked(), ui->zFit->isChecked()}; if (s.hasCell() && (curPin->mult != GUI::PBCVec{{1,1,1}})) { const auto &m = curPin->mult; s.modMultiply(m[0], m[1], m[2]); } if (s.hasCell() && (fit != std::array<bool,3>{{false, false, false}})){ auto fac = master->curStep->getCellDim(AtomFmt::Bohr) / s.getCellDim(AtomFmt::Bohr); auto cell = s.getCellVec(); const auto& target = master->curStep->getCellVec(); if (fit[0]) cell[0] = target[0] * fac; if (fit[1]) cell[1] = target[1] * fac; if (fit[2]) cell[2] = target[2] * fac; s.setCellVec(cell, true); } master->curStep->newAtoms(s); // immediately hide pinned step master->curVP->delExtraData(curPin, true); triggerUpdate(GUI::Change::atoms); } void PinWidget::on_showStep_toggled(bool checked) { if (!curPin) return; if (checked) { // insert into viewports extras master->curVP->addExtraData(curPin, true); }else{ // remove from viewports extras master->curVP->delExtraData(curPin, true); } triggerUpdate(GUI::Change::extra); } void PinWidget::on_helpButton_clicked() { QMessageBox::information(this, QString("About pinning"), "Pinned Steps are drawn along the currently active Step.\n\n" "\"Repeating\" a Step means it is drawn in periodic repetitions " "of the active Step, i.e. with the periodicity of the active Step.\n" "Contrarily, specifying the multipliers for the pinned Step " "itself draws it with its own periodicity.\n" "Specifying the offset allows the pinned Step to be shifted against the active Step " "without having to modify its structure.\n\n" "Inserting a Step takes both offset and multipliers into account, " "and additionally performs cell vector fitting if requested.\n\n" "Cell vector fitting can be used e.g. to create commensurable super cells. " "If fitting is enabled for a direction, " "the lattice will be shrunken or stretched to " "match this dimension in the active Step." ); }
8,468
2,881
// © 2018 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html #include "unicode/utypes.h" #if !UCONFIG_NO_FORMATTING // Allow implicit conversion from char16_t* to UnicodeString for this file: // Helpful in toString methods and elsewhere. #define UNISTR_FROM_STRING_EXPLICIT #include "numparse_types.h" #include "numparse_decimal.h" #include "static_unicode_sets.h" #include "numparse_utils.h" #include "unicode/uchar.h" #include "putilimp.h" #include "number_decimalquantity.h" using namespace icu; using namespace icu::numparse; using namespace icu::numparse::impl; DecimalMatcher::DecimalMatcher(const DecimalFormatSymbols& symbols, const Grouper& grouper, parse_flags_t parseFlags) { if (0 != (parseFlags & PARSE_FLAG_MONETARY_SEPARATORS)) { groupingSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kMonetaryGroupingSeparatorSymbol); decimalSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kMonetarySeparatorSymbol); } else { groupingSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kGroupingSeparatorSymbol); decimalSeparator = symbols.getConstSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol); } bool strictSeparators = 0 != (parseFlags & PARSE_FLAG_STRICT_SEPARATORS); unisets::Key groupingKey = strictSeparators ? unisets::STRICT_ALL_SEPARATORS : unisets::ALL_SEPARATORS; // Attempt to find separators in the static cache groupingUniSet = unisets::get(groupingKey); unisets::Key decimalKey = unisets::chooseFrom( decimalSeparator, strictSeparators ? unisets::STRICT_COMMA : unisets::COMMA, strictSeparators ? unisets::STRICT_PERIOD : unisets::PERIOD); if (decimalKey >= 0) { decimalUniSet = unisets::get(decimalKey); } else if (!decimalSeparator.isEmpty()) { auto* set = new UnicodeSet(); set->add(decimalSeparator.char32At(0)); set->freeze(); decimalUniSet = set; fLocalDecimalUniSet.adoptInstead(set); } else { decimalUniSet = unisets::get(unisets::EMPTY); } if (groupingKey >= 0 && decimalKey >= 0) { // Everything is available in the static cache separatorSet = groupingUniSet; leadSet = unisets::get( strictSeparators ? unisets::DIGITS_OR_ALL_SEPARATORS : unisets::DIGITS_OR_STRICT_ALL_SEPARATORS); } else { auto* set = new UnicodeSet(); set->addAll(*groupingUniSet); set->addAll(*decimalUniSet); set->freeze(); separatorSet = set; fLocalSeparatorSet.adoptInstead(set); leadSet = nullptr; } UChar32 cpZero = symbols.getCodePointZero(); if (cpZero == -1 || !u_isdigit(cpZero) || u_digit(cpZero, 10) != 0) { // Uncommon case: okay to allocate. auto digitStrings = new UnicodeString[10]; fLocalDigitStrings.adoptInstead(digitStrings); for (int32_t i = 0; i <= 9; i++) { digitStrings[i] = symbols.getConstDigitSymbol(i); } } requireGroupingMatch = 0 != (parseFlags & PARSE_FLAG_STRICT_GROUPING_SIZE); groupingDisabled = 0 != (parseFlags & PARSE_FLAG_GROUPING_DISABLED); integerOnly = 0 != (parseFlags & PARSE_FLAG_INTEGER_ONLY); grouping1 = grouper.getPrimary(); grouping2 = grouper.getSecondary(); // Fraction grouping parsing is disabled for now but could be enabled later. // See http://bugs.icu-project.org/trac/ticket/10794 // fractionGrouping = 0 != (parseFlags & PARSE_FLAG_FRACTION_GROUPING_ENABLED); } bool DecimalMatcher::match(StringSegment& segment, ParsedNumber& result, UErrorCode& status) const { return match(segment, result, 0, status); } bool DecimalMatcher::match(StringSegment& segment, ParsedNumber& result, int8_t exponentSign, UErrorCode&) const { if (result.seenNumber() && exponentSign == 0) { // A number has already been consumed. return false; } else if (exponentSign != 0) { // scientific notation always comes after the number U_ASSERT(!result.quantity.bogus); } // Initial offset before any character consumption. int32_t initialOffset = segment.getOffset(); // Return value: whether to ask for more characters. bool maybeMore = false; // All digits consumed so far. number::impl::DecimalQuantity digitsConsumed; digitsConsumed.bogus = true; // The total number of digits after the decimal place, used for scaling the result. int32_t digitsAfterDecimalPlace = 0; // The actual grouping and decimal separators used in the string. // If non-null, we have seen that token. UnicodeString actualGroupingString; UnicodeString actualDecimalString; actualGroupingString.setToBogus(); actualDecimalString.setToBogus(); // Information for two groups: the previous group and the current group. // // Each group has three pieces of information: // // Offset: the string position of the beginning of the group, including a leading separator // if there was a leading separator. This is needed in case we need to rewind the parse to // that position. // // Separator type: // 0 => beginning of string // 1 => lead separator is a grouping separator // 2 => lead separator is a decimal separator // // Count: the number of digits in the group. If -1, the group has been validated. int32_t currGroupOffset = 0; int32_t currGroupSepType = 0; int32_t currGroupCount = 0; int32_t prevGroupOffset = -1; int32_t prevGroupSepType = -1; int32_t prevGroupCount = -1; while (segment.length() > 0) { maybeMore = false; // Attempt to match a digit. int8_t digit = -1; // Try by code point digit value. UChar32 cp = segment.getCodePoint(); if (u_isdigit(cp)) { segment.adjustOffset(U16_LENGTH(cp)); digit = static_cast<int8_t>(u_digit(cp, 10)); } // Try by digit string. if (digit == -1 && !fLocalDigitStrings.isNull()) { for (int32_t i = 0; i < 10; i++) { const UnicodeString& str = fLocalDigitStrings[i]; if (str.isEmpty()) { continue; } int32_t overlap = segment.getCommonPrefixLength(str); if (overlap == str.length()) { segment.adjustOffset(overlap); digit = static_cast<int8_t>(i); break; } maybeMore = maybeMore || (overlap == segment.length()); } } if (digit >= 0) { // Digit was found. if (digitsConsumed.bogus) { digitsConsumed.bogus = false; digitsConsumed.clear(); } digitsConsumed.appendDigit(digit, 0, true); currGroupCount++; if (!actualDecimalString.isBogus()) { digitsAfterDecimalPlace++; } continue; } // Attempt to match a literal grouping or decimal separator. bool isDecimal = false; bool isGrouping = false; // 1) Attempt the decimal separator string literal. // if (we have not seen a decimal separator yet) { ... } if (actualDecimalString.isBogus() && !decimalSeparator.isEmpty()) { int32_t overlap = segment.getCommonPrefixLength(decimalSeparator); maybeMore = maybeMore || (overlap == segment.length()); if (overlap == decimalSeparator.length()) { isDecimal = true; actualDecimalString = decimalSeparator; } } // 2) Attempt to match the actual grouping string literal. if (!actualGroupingString.isBogus()) { int32_t overlap = segment.getCommonPrefixLength(actualGroupingString); maybeMore = maybeMore || (overlap == segment.length()); if (overlap == actualGroupingString.length()) { isGrouping = true; } } // 2.5) Attempt to match a new the grouping separator string literal. // if (we have not seen a grouping or decimal separator yet) { ... } if (!groupingDisabled && actualGroupingString.isBogus() && actualDecimalString.isBogus() && !groupingSeparator.isEmpty()) { int32_t overlap = segment.getCommonPrefixLength(groupingSeparator); maybeMore = maybeMore || (overlap == segment.length()); if (overlap == groupingSeparator.length()) { isGrouping = true; actualGroupingString = groupingSeparator; } } // 3) Attempt to match a decimal separator from the equivalence set. // if (we have not seen a decimal separator yet) { ... } // The !isGrouping is to confirm that we haven't yet matched the current character. if (!isGrouping && actualDecimalString.isBogus()) { if (decimalUniSet->contains(cp)) { isDecimal = true; actualDecimalString = UnicodeString(cp); } } // 4) Attempt to match a grouping separator from the equivalence set. // if (we have not seen a grouping or decimal separator yet) { ... } if (!groupingDisabled && actualGroupingString.isBogus() && actualDecimalString.isBogus()) { if (groupingUniSet->contains(cp)) { isGrouping = true; actualGroupingString = UnicodeString(cp); } } // Leave if we failed to match this as a separator. if (!isDecimal && !isGrouping) { break; } // Check for conditions when we don't want to accept the separator. if (isDecimal && integerOnly) { break; } else if (currGroupSepType == 2 && isGrouping) { // Fraction grouping break; } // Validate intermediate grouping sizes. bool prevValidSecondary = validateGroup(prevGroupSepType, prevGroupCount, false); bool currValidPrimary = validateGroup(currGroupSepType, currGroupCount, true); if (!prevValidSecondary || (isDecimal && !currValidPrimary)) { // Invalid grouping sizes. if (isGrouping && currGroupCount == 0) { // Trailing grouping separators: these are taken care of below U_ASSERT(currGroupSepType == 1); } else if (requireGroupingMatch) { // Strict mode: reject the parse digitsConsumed.clear(); digitsConsumed.bogus = true; } break; } else if (requireGroupingMatch && currGroupCount == 0 && currGroupSepType == 1) { break; } else { // Grouping sizes OK so far. prevGroupOffset = currGroupOffset; prevGroupCount = currGroupCount; if (isDecimal) { // Do not validate this group any more. prevGroupSepType = -1; } else { prevGroupSepType = currGroupSepType; } } // OK to accept the separator. // Special case: don't update currGroup if it is empty; this allows two grouping // separators in a row in lenient mode. if (currGroupCount != 0) { currGroupOffset = segment.getOffset(); } currGroupSepType = isGrouping ? 1 : 2; currGroupCount = 0; if (isGrouping) { segment.adjustOffset(actualGroupingString.length()); } else { segment.adjustOffset(actualDecimalString.length()); } } // End of main loop. // Back up if there was a trailing grouping separator. // Shift prev -> curr so we can check it as a final group. if (currGroupSepType != 2 && currGroupCount == 0) { maybeMore = true; segment.setOffset(currGroupOffset); currGroupOffset = prevGroupOffset; currGroupSepType = prevGroupSepType; currGroupCount = prevGroupCount; prevGroupOffset = -1; prevGroupSepType = 0; prevGroupCount = 1; } // Validate final grouping sizes. bool prevValidSecondary = validateGroup(prevGroupSepType, prevGroupCount, false); bool currValidPrimary = validateGroup(currGroupSepType, currGroupCount, true); if (!requireGroupingMatch) { // The cases we need to handle here are lone digits. // Examples: "1,1" "1,1," "1,1,1" "1,1,1," ",1" (all parse as 1) // See more examples in numberformattestspecification.txt int32_t digitsToRemove = 0; if (!prevValidSecondary) { segment.setOffset(prevGroupOffset); digitsToRemove += prevGroupCount; digitsToRemove += currGroupCount; } else if (!currValidPrimary && (prevGroupSepType != 0 || prevGroupCount != 0)) { maybeMore = true; segment.setOffset(currGroupOffset); digitsToRemove += currGroupCount; } if (digitsToRemove != 0) { digitsConsumed.adjustMagnitude(-digitsToRemove); digitsConsumed.truncate(); } prevValidSecondary = true; currValidPrimary = true; } if (currGroupSepType != 2 && (!prevValidSecondary || !currValidPrimary)) { // Grouping failure. digitsConsumed.bogus = true; } // Strings that start with a separator but have no digits, // or strings that failed a grouping size check. if (digitsConsumed.bogus) { maybeMore = maybeMore || (segment.length() == 0); segment.setOffset(initialOffset); return maybeMore; } // We passed all inspections. Start post-processing. // Adjust for fraction part. digitsConsumed.adjustMagnitude(-digitsAfterDecimalPlace); // Set the digits, either normal or exponent. if (exponentSign != 0 && segment.getOffset() != initialOffset) { bool overflow = false; if (digitsConsumed.fitsInLong()) { int64_t exponentLong = digitsConsumed.toLong(false); U_ASSERT(exponentLong >= 0); if (exponentLong <= INT32_MAX) { auto exponentInt = static_cast<int32_t>(exponentLong); if (result.quantity.adjustMagnitude(exponentSign * exponentInt)) { overflow = true; } } else { overflow = true; } } else { overflow = true; } if (overflow) { if (exponentSign == -1) { // Set to zero result.quantity.clear(); } else { // Set to infinity result.quantity.bogus = true; result.flags |= FLAG_INFINITY; } } } else { result.quantity = digitsConsumed; } // Set other information into the result and return. if (!actualDecimalString.isBogus()) { result.flags |= FLAG_HAS_DECIMAL_SEPARATOR; } result.setCharsConsumed(segment); return segment.length() == 0 || maybeMore; } bool DecimalMatcher::validateGroup(int32_t sepType, int32_t count, bool isPrimary) const { if (requireGroupingMatch) { if (sepType == -1) { // No such group (prevGroup before first shift). return true; } else if (sepType == 0) { // First group. if (isPrimary) { // No grouping separators is OK. return true; } else { return count != 0 && count <= grouping2; } } else if (sepType == 1) { // Middle group. if (isPrimary) { return count == grouping1; } else { return count == grouping2; } } else { U_ASSERT(sepType == 2); // After the decimal separator. return true; } } else { if (sepType == 1) { // #11230: don't accept middle groups with only 1 digit. return count != 1; } else { return true; } } } bool DecimalMatcher::smokeTest(const StringSegment& segment) const { // The common case uses a static leadSet for efficiency. if (fLocalDigitStrings.isNull() && leadSet != nullptr) { return segment.startsWith(*leadSet); } if (segment.startsWith(*separatorSet) || u_isdigit(segment.getCodePoint())) { return true; } if (fLocalDigitStrings.isNull()) { return false; } for (int32_t i = 0; i < 10; i++) { if (segment.startsWith(fLocalDigitStrings[i])) { return true; } } return false; } UnicodeString DecimalMatcher::toString() const { return u"<Decimal>"; } #endif /* #if !UCONFIG_NO_FORMATTING */
17,114
4,891
#include "UnitEventOperator.h" #include "../UnitBehavior.h" UnitEventOperator::UnitEventOperator(SharedParams_t params) : UnitEventBase(params) { } UnitEventOperator::~UnitEventOperator(void) { } // Выполняется ли условие bool UnitEventOperator::IsApprove( core::array<Event_t*>& events ) { return true; }
312
110
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #include <memory> #include <popart/op/reducemedian.hpp> #include <popart/opmanager.hpp> namespace popart { ReduceMedianOp::ReduceMedianOp( const OperatorIdentifier &opid, const nonstd::optional<std::vector<int64_t>> &axes, int64_t keepdims, const Op::Settings &settings) : ReduceOp(opid, axes, keepdims, settings) {} std::unique_ptr<Op> ReduceMedianOp::clone() const { return std::make_unique<ReduceMedianOp>(*this); } void ReduceMedianOp::setup() { ReduceOp::setup(); outInfo(getIndicesOutIndex()) = {DataType::INT32, outInfo(getOutIndex()).shape()}; } std::vector<std::unique_ptr<Op>> ReduceMedianOp::getGradOps() { std::vector<std::unique_ptr<Op>> result; result.emplace_back( std::make_unique<ReduceMedianGradOp>(*this, backward_shape)); return result; } bool ReduceMedianOp::canBeReplacedByIdentity() const { // Make sure the op is never replaced by identity as callers expect two // outputs and identity only has one. return false; } ReduceMedianGradOp::ReduceMedianGradOp(const ReduceMedianOp &fwd_op, const Shape &backward_shape) : ReduceGradOp(Onnx::CustomGradOperators::ReduceMedianGrad, fwd_op, backward_shape) {} std::unique_ptr<Op> ReduceMedianGradOp::clone() const { return std::make_unique<ReduceMedianGradOp>(*this); } const std::vector<GradInOutMapper> &ReduceMedianGradOp::gradInputInfo() const { static const std::vector<GradInOutMapper> inInfo = { // Gradient from the top for the median values (0). {getInIndex(), ReduceMedianOp::getOutIndex(), GradOpInType::GradOut}, // Indices computed during the forward pass (1). {getIndicesInIndex(), ReduceMedianOp::getIndicesOutIndex(), GradOpInType::Out}}; return inInfo; } namespace { static OpDefinition::DataTypes T = {DataType::UINT32, DataType::UINT64, DataType::INT32, DataType::INT64, DataType::FLOAT16, DataType::FLOAT}; static OpDefinition reduceMedianOpDef( {OpDefinition::Inputs({{"data", T}}), OpDefinition::Outputs({{"reduced", T}, {"indices", {DataType::INT32}}}), OpDefinition::Attributes({{"axes", {"*"}}, {"keepdims", {"*"}}})}); static OpCreator<ReduceMedianOp> ReduceMedianOpCreator( OpDefinitions({{Onnx::AiGraphcore::OpSet1::ReduceMedian, reduceMedianOpDef}}), [](const OpCreatorInfo &info) { int64_t keepdims = info.attributes.getAttribute<Attributes::Int>("keepdims", 1); nonstd::optional<std::vector<int64_t>> axes; if (info.attributes.hasAttribute("axes")) { axes = info.attributes.getAttribute<Attributes::Ints>("axes"); } return std::unique_ptr<Op>( new ReduceMedianOp(info.opid, axes, keepdims, info.settings)); }, true); } // namespace } // namespace popart
3,114
1,015
#include "dtlz.h" namespace dtlz { #define PI 3.1415926535897932384626433832795 void DTLZ1(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1]-0.5,2) - cos(20 * PI * (x[i-1]-0.5)); } g = 100 * (k + g); for (i = 1; i <= no_objs; i++) { double fi = 0.5 * (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= x[j-1]; } if (i > 1) { fi *= 1 - x[(no_objs - i + 1) - 1]; } f[i-1] = fi; } } void DTLZ2(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1]-0.5,2); } for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(x[j-1] * PI / 2); } if (i > 1) { fi *= sin(x[(no_objs - i + 1) - 1] * PI / 2); } f[i-1] = fi; } } void DTLZ3(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1]-0.5,2) - cos(20 * PI * (x[i-1]-0.5)); } g = 100 * (k + g); for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(x[j-1] * PI / 2); } if (i > 1) { fi *= sin(x[(no_objs - i + 1) - 1] * PI / 2); } f[i-1] = fi; } } void DTLZ4(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; double alpha = 100; int n = no_vars; int k = n - no_objs + 1; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1]-0.5,2); } for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(pow(x[j-1],alpha) * PI / 2); } if (i > 1) { fi *= sin(pow(x[(no_objs - i + 1) - 1],alpha) * PI / 2); } f[i-1] = fi; } } void DTLZ5(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double *theta = new double[no_objs]; double t = 0; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1] - 0.5, 2); } t = PI / (4 * (1 + g)); theta[0] = x[0] * PI / 2; for (i = 2; i <= no_objs - 1; i++) { theta[i-1] = t * (1 + 2 * g * x[i-1]); } for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(theta[j-1]); } if (i > 1) { fi *= sin(theta[(no_objs - i + 1) - 1]); } f[i-1] = fi; } delete theta; } void DTLZ6(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double *theta = new double[no_objs]; double t = 0; double g = 0; for (i = n - k + 1; i <= n; i++) { g += pow(x[i-1], 0.1); } t = PI / (4 * (1 + g)); theta[0] = x[0] * PI / 2; for (i = 2; i <= no_objs - 1; i++) { theta[i-1] = t * (1 + 2 * g * x[i-1]); } for (i = 1; i <= no_objs; i++) { double fi = (1 + g); for (j = no_objs - i; j >= 1; j--) { fi *= cos(theta[j-1]); } if (i > 1) { fi *= sin(theta[(no_objs - i + 1) - 1]); } f[i-1] = fi; } delete theta; } void DTLZ7(const double *x, double* f, const unsigned no_vars, const unsigned no_objs) { int i = 0; int j = 0; int n = no_vars; int k = n - no_objs + 1; double g = 0; double h = 0; for (i = n - k + 1; i <= n; i++) { g += x[i-1]; } g = 1 + 9 * g / k; for (i = 1; i <= no_objs - 1; i++) { f[i-1] = x[i-1]; } for (j = 1; j <= no_objs - 1; j++) { h += x[j-1] / (1 + g) * (1 + sin(3 * PI * x[j-1])); } h = no_objs - h; f[no_objs - 1] = (1 + g) * h; } } /* dtlz */
4,159
2,236
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/speech/speech_recognition_request.h" #include <vector> #include "app/l10n_util.h" #include "base/json/json_reader.h" #include "base/string_util.h" #include "base/values.h" #include "chrome/common/net/url_request_context_getter.h" #include "net/base/escape.h" #include "net/base/load_flags.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_status.h" namespace { const char* const kDefaultSpeechRecognitionUrl = "https://www.google.com/speech-api/v1/recognize?client=chromium&"; const char* const kHypothesesString = "hypotheses"; const char* const kUtteranceString = "utterance"; const char* const kConfidenceString = "confidence"; bool ParseServerResponse(const std::string& response_body, speech_input::SpeechInputResultArray* result) { if (response_body.empty()) { LOG(WARNING) << "ParseServerResponse: Response was empty."; return false; } DVLOG(1) << "ParseServerResponse: Parsing response " << response_body; // Parse the response, ignoring comments. std::string error_msg; scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError( response_body, false, NULL, &error_msg)); if (response_value == NULL) { LOG(WARNING) << "ParseServerResponse: JSONReader failed : " << error_msg; return false; } if (!response_value->IsType(Value::TYPE_DICTIONARY)) { VLOG(1) << "ParseServerResponse: Unexpected response type " << response_value->GetType(); return false; } const DictionaryValue* response_object = static_cast<DictionaryValue*>(response_value.get()); // Get the hypotheses Value* hypotheses_value = NULL; if (!response_object->Get(kHypothesesString, &hypotheses_value)) { VLOG(1) << "ParseServerResponse: Missing hypotheses attribute."; return false; } DCHECK(hypotheses_value); if (!hypotheses_value->IsType(Value::TYPE_LIST)) { VLOG(1) << "ParseServerResponse: Unexpected hypotheses type " << hypotheses_value->GetType(); return false; } const ListValue* hypotheses_list = static_cast<ListValue*>(hypotheses_value); if (hypotheses_list->GetSize() == 0) { VLOG(1) << "ParseServerResponse: hypotheses list is empty."; return false; } size_t index = 0; for (; index < hypotheses_list->GetSize(); ++index) { Value* hypothesis = NULL; if (!hypotheses_list->Get(index, &hypothesis)) { LOG(WARNING) << "ParseServerResponse: Unable to read hypothesis value."; break; } DCHECK(hypothesis); if (!hypothesis->IsType(Value::TYPE_DICTIONARY)) { LOG(WARNING) << "ParseServerResponse: Unexpected value type " << hypothesis->GetType(); break; } const DictionaryValue* hypothesis_value = static_cast<DictionaryValue*>(hypothesis); string16 utterance; if (!hypothesis_value->GetString(kUtteranceString, &utterance)) { LOG(WARNING) << "ParseServerResponse: Missing utterance value."; break; } // It is not an error if the 'confidence' field is missing. double confidence = 0.0; hypothesis_value->GetReal(kConfidenceString, &confidence); result->push_back(speech_input::SpeechInputResultItem(utterance, confidence)); } if (index < hypotheses_list->GetSize()) { result->clear(); return false; } return true; } } // namespace namespace speech_input { int SpeechRecognitionRequest::url_fetcher_id_for_tests = 0; SpeechRecognitionRequest::SpeechRecognitionRequest( URLRequestContextGetter* context, Delegate* delegate) : url_context_(context), delegate_(delegate) { DCHECK(delegate); } SpeechRecognitionRequest::~SpeechRecognitionRequest() {} bool SpeechRecognitionRequest::Send(const std::string& language, const std::string& grammar, const std::string& hardware_info, const std::string& content_type, const std::string& audio_data) { DCHECK(!url_fetcher_.get()); std::vector<std::string> parts; std::string lang_param = language; if (lang_param.empty() && url_context_) { // If no language is provided then we use the first from the accepted // language list. If this list is empty then it defaults to "en-US". // Example of the contents of this list: "es,en-GB;q=0.8", "" URLRequestContext* request_context = url_context_->GetURLRequestContext(); DCHECK(request_context); std::string accepted_language_list = request_context->accept_language(); size_t separator = accepted_language_list.find_first_of(",;"); lang_param = accepted_language_list.substr(0, separator); } if (lang_param.empty()) lang_param = "en-US"; parts.push_back("lang=" + EscapeQueryParamValue(lang_param, true)); if (!grammar.empty()) parts.push_back("lm=" + EscapeQueryParamValue(grammar, true)); if (!hardware_info.empty()) parts.push_back("xhw=" + EscapeQueryParamValue(hardware_info, true)); // TODO(satish): Remove this hardcoded value once the page is allowed to // set this via an attribute. parts.push_back("maxresults=3"); GURL url(std::string(kDefaultSpeechRecognitionUrl) + JoinString(parts, '&')); url_fetcher_.reset(URLFetcher::Create(url_fetcher_id_for_tests, url, URLFetcher::POST, this)); url_fetcher_->set_upload_data(content_type, audio_data); url_fetcher_->set_request_context(url_context_); // The speech recognition API does not require user identification as part // of requests, so we don't send cookies or auth data for these requests to // prevent any accidental connection between users who are logged into the // domain for other services (e.g. bookmark sync) with the speech requests. url_fetcher_->set_load_flags( net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES | net::LOAD_DO_NOT_SEND_AUTH_DATA); url_fetcher_->Start(); return true; } void SpeechRecognitionRequest::OnURLFetchComplete( const URLFetcher* source, const GURL& url, const URLRequestStatus& status, int response_code, const ResponseCookies& cookies, const std::string& data) { DCHECK_EQ(url_fetcher_.get(), source); bool error = !status.is_success() || response_code != 200; SpeechInputResultArray result; if (!error) error = !ParseServerResponse(data, &result); url_fetcher_.reset(); DVLOG(1) << "SpeechRecognitionRequest: Invoking delegate with result."; delegate_->SetRecognitionResult(error, result); } } // namespace speech_input
6,950
2,169
/* 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__graphics__opengl__devices_shader__hpp #define __libamtrs__graphics__opengl__devices_shader__hpp AMTRS_OPENGL_NAMESPACE_BEGIN class devices_shader : g3d::shader::memory { public: static constexpr GLuint novalue = static_cast<GLuint>(0); template<class Resources> static devices_shader* get_shader(g3d::shader* _shader, Resources* _resources) { devices_shader* thiz; if (auto m = _shader->get_memory(); m) { // すでにメモリが存在する thiz = static_cast<devices_shader*>(m); } else { // 新しくメモリを確保 thiz = new devices_shader(); _shader->set_memory(thiz); _resources->set(thiz); } // シェーダーがまだ作られていないかロストしているなら再度作成する if (thiz->mShader == novalue) { _shader->compile(); } return thiz; } void activate(const g3d::device_capacity& _capacity, const void* _uniforms) { AMTRS_G3D_OPENGL_GLGETERROR("Before glUseProgram") glUseProgram(mShader); AMTRS_G3D_OPENGL_GLGETERROR("glUseProgram") GLuint textureIndex = 0; for (const auto& uni : mUniformLayout) { if (uni.type == GL_TEXTURE_2D) { glUniform1i(uni.location, textureIndex); AMTRS_G3D_OPENGL_GLGETERROR("glUniform1i") ++textureIndex; } else { switch (uni.count) { case 4 : glUniform4fv(uni.location, 1, (const GLfloat*)((std::uintptr_t)_uniforms + uni.offset)); AMTRS_G3D_OPENGL_GLGETERROR("glUniform4fv") break; case 16 : glUniformMatrix4fv(uni.location, 1, GL_FALSE, (const GLfloat*)((std::uintptr_t)_uniforms + uni.offset)); AMTRS_G3D_OPENGL_GLGETERROR("glUniformMatrix4fv") break; } } } } template<class Callback> void enumrate_textures(const void* _uniforms, Callback&& _callback) { GLuint textureIndex = 0; for (const auto& uni : mUniformLayout) { if (uni.type == GL_TEXTURE_2D) { auto tex = *reinterpret_cast<g3d::texture**>((std::uintptr_t)_uniforms + uni.offset); _callback(textureIndex, static_cast<g3d::texture*>(tex)); ++textureIndex; } } } void deactivate() { GLuint textureIndex = 0; for (const auto& uni : mUniformLayout) { if (uni.type == GL_TEXTURE_2D) { glActiveTexture(GL_TEXTURE0 + textureIndex); AMTRS_G3D_OPENGL_GLGETERROR("glActiveTexture") glBindTexture(GL_TEXTURE_2D, 0); AMTRS_G3D_OPENGL_GLGETERROR("glBindTexture") ++textureIndex; } } glUseProgram(0); AMTRS_G3D_OPENGL_GLGETERROR("glUseProgram") } auto const& vtxlayout() const noexcept { return mVertexLayout; } protected: void on_gain() override { } void on_lost() override { if (mShader != novalue) { glDeleteShader(mShader); mShader = novalue; } } void on_compile(const attribute* _attrs, std::size_t _attr_size, const attribute* _uniforms, std::size_t _uniform_size, std::string _vertex, std::string _fragment) override { // シェーダープログラム mVertexProgram = std::move(_vertex); mFragmentProgram = std::move(_fragment); mShader = build(mVertexProgram, mFragmentProgram); // 頂点レイアウト mVertexLayout = vertex_layout::create_from_shader(mShader); mVertexLayout.mapping(_attrs, _attr_size); // 共有データレイアウト mUniformLayout = uniform_layout::create_from_shader(mShader); mUniformLayout.mapping(_uniforms, _uniform_size); } private: static GLuint build(std::string const& _vtx, std::string const& _frg) { GLuint vtxShader; GLuint frgShader; (void)glGetError(); vtxShader = compile(GL_VERTEX_SHADER, _vtx); if (vtxShader == novalue) { AMTRS_DEBUG_LOG("vtxShader error"); return novalue; } frgShader = compile(GL_FRAGMENT_SHADER, _frg); if (frgShader == novalue) { AMTRS_DEBUG_LOG("frgShader error"); glDeleteShader(vtxShader); return novalue; } // 二つをリンク GLint linkStatus = GL_FALSE; GLint shader = glCreateProgram(); if (shader == novalue) { AMTRS_DEBUG_LOG("shader error"); glDeleteShader(vtxShader); glDeleteShader(frgShader); return novalue; } glAttachShader(shader, vtxShader); glAttachShader(shader, frgShader); glLinkProgram(shader); glGetProgramiv(shader, GL_LINK_STATUS, &linkStatus); if (!linkStatus) { char temp[512+1] = ""; glGetShaderInfoLog(shader, sizeof(temp)-1, nullptr, temp); throw std::logic_error(temp); } glDeleteShader(vtxShader); glDeleteShader(frgShader); return shader; } static GLuint compile(GLenum _shaderType, std::string_view _program) { std::string program(_program); GLint compiled = GL_FALSE; GLuint shader = glCreateShader(_shaderType); const char* prgs[] = { program.c_str() }; glShaderSource(shader, 1, prgs, nullptr); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled); if (!compiled) { char temp[512+1] = ""; glGetShaderInfoLog(shader, sizeof(temp)-1, nullptr, temp); AMTRS_DEBUG_LOG("Shader compile error: %s", temp); throw std::runtime_error(format<std::string>("shader compile error: %s", temp)); } return shader; } std::string mVertexProgram; std::string mFragmentProgram; GLuint mShader = novalue; vertex_layout mVertexLayout; uniform_layout mUniformLayout; }; AMTRS_OPENGL_NAMESPACE_END #endif
5,396
2,535
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /* $Id$ */ //////////////////////////////////////////////////////////////////////////// // // Pre-Trigger simulation // // Authors: F. Reidt (Felix.Reidt@cern.ch) // // This class is used to simulate the front end box behavior of the // pretrigger system. Digits of T0 and V0 are used as input. A threshold // discrimination, masking and first processing with look up tables is // done during the simulation process // //////////////////////////////////////////////////////////////////////////// #include <TClonesArray.h> #include <TTree.h> #include "AliRunLoader.h" #include "AliLoader.h" #include "AliLog.h" #include "AliVZEROdigit.h" #include "AliVZEROCalibData.h" #include "AliT0digit.h" #include "AliTRDptrgParam.h" #include "AliTRDptrgLUT.h" #include "AliTRDptrgFEB.h" ClassImp(AliTRDptrgFEB) //______________________________________________________________________________ AliTRDptrgFEB::AliTRDptrgFEB(AliRunLoader *rl) : TObject(), fRunLoader(rl), fParam(0), fLUTArray(0), fType(AliTRDptrgParam::kUndefined), fOperatingMode(AliTRDptrgParam::kDigits), fInputChannelCount(0), fPosition(AliTRDptrgParam::kUnknown), fID(0), fThreshold(0) { // default constructor AliError("default ctor - not recommended"); } //______________________________________________________________________________ AliTRDptrgFEB::AliTRDptrgFEB(AliRunLoader *rl, AliTRDptrgParam::AliTRDptrgFEBType_t febType, AliTRDptrgParam::AliTRDptrgOperatingMode_t operatingMode, AliTRDptrgParam::AliTRDptrgFEBPosition_t position, Int_t id, AliTRDptrgParam *param) : TObject(), fRunLoader(rl), fParam(param), fLUTArray(0), fType(febType), fOperatingMode(operatingMode), fInputChannelCount(0), fPosition(position), fID(id), fThreshold(0x0) { // prefered constructor this->LoadParams(); // load configuration parameters } //______________________________________________________________________________ AliTRDptrgFEB::~AliTRDptrgFEB() { // destructor if (this->fParam == 0x0) { if (this->fThreshold != 0x0) { delete[] this->fThreshold; this->fThreshold = 0x0; } } // delete LUTArray this->fLUTArray.Delete(); } //______________________________________________________________________________ Int_t AliTRDptrgFEB::LoadDigits() { // loads T0 or V0 digits and discriminates them automatically if (this->fType == AliTRDptrgParam::kVZERO) { // load V0's digits -------------------------------------------------------- // behavior adapted for AliVZERODigitizer.cxx 40613 2010-04-22 09:57:15Z // get V0 run loader AliLoader* loader = this->fRunLoader->GetLoader( "VZEROLoader" ); if (!loader) { AliError("Cannot get VZERO loader"); return -1; } loader->LoadDigits("READ"); TTree* vzeroDigitsTree = loader->TreeD(); if (!vzeroDigitsTree) { AliError("Cannot get the VZERO digit tree"); return -1; } TClonesArray* vzeroDigits = NULL; TBranch* digitBranch = vzeroDigitsTree->GetBranch("VZERODigit"); digitBranch->SetAddress(&vzeroDigits); vzeroDigitsTree->GetEvent(0); Int_t nDigits = vzeroDigits->GetEntriesFast(); // get digit count AliDebug(5, Form("Found a whole of %d digits", nDigits)); Int_t inputVector = 0x0; // Vector which is feed into the LUT for (Int_t iDigit=0; iDigit<nDigits; iDigit++) { // loop over all digits AliDebug(5, "Looping over digit"); AliVZEROdigit* digit = (AliVZEROdigit*)vzeroDigits->At(iDigit); Int_t pmNumber = digit->PMNumber(); // Int_t board = pmNumber / 8; // changed in Version 40613 Int_t feeBoard = AliVZEROCalibData::GetBoardNumber(pmNumber); Int_t board = feeBoard % 4; // feeBoard V0-A: 1-4; V0-C: 5-8 => board: 1-4 Int_t channel = pmNumber % 8; Int_t position = -1; if ((pmNumber >= 32) && (pmNumber <= 63)) { // V0-A (matched v40613) position = 1; // AliTRDptrgParam::kA } else if ((pmNumber >= 0) && (pmNumber <= 31)) { // V0-C (matched v40613) position = 2; // kB } AliDebug(5, Form("pmNumber: %d; feeBoard: %d; board: %d; channel: %d; position %d", pmNumber, feeBoard, board, channel, position)); if (position == -1) { AliError("Wrong VZERO pmt position found"); loader->UnloadDigits(); return -1; } // check whether the digits belongs to the current FEB, otherwise omit it if ((position == this->fPosition) && (board == this->fID)) { AliDebug(5, "Found an digit corresponding to the current FEB"); Float_t value = digit->ADC(); AliDebug(5, Form("ADC value: %f\n", value)); Int_t channelBitMask = 0x01; // channel0 => 0x01; channel1=> 0x02; 2^(channel number) channelBitMask <<= channel; if (value >= this->fThreshold[channel]) { inputVector |= channelBitMask; AliDebug(5, Form("Threshold exceeded in channel %d, new inputVector 0x%x", channel, inputVector)); } } } AliDebug(5, Form("inputVector: 0x%x", inputVector)); loader->UnloadDigits(); return inputVector; } else if (this->fType == AliTRDptrgParam::kTZERO) { // load T0's digits -------------------------------------------------------- AliLoader * fT0Loader = this->fRunLoader->GetLoader("T0Loader"); // AliT0digit *fDigits; if (!fT0Loader) { AliError("Cannot get T0 loader"); return -1; } fT0Loader->LoadDigits("READ"); // Creating T0 data container TTree* treeD = fT0Loader->TreeD(); if (!treeD) { AliError("no digits tree"); return -1; } AliT0digit* digits = new AliT0digit(); TBranch *brDigits = treeD->GetBranch("T0"); if (brDigits) { brDigits->SetAddress(&digits); } else { AliError("Branch T0 DIGIT not found"); return -1; } brDigits->GetEntry(0); TArrayI qtc0(24); // Array must have 24 entries! TArrayI qtc1(24); // Array must have 24 entries! digits->GetQT0(qtc0); // baseline (reference level) digits->GetQT1(qtc1); // measurement value Int_t inputVector = 0x0; // vector to be fed into the look up table // PMT Positions // C: 0 to 11 // A: 12 to 23 // positions according to AliT0Digitizer.cxx Revision 37491 Int_t nStart = 0; if (this->fPosition == AliTRDptrgParam::kC) { // C nStart = 0; } else if (this->fPosition == AliTRDptrgParam::kA) { // A nStart = 12; } Int_t channelBitMask = 0x01; for (Int_t i = 0 + nStart; i < nStart + 12; i++) { //Int_t channelBitMask = 0x01; AliDebug(5, Form("channel: %d", i)); Int_t value = qtc1[i] - qtc0[i]; // calculate correct measurement value if (value > (Int_t)this->fThreshold[i - nStart]) { inputVector |= channelBitMask; // Add bit AliDebug(5, Form("Threshold exceeded in channel %d,", i)); AliDebug(5, Form("new inputVector 0x%x", inputVector)); AliDebug(5, Form("channelBitMask 0x%x", channelBitMask)); } channelBitMask <<= 1; // go on to the next channel } delete digits; return inputVector; } return -1; } //______________________________________________________________________________ Int_t AliTRDptrgFEB::LoadAndProcessHits() { // loads TO or VO hits and converts them to digits optimized for ptrg // afterwards the digits will be discriminated AliError("LoadAndProcessHits() - not yet implemented!\n"); if (this->fType == AliTRDptrgParam::kVZERO) { return 0; } else if (this->fType == AliTRDptrgParam::kTZERO) { return 0; } return -1; } //______________________________________________________________________________ Bool_t AliTRDptrgFEB::LoadParams() { // Load Parameters if (this->fParam == 0x0) { AliWarning("No paramater object specified - start loading defaults\n"); if (this->fType == AliTRDptrgParam::kVZERO) { // initialize threshold this->fThreshold = new UInt_t[8]; for (Int_t i = 0; i < 8; i++) { this->fThreshold[i] = 10; } // initialize LUTsoutputWidth=<value optimized out> AliTRDptrgLUT* lut = new AliTRDptrgLUT(); this->fLUTArray.AddLast(lut); lut = new AliTRDptrgLUT(); this->fLUTArray.AddLast(lut); // the following lines are only needed for test reasons Int_t* initData = new Int_t[256]; // 2^8 lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(0)); if (lut) { for (Int_t i = 0; i < 256; i++ ) { initData[i] = i; } lut->InitTable(8, 8, initData, kTRUE); // make copy of initData } lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(1)); if (lut) { for (Int_t i = 255; i >= 0; i--) { initData[255 - i] = i; // inverse ramp } lut->InitTable(8, 8, initData, kTRUE); } delete [] initData; } else { // initialize threshold this->fThreshold = new UInt_t[12]; for (Int_t i = 0; i < 12; i++) { this->fThreshold[i] = 10; } // initialize LUTsoutputWidth=<value optimized out> AliTRDptrgLUT* lut = new AliTRDptrgLUT(); this->fLUTArray.AddLast(lut); lut = new AliTRDptrgLUT(); // this->fRunLoader this->fLUTArray.AddLast(lut); // the following lines are only needed for test reasons lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(0)); Int_t* initData = new Int_t[4096]; // 2^12 if (lut) { for (Int_t i = 0; i < 4096; i++ ) { initData[i] = i; } lut->InitTable(12, 12, initData, kTRUE); // make a copy of the table } lut = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray.At(1)); if (lut) { //for (Int_t i = 4095; i >= 0; i--) { for (Int_t i = 4096; i > 0; i--) { initData[4096 - i] = i; // inverse ramp } lut->InitTable(12, 12, initData, kTRUE); // make a copy of the table } delete [] initData; } return false; } else { // load parameters from object if (this->fType == AliTRDptrgParam::kVZERO) { // threshold this->fThreshold = this->fParam->GetFEBV0Thresholds(this->fPosition, (this->fID - 1)); // look up tables // 1 AliTRDptrgLUT* LUT = new AliTRDptrgLUT(); LUT->InitTable(8, 8, this->fParam->GetFEBV0LUT(this->fPosition, (this->fID - 1), 0), kFALSE); // do not make a copy of the table due to performance reasons this->fLUTArray.AddLast(LUT); // 2 LUT = new AliTRDptrgLUT(); LUT->InitTable(8, 8, this->fParam->GetFEBV0LUT(this->fPosition, (this->fID - 1), 1), kFALSE); // do not make a copy of the table due to performance reasons this->fLUTArray.AddLast(LUT); } else { // threshold this->fThreshold = this->fParam->GetFEBT0Thresholds(this->fPosition); // look up tables // 1 AliTRDptrgLUT* LUT = new AliTRDptrgLUT(); LUT->InitTable(12, 12, fParam->GetFEBT0LUT(this->fPosition, 0), kFALSE); // do not make a copy of the table due to performance reasosn this->fLUTArray.AddLast(LUT); // 2 LUT = new AliTRDptrgLUT(); LUT->InitTable(12, 12, fParam->GetFEBT0LUT(this->fPosition, 1), kFALSE); // do not make a copy of the table due to performance reasosn this->fLUTArray.AddLast(LUT); } return true; } return false; } //______________________________________________________________________________ Int_t* AliTRDptrgFEB::Simulate() { // simulates the FEB behavior and returns a 2 bit ouput // (least significant bits) Int_t *result = new Int_t; (*result) = -1; if (this->fOperatingMode == AliTRDptrgParam::kDigits) { Int_t inputVector = this->LoadDigits(); delete result; // delete error return value // perform look up Int_t nLUTs = this->fLUTArray.GetEntriesFast(); // get LUT count result = new Int_t[nLUTs + 1]; // generate new return array result[0] = nLUTs; // storage array length in the first array value for (Int_t iLUT = 0; iLUT < nLUTs; iLUT++) { // process the return value for each LUT and store the result in the array AliDebug(4, Form("FEB: (pos=%d,id=%d,lut=%d,vector=0x%x)", this->fPosition, this->fID, iLUT, inputVector)); AliTRDptrgLUT *lutTmp = dynamic_cast<AliTRDptrgLUT*>(this->fLUTArray[iLUT]); if (lutTmp) { result[iLUT + 1] = lutTmp->LookUp(inputVector); } AliDebug(4, Form("FEB result[%d] = 0x%x",(iLUT + 1),result[iLUT + 1])); } } else if (this->fOperatingMode == AliTRDptrgParam::kHits) { return result; } return result; }
14,579
5,011
// // TM & (c) 2017 Lucasfilm Entertainment Company Ltd. and Lucasfilm Ltd. // All rights reserved. See LICENSE.txt for license. // #include <MaterialXTest/Catch/catch.hpp> #include <MaterialXCore/Document.h> namespace mx = MaterialX; TEST_CASE("Document", "[document]") { // Create a document. mx::DocumentPtr doc = mx::createDocument(); // Create a node graph with a constant color output. mx::NodeGraphPtr nodeGraph = doc->addNodeGraph(); mx::NodePtr constant = nodeGraph->addNode("constant"); constant->setParameterValue("value", mx::Color3(0.5f, 0.5f, 0.5f)); mx::OutputPtr output = nodeGraph->addOutput(); output->setConnectedNode(constant); REQUIRE(doc->validate()); // Create and test a type mismatch. output->setType("float"); REQUIRE(!doc->validate()); output->setType("color3"); REQUIRE(doc->validate()); // Test hierarchical name paths. REQUIRE(constant->getNamePath() == "nodegraph1/node1"); REQUIRE(constant->getNamePath(nodeGraph) == "node1"); // Create a simple shader interface. mx::NodeDefPtr shader = doc->addNodeDef("", "surfaceshader", "simpleSrf"); mx::InputPtr diffColor = shader->addInput("diffColor", "color3"); mx::InputPtr specColor = shader->addInput("specColor", "color3"); mx::ParameterPtr roughness = shader->addParameter("roughness", "float"); // Create a material that instantiates the shader. mx::MaterialPtr material = doc->addMaterial(); mx::ShaderRefPtr shaderRef = material->addShaderRef("", "simpleSrf"); // Bind the diffuse color input to the constant color output. mx::BindInputPtr bindInput = shaderRef->addBindInput("diffColor"); bindInput->setConnectedOutput(output); REQUIRE(diffColor->getUpstreamElement(material) == output); // Create a collection mx::CollectionPtr collection = doc->addCollection(); REQUIRE(doc->getCollections().size() == 1); REQUIRE(doc->getCollection(collection->getName())); doc->removeCollection(collection->getName()); REQUIRE(doc->getCollections().size() == 0); // Create a property set mx::PropertySetPtr propertySet = doc->addPropertySet(); REQUIRE(doc->getPropertySets().size() == 1); REQUIRE(doc->getPropertySet(propertySet->getName()) != nullptr); doc->removePropertySet(propertySet->getName()); REQUIRE(doc->getPropertySets().size() == 0); // Generate and verify require string. doc->generateRequireString(); REQUIRE(doc->getRequireString().find(mx::Document::REQUIRE_STRING_MATNODEGRAPH) != std::string::npos); // Validate the document. REQUIRE(doc->validate()); // Copy and reorder the document. mx::DocumentPtr doc2 = doc->copy(); REQUIRE(*doc2 == *doc); int origIndex = doc2->getChildIndex(shader->getName()); doc2->setChildIndex(shader->getName(), origIndex + 1); REQUIRE(*doc2 != *doc); doc2->setChildIndex(shader->getName(), origIndex); REQUIRE(*doc2 == *doc); REQUIRE_THROWS_AS(doc2->setChildIndex(shader->getName(), 100), mx::Exception); // Create and test an orphaned element. mx::ElementPtr orphan; { mx::DocumentPtr doc3 = doc->copy(); for (mx::ElementPtr elem : doc3->traverseTree()) { if (elem->isA<mx::Node>("constant")) { orphan = elem; } } REQUIRE(orphan); } REQUIRE_THROWS_AS(orphan->getDocument(), mx::ExceptionOrphanedElement); }
3,482
1,132
#include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> using namespace std; string SRC = "src/"; string WG_SRC = SRC + "webgraph/"; struct Execution{ FILE* f; int retCode; Execution(FILE* f, int retCode){ this->f = f; this->retCode = retCode; } }; bool startswith(const string& path, const string& st){ return path.substr(0, st.size()) == st; } void help(){ cout << "Usage: ./fhgc <command>" << endl; cout << "Valid commands:" << endl << " create-dataset <dataset-in>/<raw-data> <dataset-out> [options]" << endl << " clusters faststep/louvain/LLP <dataset> <output-folder> [options]" << endl << " labels faststep/louvain/LLP <dataset> <output-file> [options]" << endl << " clusterings2labels <dataset> <clusterings-prefix> <output-file> [options]" << endl << " reorder <dataset-in> <dataset-out> <indexes>" << endl << " compare-clusters <cluster-file-1> <cluster-file-2> [options]" << endl << " compare-clusters-list <regex-clusters-1> <regex-clusters-2> [options]" << endl << " size <dataset> [<more datasets>]" << endl << " countClusters <cluster-file>" << endl << " help" << endl; } void readfile(FILE* f){ const int SIZE = 1000; char str[SIZE+1]; while(fgets(str, SIZE, f) != NULL){ cout << str; } } void readfile(FILE* f, ofstream& ost){ const int SIZE = 1000; char str[SIZE+1]; while(fgets(str, SIZE, f) != NULL){ ost << str; cout << str; } ost.close(); } Execution exec(string s){ FILE* f; f = popen(s.c_str(), "r"); readfile(f); int ret = pclose(f); return Execution(f, ret); } Execution exec(string s, ofstream& ost){ FILE* f; f = popen(s.c_str(), "r"); readfile(f, ost); int ret = pclose(f); return Execution(f, ret); } void ls(string path, vector<string>& files){ string s = string("ls -1 ") + path; FILE* f; f = popen(s.c_str(), "r"); const int SIZE = 1000; char str[SIZE+1]; while(fgets(str, SIZE, f) != NULL){ string fname(str); fname = fname.substr(0, fname.size()-1); files.push_back(fname); } } string join(vector<string>& l, string d){ string s; for(int i=0; i<(int)l.size()-1; i++) s += l[i] + d; s += l[l.size()-1]; return s; } int main(int argc, char** argv){ if(argc < 2){ help(); return 0; } string command = argv[1]; if(command == "create-dataset"){ if(argc < 4){ cout << "Usage: ./fhgc create-dataset" << endl << " create-dataset <raw-data> <dataset-out> [options]" << endl << "<raw-data>: file with one line per edge of the graph, with two integers per line." << endl << " By default, the vertex indexes start at one and the edges are considered undirected." << endl << "[options]:" << endl << " --shuffle: randomly shuffle the indexes of the vertices of the graph" << endl << " --sub0: assume that indexes of nodes of the input start at zero" << endl << " --directed: the edges are considered as directed links" << endl; return 1; }else{ string s = WG_SRC + string("create-dataset.new.sh "); for(int i=2; i<argc; i++){ s += argv[i]; s += " "; } cout << "Running: " << s << endl; int ret = exec(s).retCode; if(ret != 0) return 1; } }else if(command == "clusters" || command == "labels"){ bool CLUSTERS = false; if(command == "clusters") CLUSTERS = true; if(argc < 5){ cout << "Usage: ./fhgc " << command << endl; if(CLUSTERS) cout << " " << command << " faststep/louvain/LLP <dataset> <output-folder> [options]" << endl; else cout << " " << command << " faststep/louvain/LLP <dataset> <output-file> [options]" << endl; return 1; }else{ string method = argv[2]; string s; if(method == "LLP"){ s = WG_SRC + string("LLP.sh "); if(CLUSTERS) s += argv[3] + string(" /tmp/labels.txt -l ") + argv[4] + "/communities"; else s += argv[3] + string(" ") + argv[4]; }else if(method == "faststep"){ s = WG_SRC + string("faststep.sh "); if(CLUSTERS) s += argv[3] + string(" -c ") + argv[4]; else s += argv[3] + string(" ") + argv[4]; }else if(method == "louvain"){ s = WG_SRC + string("louvain.sh "); if(CLUSTERS) s += argv[3] + string(" -c ") + argv[4]; else s += argv[3] + string(" ") + argv[4]; }else{ cout << "Invalid method " << method << endl; return 1; } cout << "Running: " << s << endl; int ret = exec(s).retCode; if(ret != 0) cout << "Method failed with error: " << ret << endl; return ret != 0; } }else if(command == "reorder"){ if(argc < 5){ cout << "Usage: ./fhgc " << command << endl; cout << " reorder <dataset-in> <dataset-out> <indexes>" << endl; return 1; }else{ string s = WG_SRC + "transform.sh " + argv[2] + " " + argv[3] + " " + argv[4]; return exec(s).retCode; } }else if(command == "compare-clusters"){ if(argc < 4){ cout << "Usage: ./fhgc compare-clusters" << endl << " compare-clusters <cluster-file-1> <cluster-file-2>" << endl; return 1; }else{ string s = WG_SRC + "compareClusters " + argv[2] + " " + argv[3]; if(argc >= 5) s += string(" ") + argv[4]; cout << s << endl; return exec(s).retCode; } }else if(command == "compare-clusters-list"){ if(argc < 4){ cout << "Usage: ./fhgc compare-clusters-list" << endl << " <file-list-1> <file-list-2> [<more-file-lists>]" << endl << "[options]:" << endl << " --matrix <method1> <method2>: print the results in matrix form. Accepted values for method1 and method2 are \"LLP\", \"Louvain\" or \"Faststep\" " << endl; return 1; } bool printMatrix = false; bool genImage = false; string method1, method2; vector<vector<string> > filelists; string args = "--nmi"; for(int i=2; i<argc; i++){ if(startswith(argv[i], "--")){ if(string(argv[i]) == "--matrix"){ if(i+2 >= argc){ cout << "--matrix option expects the method names" << endl; return 1; } cout << "Printing matrix of results for methods " << argv[i+1] << " and " << argv[i+2] << endl; method1 = argv[i+1]; method2 = argv[i+2]; i += 2; printMatrix = true; }else if(string(argv[i]) == "--jaccard"){ args = "--jaccard"; }else if(string(argv[i]) == "--nmi"){ args = "--nmi"; }else if(string(argv[i]) == "--all-jaccards"){ args = "--all-jaccards"; }else if(string(argv[i]) == "--onmi"){ args = "--onmi"; }else if(string(argv[i]) == "--image"){ genImage = true; } }else{ string s = string("ls -1 ") + argv[i]; FILE* f; f = popen(s.c_str(), "r"); const int SIZE = 1000; char str[SIZE+1]; filelists.resize(filelists.size()+1); while(fgets(str, SIZE, f) != NULL){ string fname(str); fname = fname.substr(0, fname.size()-1); filelists[filelists.size()-1].push_back(fname); } } } string s = WG_SRC + "comparisonMatrix " + args + " "; for(int i=0; i<(int)filelists.size(); i++){ s += "\""; for(int j=0; j<(int)filelists[i].size(); j++){ s += filelists[i][j]; if(j<(int)filelists[i].size() - 1) s += "|"; } s += "\""; s += " "; } if(!printMatrix){ return exec(s).retCode; }else{ ofstream out("/tmp/comp.txt"); out << method1 << " with " << method2 << endl; int r = exec(s, out).retCode; if(r != 0) return r; string outputImage = ""; if(genImage) outputImage = " --image"; return exec(string("python ") + WG_SRC + "genCompMatrix.py /tmp/comp.txt" + outputImage).retCode; } }else if(command == "size"){ if(argc < 3){ cout << "Usage: ./fhgc size" << endl << " size <dataset> [<more datasets>]" << endl; return 1; } bool showPercentage = false; string firstGraph; int firstSize = 1; vector<string> args; for(int i=2; i<argc; i++){ string arg = argv[i]; if(startswith(arg, "--")){ if(arg == "--percent") showPercentage = true; continue; } if(firstGraph == "") firstGraph = arg; args.push_back(arg); } for(int i=0; i<(int)args.size(); i++){ string arg = args[i]; string s = string("ls -s --block-size=KB ") + arg + string(".graph"); FILE* f; f = popen(s.c_str(), "r"); const int SIZE = 1000; char str[SIZE+1]; while(fgets(str, SIZE, f) != NULL){ stringstream ss(str); string s1, s2; ss >> s1 >> s2; int fSize; istringstream(s1.substr(0, s1.size()-2)) >> fSize; if(firstGraph == arg) firstSize = fSize; if(showPercentage && firstGraph != arg) cout << arg << ": " << s1 << " " << 100 * (1.0 - (double)fSize / firstSize) << endl; else cout << arg << ": " << s1 << endl; } } }else if(command == "clusterings2labels"){ if(argc < 5){ cout << "Usage: ./fhgc clusterings2labels" << endl << " clusterings2labels <dataset> <clusterings-prefix> <output-file> [--hierarchical]" << endl << " - Generates a reordering for the graph using external data, either clusterings with multiple levels of granularity or hierarchical clusterings" << endl << endl << "Parameters:" << endl << " - <clusterings-prefix>: the prefix of the files containing the clusterings," << "e.g., \"communities-\" which corresponds to \"communities-0.txt\", \"communities-1.txt\", \"communities-2.txt\", etc. (files must start at zero and any file suffix is accepted)" << endl << " - --hierarchical: assumes that the communities are hierarchical" << endl; return 1; } vector<string> files; string prefix = argv[3]; ls(string(" ") + prefix + "*", files); vector<string> ordered(files.size()); int useOrder = true; for(int i=0; i<(int)files.size(); i++){ cout << files[i] << endl; string e = files[i].substr(prefix.size(), string::npos); stringstream ss(e); int n; ss >> n; if(n < (int) ordered.size()) ordered[n] = files[i]; else useOrder = false; } for(int i=0; i<(int)ordered.size(); i++) if(ordered[i].size() == 0){ useOrder = false; break; } string clusters = ""; if(useOrder){ clusters = join(ordered, ","); cout << "Using ordered clusterings" << endl; }else{ clusters = join(files, ","); cout << "Can't use ordered clusterings" << endl; } string s = string("java -cp src/law+faststep/jars/runtime/'*':src/law+faststep/build it.unimi.dsi.law.graph.LayeredLabelPropagation ") + argv[2] + " " + argv[4] + " -l my-labels --inClusters " + clusters; exec(s); s = string("src/webgraph/labels2txt.sh ") + argv[4] + string("; mv ") + argv[4] + string(".txt ") + argv[4]; exec(s); }else if(command == "countClusters"){ if(argc < 3){ cout << "Usage: ./fhgc countClusters" << endl << " countClusters <clusters-file>" << endl; return 1; } return exec(WG_SRC + "countClusters " + argv[2]).retCode; }else if(command == "help"){ help(); }else{ cout << "Invalid command" << endl; help(); } return 0; }
10,937
4,819
/* * Copyright (c) Meta, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include "gtn/gtn.h" using namespace gtn; using namespace gtn::criterion; namespace py = pybind11; using namespace py::literals; PYBIND11_MODULE(_criterions, m) { m.def( "ctc_loss", [](const Graph& logProbs, const std::vector<int>& target, int blankIdx) { py::gil_scoped_release release; return ctcLoss(logProbs, target, blankIdx); }, "log_probs"_a, "target"_a, "blank_idx"_a); }
680
258
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file depthWriteAttrib.cxx * @author drose * @date 2002-03-04 */ #include "depthWriteAttrib.h" #include "graphicsStateGuardianBase.h" #include "dcast.h" #include "bamReader.h" #include "bamWriter.h" #include "datagram.h" #include "datagramIterator.h" TypeHandle DepthWriteAttrib::_type_handle; int DepthWriteAttrib::_attrib_slot; /** * Constructs a new DepthWriteAttrib object. */ CPT(RenderAttrib) DepthWriteAttrib:: make(DepthWriteAttrib::Mode mode) { DepthWriteAttrib *attrib = new DepthWriteAttrib(mode); return return_new(attrib); } /** * Returns a RenderAttrib that corresponds to whatever the standard default * properties for render attributes of this type ought to be. */ CPT(RenderAttrib) DepthWriteAttrib:: make_default() { return return_new(new DepthWriteAttrib); } /** * */ void DepthWriteAttrib:: output(std::ostream &out) const { out << get_type() << ":"; switch (get_mode()) { case M_off: out << "off"; break; case M_on: out << "on"; break; } } /** * Intended to be overridden by derived DepthWriteAttrib types to return a * unique number indicating whether this DepthWriteAttrib is equivalent to the * other one. * * This should return 0 if the two DepthWriteAttrib objects are equivalent, a * number less than zero if this one should be sorted before the other one, * and a number greater than zero otherwise. * * This will only be called with two DepthWriteAttrib objects whose get_type() * functions return the same. */ int DepthWriteAttrib:: compare_to_impl(const RenderAttrib *other) const { const DepthWriteAttrib *ta = (const DepthWriteAttrib *)other; return (int)_mode - (int)ta->_mode; } /** * Intended to be overridden by derived RenderAttrib types to return a unique * hash for these particular properties. RenderAttribs that compare the same * with compare_to_impl(), above, should return the same hash; RenderAttribs * that compare differently should return a different hash. */ size_t DepthWriteAttrib:: get_hash_impl() const { size_t hash = 0; hash = int_hash::add_hash(hash, (int)_mode); return hash; } /** * Tells the BamReader how to create objects of type DepthWriteAttrib. */ void DepthWriteAttrib:: register_with_read_factory() { BamReader::get_factory()->register_factory(get_class_type(), make_from_bam); } /** * Writes the contents of this object to the datagram for shipping out to a * Bam file. */ void DepthWriteAttrib:: write_datagram(BamWriter *manager, Datagram &dg) { RenderAttrib::write_datagram(manager, dg); dg.add_int8(_mode); } /** * This function is called by the BamReader's factory when a new object of * type DepthWriteAttrib is encountered in the Bam file. It should create the * DepthWriteAttrib and extract its information from the file. */ TypedWritable *DepthWriteAttrib:: make_from_bam(const FactoryParams &params) { DepthWriteAttrib *attrib = new DepthWriteAttrib; DatagramIterator scan; BamReader *manager; parse_params(params, scan, manager); attrib->fillin(scan, manager); return attrib; } /** * This internal function is called by make_from_bam to read in all of the * relevant data from the BamFile for the new DepthWriteAttrib. */ void DepthWriteAttrib:: fillin(DatagramIterator &scan, BamReader *manager) { RenderAttrib::fillin(scan, manager); _mode = (Mode)scan.get_int8(); }
3,659
1,183
#pragma once #include "../pch.h" #include "../gstd/GstdLib.hpp" #include "DxTypes.hpp" #if defined(DNH_PROJ_EXECUTOR) #include "Vertex.hpp" #endif
149
68
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/service/memory_space_assignment_utils.h" #include "tensorflow/compiler/xla/service/hlo_casting_utils.h" #include "tensorflow/compiler/xla/service/hlo_instructions.h" namespace xla { bool MemorySpaceAssignmentUtils::IsValueAllowedInAlternateMemory( const HloValue* value) { // If the buffer is a tuple, don't use this algorithm for now. The buffers // that are pointed to by the tuple will still use this algorithm. Because // tuples are cheap to place in the alternate memory (they are just pointers) // we don't need to use prefetch/evict logic. if (value->shape().IsTuple()) { VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it is a tuple."; return false; } // Don't place scalars in the alternate memory. if (ShapeUtil::IsEffectiveScalar(value->shape())) { VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it is a scalar."; return false; } // The semantics of TupleSelect are weird: TupleSelect doesn't define a // buffer, but just forwards the buffers in the either left or right side. // This means the two different inputs to TupleSelect must not alias, yet they // should be allocated in the same memory space, and both buffers must be kept // alive for the entire live range of TupleSelect. Instead, just don't // allocate TupleSelect in the alternate memory space. // TODO(berkin): Not allocating add-dependencies either since they need to be // treated specially. We should revisit this later. for (const HloPosition& position : value->positions()) { if (position.instruction->opcode() == HloOpcode::kTupleSelect || position.instruction->opcode() == HloOpcode::kAddDependency) { VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it has a tuple-select or " << "add-dependency position."; return false; } } // Send and Recv HLOs return a request identifier. These should not be // allocated in the alternate memory. for (const HloPosition& position : value->positions()) { if ((position.instruction->opcode() == HloOpcode::kSend || position.instruction->opcode() == HloOpcode::kRecv) && DynCast<HloSendRecvInstruction>(position.instruction) ->is_host_transfer()) { // TODO(berkin): Host transfers using alternate memory space doesn't seem // to work at the moment. VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it is a send/recv buffer used for " "host transfer."; return false; } if (auto* custom_call = DynCast<HloCustomCallInstruction>(position.instruction)) { for (const auto& pair : custom_call->output_to_operand_aliasing()) { if (position.index == pair.first) { VLOG(4) << "Keeping value " << value->ToShortString() << " in default mem because it is a custom-call output that " "aliases an operand buffer."; return false; } } } } return true; } bool MemorySpaceAssignmentUtils::IsIntervalAllowedInAlternateMemory( const GlobalDecreasingSizeBestFitHeap<HloValue>::BufferInterval& interval) { return IsValueAllowedInAlternateMemory(interval.buffer) && absl::c_all_of(interval.colocations, IsValueAllowedInAlternateMemory); } /*static*/ void MemorySpaceAssignmentUtils::HoistConstantOperations( HloModule& module) { CHECK(module.has_schedule()); HloSchedule& schedule = module.schedule(); for (const HloComputation* computation : module.MakeNonfusionComputations()) { CHECK(schedule.is_computation_scheduled(computation)); const HloInstructionSequence& sequence = schedule.sequence(computation); // Conservatively don't modify the schedule if any instruction has a control // successor or predecessor on a constant op. Computations with these // dependencies should be very rare anyway. bool contains_constant_successor_or_predecessors = false; for (HloInstruction* instruction : sequence.instructions()) { if (instruction->opcode() == HloOpcode::kConstant) { contains_constant_successor_or_predecessors |= !instruction->control_predecessors().empty(); contains_constant_successor_or_predecessors |= !instruction->control_successors().empty(); } else { auto is_constant = [](const HloInstruction* inst) { return inst->opcode() == HloOpcode::kConstant; }; contains_constant_successor_or_predecessors |= absl::c_find_if(instruction->control_predecessors(), is_constant) != instruction->control_predecessors().end(); contains_constant_successor_or_predecessors |= absl::c_find_if(instruction->control_successors(), is_constant) != instruction->control_successors().end(); } } if (contains_constant_successor_or_predecessors) { continue; } HloInstructionSequence new_sequence; for (HloInstruction* instruction : sequence.instructions()) { if (instruction->opcode() == HloOpcode::kConstant) { new_sequence.push_back(instruction); } } for (HloInstruction* instruction : sequence.instructions()) { if (instruction->opcode() != HloOpcode::kConstant) { new_sequence.push_back(instruction); } } CHECK_EQ(new_sequence.size(), sequence.size()); schedule.set_sequence(computation, new_sequence); } } } // namespace xla
6,307
1,819
/****************************************************************************** * Copyright (c) 2020, Intel Corporation. All rights reserved. * * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception. * *****************************************************************************/ #include "sct_assert.h" #include "systemc.h" #include <iostream> using namespace sc_core; // Record array elements as function parameters class A : public sc_module { public: sc_in<sc_uint<2>> a{"a"}; sc_signal<sc_uint<2>> as{"as"}; sc_in<sc_int<2>> as_i{"as_i"}; sc_signal<int> s{"s"}; SC_CTOR(A) { for (int i = 0; i < 3; i++) { spp[i] = new sc_signal<int>(""); } SC_METHOD(rec_arr_elem_func_param_val); sensitive << s; SC_METHOD(rec_arr_elem_func_param_val2); sensitive << s; SC_METHOD(rec_arr_elem_func_param_val3); sensitive << s; SC_METHOD(rec_arr_elem_func_param_ref); sensitive << s; SC_METHOD(rec_arr_elem_func_param_ref2); sensitive << s; SC_METHOD(rec_arr_elem_func_param_ref3); sensitive << s; SC_METHOD(arr_elem_in_index); sensitive << s << srr[0] << *spp[0]; // TODO: Fix me, #99 //SC_METHOD(rec_arr_elem_in_index); //sensitive << s; /*SC_METHOD(record_var_if); sensitive << a << as << as_i << s; SC_METHOD(record_var_if_bitwise); sensitive << a << as << as_i << s; SC_METHOD(record_var_if_arith); sensitive << a << as << as_i << s;*/ } //--------------------------------------------------------------------------- struct MyRec { sc_int<2> a; sc_uint<4> b; }; void f1(MyRec par) { int k = par.b; } int f1_two(MyRec par1, MyRec par2) { return (par1.b + par2.b); } // Record array element as function parameter by value void rec_arr_elem_func_param_val() { MyRec sr; f1(sr); MyRec sra[3]; f1(sra[1]); int i = s.read(); f1(sra[i]); } // Two record array elements as function parameters by value void rec_arr_elem_func_param_val2() { MyRec xr, yr; f1_two(xr, yr); MyRec xra[3]; MyRec yra[2]; f1_two(xra[2], yra[1]); f1_two(xra[2], xra[1]); f1_two(xra[2], xra[2]); f1_two(xra[2], yr); int i = f1_two(yr, xra[1]); } // Record array element at unknown index as function parameters by value void rec_arr_elem_func_param_val3() { int i = s.read(); MyRec qr; MyRec qra[3]; f1_two(qra[i], qra[i]); f1_two(qr, qra[i+1]); if (i) { f1_two(qra[i-1], qr); } else { if (i == 1) f1(qra[i]); } } //----------------------------------------------------------------------------- void f2(MyRec& par) { int k = par.b; } void f2_two(MyRec& par1, MyRec& par2) { int k = par1.b + par2.b; } int f2_two_cond(MyRec& par1, bool a, MyRec& par2) { return (a ? par1.b : par2.b); } // Record array element as function parameter by reference void rec_arr_elem_func_param_ref() { MyRec vr[3]; f2(vr[1]); int i = s.read(); f2(vr[i]); } // Two record array elements as function parameters by reference void rec_arr_elem_func_param_ref2() { MyRec er[3]; MyRec fr; f2_two(fr, er[2]); f2_two(er[1], er[2]); f2_two(er[1], er[1]); bool a; int i = s.read(); a = f2_two_cond(er[i], true, fr); f2_two_cond(er[i+1], a, er[i+1]); } int f3_val(sc_uint<4> par) { return (par+1); } int f3_ref(sc_uint<4>& par) { par++; return par; } // Record array elements as function parameters in IF, passed by reference void rec_arr_elem_func_param_ref3() { MyRec err[3]; MyRec frr; int i = s.read(); frr.a = f3_val(err[i].b); frr.a = f3_ref(err[i+1].b); f2_two(err[i], err[frr.a]); } // Use record array element as index for the same array sc_signal<int> srr[3]; sc_signal<int>* spp[3]; void arr_elem_in_index() { int i = s.read(); int irr[3]; irr[irr[1]] = 1; irr[irr[i]] = irr[i+1]; srr[srr[1]] = 1; srr[srr[i]] = srr[srr[i+1]+1]; *spp[spp[1]->read()] = 1; *spp[*spp[1]] = 1; *spp[*spp[i]] = *spp[i+*spp[i+1]]; } void rec_arr_elem_in_index() { MyRec err[3]; err[err[1].b].a = 1; } //----------------------------------------------------------------------------- // Function with records struct Simple { int a; sc_uint<2> b; Simple(): a(1){ } int geta(){ return a; } void seta(int bval){ a = bval; } }; struct Simple_arith { sc_uint<32> a; sc_uint<16> b; Simple_arith(): a(30), b(15){ } sc_uint<32> geta(){ return a; } sc_uint<32> getaplusb(){ return a + b; } sc_uint<32> getaminusb(){ return a - b; } sc_uint<32> getamultb(){ return a * b; } sc_uint<32> getadivb(){ return a / b; } sc_uint<32> getamodb(){ return a % b; } void seta(sc_uint<32> aval){ a = aval; } void setb(sc_uint<16> bval){ b = bval; } }; struct Simple_bitwise { sc_uint<32> a; sc_uint<16> b; Simple_bitwise(): a(30), b(15){ } sc_uint<32> geta(){ return a; } void seta(sc_uint<32> aval){ a = aval; } void setb(sc_uint<16> bval){ b = bval; } sc_uint<32> getaorb(){ return a | b; } sc_uint<32> getaandb(){ return a & b; } sc_uint<32> getnota(){ return !a; } sc_uint<32> getaxorb(){ return a ^ b; } sc_uint<32> getalorb(){ return a || b; } sc_uint<32> getalandb(){ return a && b; } }; Simple rec[16]; Simple_arith reca[16]; Simple_bitwise recb[16]; void record_var_if() { int num1 = 0; int num2 = 1; int val1 = 0; if (num1==0) { rec[num1].seta(val1); } else { rec[num1].seta(1); } if (num2!=1) { rec[num2].seta(0); } else { rec[num2].seta(1); } //cout << "rec[0] = "<< rec[0].a << endl; //cout << "rec[1] = "<< rec[1].a << endl; sct_assert_const(rec[0].geta()==0); sct_assert_const(rec[1].geta()==1); if (as_i.read()==0) { rec[as_i.read()].seta(35); rec[s.read()].seta(45); } else { rec[as_i.read()].seta(25); rec[s.read()].seta(50); } } void record_var_if_arith() { reca[0].seta(16); reca[0].setb(5); sct_assert_const(reca[0].getaplusb()== 21); sct_assert_const(reca[0].getaminusb()== 11); sct_assert_const(reca[0].getamultb()== 80); sct_assert_const(reca[0].getadivb()== 3); sct_assert_const(reca[0].getamodb()== 1); for(int i=0; i<17; i++) { reca[i].seta(i*3); reca[i].setb(i*2+2); //cout << "sc_assert (reca[" << i << "].getaplusb() == " << reca[i].getaplusb() << ");" << endl; //cout << "sc_assert (reca[" << i << "].getaminusb() == " << reca[i].getaminusb() << ");" << endl; //cout << "sc_assert (reca[" << i << "].getamultb() == " << reca[i].getamultb() << ");" << endl; //cout << "sc_assert (reca[" << i << "].getadivb() == " << reca[i].getadivb() << ");" << endl; //cout << "sc_assert (reca[" << i << "].getamodb() == " << reca[i].getamodb() << ");" << endl; } sc_assert (reca[0].getaplusb() == 2); sc_assert (reca[0].getaminusb() == 4294967294); sc_assert (reca[0].getamultb() == 0); sc_assert (reca[0].getadivb() == 0); sc_assert (reca[0].getamodb() == 0); sc_assert (reca[1].getaplusb() == 7); sc_assert (reca[1].getaminusb() == 4294967295); sc_assert (reca[1].getamultb() == 12); sc_assert (reca[1].getadivb() == 0); sc_assert (reca[1].getamodb() == 3); sc_assert (reca[2].getaplusb() == 12); sc_assert (reca[2].getaminusb() == 0); sc_assert (reca[2].getamultb() == 36); sc_assert (reca[2].getadivb() == 1); sc_assert (reca[2].getamodb() == 0); sc_assert (reca[3].getaplusb() == 17); sc_assert (reca[3].getaminusb() == 1); sc_assert (reca[3].getamultb() == 72); sc_assert (reca[3].getadivb() == 1); sc_assert (reca[3].getamodb() == 1); sc_assert (reca[4].getaplusb() == 22); sc_assert (reca[4].getaminusb() == 2); sc_assert (reca[4].getamultb() == 120); sc_assert (reca[4].getadivb() == 1); sc_assert (reca[4].getamodb() == 2); sc_assert (reca[5].getaplusb() == 27); sc_assert (reca[5].getaminusb() == 3); sc_assert (reca[5].getamultb() == 180); sc_assert (reca[5].getadivb() == 1); sc_assert (reca[5].getamodb() == 3); sc_assert (reca[6].getaplusb() == 32); sc_assert (reca[6].getaminusb() == 4); sc_assert (reca[6].getamultb() == 252); sc_assert (reca[6].getadivb() == 1); sc_assert (reca[6].getamodb() == 4); sc_assert (reca[7].getaplusb() == 37); sc_assert (reca[7].getaminusb() == 5); sc_assert (reca[7].getamultb() == 336); sc_assert (reca[7].getadivb() == 1); sc_assert (reca[7].getamodb() == 5); sc_assert (reca[8].getaplusb() == 42); sc_assert (reca[8].getaminusb() == 6); sc_assert (reca[8].getamultb() == 432); sc_assert (reca[8].getadivb() == 1); sc_assert (reca[8].getamodb() == 6); sc_assert (reca[9].getaplusb() == 47); sc_assert (reca[9].getaminusb() == 7); sc_assert (reca[9].getamultb() == 540); sc_assert (reca[9].getadivb() == 1); sc_assert (reca[9].getamodb() == 7); sc_assert (reca[10].getaplusb() == 52); sc_assert (reca[10].getaminusb() == 8); sc_assert (reca[10].getamultb() == 660); sc_assert (reca[10].getadivb() == 1); sc_assert (reca[10].getamodb() == 8); sc_assert (reca[11].getaplusb() == 57); sc_assert (reca[11].getaminusb() == 9); sc_assert (reca[11].getamultb() == 792); sc_assert (reca[11].getadivb() == 1); sc_assert (reca[11].getamodb() == 9); sc_assert (reca[12].getaplusb() == 62); sc_assert (reca[12].getaminusb() == 10); sc_assert (reca[12].getamultb() == 936); sc_assert (reca[12].getadivb() == 1); sc_assert (reca[12].getamodb() == 10); sc_assert (reca[13].getaplusb() == 67); sc_assert (reca[13].getaminusb() == 11); sc_assert (reca[13].getamultb() == 1092); sc_assert (reca[13].getadivb() == 1); sc_assert (reca[13].getamodb() == 11); sc_assert (reca[14].getaplusb() == 72); sc_assert (reca[14].getaminusb() == 12); sc_assert (reca[14].getamultb() == 1260); sc_assert (reca[14].getadivb() == 1); sc_assert (reca[14].getamodb() == 12); sc_assert (reca[15].getaplusb() == 77); sc_assert (reca[15].getaminusb() == 13); sc_assert (reca[15].getamultb() == 1440); sc_assert (reca[15].getadivb() == 1); sc_assert (reca[15].getamodb() == 13); sc_assert (reca[16].getaplusb() == 82); sc_assert (reca[16].getaminusb() == 14); sc_assert (reca[16].getamultb() == 1632); sc_assert (reca[16].getadivb() == 1); sc_assert (reca[16].getamodb() == 14); } void record_var_if_bitwise() { for(int i=0; i<17; i++) { recb[i].seta(i*3); recb[i].setb(i*2+2); //cout << "sc_assert (recb[" << i << "].getaorb() == " << recb[i].getaorb() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getaandb() == " << recb[i].getaandb() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getnota() == " << recb[i].getnota() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getaxorb() == " << recb[i].getaxorb() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getalorb() == " << recb[i].getalorb() << ");" << endl; //cout << "sc_assert (recb[" << i << "].getalandb() == " << recb[i].getalandb() << ");" << endl; } sc_assert (recb[0].getaorb() == 2); sc_assert (recb[0].getaandb() == 0); sc_assert (recb[0].getnota() == 1); sc_assert (recb[0].getaxorb() == 2); sc_assert (recb[0].getalorb() == 1); sc_assert (recb[0].getalandb() == 0); sc_assert (recb[1].getaorb() == 7); sc_assert (recb[1].getaandb() == 0); sc_assert (recb[1].getnota() == 0); sc_assert (recb[1].getaxorb() == 7); sc_assert (recb[1].getalorb() == 1); sc_assert (recb[1].getalandb() == 1); sc_assert (recb[2].getaorb() == 6); sc_assert (recb[2].getaandb() == 6); sc_assert (recb[2].getnota() == 0); sc_assert (recb[2].getaxorb() == 0); sc_assert (recb[2].getalorb() == 1); sc_assert (recb[2].getalandb() == 1); sc_assert (recb[3].getaorb() == 9); sc_assert (recb[3].getaandb() == 8); sc_assert (recb[3].getnota() == 0); sc_assert (recb[3].getaxorb() == 1); sc_assert (recb[3].getalorb() == 1); sc_assert (recb[3].getalandb() == 1); sc_assert (recb[4].getaorb() == 14); sc_assert (recb[4].getaandb() == 8); sc_assert (recb[4].getnota() == 0); sc_assert (recb[4].getaxorb() == 6); sc_assert (recb[4].getalorb() == 1); sc_assert (recb[4].getalandb() == 1); sc_assert (recb[5].getaorb() == 15); sc_assert (recb[5].getaandb() == 12); sc_assert (recb[5].getnota() == 0); sc_assert (recb[5].getaxorb() == 3); sc_assert (recb[5].getalorb() == 1); sc_assert (recb[5].getalandb() == 1); sc_assert (recb[6].getaorb() == 30); sc_assert (recb[6].getaandb() == 2); sc_assert (recb[6].getnota() == 0); sc_assert (recb[6].getaxorb() == 28); sc_assert (recb[6].getalorb() == 1); sc_assert (recb[6].getalandb() == 1); sc_assert (recb[7].getaorb() == 21); sc_assert (recb[7].getaandb() == 16); sc_assert (recb[7].getnota() == 0); sc_assert (recb[7].getaxorb() == 5); sc_assert (recb[7].getalorb() == 1); sc_assert (recb[7].getalandb() == 1); sc_assert (recb[8].getaorb() == 26); sc_assert (recb[8].getaandb() == 16); sc_assert (recb[8].getnota() == 0); sc_assert (recb[8].getaxorb() == 10); sc_assert (recb[8].getalorb() == 1); sc_assert (recb[8].getalandb() == 1); sc_assert (recb[9].getaorb() == 31); sc_assert (recb[9].getaandb() == 16); sc_assert (recb[9].getnota() == 0); sc_assert (recb[9].getaxorb() == 15); sc_assert (recb[9].getalorb() == 1); sc_assert (recb[9].getalandb() == 1); sc_assert (recb[10].getaorb() == 30); sc_assert (recb[10].getaandb() == 22); sc_assert (recb[10].getnota() == 0); sc_assert (recb[10].getaxorb() == 8); sc_assert (recb[10].getalorb() == 1); sc_assert (recb[10].getalandb() == 1); sc_assert (recb[11].getaorb() == 57); sc_assert (recb[11].getaandb() == 0); sc_assert (recb[11].getnota() == 0); sc_assert (recb[11].getaxorb() == 57); sc_assert (recb[11].getalorb() == 1); sc_assert (recb[11].getalandb() == 1); sc_assert (recb[12].getaorb() == 62); sc_assert (recb[12].getaandb() == 0); sc_assert (recb[12].getnota() == 0); sc_assert (recb[12].getaxorb() == 62); sc_assert (recb[12].getalorb() == 1); sc_assert (recb[12].getalandb() == 1); sc_assert (recb[13].getaorb() == 63); sc_assert (recb[13].getaandb() == 4); sc_assert (recb[13].getnota() == 0); sc_assert (recb[13].getaxorb() == 59); sc_assert (recb[13].getalorb() == 1); sc_assert (recb[13].getalandb() == 1); sc_assert (recb[14].getaorb() == 62); sc_assert (recb[14].getaandb() == 10); sc_assert (recb[14].getnota() == 0); sc_assert (recb[14].getaxorb() == 52); sc_assert (recb[14].getalorb() == 1); sc_assert (recb[14].getalandb() == 1); sc_assert (recb[15].getaorb() == 45); sc_assert (recb[15].getaandb() == 32); sc_assert (recb[15].getnota() == 0); sc_assert (recb[15].getaxorb() == 13); sc_assert (recb[15].getalorb() == 1); sc_assert (recb[15].getalandb() == 1); sc_assert (recb[16].getaorb() == 50); sc_assert (recb[16].getaandb() == 32); sc_assert (recb[16].getnota() == 0); sc_assert (recb[16].getaxorb() == 18); sc_assert (recb[16].getalorb() == 1); sc_assert (recb[16].getalandb() == 1); } }; class B_top : public sc_module { public: sc_signal<sc_uint<2>> a{"a"}; sc_signal<sc_uint<2>> as{"as"}; sc_signal<sc_int<2>> as_i{"as_i"}; A a_mod{"a_mod"}; SC_CTOR(B_top) { a_mod.a(a); a_mod.as_i(as_i); } }; int sc_main(int argc, char *argv[]) { B_top b_mod{"b_mod"}; sc_start(); return 0; }
18,257
7,518
/* * File name: Folder.impl.hpp * Description: 文件夹类,用于捕捉所有文件夹下的非隐藏文件 * Author: 王锦润 * Version: 2 * Date: 2019.6.11 * History: 此程序被纳入git,可以直接使用git查询。 */ //防卫式声明,必须要有 //就算没有重复包含也建议有,这是代码习惯 #ifndef _FOLDER_IMPL_HPP_ #define _FOLDER_IMPL_HPP_ #include "Folder.hpp" #include <algorithm> #include <iostream> using std::cout; using std::endl; /* * Function: 构造函数 * Description: 构建文件夹,并搜索所有在文件夹下的文件 * Input: 文件路径 * Calls: _M_update_base, _M_update_ext */ Folder::Folder(const string &filedir) { _M_only_file = 0; //首先清空唯一文件属性 _M_update_base(filedir); //然后尝试更新文件夹路径 if (_M_only_file == 0 && _M_base_dir.size()) //如果更新成功,更新所有文件 _M_update_ext(""); //此处排序复杂度接近于线性,主要原因在于操作系统给出的文件句柄顺序 std::sort(_M_ext_dirs.begin(), _M_ext_dirs.end()); //排序使得有集合性质,方便调用差集,交集等集合运算 } /* * Function: print_everything * Description: 打印所有的文件路径 */ void Folder::print_everything() { cout << _M_only_file << endl; cout << _M_base_dir << endl; for (string ext_dir : _M_ext_dirs) cout << ext_dir << endl; } /* * Function: _M_update_base * Description: 检验文件/文件夹,如果为单个文件则同时更新basedir和extdir,如果不是则只更新basedir * Input: 文件路径filedir */ void Folder::_M_update_base(const string &filedir) { //首先清空文件属性 _M_base_dir.clear(); _M_ext_dirs.clear(); _finddata_t fileinfo; //C的结构体,用于访问文件系统 long hfile = 0; //文件句柄 if ((hfile = _findfirst(filedir.c_str(), &fileinfo)) != -1) //如果文件存在 { //如果是文件 if (fileinfo.attrib & _A_ARCH) { size_t pos = std::max(filedir.find_last_of('/') + 1, filedir.find_last_of('\\') + 1); _M_base_dir = filedir.substr(0, pos); //basedir更新 _M_ext_dirs.push_back(filedir.substr(pos)); //更新extdir _M_only_file = 1; } else if (fileinfo.attrib & _A_SUBDIR) { _M_base_dir = filedir; //更新文件夹 if (_M_base_dir.back() != '/' && _M_base_dir.back() != '\\') _M_base_dir.push_back('\\'); //如果没有则自动补全 } } //如果访问不到则啥都不做 else cout << "Wrong file or folder" << endl; } /* * Function: _M_update_base * Description: 检验文件/文件夹,如果为单个文件则同时更新basedir和extdir,如果不是则只更新basedir * Input: 文件路径filedir */ void Folder::_M_update_ext(const string &dir) { _finddata_t fileinfo; long hfile = 0; string p; if ((hfile = _findfirst(p.assign(_M_base_dir).append(dir).append("*").c_str(), &fileinfo)) != -1) //如果找到内容 { //按照文件更新 do { //如果是非隐藏文件夹则递归更新 if ((fileinfo.attrib & _A_SUBDIR) && (fileinfo.attrib & _A_HIDDEN) == 0) { //.和..是两个必备文件夹,..会递归到上层,需要避开 if (strcmp(fileinfo.name, ".") != 0 && strcmp(fileinfo.name, "..") != 0) _M_update_ext(p.assign(dir).append(fileinfo.name).append("\\")); } //如果是文件则加入文件 else if ((fileinfo.attrib & _A_HIDDEN) == 0) _M_ext_dirs.push_back(p.assign(dir).append(fileinfo.name)); } while (_findnext(hfile, &fileinfo) == 0); //句柄的用处 } } #endif
3,191
1,558
#ifdef IZENELIB_DRIVER_VALUE_INLINE /** * @file izenelib/driver/value/size.inl * @author Ian Yang * @date Created <2010-06-08 11:31:29> * @brief Gets size of a value */ namespace izenelib { namespace driver { namespace detail { class ValueSizeVisitor : public boost::static_visitor<std::size_t> { public: typedef std::size_t size_type; /// @brief Returns 1 for all singular value template<typename T> size_type operator()(const T&) const { return 1; } /// @brief Returns 0 for Null size_type operator()(const Value::NullType&) const { return 0; } /// @brief Gets size of Array size_type operator()(const Value::ArrayType& value) const { return value.size(); } /// @brief Gets size of Object size_type operator()(const Value::ObjectType& value) const { return value.size(); } }; } // namespace detail std::size_t Value::size() const { return boost::apply_visitor(detail::ValueSizeVisitor(), value_); } }} // namespace izenelib::driver #endif // IZENELIB_DRIVER_VALUE_INLINE
1,096
385
// Problema 18 - Fisa Gradinariu (TEMA) #include "pch.h" #include "fstream" #include "iostream" using namespace std; // ifstream fin("date.in"); // ofstream fout("date.out"); int index = 1, v[101], suma1, suma2, aux1, aux2; int main() { int x; cin >> x; while (x != 0) { v[index] = x; index++; cin >> x; } for (int i = 1; i < index; i++) { suma1 = 0; suma2 = 0; aux1 = v[i]; aux2 = v[i + 1]; while (aux1) { suma1 = suma1 + aux1 % 10; aux1 = aux1 / 10; } while (aux2) { suma2 = suma2 + aux2 % 10; aux2 = aux2 / 10; } if (suma1 % 2 == 0 && suma2 % 2 == 1) { cout << v[i] << " " << v[i + 1] << endl; } } return 0; }
667
370
/* Copyright © 2017 Ezer IT Consulting. * Released under an MIT License. */ #include <deque> #include <map> #include <string> #include <iostream> #include "util.hpp" #include "translit_handler.hpp" #include "hebrew_transliterator.hpp" using namespace std; struct translit_strings { string g_word_translit; string g_word_nopunct_translit; string g_suffix_translit; string g_lex_translit; string g_prs_translit; string g_vbs_translit; string g_pfm_translit; string g_vbe_translit; string g_nme_translit; string g_uvf_translit; string g_voc_lex_translit; string qere_translit; }; class translit_handler : public handler { public: translit_handler(); virtual void list_features(set<string>&) override; virtual void prepare_object(map<string,string>&) override; virtual void finish_prepare() override; virtual string define_features() override; virtual string update_object(const map<string,string>&) override; private: // Transliteration context. We need five words (two before and two after the current one) deque<map<string,string>> words; map<int, translit_strings> transliterations; // Indexed by self void chk_o(const map<string,string> * fmapp); }; shared_ptr<handler> make_translit_handler() { return shared_ptr<handler>{new translit_handler}; } translit_handler::translit_handler() { // Start by providing two empty words of context words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}}); words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}}); } void translit_handler::list_features(set<string>& req) { initialize_translit_rules(); initialize_translit_verbrules(); req.insert({"g_prs_utf8", "g_vbs_utf8", "g_pfm_utf8", "g_vbe_utf8", "g_nme_utf8", "g_uvf_utf8", "g_word", "g_suffix_utf8", "g_word_utf8", "g_voc_lex_utf8", "qere_utf8", "lex", "sp", "ps", "gn", "nu", "vs", "vt"}); } void translit_handler::chk_o(const map<string,string> * fmapp) { if (!fmapp) // Running from finish_prepare(). Add final empty word of context words.emplace_back(map<string,string>{{"g_word_utf8",""},{"g_suffix_utf8",""}}); else words.emplace_back(*fmapp); if (words.size()==5) { // Now we can transliterate the middle word bool ketiv = !words[2].at("qere_utf8").empty(); translit_strings translits; translits.g_suffix_translit = suffix_transliterate(words[2].at("g_suffix_utf8")); words[2]["g_suffix_translit"] = translits.g_suffix_translit; // used by transliterate() translits.g_word_translit = transliterate(words[0].at("g_word_utf8")+words[0].at("g_suffix_utf8")+ words[1].at("g_word_utf8")+words[1].at("g_suffix_utf8"), words[2].at(ketiv ? "g_word_cons_utf8" : "g_word_utf8"), words[2].at("g_suffix_utf8")+ words[3].at("g_word_utf8")+words[3].at("g_suffix_utf8")+ words[4].at("g_word_utf8")+words[4].at("g_suffix_utf8"), words[2], ketiv, true, true); translits.g_prs_translit = transliterate("", words[2].at("g_prs_utf8"), "", words[2], false, false, false); translits.g_vbs_translit = transliterate("", words[2].at("g_vbs_utf8"), "", words[2], false, false, false); translits.g_pfm_translit = transliterate("", words[2].at("g_pfm_utf8"), "", words[2], false, false, false); translits.g_vbe_translit = transliterate("", words[2].at("g_vbe_utf8"), "", words[2], false, false, false); translits.g_nme_translit = transliterate("", words[2].at("g_nme_utf8"), "", words[2], false, false, false); translits.g_uvf_translit = transliterate("", words[2].at("g_uvf_utf8"), "", words[2], false, false, false); if (words[2].at("sp")=="verb") translits.g_voc_lex_translit = transliterate_verb_lex(words[2].at("g_voc_lex_utf8")); else translits.g_voc_lex_translit = transliterate("", words[2].at("g_voc_lex_utf8"), "", words[2], false, false, false); // No words have both a g_vbe_utf8 and a g_nme_utf8. // g_nme_utf8 always starts with a GERESH ("\u059c" or "\xd6\x9c") if (!words[2].at("g_vbe_utf8").empty()) translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), words[2].at("g_vbe_utf8") + words[2].at("g_uvf_utf8"), words[2], false, false, false); else if (!words[2].at("g_nme_utf8").empty()) { string nm = words[2]["g_nme_utf8"]; if (nm[0]!='\xd6' || nm[1]!='\x9c') cerr << "self=" << words[2].at("self") << " g_nme_utf8 does not start with GERES\n"; else translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), nm.substr(2) + words[2].at("g_uvf_utf8"), words[2], false, false, false); } else translits.g_lex_translit = transliterate("", words[2].at("g_lex_utf8"), words[2].at("g_uvf_utf8"), words[2], false, false, false); if (!words[2].at("qere_utf8").empty()) translits.qere_translit = transliterate("", words[2].at("qere_utf8"), "", words[2], false, false, false); char last_char = translits.g_word_translit.back(); string last_2_char = translits.g_word_translit.length()>=2 ? translits.g_word_translit.substr(translits.g_word_translit.length()-2) : "" ; if (last_char=='|' || last_char=='-' || last_char==' ') translits.g_word_nopunct_translit = translits.g_word_translit.substr(0, translits.g_word_translit.length()-1); else if (last_2_char=="\u05be") translits.g_word_nopunct_translit = translits.g_word_translit.substr(0, translits.g_word_translit.length()-2); else translits.g_word_nopunct_translit = translits.g_word_translit; if (translits.g_word_nopunct_translit == "HÎʔ") translits.g_word_nopunct_translit = "hîʔ"; transliterations[stol(words[2].at("self"))] = translits; words.pop_front(); } } void translit_handler::prepare_object(map<string,string>& fmap) { chk_o(&fmap); } void translit_handler::finish_prepare() { chk_o(nullptr); chk_o(nullptr); } string translit_handler::define_features() { return " ADD g_word_translit : string DEFAULT \"\";\n" " ADD g_word_nopunct_translit : string DEFAULT \"\";\n" " ADD g_suffix_translit : string DEFAULT \"\";\n" " ADD g_lex_translit : string DEFAULT \"\";\n" " ADD g_prs_translit : string DEFAULT \"\";\n" " ADD g_vbs_translit : string DEFAULT \"\";\n" " ADD g_pfm_translit : string DEFAULT \"\";\n" " ADD g_vbe_translit : string DEFAULT \"\";\n" " ADD g_nme_translit : string DEFAULT \"\";\n" " ADD g_uvf_translit : string DEFAULT \"\";\n" " ADD g_voc_lex_translit : string DEFAULT \"\";\n" " ADD qere_translit : string DEFAULT \"\";\n"; } string translit_handler::update_object(const map<string,string>& fmap) { const translit_strings& translits = transliterations.at(stoi(fmap.at("self"))); return " g_word_translit := \"" + translits.g_word_translit + "\";\n" " g_word_nopunct_translit := \"" + translits.g_word_nopunct_translit + "\";\n" " g_suffix_translit := \"" + translits.g_suffix_translit + "\";\n" " g_lex_translit := \"" + translits.g_lex_translit + "\";\n" " g_prs_translit := \"" + translits.g_prs_translit + "\";\n" " g_vbs_translit := \"" + translits.g_vbs_translit + "\";\n" " g_pfm_translit := \"" + translits.g_pfm_translit + "\";\n" " g_vbe_translit := \"" + translits.g_vbe_translit + "\";\n" " g_nme_translit := \"" + translits.g_nme_translit + "\";\n" " g_uvf_translit := \"" + translits.g_uvf_translit + "\";\n" " g_voc_lex_translit := \"" + translits.g_voc_lex_translit + "\";\n" " qere_translit := \"" + translits.qere_translit + "\";\n"; }
8,727
3,152
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <aws/servicecatalog/model/PortfolioShareType.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace ServiceCatalog { namespace Model { namespace PortfolioShareTypeMapper { static const int IMPORTED_HASH = HashingUtils::HashString("IMPORTED"); static const int AWS_SERVICECATALOG_HASH = HashingUtils::HashString("AWS_SERVICECATALOG"); static const int AWS_ORGANIZATIONS_HASH = HashingUtils::HashString("AWS_ORGANIZATIONS"); PortfolioShareType GetPortfolioShareTypeForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == IMPORTED_HASH) { return PortfolioShareType::IMPORTED; } else if (hashCode == AWS_SERVICECATALOG_HASH) { return PortfolioShareType::AWS_SERVICECATALOG; } else if (hashCode == AWS_ORGANIZATIONS_HASH) { return PortfolioShareType::AWS_ORGANIZATIONS; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<PortfolioShareType>(hashCode); } return PortfolioShareType::NOT_SET; } Aws::String GetNameForPortfolioShareType(PortfolioShareType enumValue) { switch(enumValue) { case PortfolioShareType::IMPORTED: return "IMPORTED"; case PortfolioShareType::AWS_SERVICECATALOG: return "AWS_SERVICECATALOG"; case PortfolioShareType::AWS_ORGANIZATIONS: return "AWS_ORGANIZATIONS"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return ""; } } } // namespace PortfolioShareTypeMapper } // namespace Model } // namespace ServiceCatalog } // namespace Aws
2,888
877
#include <pbdata/saf/AlnGroup.hpp> int AlnGroup::FindPath(unsigned int idKey, std::string &val) { for (size_t i = 0; i < id.size(); i++) { if (idKey == id[i]) { val = path[i]; return 1; } } return 0; }
255
101
// OutputForce.cc // // Description: // Implementation of output routine for writing a list of force coefficients. // // Author(s): // Clancy Rowley // Steve Brunton // // Date: 22 Aug 2008 // // $Revision$ // $LastChangedDate$ // $LastChangedBy$ // $HeadURL$ #include "OutputForce.h" #include "BaseFlow.h" #include "State.h" #include "Output.h" #include "VectorOperations.h" #include <stdio.h> #include <string> using namespace std; namespace ibpm { OutputForce::OutputForce(string filename) : _filename( filename ) {} bool OutputForce::init() { _fp = fopen( _filename.c_str(), "w" ); if ( _fp == NULL ) return false; else return true; } bool OutputForce::cleanup() { bool status = true; if ( _fp != NULL ) { status = fclose( _fp ); } return status; } // Method to compute lift, drag from state (x), angle of attack (alpha), and freestream velocity (mag) bool OutputForce::doOutput( const double alpha, const double mag, const State& x) { double xF, yF; // force in x and y direction in domain double drag, lift; // actual drag and lift, wrt alpha x.computeNetForce( xF, yF ); drag = xF * cos(alpha) + yF * sin(alpha); lift = xF * -1.*sin(alpha) + yF * cos(alpha); // Convert forces to lift and drag coefficients: // If L_d is dimensional lift, then in the nondimensionalization of the // code (lengths by c, density by rho, velocity by U), we have // L = L_d / (c rho U^2) // so // C_L = L_d / (1/2 rho U^2) // = 2 L drag *= 2./(mag*mag); lift *= 2./(mag*mag); if ( _fp == NULL ) return false; fprintf( _fp, "%5d %.5e %.5e %.5e\n", x.timestep, x.time, drag, lift ); fflush( _fp ); return true; } // If no other information is provided, assume zero angle of attack, unity freestrem velocity bool OutputForce::doOutput(const State& x) { double alpha = 0.; double mag = 1.; return doOutput(alpha, mag, x); } bool OutputForce::doOutput( const BaseFlow& q, const State& x) { double alpha = q.getAlpha(); double mag = q.getMag(); return doOutput(alpha, mag, x); } } // namespace ibpm
2,177
764
// Copyright 2017 Rainer Gemulla // // 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. /** \file * * Illustrates matrix factorization with parallel SGD. We first create factors and then a data matrix * from these factors. This process ensures that we know the best factorization of the input. * These matrices are distributed across a cluster. We then try to reconstruct the factors * using PSGD. */ #include <iostream> #include <sstream> #include <boost/filesystem.hpp> #include <boost/program_options.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/math/distributions/normal.hpp> #include <boost/random/uniform_real.hpp> #include <mf/matrix/io/generateDistributedMatrix.h> #include <util/evaluation.h> #include <mpi2/mpi2.h> #include <mf/mf.h> log4cxx::LoggerPtr logger(log4cxx::Logger::getLogger("main")); using namespace std; using namespace mf; using namespace mpi2; using namespace rg; using namespace boost::numeric::ublas; // type of SGD typedef UpdateTruncate<UpdateNzslL2> Update; typedef RegularizeNone Regularize; typedef SumLoss<NzslLoss, L2Loss> Loss; typedef NzslLoss TestLoss; int main(int argc, char* argv[]) { using namespace boost::program_options; // initialize mf library and mpi2 boost::mpi::communicator& world = mfInit(argc, argv); mfStart(); if (world.rank() == 0) { #ifndef NDEBUG LOG4CXX_WARN(logger, "Warning: Debug mode activated (runtimes may be slow)."); #endif //data mf_size_type epochs; string inputSampleMatrixFile; string inputMatrixFile; string inputRowFacFile; string inputColFacFile; string outputRowFacFile; string outputColFacFile; string inputTestMatrixFile; string traceFile,traceVar; string shuffleStr; double lambda = 50; double eps0 = 0.01; // parameters for distribution int tasks; options_description desc("Options"); desc.add_options() ("help", "produce help message") ("epochs", value<mf_size_type>(&epochs)->default_value(10), "number of epochs to run [10]") ("lambda", value<double>(&lambda)->default_value(50), "lambda") ("eps0", value<double>(&eps0)->default_value(0.01), "initial step size for BoldDriver") ("tasks-per-rank", value<int>(&tasks)->default_value(1), "number of concurrent tasks [1]") ("trace", value<string>(&traceFile)->default_value("trace.R"), "filename of trace [trace.R]") ("traceVar", value<string>(&traceVar)->default_value("trace"), "variable name for trace [traceVar]") ("input-file", value<string>(&inputMatrixFile), "input matrix") ("input-test-file", value<string>(&inputTestMatrixFile), "input test matrix") ("input-row-file", value<string>(&inputRowFacFile), "input initial row factor") ("input-col-file", value<string>(&inputColFacFile), "input initial column factor") ("output-row-file", value<string>(&outputRowFacFile), "output initial row factor") ("output-col-file", value<string>(&outputColFacFile), "output initial column factor") ("shuffle",value<string>(&shuffleStr)->default_value("seq"),"shuffle method eg seq, par, parAdd") ; positional_options_description pdesc; pdesc.add("input-file", 1); pdesc.add("input-test-file", 2); pdesc.add("input-sample-matrix-file", 3); pdesc.add("input-row-file", 4); pdesc.add("input-col-file", 5); variables_map vm; store(command_line_parser(argc, argv).options(desc).positional(pdesc).run(), vm); notify(vm); if (vm.count("help") || vm.count("input-file")==0) { cout << "psgd with L2 NoLock (Hogwild-style) [options] <input-file> " << endl << endl; cout << desc << endl; return 1; } LOG4CXX_INFO(logger, "Using " << tasks << " parallel tasks"); PsgdShuffle shuffle; if (shuffleStr.compare("seq") == 0) shuffle= PSGD_SHUFFLE_SEQ; else if (shuffleStr.compare("par") == 0) shuffle= PSGD_SHUFFLE_PARALLEL; else shuffle= PSGD_SHUFFLE_PARALLEL_ADDITIONAL_TASK; LOG4CXX_INFO(logger, "Using " << shuffle); // Read matrices Random32 random; // SparseMatrix v,vTest; // DenseMatrix w; // DenseMatrixCM h; // readMatrix(inputMatrixFile,v); // readMatrix(inputTestMatrixFile,vTest); // readMatrix(inputRowFacFile,w); // readMatrix(inputColFacFile,h); Timer t; t.start(); std::vector<DistributedSparseMatrix> dataVector=getDataMatrices<SparseMatrix>(inputMatrixFile,"V",true, tasks, 1, 1, 1, true, false, &inputTestMatrixFile); SparseMatrix& v = *mpi2::env().get<SparseMatrix>(dataVector[0].blocks()(0,0).var()); SparseMatrix& vTest = *mpi2::env().get<SparseMatrix>(dataVector[1].blocks()(0,0).var()); std::pair<DistributedDenseMatrix, DistributedDenseMatrixCM> factorsPair= getFactors(inputRowFacFile, inputColFacFile, tasks, 1, 1, 1, true); t.stop(); LOG4CXX_INFO(logger, "Total time for loading matrices: " << t); DenseMatrix w = *mpi2::env().get<DenseMatrix>(factorsPair.first.blocks()(0,0).var()); DenseMatrixCM h = *mpi2::env().get<DenseMatrixCM>(factorsPair.second.blocks()(0,0).var()); // parameters for SGD SgdOrder order = SGD_ORDER_WOR; Update update = Update(UpdateNzslL2(lambda), -100, 100); // truncate for numerical stability Regularize regularize; Loss loss((NzslLoss()), L2Loss(lambda)); TestLoss testLoss; BalanceType balanceType = BALANCE_NONE; BalanceMethod balanceMethod = BALANCE_OPTIMAL; // initialize the DSGD PsgdRunner psgdRunner(random); PsgdJob<Update,Regularize> psgdJob(v, w, h, update, regularize, order, tasks, shuffle); BoldDriver decay(eps0); Trace trace; trace.addField("Loss", "L2"); trace.addField("Shuffle_method", shuffle); trace.addField("input_file", inputMatrixFile); trace.addField("sample_matrix", inputSampleMatrixFile); trace.addField("tasks", tasks); // print the test loss FactorizationData<> testData(vTest, w, h); LOG4CXX_INFO(logger, "Initial test loss: " << testLoss(testData)); // run HogwildSGD to try to reconstruct the original factors t.start(); psgdRunner.run(psgdJob, loss, epochs, decay, trace, balanceType, balanceMethod, &testData, &testLoss); t.stop(); LOG4CXX_INFO(logger, "Total time: " << t); // print the test loss LOG4CXX_INFO(logger, "Final test loss: " << testLoss(testData)); // write trace to an R file LOG4CXX_INFO(logger, "Writing trace to " << traceFile); trace.toRfile(traceFile, traceVar); // write computed factors to file if (outputRowFacFile.length() > 0) { LOG4CXX_INFO(logger, "Writing row factors to " << outputRowFacFile); //DenseMatrix w0; //unblock(dw, w0); writeMatrix(outputRowFacFile, w); } if (outputColFacFile.length() > 0) { LOG4CXX_INFO(logger, "Writing column factors to " << outputColFacFile); //DenseMatrixCM h0; //unblock(dh, h0); writeMatrix(outputColFacFile, h); } } mfStop(); mfFinalize(); return 0; }
7,418
2,843
// client.cpp // Implementation of the client class for the mqtt C++ client library. /******************************************************************************* * Copyright (c) 2013-2017 Frank Pagliughi <fpagliughi@mindspring.com> * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Frank Pagliughi - initial implementation and documentation *******************************************************************************/ #include "client.h" #include <memory> #include <iostream> namespace mqtt { const std::chrono::minutes client::DFLT_TIMEOUT = std::chrono::minutes(5); constexpr int client::DFLT_QOS; ///////////////////////////////////////////////////////////////////////////// client::client(const string& serverURI, const string& clientId, iclient_persistence* persistence /*=nullptr*/) : cli_(serverURI, clientId, persistence), timeout_(DFLT_TIMEOUT), userCallback_(nullptr) { } client::client(const string& serverURI, const string& clientId, const string& persistDir) : cli_(serverURI, clientId, persistDir), timeout_(DFLT_TIMEOUT), userCallback_(nullptr) { } client::client(const string& serverURI, const string& clientId, int maxBufferedMessages, iclient_persistence* persistence /*=nullptr*/) : cli_(serverURI, clientId, maxBufferedMessages, persistence), timeout_(DFLT_TIMEOUT), userCallback_(nullptr) { } client::client(const string& serverURI, const string& clientId, int maxBufferedMessages, const string& persistDir) : cli_(serverURI, clientId, maxBufferedMessages, persistDir), timeout_(DFLT_TIMEOUT), userCallback_(nullptr) { } void client::set_callback(callback& cb) { userCallback_ = &cb; cli_.set_callback(*this); } void client::subscribe(const string_collection& topicFilters) { qos_collection qos; for (size_t i=0; i<topicFilters.size(); ++i) qos.push_back(DFLT_QOS); cli_.subscribe(ptr(topicFilters), qos)->wait_for(timeout_); } ///////////////////////////////////////////////////////////////////////////// // end namespace mqtt }
2,433
740
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ // This is a GPU-backend specific test. It relies on static intializers to work #include "SkTypes.h" #if defined(SK_VULKAN) #include "GrContextFactory.h" #include "GrContextPriv.h" #include "GrSurfaceProxy.h" #include "GrTest.h" #include "ProxyUtils.h" #include "SkGr.h" #include "Test.h" #include "TestUtils.h" #include "vk/GrVkGpu.h" using sk_gpu_test::GrContextFactory; void basic_texture_test(skiatest::Reporter* reporter, GrContext* context, SkColorType ct, bool renderTarget) { const int kWidth = 16; const int kHeight = 16; SkAutoTMalloc<GrColor> srcBuffer(kWidth*kHeight); SkAutoTMalloc<GrColor> dstBuffer(kWidth*kHeight); fill_pixel_data(kWidth, kHeight, srcBuffer.get()); auto proxy = sk_gpu_test::MakeTextureProxyFromData(context, renderTarget, kWidth, kHeight, ct, kTopLeft_GrSurfaceOrigin, srcBuffer, 0); REPORTER_ASSERT(reporter, proxy); if (proxy) { sk_sp<GrSurfaceContext> sContext = context->contextPriv().makeWrappedSurfaceContext(proxy); SkImageInfo dstInfo = SkImageInfo::Make(kWidth, kHeight, ct, kPremul_SkAlphaType); bool result = sContext->readPixels(dstInfo, dstBuffer, 0, 0, 0); REPORTER_ASSERT(reporter, result); REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer, dstBuffer, kWidth, kHeight)); dstInfo = SkImageInfo::Make(10, 2, ct, kPremul_SkAlphaType); result = sContext->writePixels(dstInfo, srcBuffer, 0, 2, 10); REPORTER_ASSERT(reporter, result); memset(dstBuffer, 0, kWidth*kHeight*sizeof(GrColor)); result = sContext->readPixels(dstInfo, dstBuffer, 0, 2, 10); REPORTER_ASSERT(reporter, result); REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer, dstBuffer, 10, 2)); } proxy = sk_gpu_test::MakeTextureProxyFromData(context, renderTarget, kWidth, kHeight, ct, kBottomLeft_GrSurfaceOrigin, srcBuffer, 0); REPORTER_ASSERT(reporter, proxy); if (proxy) { sk_sp<GrSurfaceContext> sContext = context->contextPriv().makeWrappedSurfaceContext(proxy); SkImageInfo dstInfo = SkImageInfo::Make(kWidth, kHeight, ct, kPremul_SkAlphaType); bool result = sContext->readPixels(dstInfo, dstBuffer, 0, 0, 0); REPORTER_ASSERT(reporter, result); REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer, dstBuffer, kWidth, kHeight)); dstInfo = SkImageInfo::Make(4, 5, ct, kPremul_SkAlphaType); result = sContext->writePixels(dstInfo, srcBuffer, 0, 5, 4); REPORTER_ASSERT(reporter, result); memset(dstBuffer, 0, kWidth*kHeight*sizeof(GrColor)); result = sContext->readPixels(dstInfo, dstBuffer, 0, 5, 4); REPORTER_ASSERT(reporter, result); REPORTER_ASSERT(reporter, does_full_buffer_contain_correct_color(srcBuffer, dstBuffer, 4, 5)); } } DEF_GPUTEST_FOR_VULKAN_CONTEXT(VkUploadPixelsTests, reporter, ctxInfo) { // RGBA basic_texture_test(reporter, ctxInfo.grContext(), kRGBA_8888_SkColorType, false); basic_texture_test(reporter, ctxInfo.grContext(), kRGBA_8888_SkColorType, true); // BGRA basic_texture_test(reporter, ctxInfo.grContext(), kBGRA_8888_SkColorType, false); basic_texture_test(reporter, ctxInfo.grContext(), kBGRA_8888_SkColorType, true); } #endif
4,484
1,380
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2020 projectchrono.org // All right reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= // // Wheeled vehicle system co-simulated with tire nodes and a terrain node. // // The global reference frame has Z up, X towards the front of the vehicle, and // Y pointing to the left. // // ============================================================================= #include <fstream> #include <algorithm> #include <set> #include <vector> #include "chrono/ChConfig.h" #include "chrono_vehicle/ChVehicleModelData.h" #include "chrono_vehicle/utils/ChUtilsJSON.h" #include "chrono_vehicle/wheeled_vehicle/vehicle/WheeledVehicle.h" #include "chrono_vehicle/cosim/mbs/ChVehicleCosimVehicleNode.h" using std::cout; using std::endl; namespace chrono { namespace vehicle { // ----------------------------------------------------------------------------- class WheeledVehicleDBPDriver : public ChDriver { public: WheeledVehicleDBPDriver(std::shared_ptr<ChWheeledVehicle> vehicle, std::shared_ptr<ChFunction> dbp_mot_func) : ChDriver(*vehicle), m_wheeled_vehicle(vehicle), m_func(dbp_mot_func) {} virtual void Synchronize(double time) override { m_steering = 0; m_braking = 0; double ang_speed = m_func->Get_y(time); for (auto& axle : m_wheeled_vehicle->GetAxles()) { axle->m_suspension->GetAxle(VehicleSide::LEFT)->SetPos_dt(ang_speed); axle->m_suspension->GetAxle(VehicleSide::RIGHT)->SetPos_dt(ang_speed); } } std::shared_ptr<ChWheeledVehicle> m_wheeled_vehicle; std::shared_ptr<ChFunction> m_func; }; // ----------------------------------------------------------------------------- ChVehicleCosimVehicleNode::ChVehicleCosimVehicleNode(const std::string& vehicle_json, const std::string& powertrain_json) : ChVehicleCosimMBSNode(), m_num_spindles(0) { m_vehicle = chrono_types::make_shared<WheeledVehicle>(m_system, vehicle_json); m_powertrain = ReadPowertrainJSON(powertrain_json); m_terrain = chrono_types::make_shared<ChTerrain>(); } ChVehicleCosimVehicleNode::~ChVehicleCosimVehicleNode() {} // ----------------------------------------------------------------------------- void ChVehicleCosimVehicleNode::InitializeMBS(const std::vector<ChVector<>>& tire_info, const ChVector2<>& terrain_size, double terrain_height) { // Initialize vehicle ChCoordsys<> init_pos(m_init_loc + ChVector<>(0, 0, terrain_height), Q_from_AngZ(m_init_yaw)); m_vehicle->Initialize(init_pos); m_vehicle->SetChassisVisualizationType(VisualizationType::MESH); m_vehicle->SetSuspensionVisualizationType(VisualizationType::PRIMITIVES); m_vehicle->SetSteeringVisualizationType(VisualizationType::PRIMITIVES); m_vehicle->SetWheelVisualizationType(VisualizationType::MESH); // Initialize powertrain m_vehicle->InitializePowertrain(m_powertrain); // Create and initialize the dummy tires int itire = 0; for (auto& axle : m_vehicle->GetAxles()) { for (auto& wheel : axle->GetWheels()) { auto tire = chrono_types::make_shared<DummyTire>(itire, tire_info[itire].x(), tire_info[itire].y(), tire_info[itire].z()); m_vehicle->InitializeTire(tire, wheel, VisualizationType::NONE); m_tires.push_back(tire); itire++; } } // Extract and cache spindle bodies auto num_axles = m_vehicle->GetNumberAxles(); m_num_spindles = 2 * num_axles; assert(m_num_spindles == (int)m_num_tire_nodes); auto total_mass = m_vehicle->GetVehicleMass(); for (int is = 0; is < m_num_spindles; is++) { auto tire_mass = tire_info[is].x(); m_spindle_loads.push_back(tire_mass + total_mass / m_num_spindles); } } // ----------------------------------------------------------------------------- int ChVehicleCosimVehicleNode::GetNumSpindles() const { return m_num_spindles; } std::shared_ptr<ChBody> ChVehicleCosimVehicleNode::GetSpindleBody(unsigned int i) const { VehicleSide side = (i % 2 == 0) ? VehicleSide::LEFT : VehicleSide::RIGHT; return m_vehicle->GetWheel(i / 2, side)->GetSpindle(); } double ChVehicleCosimVehicleNode::GetSpindleLoad(unsigned int i) const { return m_spindle_loads[i]; } BodyState ChVehicleCosimVehicleNode::GetSpindleState(unsigned int i) const { VehicleSide side = (i % 2 == 0) ? VehicleSide::LEFT : VehicleSide::RIGHT; auto spindle_body = m_vehicle->GetWheel(i / 2, side)->GetSpindle(); BodyState state; state.pos = spindle_body->GetPos(); state.rot = spindle_body->GetRot(); state.lin_vel = spindle_body->GetPos_dt(); state.ang_vel = spindle_body->GetWvel_par(); return state; } std::shared_ptr<ChBody> ChVehicleCosimVehicleNode::GetChassisBody() const { return m_vehicle->GetChassisBody(); } void ChVehicleCosimVehicleNode::OnInitializeDBPRig(std::shared_ptr<ChFunction> func) { // Disconnect the driveline m_vehicle->DisconnectDriveline(); // Overwrite any driver attached to the vehicle with a custom driver which imposes zero steering and braking and // directly sets the angular speed of the vehicle axleshafts as returned by the provided motor function. SetDriver(chrono_types::make_shared<WheeledVehicleDBPDriver>(m_vehicle, func)); } // ----------------------------------------------------------------------------- void ChVehicleCosimVehicleNode::PreAdvance() { // Synchronize vehicle systems double time = m_vehicle->GetChTime(); ChDriver::Inputs driver_inputs; if (m_driver) { driver_inputs = m_driver->GetInputs(); m_driver->Synchronize(time); } else { driver_inputs.m_steering = 0; driver_inputs.m_throttle = 0.5; driver_inputs.m_braking = 0; } m_vehicle->Synchronize(time, driver_inputs, *m_terrain); } void ChVehicleCosimVehicleNode::ApplySpindleForce(unsigned int i, const TerrainForce& spindle_force) { // Cache the spindle force on the corresponding dummy tire. This force will be applied to the associated ChWheel on // synchronization of the vehicle system (in PreAdvance) m_tires[i]->m_force = spindle_force; } // ----------------------------------------------------------------------------- void ChVehicleCosimVehicleNode::OnOutputData(int frame) { // Append to results output file if (m_outf.is_open()) { std::string del(" "); const ChVector<>& pos = m_vehicle->GetVehiclePos(); m_outf << m_system->GetChTime() << del; // Body states m_outf << pos.x() << del << pos.y() << del << pos.z() << del; // Solver statistics (for last integration step) m_outf << m_system->GetTimerStep() << del << m_system->GetTimerLSsetup() << del << m_system->GetTimerLSsolve() << del << m_system->GetTimerUpdate() << del; if (m_int_type == ChTimestepper::Type::HHT) { m_outf << m_integrator->GetNumIterations() << del << m_integrator->GetNumSetupCalls() << del << m_integrator->GetNumSolveCalls() << del; } m_outf << endl; } // Create and write frame output file. utils::CSV_writer csv(" "); csv << m_system->GetChTime() << endl; // current time WriteBodyInformation(csv); // vehicle body states std::string filename = OutputFilename(m_node_out_dir + "/simulation", "data", "dat", frame + 1, 5); csv.write_to_file(filename); if (m_verbose) cout << "[Vehicle node] write output file ==> " << filename << endl; } void ChVehicleCosimVehicleNode::WriteBodyInformation(utils::CSV_writer& csv) { // Write number of bodies csv << 1 + m_num_spindles << endl; // Write body state information auto chassis = m_vehicle->GetChassisBody(); csv << chassis->GetPos() << chassis->GetRot() << chassis->GetPos_dt() << chassis->GetRot_dt() << endl; for (auto& axle : m_vehicle->GetAxles()) { for (auto& wheel : axle->GetWheels()) { auto spindle_body = wheel->GetSpindle(); csv << spindle_body->GetPos() << spindle_body->GetRot() << spindle_body->GetPos_dt() << spindle_body->GetRot_dt() << endl; } } } } // end namespace vehicle } // end namespace chrono
8,952
2,987
/* * Copyright (C) 2017-2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "runtime/context/context.h" #include "cl_api_tests.h" using namespace NEO; typedef api_tests clRetainReleaseSamplerTests; namespace ULT { TEST_F(clRetainReleaseSamplerTests, GivenValidSamplerWhenRetainingThenSamplerReferenceCountIsIncremented) { cl_int retVal = CL_SUCCESS; auto sampler = clCreateSampler(pContext, CL_TRUE, CL_ADDRESS_CLAMP, CL_FILTER_NEAREST, &retVal); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_NE(nullptr, sampler); cl_uint theRef; retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &theRef, NULL); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(1u, theRef); retVal = clRetainSampler(sampler); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &theRef, NULL); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(2u, theRef); retVal = clReleaseSampler(sampler); EXPECT_EQ(CL_SUCCESS, retVal); retVal = clGetSamplerInfo(sampler, CL_SAMPLER_REFERENCE_COUNT, sizeof(cl_uint), &theRef, NULL); EXPECT_EQ(CL_SUCCESS, retVal); EXPECT_EQ(1u, theRef); retVal = clReleaseSampler(sampler); EXPECT_EQ(CL_SUCCESS, retVal); } } // namespace ULT
1,431
543
// // Distributed Linear Algebra with Future (DLAF) // // Copyright (c) 2018-2019, ETH Zurich // All rights reserved. // // Please, refer to the LICENSE file in the root directory. // SPDX-License-Identifier: BSD-3-Clause // #include "dlaf/common/data_descriptor.h" #include <memory> #include <type_traits> #include <gtest/gtest.h> #include "dlaf/types.h" #include "dlaf_test/util_types.h" using namespace dlaf; template <typename T> struct memory_data { std::unique_ptr<T[]> data; std::size_t num_blocks; std::size_t block_size; std::size_t stride; T& operator[](std::size_t index) { auto i_block = index / block_size; auto i_element = index % block_size; return data.get()[i_block * stride + i_element]; } }; template <class T> memory_data<T> create_memory(const std::size_t num_blocks, const std::size_t blocksize, const std::size_t stride) { assert(num_blocks > 0); assert(blocksize <= stride || stride == 0); if (num_blocks == 1) return {std::make_unique<T[]>(blocksize), num_blocks, blocksize, stride}; // the last element does not have additional padding // no additional padding to the next (non-existing) element auto distance = std::max(blocksize, stride); auto memory_footprint = (num_blocks - 1) * distance + blocksize; return {std::make_unique<T[]>(memory_footprint), num_blocks, blocksize, stride}; } enum class MEMORY_TYPE { ARRAY_CONTIGUOUS, ARRAY_STRIDED, ARRAY_CONTIGUOUS_AS_STRIDED }; template <class T> memory_data<T> create_memory(MEMORY_TYPE type) { switch (type) { case MEMORY_TYPE::ARRAY_CONTIGUOUS: // 1 block // 13 elements // E E E E E E E E E E E E E return create_memory<T>(1, 13, 0); case MEMORY_TYPE::ARRAY_STRIDED: // 3 blocks // 2 elements each // 5 elements between start of each block // E E - - - E E - - - E E (without padding at the end) return create_memory<T>(3, 2, 5); case MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED: // 3 blocks // 5 elements each // 5 elements between start of each block // E E E E E E E E E E E E E E E return create_memory<T>(3, 5, 5); default: throw std::runtime_error("Unknown memory type"); } } template <class Type> class DataDescriptorTest : public ::testing::Test {}; TYPED_TEST_SUITE(DataDescriptorTest, dlaf_test::ElementTypes); TYPED_TEST(DataDescriptorTest, MakeFromPointer) { TypeParam value = 26; TypeParam* value_ptr = &value; auto data = common::make_data(value_ptr, 1); EXPECT_EQ(value_ptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(1, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromPointerConst) { TypeParam value = 26; const TypeParam* value_ptr = &value; auto data = common::make_data(value_ptr, 1); EXPECT_EQ(value_ptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(1, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromCArray) { const int N = 13; TypeParam value_array[N]{}; auto data = common::make_data(value_array, N); EXPECT_EQ(&value_array[0], data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(std::extent<decltype(value_array)>::value, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromCArrayConst) { const int N = 13; const TypeParam value_array[N]{}; auto data = common::make_data(value_array, N); EXPECT_EQ(&value_array[0], data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(std::extent<decltype(value_array)>::value, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromContiguousArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromContiguousArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromContiguousAsStridedArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(memory.num_blocks * memory.block_size, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromContiguousAsStridedArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(memory.num_blocks * memory.block_size, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromStridedArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_FALSE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeFromStridedArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_FALSE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, MakeBufferUniquePtr) { const std::size_t N = 13; auto data = common::Buffer<TypeParam>(N); EXPECT_NE(nullptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(N, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); } TYPED_TEST(DataDescriptorTest, CtorFromPointer) { TypeParam value = 26; TypeParam* value_ptr = &value; auto data = common::DataDescriptor<TypeParam>{value_ptr, 1}; EXPECT_EQ(value_ptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(1, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromPointerConst) { TypeParam value = 26; const TypeParam* value_ptr = &value; auto data = common::DataDescriptor<const TypeParam>{value_ptr, 1}; EXPECT_EQ(value_ptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(1, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromCArray) { const int N = 13; TypeParam value_array[N]{}; auto data = common::DataDescriptor<decltype(value_array)>{value_array}; EXPECT_EQ(&value_array[0], data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(std::extent<decltype(value_array)>::value, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromCArrayConst) { const int N = 13; const TypeParam value_array[N]{}; auto data = common::DataDescriptor<decltype(value_array)>{value_array}; EXPECT_EQ(&value_array[0], data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(std::extent<decltype(value_array)>::value, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromContiguousArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromContiguousArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromContiguousAsStridedArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(memory.num_blocks * memory.block_size, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromContiguousAsStridedArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(memory.num_blocks * memory.block_size, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromStridedArray) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_FALSE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorFromStridedArrayConst) { memory_data<TypeParam> memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); EXPECT_EQ(memory.data.get(), data_pointer(data)); EXPECT_EQ(memory.num_blocks, data_nblocks(data)); EXPECT_EQ(memory.block_size, data_blocksize(data)); EXPECT_EQ(memory.stride, data_stride(data)); EXPECT_FALSE(data_iscontiguous(data)); static_assert(common::is_data<decltype(data)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<const TypeParam, typename common::data_traits<decltype(data)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CtorBufferUniquePtr) { const std::size_t N = 13; auto data = common::Buffer<TypeParam>(N); EXPECT_NE(nullptr, data_pointer(data)); EXPECT_EQ(1, data_nblocks(data)); EXPECT_EQ(N, data_blocksize(data)); EXPECT_EQ(0, data_stride(data)); EXPECT_TRUE(data_iscontiguous(data)); } template <class TypeParam, class Buffer> void check_copy_ctor(Buffer& data) { auto data_copy = data; EXPECT_EQ(data_pointer(data), data_pointer(data_copy)); EXPECT_EQ(data_nblocks(data), data_nblocks(data_copy)); EXPECT_EQ(data_blocksize(data), data_blocksize(data_copy)); EXPECT_EQ(data_stride(data), data_stride(data_copy)); EXPECT_EQ(data_iscontiguous(data), data_iscontiguous(data_copy)); static_assert(common::is_data<decltype(data_copy)>::value, "It should be a Buffer (concept)"); static_assert(std::is_same<TypeParam, typename common::data_traits<decltype(data_copy)>::element_t>::value, "Wrong type returned"); } TYPED_TEST(DataDescriptorTest, CopyCtorFromPointer) { TypeParam value = 26; auto data = common::make_data(&value, 1); check_copy_ctor<TypeParam>(data); const TypeParam value_const = value; auto data_const = common::make_data(&value_const, 1); check_copy_ctor<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CopyCtorFromCArray) { const int N = 13; TypeParam value_array[N]{}; auto data = common::make_data(value_array, N); check_copy_ctor<TypeParam>(data); const TypeParam value_array_const[N]{}; auto data_const = common::make_data(value_array_const, N); check_copy_ctor<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CopyCtorFromContiguousArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<TypeParam>(data); auto data_const = common::make_data(static_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CopyCtorFromContiguousAsStridedArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<TypeParam>(data); auto data_const = common::make_data(static_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CopyCtorFromStridedArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<TypeParam>(data); auto data_const = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_copy_ctor<const TypeParam>(data_const); } template <class TypeParam, class Buffer> void check_temporary(Buffer& data) { auto data_temp = create_temporary_buffer(data); EXPECT_NE(common::data_pointer(data), common::data_pointer(data_temp)); EXPECT_EQ(common::data_count(data), common::data_count(data_temp)); EXPECT_TRUE(common::data_iscontiguous(data_temp)); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromPointer) { TypeParam value = 26; auto data = common::make_data(&value, 1); check_temporary<TypeParam>(data); const TypeParam value_const = value; auto data_const = common::make_data(&value_const, 1); check_temporary<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromCArray) { const int N = 13; TypeParam value_array[N]{}; auto data = common::make_data(value_array, N); check_temporary<TypeParam>(data); const TypeParam value_array_const[N]{}; auto data_const = common::make_data(value_array_const, N); check_temporary<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromContiguousArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_temporary<TypeParam>(data); auto data_const = common::make_data(static_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_temporary<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromContiguousAsStridedArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_temporary<TypeParam>(data); auto data_const = common::make_data(static_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_temporary<const TypeParam>(data_const); } TYPED_TEST(DataDescriptorTest, CreateTemporaryFromStridedArray) { auto memory = create_memory<TypeParam>(MEMORY_TYPE::ARRAY_STRIDED); auto data = common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); check_temporary<TypeParam>(data); auto data_const = common::make_data(const_cast<const TypeParam*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); check_temporary<const TypeParam>(data_const); } template <class T> auto create_data_from_memory(memory_data<T>& memory) { return common::make_data(memory.data.get(), memory.num_blocks, memory.block_size, memory.stride); } template <class T> auto create_const_data_from_memory(memory_data<T>& memory) { return common::make_data(const_cast<const T*>(memory.data.get()), memory.num_blocks, memory.block_size, memory.stride); } TYPED_TEST(DataDescriptorTest, CopyDataCArrays) { const int N = 13; TypeParam memory_src[N]; TypeParam memory_dst[N]; for (int i = 0; i < N; ++i) memory_src[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); auto data_src = common::make_data(const_cast<const TypeParam*>(memory_src), N); auto data_dest = common::make_data(memory_dst, N); common::copy(data_src, data_dest); for (int i = 0; i < N; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_dst[i]); } TYPED_TEST(DataDescriptorTest, CopyDataArrays) { auto memory_types = {MEMORY_TYPE::ARRAY_CONTIGUOUS, MEMORY_TYPE::ARRAY_CONTIGUOUS_AS_STRIDED, MEMORY_TYPE::ARRAY_STRIDED}; for (auto memory_type : memory_types) { auto memory_src = create_memory<TypeParam>(memory_type); auto memory_dest = create_memory<TypeParam>(memory_type); for (std::size_t i = 0; i < memory_src.num_blocks * memory_src.block_size; ++i) memory_src[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); auto data_src = create_const_data_from_memory(memory_src); auto data_dest = create_data_from_memory(memory_dest); common::copy(data_src, data_dest); for (std::size_t i = 0; i < memory_src.num_blocks * memory_src.block_size; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_dest[i]); } } TYPED_TEST(DataDescriptorTest, CopyDataHeterogeneous) { const std::size_t N = 26; const std::size_t N_GROUPS = 2; static_assert(N % N_GROUPS == 0, "Incompatible geometry"); std::vector<memory_data<TypeParam>> memory_types; // memory contiguous memory_types.emplace_back(create_memory<TypeParam>(1, N, 0)); // memory contiguous as strided memory_types.emplace_back(create_memory<TypeParam>(N_GROUPS, N / N_GROUPS, N / N_GROUPS)); // memory strided memory_types.emplace_back(create_memory<TypeParam>(N_GROUPS, N / N_GROUPS, N / N_GROUPS + 5)); // CArray as source for (auto& memory_dest : memory_types) { TypeParam memory_array[N]; for (std::size_t i = 0; i < N; ++i) memory_array[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); for (std::size_t i = 0; i < N; ++i) memory_dest[i] = 0; auto data_array = common::make_data(memory_array, N); auto data_dest = create_data_from_memory(memory_dest); copy(data_array, data_dest); for (std::size_t i = 0; i < N; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_dest[i]); } // CArray as destination for (auto& memory_src : memory_types) { TypeParam memory_array[N]; for (std::size_t i = 0; i < N; ++i) memory_array[i] = 0; for (std::size_t i = 0; i < N; ++i) memory_src[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); auto data_src = create_const_data_from_memory(memory_src); auto data_array = common::make_data(memory_array, N); copy(data_src, data_array); for (std::size_t i = 0; i < N; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_array[i]); } // Other combinations for (auto& memory_src : memory_types) { for (auto& memory_dest : memory_types) { if (&memory_src == &memory_dest) continue; for (std::size_t i = 0; i < N; ++i) memory_src[i] = dlaf_test::TypeUtilities<TypeParam>::element(i, 0); for (std::size_t i = 0; i < N; ++i) memory_dest[i] = 0; auto data_src = create_const_data_from_memory(memory_src); auto data_dest = create_data_from_memory(memory_dest); copy(data_src, data_dest); for (std::size_t i = 0; i < N; ++i) EXPECT_EQ(dlaf_test::TypeUtilities<TypeParam>::element(i, 0), memory_dest[i]); } } }
27,372
9,882
/* This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/> */ #include <iostream> #define GLEW_STATIC #include <GL/glew.h> #include <gl/freeglut.h> #include "LoadShaders.h" #include <glm/glm.hpp> #include <glm/gtx/transform.hpp> #include <glm/gtc/type_ptr.hpp> using namespace glm; using namespace std; mat4 matMV; mat4 matP; enum eVertexArrayObject { VAOCurve, VAOCount }; enum eVertexBufferObject { VBOCurve, VBOCount }; enum eShader { BezierCurveShader, FixedFuncShader, ShaderCount }; GLuint vao[VAOCount]; GLuint vbo[VBOCount]; GLuint glsl[ShaderCount]; GLfloat curve_pts[][3] = { { -4.f, -3.f, 0.f }, { -2.f, 3.f, 0.f }, { 3.f, 2.f, 0.f }, { 4.f,-1.f, 0.f } }; const double WORLD_SIZE = 5.; void initBezierCurveShader() { ShaderInfo shader_info[] = { { GL_VERTEX_SHADER, "../src/glsl/bezier_curve.vert" }, { GL_TESS_CONTROL_SHADER, "../src/glsl/bezier_curve.tess" }, { GL_TESS_EVALUATION_SHADER, "../src/glsl/bezier_curve.eval" }, { GL_FRAGMENT_SHADER, "../src/glsl/bezier_curve.frag" }, { GL_NONE, NULL } }; glsl[BezierCurveShader] = LoadShaders(shader_info); glBindVertexArray( vao[ VAOCurve ] ); glBindBuffer( GL_ARRAY_BUFFER, vbo[ VBOCurve ] ); glBufferData( GL_ARRAY_BUFFER, sizeof(curve_pts), curve_pts, GL_STATIC_DRAW ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); } void initFixedFuncShader() { ShaderInfo ff_shader_info[] = { { GL_VERTEX_SHADER, "../src/glsl/vertex.glsl" }, { GL_FRAGMENT_SHADER, "../src/glsl/fragment.glsl" }, { GL_NONE, NULL } }; glsl[FixedFuncShader] = LoadShaders( ff_shader_info ); } void initGL() { glClearColor(0.7, 0.7, 0.7, 1.); glPointSize(3.); glEnable (GL_LINE_SMOOTH); glEnable (GL_BLEND); glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glHint (GL_LINE_SMOOTH_HINT, GL_DONT_CARE); glGenVertexArrays( VAOCount, &vao[ 0 ] ); glGenBuffers( VBOCount, &vbo[ 0 ] ); initBezierCurveShader(); initFixedFuncShader(); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glBindVertexArray( 0 ); } void cbReshape(int w, int h) { float ar = (float) w / h; glViewport(0,0, w,h); matP = glm::ortho( -WORLD_SIZE*ar, WORLD_SIZE*ar, -WORLD_SIZE, WORLD_SIZE, -1., 1. ); matMV = glm::mat4(1.); } void cbKey(unsigned char c, int w, int h ) { switch(c) { case 27:case'q': glutExit(); break; } } void drawBezierCurve() { glUseProgram( glsl[BezierCurveShader] ); GLuint locMatP = glGetUniformLocation( glsl[BezierCurveShader], "matProjection" ); GLuint locMatMV = glGetUniformLocation( glsl[BezierCurveShader], "matModelView" ); glUniformMatrix4fv( locMatP, 1, GL_FALSE, glm::value_ptr( matP ) ); glUniformMatrix4fv( locMatMV, 1, GL_FALSE, glm::value_ptr( matMV ) ); glBindVertexArray( vao[ VAOCurve ] ); glBindBuffer( GL_ARRAY_BUFFER, vbo[ VBOCurve ] ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, 0 ); glEnableVertexAttribArray( 0 ); glPatchParameteri( GL_PATCH_VERTICES, 4 ); glDrawArrays( GL_PATCHES, 0, 4 ); glUseProgram( glsl[FixedFuncShader] ); locMatP = glGetUniformLocation( glsl[FixedFuncShader], "matProjection" ); locMatMV = glGetUniformLocation( glsl[FixedFuncShader], "matModelView" ); glUniformMatrix4fv( locMatP, 1, GL_FALSE, glm::value_ptr( matP ) ); glUniformMatrix4fv( locMatMV, 1, GL_FALSE, glm::value_ptr( matMV ) ); glDrawArrays( GL_LINE_STRIP, 0, 4 ); glDrawArrays( GL_POINTS, 0, 4 ); glBindVertexArray( 0 ); glBindBuffer( GL_ARRAY_BUFFER, 0 ); glDisableVertexAttribArray( 0 ); } void cbDisplay() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); drawBezierCurve(); glutSwapBuffers(); } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH | GLUT_DOUBLE ); glutInitWindowSize(512, 512 ); glutInitContextProfile(GLUT_CORE_PROFILE); glutCreateWindow("Bezier Curve"); glutReshapeFunc(cbReshape); glutKeyboardFunc(cbKey); glutDisplayFunc(cbDisplay); glewExperimental = GL_TRUE; glewInit(); initGL(); glutMainLoop(); return 0; }
4,607
2,060
#include "RtcClientPch.h" #include "RtcClient.h" #include <grpc++/channel_interface.h> #include <grpc++/client_context.h> #include <grpc++/status.h> #include <grpc++/stream.h> using grpc::CompletionQueue; using grpc::ChannelInterface; using grpc::ClientContext; using grpc::ClientReader; using grpc::ClientReaderWriter; using grpc::ClientWriter; using grpc::Status; RtcClient::RtcClient(std::shared_ptr<ChannelInterface> channel) :stub_(peer_connection::PeerConnectionApi::NewStub(channel)) { } boost::optional<std::string> RtcClient::createOffer(const std::string& sContentType) { ClientContext context; peer_connection::OfferDescriptor desc; desc.set_content_type(sContentType); peer_connection::CreateSessionDescriptionResponse response; Status status = stub_->createOffer(&context, desc, &response); if (status.IsOk()) { LOG(INFO) << "RPC createOffer success"; if (response.response_code() == 200) { return boost::optional<std::string>(response.session_description().session_description()); } else { LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description(); return boost::optional<std::string>(); } } else { LOG(WARNING) << "RPC createOffer failed"; return boost::optional<std::string>(); } } boost::optional<std::string> RtcClient::createAnswer(const std::string& sSessionDescription, const std::string& sContentType) { ClientContext context; peer_connection::AnswerDescriptor desc; peer_connection::SessionDescription* pOffer = new peer_connection::SessionDescription(); pOffer->set_content_type(sContentType); pOffer->set_session_description(sSessionDescription); desc.set_allocated_session_description(pOffer); peer_connection::CreateSessionDescriptionResponse response; Status status = stub_->createAnswer(&context, desc, &response); if (status.IsOk()) { LOG(INFO) << "RPC createAnswer success"; if (response.response_code() == 200) { return boost::optional<std::string>(response.session_description().session_description()); } else { LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description(); return boost::optional<std::string>(); } } else { LOG(WARNING) << "RPC createAnswer failed"; return boost::optional<std::string>(); } } bool RtcClient::setRemoteDescription(const std::string& sSessionDescription, const std::string& sContentType) { ClientContext context; peer_connection::SessionDescription remoteSdp; remoteSdp.set_content_type(sContentType); remoteSdp.set_session_description(sSessionDescription); peer_connection::SetSessionDescriptionResponse response; Status status = stub_->setRemoteDescription (&context, remoteSdp, &response); if (status.IsOk()) { LOG(INFO) << "RPC setRemoteDescription success"; if (response.response_code() == 200) { return true; } else { LOG(WARNING) << "Server returned error: " << response.response_code() << " " << response.response_description(); return false; } } else { LOG(WARNING) << "RPC setRemoteDescription failed"; return false; } } bool RtcClient::startStreaming() { ClientContext context; peer_connection::StartStreamingRequest request; peer_connection::StartStreamingResponse response; Status status = stub_->startStreaming(&context, request, &response); if (status.IsOk()) { LOG(INFO) << "RPC startStreaming success"; if (response.response_code() == 200) { return true; } else { LOG(WARNING) << "startStreaming: Server returned error: " << response.response_code() << " " << response.response_description(); return false; } } else { LOG(WARNING) << "RPC startStreaming failed"; return false; } } bool RtcClient::stopStreaming() { ClientContext context; peer_connection::StopStreamingRequest request; peer_connection::StopStreamingResponse response; Status status = stub_->stopStreaming(&context, request, &response); if (status.IsOk()) { LOG(INFO) << "RPC stopStreaming success"; if (response.response_code() == 200) { return true; } else { LOG(WARNING) << "stopStreaming: Server returned error: " << response.response_code() << " " << response.response_description(); return false; } } else { LOG(WARNING) << "RPC stopStreaming failed"; return false; } } bool RtcClient::shutdownRemoteRtcServer() { ClientContext context; peer_connection::ShutdownRequest request; peer_connection::ShutdownResponse response; Status status = stub_->shutdown(&context, request, &response); if (status.IsOk()) { LOG(INFO) << "RPC shutdown success"; if (response.response_code() == 200) { return true; } else { LOG(WARNING) << "shutdown: Server returned error: " << response.response_code() << " " << response.response_description(); return false; } } else { LOG(WARNING) << "RPC shutdown failed"; return false; } } void RtcClient::reset() { stub_.reset(); }
5,199
1,632
#ifndef TEST #include "CalcScreen.h" #include "../Any/View.h" #include <SDL.h> #include "../Any/Enums.h" #include "../Struct/Pair.h" #include "../Struct/Message.h" #include "../Struct/Rect.h" #include "../Struct/Point.h" #include "../Struct/Size.h" namespace ii887522::Calculator { CalcScreen::CalcScreen(SDL_Renderer*const renderer, const Rect& rect) : View{ renderer }, viewModel{ Rect{ Point{ rect.position.x, rect.position.y + 26 }, Size{ rect.size.w, rect.size.h - 26 } } }, rect{ rect } { } Action CalcScreen::reactMouseMotion(const SDL_MouseMotionEvent& motionEvent) { viewModel.reactMouseMotion(Point{ motionEvent.x, motionEvent.y }); return Action::NONE; } Action CalcScreen::reactRightMouseButtonDown(const SDL_MouseButtonEvent&) { viewModel.reactRightMouseButtonDown(); return Action::NONE; } Pair<Action, Message> CalcScreen::reactRightMouseButtonUp(const SDL_MouseButtonEvent&) { viewModel.reactRightMouseButtonUp(); return Pair{ Action::NONE, viewModel.getMessage() }; } Action CalcScreen::reactMouseLeaveWindow(const SDL_WindowEvent&) { viewModel.reactMouseLeaveWindow(); return Action::NONE; } void CalcScreen::render() { SDL_SetRenderDrawColor(getRenderer(), 192u, 192u, 192u, 255u); const SDL_Rect sdl_rect{ rect.position.x, rect.position.y, rect.size.w, rect.size.h }; SDL_RenderFillRect(getRenderer(), &sdl_rect); } } #endif
1,392
543
#include <mbgl/storage/asset_file_source.hpp> #include <mbgl/storage/file_source_request.hpp> #include <mbgl/storage/local_file_request.hpp> #include <mbgl/storage/response.hpp> #include <mbgl/util/string.hpp> #include <mbgl/util/thread.hpp> #include <mbgl/util/url.hpp> namespace { const std::string assetProtocol = "asset://"; } // namespace namespace mbgl { class AssetFileSource::Impl { public: Impl(ActorRef<Impl>, std::string root_) : root(std::move(root_)) { } void request(const std::string& url, ActorRef<FileSourceRequest> req) { if (!acceptsURL(url)) { Response response; response.error = std::make_unique<Response::Error>(Response::Error::Reason::Other, "Invalid asset URL"); req.invoke(&FileSourceRequest::setResponse, response); return; } // Cut off the protocol and prefix with path. const auto path = root + "/" + mbgl::util::percentDecode(url.substr(assetProtocol.size())); requestLocalFile(path, std::move(req)); } private: std::string root; }; AssetFileSource::AssetFileSource(const std::string& root) : impl(std::make_unique<util::Thread<Impl>>("AssetFileSource", root)) { } AssetFileSource::~AssetFileSource() = default; std::unique_ptr<AsyncRequest> AssetFileSource::request(const Resource& resource, Callback callback) { auto req = std::make_unique<FileSourceRequest>(std::move(callback)); impl->actor().invoke(&Impl::request, resource.url, req->actor()); return std::move(req); } bool AssetFileSource::acceptsURL(const std::string& url) { return 0 == url.rfind(assetProtocol, 0); } } // namespace mbgl
1,740
536
#include "libews.h" #include "ewsnNotificationServiceBindingService.h" #include "ewsnNotificationServiceBinding12Service.h" #include "ews_push_notification_server.h" #include <iostream> #include <sstream> #include <memory> #include "urlparser.h" #include "libews_c_subscribe_callback.h" #ifndef _WIN32 #define closesocket close #endif namespace ewsn { static bool get_sock_port(int sock, int & port) { struct sockaddr_in name; socklen_t namelen = sizeof(name); int err = getsockname(sock, (struct sockaddr*) &name, &namelen); if (err == -1) { return false; } port = ntohs(name.sin_port); return true; } static bool get_bind_ip(const char * ews_server, int ews_server_port, char* buffer, size_t buflen) { bool ret = false; int sock = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in name; socklen_t namelen = sizeof(name); int err; struct sockaddr_in serv; const char * p = NULL; struct hostent *server; if (sock == -1) return false; server = gethostbyname(ews_server); if (server == NULL) { return false; } memset(&serv, 0, sizeof(serv)); serv.sin_family = AF_INET; memmove((char *)&serv.sin_addr.s_addr, (char *)server->h_addr, server->h_length); serv.sin_port = htons(ews_server_port); err = connect(sock, (const struct sockaddr*) &serv, sizeof(serv)); if (err == -1) goto END; err = getsockname(sock, (struct sockaddr*) &name, &namelen); if (err == -1) goto END; p = inet_ntop(AF_INET, &name.sin_addr, buffer, buflen); if (!p) goto END; ret = true; END: closesocket(sock); return ret; } typedef ewsn2__NotificationType ews2__NotificationType; typedef ewsn2__BaseObjectChangedEventType ews2__BaseObjectChangedEventType; typedef _ewsn2__union_BaseObjectChangedEventType _ews2__union_BaseObjectChangedEventType; typedef ewsn2__ModifiedEventType ews2__ModifiedEventType; typedef ewsn2__MovedCopiedEventType ews2__MovedCopiedEventType; typedef _ewsn2__union_MovedCopiedEventType_ _ews2__union_MovedCopiedEventType_; typedef __ewsn2__union_NotificationType __ews2__union_NotificationType; #define SOAP_UNION__ews2__union_NotificationType_CopiedEvent SOAP_UNION__ewsn2__union_NotificationType_CopiedEvent #define SOAP_UNION__ews2__union_MovedCopiedEventType__OldFolderId SOAP_UNION__ewsn2__union_MovedCopiedEventType__OldFolderId #define SOAP_UNION__ews2__union_BaseObjectChangedEventType_FolderId SOAP_UNION__ewsn2__union_BaseObjectChangedEventType_FolderId #define SOAP_UNION__ews2__union_MovedCopiedEventType__OldItemId SOAP_UNION__ewsn2__union_MovedCopiedEventType__OldItemId #define SOAP_UNION__ews2__union_BaseObjectChangedEventType_ItemId SOAP_UNION__ewsn2__union_BaseObjectChangedEventType_ItemId #define SOAP_UNION__ews2__union_NotificationType_CreatedEvent SOAP_UNION__ewsn2__union_NotificationType_CreatedEvent #define SOAP_UNION__ews2__union_BaseObjectChangedEventType_FolderId SOAP_UNION__ewsn2__union_BaseObjectChangedEventType_FolderId #define SOAP_UNION__ews2__union_BaseObjectChangedEventType_ItemId SOAP_UNION__ewsn2__union_BaseObjectChangedEventType_ItemId #define SOAP_UNION__ews2__union_NotificationType_DeletedEvent SOAP_UNION__ewsn2__union_NotificationType_DeletedEvent #define SOAP_UNION__ews2__union_NotificationType_ModifiedEvent SOAP_UNION__ewsn2__union_NotificationType_ModifiedEvent #define SOAP_UNION__ews2__union_NotificationType_MovedEvent SOAP_UNION__ewsn2__union_NotificationType_MovedEvent #define SOAP_UNION__ews2__union_NotificationType_NewMailEvent SOAP_UNION__ewsn2__union_NotificationType_NewMailEvent #include "ews_gsoap_notification_handler.cpp" class DLL_LOCAL CLocalEwsGsoapNotificationServerImpl : public NotificationServiceBindingService { public: CLocalEwsGsoapNotificationServerImpl(ews::CEWSSession * pSession, ews::CEWSSubscriptionCallback * pCallback, char * ip, int port, bool useHttps) : m_pSession(pSession) , m_pCallback(pCallback) , m_Url("") , m_Error() , m_Ip(ip) , m_Port(port) , m_UseHttps(useHttps) , m_Running(false){ } virtual ~CLocalEwsGsoapNotificationServerImpl() { } public: const ews::CEWSError * GetLastError() const { return &m_Error; } const ews::CEWSString & GetURL() const { return m_Url; } virtual int SendNotification(ewsn::ewsn__SendNotificationResponseType* response, ewsn::ewsn__SendNotificationResultType&); virtual int run(int port); virtual int stop(); virtual SOAP_SOCKET bind(const char *host, int port, int backlog); virtual bool BuildUrl(); private: ews::CEWSSession * m_pSession; std::auto_ptr<ews::CEWSSubscriptionCallback> m_pCallback; ews::CEWSString m_Url; ews::CEWSError m_Error; public: char * m_Ip; int m_Port; bool m_UseHttps; bool m_Running; }; } using namespace ewsn; int ewsn::NotificationServiceBindingService::SendNotification(ewsn::ewsn__SendNotificationResponseType*, ewsn::ewsn__SendNotificationResultType&) { return SOAP_SVR_FAULT; } int ewsn::NotificationServiceBinding12Service::SendNotification(ewsn::ewsn__SendNotificationResponseType*, ewsn::ewsn__SendNotificationResultType&) { return SOAP_SVR_FAULT; } CLocalEWSPushNotificationServer::CLocalEWSPushNotificationServer(ews::CEWSSession * pSession, ews::CEWSSubscriptionCallback * pCallback, char * ip, int port, bool useHttps) : m_pSession(pSession) , m_pCallback(pCallback) , m_pServerImpl(new CLocalEwsGsoapNotificationServerImpl(m_pSession, m_pCallback, ip, port, useHttps)) { } CLocalEWSPushNotificationServer::~CLocalEWSPushNotificationServer() { } int CLocalEWSPushNotificationServer::Bind() { SOAP_SOCKET s = m_pServerImpl->bind(m_pServerImpl->m_Ip, m_pServerImpl->m_Port /*port*/, 100); if (!soap_valid_socket(s)) return EWS_FAIL; if (!m_pServerImpl->BuildUrl()) { return EWS_FAIL; } return EWS_SUCCESS; } int CLocalEWSPushNotificationServer::Run() { int ret = m_pServerImpl->run(0); if (ret == SOAP_OK) return EWS_SUCCESS; else { return EWS_FAIL; } } int CLocalEWSPushNotificationServer::Stop() { m_pServerImpl->stop(); return EWS_SUCCESS; } const ews::CEWSString & CLocalEWSPushNotificationServer::GetURL() const { return m_pServerImpl->GetURL(); } const ews::CEWSError * CLocalEWSPushNotificationServer::GetLastError() const { return m_pServerImpl->GetLastError(); } int CLocalEwsGsoapNotificationServerImpl::SendNotification(ewsn::ewsn__SendNotificationResponseType* response, ewsn::ewsn__SendNotificationResultType&) { ewsn::__ewsn__union_ArrayOfResponseMessagesType * __union_ArrayOfResponseMessagesType = response->ResponseMessages->__union_ArrayOfResponseMessagesType; ewsn::ewsn2__NotificationType * Notification = __union_ArrayOfResponseMessagesType->union_ArrayOfResponseMessagesType.SendNotificationResponseMessage->Notification; ewsn::ProcessNotificationMessage(Notification, m_pCallback.get()); return SOAP_OK; } bool CLocalEwsGsoapNotificationServerImpl::BuildUrl() { if (!soap_valid_socket(this->master)) { m_Error.SetErrorCode(EWS_FAIL); m_Error.SetErrorMessage("Build Url failed, invalid socket."); return false; } //build url int port = m_Port; char bind_ip[255] = {0}; char port_buf[255] = {0}; if (!m_Ip) { UrlParser parser(m_pSession->GetConnectionInfo()->Endpoint.GetData()); std::string endpoint_host; int endpoint_port = 0; endpoint_host = parser.GetHost(); if (parser.GetPort().empty()) { std::string schema = parser.GetSchema(); UrlParser::strToLower(schema); if (!schema.compare(std::string("https"))) { endpoint_port = 443; } else { endpoint_port = 80; } } else { endpoint_port = atoi(parser.GetPort().c_str()); } if (!get_sock_port(this->master, port) || !get_bind_ip(endpoint_host.c_str(), endpoint_port, bind_ip, 254)) { m_Error.SetErrorCode(EWS_FAIL); m_Error.SetErrorMessage("Build Url failed, unable to get port or ip."); return false; } } else { sprintf(bind_ip, "%s", m_Ip); } sprintf(port_buf, "%d", (port & 0xFFFF)); m_Url.Clear(); if (m_UseHttps) { m_Url.Append("https://"); } else { m_Url.Append("http://"); } m_Url.Append(bind_ip); m_Url.Append(":"); m_Url.Append(port_buf); return true; } int CLocalEwsGsoapNotificationServerImpl::stop() { m_Running = false; return 0; } int CLocalEwsGsoapNotificationServerImpl::run(int port) { this->accept_timeout = 5; m_Running = true; if (soap_valid_socket(this->master) || soap_valid_socket(bind(NULL, port, 100))) { while(m_Running) { SOAP_SOCKET s = accept(); if (!m_Running) { break; } if (!soap_valid_socket(s)) { if (this->errnum || !m_Running) break; continue; } if (serve()) break; soap_destroy(this); soap_end(this); } } if (this->error != SOAP_OK && m_Running) { m_Error.SetErrorCode(EWS_FAIL); std::stringstream os; os << "error code:" << this->error << std::endl; soap_stream_fault(os); m_Error.SetErrorMessage(os.str().c_str()); } m_Running = false; return this->error; } SOAP_SOCKET CLocalEwsGsoapNotificationServerImpl::bind(const char *host, int port, int backlog) { int ret = NotificationServiceBindingService::bind(host, port, backlog); if (this->error != SOAP_OK) { m_Error.SetErrorCode(EWS_FAIL); std::stringstream os; os << "error code:" << this->error << std::endl; soap_stream_fault(os); m_Error.SetErrorMessage(os.str().c_str()); } return ret; } int ews_notification_server_bind(ews_notification_server * server) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; return s->Bind(); } int ews_notification_server_run(ews_notification_server * server) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; return s->Run(); } int ews_notification_server_stop(ews_notification_server * server) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; return s->Stop(); } int ews_free_notification_server(ews_notification_server * server) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; delete s; return EWS_SUCCESS; } int ews_notification_server_get_url(ews_notification_server * server, char ** pp_url) { CLocalEWSPushNotificationServer * s = (CLocalEWSPushNotificationServer*)server; std::string url = s->GetURL().GetData(); *pp_url = strdup(url.c_str()); return EWS_SUCCESS; } ews_notification_server * ews_create_notification_server(ews_session * session, ews_event_notification_callback * pcallback, ews_notification_server_params * params ) { std::auto_ptr<ews::c::CLocalEWSSubscriptionCallback_C> callback(new ews::c::CLocalEWSSubscriptionCallback_C(pcallback)); std::auto_ptr<CLocalEWSPushNotificationServer> server(new CLocalEWSPushNotificationServer((ews::CEWSSession *)session, callback.release(), params? params->ip : NULL, params? params->port : 0, params? (params->use_https ? true : false) : false)); return (ews_notification_server*)server.release(); }
12,920
4,187
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "inc/Client/Options.h" #include "inc/Client/ClientWrapper.h" #include <cstdio> #include <atomic> #include <iostream> std::unique_ptr<SPTAG::Client::ClientWrapper> g_client; int main(int argc, char** argv) { SPTAG::Client::ClientOptions options; if (!options.Parse(argc - 1, argv + 1)) { return 1; } g_client.reset(new SPTAG::Client::ClientWrapper(options)); if (!g_client->IsAvailable()) { return 1; } g_client->WaitAllFinished(); fprintf(stdout, "connection done\n"); std::string line; std::cout << "Query: " << std::flush; while (std::getline(std::cin, line)) { if (line.empty()) { break; } SPTAG::Socket::RemoteQuery query; query.m_type = SPTAG::Socket::RemoteQuery::QueryType::String; query.m_queryString = std::move(line); SPTAG::Socket::RemoteSearchResult result; auto callback = [&result](SPTAG::Socket::RemoteSearchResult p_result) { result = std::move(p_result); }; g_client->SendQueryAsync(query, callback, options); g_client->WaitAllFinished(); std::cout << "Status: " << static_cast<std::uint32_t>(result.m_status) << std::endl; for (const auto& indexRes : result.m_allIndexResults) { fprintf(stdout, "Index: %s\n", indexRes.m_indexName.c_str()); int idx = 0; for (const auto& res : indexRes.m_results) { fprintf(stdout, "------------------\n"); fprintf(stdout, "DocIndex: %d Distance: %f\n", res.VID, res.Dist); if (indexRes.m_results.WithMeta()) { const auto& metadata = indexRes.m_results.GetMetadata(idx); fprintf(stdout, " MetaData: %.*s\n", static_cast<int>(metadata.Length()), metadata.Data()); } ++idx; } } std::cout << "Query: " << std::flush; } return 0; }
2,137
672
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef airsim_core_PhysicsEngineBase_hpp #define airsim_core_PhysicsEngineBase_hpp #include "common/UpdatableContainer.hpp" #include "common/Common.hpp" #include "PhysicsBody.hpp" namespace msr { namespace airlib { class PhysicsEngineBase : public UpdatableObject { public: virtual void update() override { UpdatableObject::update(); } virtual void reportState(StateReporter& reporter) override { unused(reporter); //default nothing to report for physics engine } //TODO: reduce copy-past from UpdatableContainer which has same code /********************** Container interface **********************/ typedef PhysicsBody* TUpdatableObjectPtr; typedef vector<TUpdatableObjectPtr> MembersContainer; typedef typename MembersContainer::iterator iterator; typedef typename MembersContainer::const_iterator const_iterator; typedef typename MembersContainer::value_type value_type; iterator begin() { return members_.begin(); } iterator end() { return members_.end(); } const_iterator begin() const { return members_.begin(); } const_iterator end() const { return members_.end(); } uint size() const { return static_cast<uint>(members_.size()); } const TUpdatableObjectPtr &at(uint index) const { return members_.at(index); } TUpdatableObjectPtr &at(uint index) { return members_.at(index); } //allow to override membership modifications virtual void clear() { members_.clear(); } virtual void insert(TUpdatableObjectPtr member) { members_.push_back(member); } virtual void erase_remove(TUpdatableObjectPtr obj) { members_.erase(std::remove(members_.begin(), members_.end(), obj), members_.end()); } private: MembersContainer members_; }; }} //namespace #endif
1,950
544
/*++ Copyright (c) 1999-2001 Microsoft Corporation Module Name : server_support.cxx Abstract: IIS Plus ServerSupportFunction command implementations Author: Wade Hilmo (wadeh) 05-Apr-2000 Project: w3isapi.dll --*/ #include "precomp.hxx" #include "isapi_context.hxx" #include "server_support.hxx" // // BUGBUG - stristr is declared in iisrearc\core\inc\irtlmisc.h, // but doesn't appear to be implemented anywhere. Because of the // way it's declared in that file, we have to use a different // function name here... // const char* stristr2( const char* pszString, const char* pszSubString ); HRESULT SSFSendResponseHeader( ISAPI_CONTEXT * pIsapiContext, LPSTR szStatus, LPSTR szHeaders ) /*++ Routine Description: Sends HTTP status and headers to the client. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szStatus - The status to send to the client (ie. "200 OK") szHeaders - Headers to send to the client (ie. foo1: value1\r\n\r\n") Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER[%p]: Function Entry\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szStatus, szHeaders )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // We need validate the fKeepConn status for the request now, // since http.sys will generate the connection response // header based on it. // // If we're going to support keep-alive, then the // ISAPI must return either a content-length header, // or use chunked transfer encoding. We'll check for // that here. // if ( pIsapiContext->QueryClientKeepConn() ) { if ( szHeaders != NULL && ( stristr2( szHeaders, "content-length: " ) != NULL || stristr2( szHeaders, "transfer-encoding: chunked" ) != NULL ) ) { pIsapiContext->SetKeepConn( TRUE ); } } // // Since we automatically decided to keep the connection alive // or not, we should not honor HSE_STATUS_SUCCESS_AND_KEEP_CONN. // This maintains compatibility with previous IIS versions. // pIsapiContext->SetHonorAndKeepConn( FALSE ); // // Note that NULL is valid for both szStatus and szHeaders, // so there's no need to validate them. // hr = pIsapiCore->SendResponseHeaders( !pIsapiContext->QueryKeepConn(), szStatus, szHeaders, HSE_IO_SYNC ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } else { pIsapiContext->SetHeadersSent( TRUE ); } IF_DEBUG( ISAPI_SSF_DETAILS ) { IF_DEBUG( ISAPI_SUCCESS_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER[%p]: Succeeded\r\n" " <END>\r\n\r\n", pIsapiContext )); } } return hr; } HRESULT SSFSendResponseHeaderEx( ISAPI_CONTEXT * pIsapiContext, HSE_SEND_HEADER_EX_INFO * pHeaderInfo ) /*++ Routine Description: Sends HTTP status and headers to the client, and offers explicit control over keep-alive for this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pHeaderInfo - The response info to be passed to the client Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Function Entry\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " KeepConn: %d\r\n", pIsapiContext, pHeaderInfo->pszStatus, pHeaderInfo->pszHeader, pHeaderInfo->fKeepConn )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pHeaderInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Parameter validation failure\r\n" " pHeaderInfo: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Set the keep connection flag. It can only be TRUE if the // ISAPI and the client both want keep alive. // // Note that we are trusting the ISAPI to provide some kind // of content length in the case where it's setting fKeepConn // to TRUE. This is the same behavior as IIS 5 which, for // performance reasons, doesn't try to parse the headers from // the ISAPI. // if ( pHeaderInfo->fKeepConn && pIsapiContext->QueryClientKeepConn() ) { pIsapiContext->SetKeepConn( TRUE ); } hr = pIsapiCore->SendResponseHeaders( !pIsapiContext->QueryKeepConn(), const_cast<LPSTR>( pHeaderInfo->pszStatus ), const_cast<LPSTR>( pHeaderInfo->pszHeader ), HSE_IO_SYNC ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Failed.\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } else { pIsapiContext->SetHeadersSent( TRUE ); } IF_DEBUG( ISAPI_SSF_DETAILS ) { IF_DEBUG( ISAPI_SUCCESS_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_RESPONSE_HEADER_EX[%p]: Succeeded\r\n" " <END>\r\n", pIsapiContext )); } } return hr; } HRESULT SSFMapUrlToPath( ISAPI_CONTEXT * pIsapiContext, LPSTR szBuffer, LPDWORD pcbBuffer ) /*++ Routine Description: Maps a URL into a physical path Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szBuffer - On entry, contains the URL to map. On return, contains the mapped physical path. pcbBuffer - On entry, the size of szBuffer. On successful return, the number of bytes copied to szUrl. On failed return, the number of bytes needed for the physical path. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Function Entry\r\n" " URL: %s\r\n" " <END>\r\n\r\n", pIsapiContext, szBuffer )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( szBuffer == NULL || pcbBuffer == NULL || *pcbBuffer == 0 ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Parameter validation failure\r\n" " Buffer: '%s'\r\n" " Buffer Size Ptr: %p\r\n" " Buffer Size: %d\r\n", pIsapiContext, pcbBuffer, pcbBuffer ? *pcbBuffer : 0 )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->MapPath( reinterpret_cast<BYTE*>( szBuffer ), *pcbBuffer, pcbBuffer, FALSE ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } IF_DEBUG( ISAPI_SSF_DETAILS ) { IF_DEBUG( ISAPI_SUCCESS_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH[%p]: Succeeded\r\n" " Mapped URL: %s\r\n" " <END>\r\n\r\n", pIsapiContext, szBuffer )); } } return hr; } HRESULT SSFMapUrlToPathEx( ISAPI_CONTEXT * pIsapiContext, LPSTR szUrl, HSE_URL_MAPEX_INFO * pHseMapInfo, LPDWORD pcbMappedPath ) /*++ Routine Description: Maps a URL to a physical path and returns some metadata metrics for the URL to the caller. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szUrl - The URL to map pHseMapInfo - Upon return, contains the mapped URL info pcbMappedPath - If non-NULL, contains the buffer size needed to store the mapped physical path. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; DWORD cbMapped; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH_EX[%p]: Function Entry\r\n" " URL='%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MA_URL_TO_PATH_EX[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Additional parameter validation // if ( szUrl == NULL || pHseMapInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH_EX[%p]: Parameter validation failure\r\n" " URL: '%s'\r\n" " HSE_URL_MAPEX_INFO: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pHseMapInfo )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // The inline buffer within the HSE_URL_MAPEX_INFO structure // is defined as being MAX_PATH size. // cbMapped = MAX_PATH; pHseMapInfo->dwReserved1 = 0; pHseMapInfo->dwReserved2 = 0; hr = pIsapiCore->MapPathEx( reinterpret_cast<BYTE*>( szUrl ), (DWORD)strlen(szUrl) + 1, reinterpret_cast<BYTE*>( pHseMapInfo->lpszPath ), cbMapped, pcbMappedPath ? pcbMappedPath : &cbMapped, &pHseMapInfo->cchMatchingPath, &pHseMapInfo->cchMatchingURL, &pHseMapInfo->dwFlags, FALSE ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_URL_TO_PATH_EX[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFMapUnicodeUrlToPath( ISAPI_CONTEXT * pIsapiContext, LPWSTR szBuffer, LPDWORD pcbBuffer ) /*++ Routine Description: Maps a URL into a physical path Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szBuffer - On entry, contains the URL to map. On return, contains the mapped physical path. pcbBuffer - On entry, the size of szBuffer. On successful return, the number of bytes copied to szUrl. On failed return, the number of bytes needed for the physical path. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH[%p]: Function Entry\r\n" " URL='%S'\r\n" " <END>\r\n\r\n", pIsapiContext, szBuffer )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MA_UNICODE_URL_TO_PATH[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( szBuffer == NULL || pcbBuffer == NULL || *pcbBuffer == 0 ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH[%p]: Parameter validation failure\r\n" " Buffer: '%S'\r\n" " Buffer Size Ptr: %p\r\n" " Buffer Size: %d\r\n" " <END>\r\n\r\n", pIsapiContext, szBuffer, pcbBuffer, pcbBuffer ? *pcbBuffer : 0 )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->MapPath( reinterpret_cast<BYTE*>( szBuffer ), *pcbBuffer, pcbBuffer, TRUE ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFMapUnicodeUrlToPathEx( ISAPI_CONTEXT * pIsapiContext, LPWSTR szUrl, HSE_UNICODE_URL_MAPEX_INFO *pHseMapInfo, LPDWORD pcbMappedPath ) /*++ Routine Description: Maps a URL to a physical path and returns some metadata metrics for the URL to the caller. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szUrl - The URL to map pHseMapInfo - Upon return, contains the mapped URL info pcbMappedPath - If non-NULL, contains the buffer size needed to store the mapped physical path. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; DWORD cbMapped; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH_EX[%p]: Function Entry\r\n" " URL='%S'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MA_UNICODE_URL_TO_PATH_EX[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Additional parameter validation // if ( szUrl == NULL || pHseMapInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH_EX[%p]: Parameter validation failure\r\n" " URL: '%s'\r\n" " pHseMapInfo: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pHseMapInfo )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // The inline buffer within the HSE_URL_MAPEX_INFO structure // is defined as being MAX_PATH size. // cbMapped = MAX_PATH * sizeof(WCHAR); hr = pIsapiCore->MapPathEx( reinterpret_cast<BYTE*>( szUrl ), (DWORD)(wcslen(szUrl) + 1)*sizeof(WCHAR), reinterpret_cast<BYTE*>( pHseMapInfo->lpszPath ), cbMapped, pcbMappedPath ? pcbMappedPath : &cbMapped, &pHseMapInfo->cchMatchingPath, &pHseMapInfo->cchMatchingURL, &pHseMapInfo->dwFlags, TRUE ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_MAP_UNICODE_URL_TO_PATH_EX[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFGetImpersonationToken( ISAPI_CONTEXT * pIsapiContext, HANDLE * phToken ) /*++ Routine Description: Returns a (non-duplicated) copy of the token that the server is using to impersonate the client for this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. phToken - Upon return, contains a copy of the token. Return Value: HRESULT --*/ { DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_IMPERSONATION_TOKEN[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } // // Validate parameters // if ( phToken == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_IMPERSONATION_TOKEN[%p]: Parameter validation failure\r\n" " Token Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } *phToken = pIsapiContext->QueryToken(); return NO_ERROR; } HRESULT SSFIsKeepConn( ISAPI_CONTEXT * pIsapiContext, BOOL * pfIsKeepAlive ) /*++ Routine Description: Returns information about whether the client wants us to keep the connection open or not at completion of this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pfIsKeepAlive - Upon return, TRUE if IIS will be keeping the connection alive, else FALSE. Return Value: HRESULT --*/ { DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_KEEP_CONN[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } // // Validate parameters // if ( pfIsKeepAlive == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_KEEP_CONN[%p]: Parameter validation failure\r\n" " KeepAlive Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } *pfIsKeepAlive = pIsapiContext->QueryClientKeepConn(); return NO_ERROR; } HRESULT SSFDoneWithSession( ISAPI_CONTEXT * pIsapiContext, DWORD * pHseResult ) /*++ Routine Description: Notifies the server that the calling ISAPI is done with the ECB (and ISAPI_CONTEXT) for this request and that the server can clean up. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pHseResult - A pointer to the HSE_STATUS code that the extension wants to use. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_ASSERT( pIsapiContext->QueryIoState() == NoAsyncIoPending ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_DONE_WITH_SESSION[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } // // If the caller wants to do STATUS_SUCCESS_AND_KEEP_CONN, // then we need to do that now. // // Note that this overrides our own determination of whether // the client can support keep-alive or not. We are trusting // the caller to have returned the right headers to make this // work with the client. // if ( pHseResult && *pHseResult == HSE_STATUS_SUCCESS_AND_KEEP_CONN ) { if ( pIsapiContext->QueryClientKeepConn() ) { pIsapiContext->SetKeepConn( TRUE ); pIsapiCore->SetConnectionClose( !pIsapiContext->QueryKeepConn() ); } } // // We'll just release the reference on IsapiContext. // Its destructor will do the rest. // pIsapiContext->DereferenceIsapiContext(); pIsapiContext = NULL; return NO_ERROR; } HRESULT SSFGetCertInfoEx( ISAPI_CONTEXT * pIsapiContext, CERT_CONTEXT_EX * pCertContext ) /*++ Routine Description: Returns certificate information about the client associated with this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pCertContext - Upon return, contains info about the client cert. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CERT_INFO_EX[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CERT_INFO_EX[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pCertContext == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CERT_INFO_EX[%p]: Parameter validation failure\r\n" " CertContext Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetCertificateInfoEx( pCertContext->cbAllocated, &( pCertContext->CertContext.dwCertEncodingType ), pCertContext->CertContext.pbCertEncoded, &( pCertContext->CertContext.cbCertEncoded ), &( pCertContext->dwCertificateFlags ) ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CERT_INFO_EX[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFIoCompletion( ISAPI_CONTEXT * pIsapiContext, PFN_HSE_IO_COMPLETION pCompletionRoutine, LPVOID pHseIoContext ) /*++ Routine Description: Establishes the I/O completion routine and user-defined context to be used for asynchronous operations associated with this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pCompletionRoutine - The function to call upon I/O completion pHseIoContext - The user-defined context to be passed to the completion routine. Return Value: HRESULT --*/ { DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IO_COMPLETION[%p]: Function Entry\r\n" " Completion Routine: %p\r\n" " Context: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pCompletionRoutine, pHseIoContext )); } // // Validate parameters // if ( pCompletionRoutine == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IO_COMPLETION[%p]: Parameter validation failure\r\n" " Completion Routine: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } pIsapiContext->SetPfnIoCompletion( pCompletionRoutine ); pIsapiContext->SetExtensionContext( pHseIoContext ); return NO_ERROR; } HRESULT SSFAsyncReadClient( ISAPI_CONTEXT * pIsapiContext, LPVOID pBuffer, LPDWORD pcbBuffer ) /*++ Routine Description: Queues an asynchronous read of data from the client. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pBuffer - Buffer to be filled with read data. pcbBuffer - The size of pBuffer Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; DWORD cbBuffer; HRESULT hr = NOERROR; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Function Entry\r\n" " Bytes to Read: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pcbBuffer ? *pcbBuffer : 0 )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pIsapiContext->QueryPfnIoCompletion() == NULL || pBuffer == NULL || pcbBuffer == NULL || *pcbBuffer == 0 ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Parameter validation failure\r\n" " Completion Routine: %p\r\n" " Buffer Ptr: %p\r\n" " Buffer Size Ptr: %p\r\n" " Buffer Size: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pIsapiContext->QueryPfnIoCompletion(), pBuffer, pcbBuffer, pcbBuffer ? *pcbBuffer : 0 )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Do the async ReadClient call // if ( pIsapiContext->TryInitAsyncIo( AsyncReadPending ) == FALSE ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Failed\r\n" " Another async operation is already pending\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Since we're never actually reading any data in the async // case, we want to prevent pIsapiCore->ReadClient() from // modifying the buffer size we report back to the caller, // so we'll use a local for cbBuffer. // cbBuffer = *pcbBuffer; // // If this call will be going OOP, save a pointer to the // read buffer so that the core can fill it when the // operation completes. // if ( pIsapiContext->QueryIsOop() ) { DBG_ASSERT( pIsapiContext->QueryAsyncIoBuffer() == NULL ); DBG_ASSERT( pIsapiContext->QueryLastAsyncIo() == 0 ); pIsapiContext->SetAsyncIoBuffer( pBuffer ); pIsapiContext->SetLastAsyncIo( cbBuffer ); } hr = pIsapiCore->ReadClient( reinterpret_cast<DWORD64>( pIsapiContext ), pIsapiContext->QueryIsOop() ? NULL : reinterpret_cast<unsigned char*>( pBuffer ), pIsapiContext->QueryIsOop() ? 0 : cbBuffer, cbBuffer, &cbBuffer, HSE_IO_ASYNC ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ASYNC_READ_CLIENT[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } pIsapiContext->SetAsyncIoBuffer( NULL ); pIsapiContext->SetLastAsyncIo( 0 ); pIsapiContext->UninitAsyncIo(); } return hr; } HRESULT SSFTransmitFile( ISAPI_CONTEXT * pIsapiContext, HSE_TF_INFO * pTfInfo ) /*++ Routine Description: Transmits a file, a portion of a file, or some other data (in the event on a NULL file handle) to the client. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pTfInfo - Describes the desired transmit file action. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; LARGE_INTEGER cbFileSize; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { STACK_STRA( strFilename,MAX_PATH ); DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Function Entry\r\n" " Completion Routine: %p\r\n" " Context: %p\r\n" " File Handle: %p\r\n" " Status Code: '%s'\r\n" " Bytes To Write: %d\r\n" " Offset: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pTfInfo ? pTfInfo->pfnHseIO : 0, pTfInfo ? pTfInfo->pContext : 0, pTfInfo ? pTfInfo->hFile : 0, pTfInfo ? pTfInfo->pszStatusCode : 0, pTfInfo ? pTfInfo->BytesToWrite : 0, pTfInfo ? pTfInfo->Offset : 0 )); IF_DEBUG( ISAPI_DUMP_BUFFERS ) { if ( pTfInfo ) { STACK_STRA( strHead,MAX_PATH ); STACK_STRA( strTail,MAX_PATH ); DWORD dwBytesToDump; dwBytesToDump = pTfInfo->HeadLength; if ( dwBytesToDump > MAX_DEBUG_DUMP ) { dwBytesToDump = MAX_DEBUG_DUMP; } if ( FAILED( strHead.CopyBinary( pTfInfo->pHead, dwBytesToDump ) ) ) { strHead.Copy( "" ); } dwBytesToDump = pTfInfo->TailLength; if ( dwBytesToDump > MAX_DEBUG_DUMP ) { dwBytesToDump = MAX_DEBUG_DUMP; } if ( FAILED( strTail.CopyBinary( pTfInfo->pTail, dwBytesToDump ) ) ) { strTail.Copy( "" ); } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Dump of up to %d bytes of head and tail data\r\n" " Head Data:\r\n" "%s" " Tail Data:\r\n" "%s" " <END>\r\n", pIsapiContext, MAX_DEBUG_DUMP, strHead.QueryStr(), strTail.QueryStr() )); } } } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters - For TRANSMIT_FILE, this means: // // - We must have an ISAPI core interface to call through // - We must have an HSE_TF_INFO structure // - The HSE_IO_ASYNC flag must be set // - If HeadLength is set, pHead cannot be NULL // - If TailLength is set, pTail cannot be NULL // - We must have either a completion routine already set // in the ISAPI_CONTEXT, or the HSE_TF_INFO must provide // one // - There can be no other async operations in progress // if ( pTfInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Parameter validation failure\r\n" " Transmit File Info Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( ( pTfInfo->dwFlags & HSE_IO_ASYNC ) == 0 || pTfInfo->hFile == INVALID_HANDLE_VALUE || ( pTfInfo->HeadLength != 0 && pTfInfo->pHead == NULL ) || ( pTfInfo->TailLength != 0 && pTfInfo->pTail == NULL ) || ( pIsapiContext->QueryPfnIoCompletion() == NULL && pTfInfo->pfnHseIO == NULL ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Parameter validation failure\r\n" " %s\r\n", " File Handle: %p\r\n" " Head: %p\r\n" " Head Length: %d\r\n" " Tail: %p\r\n" " Tail Length: %d\r\n" " Completion Routine: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pTfInfo->dwFlags & HSE_IO_ASYNC ? "Async flag set" : "Async flag not set", pTfInfo->hFile, pTfInfo->pHead, pTfInfo->HeadLength, pTfInfo->pTail, pTfInfo->TailLength, pTfInfo->pfnHseIO ? pTfInfo->pfnHseIO : pIsapiContext->QueryPfnIoCompletion() )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pIsapiContext->TryInitAsyncIo( AsyncWritePending ) == FALSE ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Failed\r\n" " Another async operation is already pending.\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // We'll do some extra validation in the case where we've been // provided a file handle. // // Specifically, we'll check to make sure that the offset and // bytes-to-write are valid for the file. // // CODEWORK - Do we really need to do this, or can http.sys handle // it? Also, does http.sys treat zero bytes to write // the same as TransmitFile (ie. send the whole file?) // if ( pTfInfo->hFile != NULL ) { if (!GetFileSizeEx(pTfInfo->hFile, &cbFileSize)) { hr = HRESULT_FROM_WIN32( GetLastError() ); goto Done; } if ( pTfInfo->Offset > cbFileSize.QuadPart || (pTfInfo->Offset > 0 && pTfInfo->Offset == cbFileSize.QuadPart ) || pTfInfo->Offset + pTfInfo->BytesToWrite > cbFileSize.QuadPart ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Parameter validation failure\r\n" " File Size: %d\r\n" " Offset: %d\r\n" " Bytes to Write: %d\r\n" " <END>\r\n\r\n", pIsapiContext, cbFileSize.QuadPart, pTfInfo->Offset, pTfInfo->BytesToWrite )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } else { // // No file handle, so initialize the size to zero // cbFileSize.QuadPart = 0; } // // If the HSE_TF_INFO includes I/O completion or context // information, override the existing settings. // if ( pTfInfo->pfnHseIO ) { pIsapiContext->SetPfnIoCompletion( pTfInfo->pfnHseIO ); } if ( pTfInfo->pContext ) { pIsapiContext->SetExtensionContext( pTfInfo->pContext ); } // // If the extension is setting HSE_IO_SEND_HEADERS, then we need // to determine if it's sending some kind of content length. If // it's not, then we need to set _fKeepConn to FALSE. // // CODEWORK // Note that we're making a bold assumption here that if // HSE_IO_SEND_HEADERS is set, then pHead points to a NULL // terminated string. // if ( pIsapiContext->QueryClientKeepConn() && pTfInfo->pHead && ( pTfInfo->dwFlags & HSE_IO_SEND_HEADERS ) && !( pTfInfo->dwFlags & HSE_IO_DISCONNECT_AFTER_SEND ) ) { if ( stristr2( (LPSTR)pTfInfo->pHead, "content-length: " ) != NULL || stristr2( (LPSTR)pTfInfo->pHead, "transfer-encoding: chunked" ) != NULL ) { pIsapiContext->SetKeepConn( TRUE ); } } if ( pIsapiContext->QueryKeepConn() == FALSE ) { pTfInfo->dwFlags |= HSE_IO_DISCONNECT_AFTER_SEND; } else { // // We need to clear the HSE_IO_DISCONNECT_AFTER_SEND flag // in the case where QueryKeepConn is TRUE. // pTfInfo->dwFlags &= ~HSE_IO_DISCONNECT_AFTER_SEND; } // // Save the BytesToWrite part as _cbLastAsyncIo, since the size of // pHead and pTail confuses ISAPI's that examine the cbWritten // value on completion. // ULARGE_INTEGER cbToWrite; if ( pTfInfo->BytesToWrite ) { cbToWrite.QuadPart = pTfInfo->BytesToWrite; } else { cbToWrite.QuadPart = cbFileSize.QuadPart - pTfInfo->Offset; } // // Note that ISAPI doesn't support large integer values, so the // best we can do here is to store the low bits. // pIsapiContext->SetLastAsyncIo( cbToWrite.LowPart ); hr = pIsapiCore->TransmitFile( reinterpret_cast<DWORD64>( pIsapiContext ), reinterpret_cast<DWORD_PTR>( pTfInfo->hFile ), pTfInfo->Offset, cbToWrite.QuadPart, (pTfInfo->dwFlags & HSE_IO_SEND_HEADERS) ? const_cast<LPSTR>( pTfInfo->pszStatusCode ) : NULL, reinterpret_cast<LPBYTE>( pTfInfo->pHead ), pTfInfo->HeadLength, reinterpret_cast<LPBYTE>( pTfInfo->pTail ), pTfInfo->TailLength, pTfInfo->dwFlags ); Done: if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_TRANSMIT_FILE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } pIsapiContext->SetLastAsyncIo( 0 ); pIsapiContext->UninitAsyncIo(); } return hr; } HRESULT SSFSendRedirect( ISAPI_CONTEXT * pIsapiContext, LPSTR szUrl ) /*++ Routine Description: Sends a 302 redirect to the client associated with this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szUrl - The target URL for the redirection. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_REDIRECT[%p]: Function Entry\r\n" " URL: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_REDIRECT[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pIsapiContext == NULL || szUrl == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_REDIRECT[%p]: Parameter validation failure\r\n" " szUrl: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pIsapiContext->QueryClientKeepConn() ) { pIsapiContext->SetKeepConn( TRUE ); } hr = pIsapiCore->SendRedirect( szUrl, !pIsapiContext->QueryKeepConn() ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_REDIRECT[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFIsConnected( ISAPI_CONTEXT * pIsapiContext, BOOL * pfIsConnected ) /*++ Routine Description: Returns the connection state (connected or not connected) of the client associated with this request. Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pfIsConnected - TRUE upon return if the client is connected, else FALSE. Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_CONNECTED[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_CONNECTED[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( pfIsConnected == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_CONNECTED[%p]: Parameter validation failure\r\n" " IsConnected Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->TestConnection( pfIsConnected ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_CONNECTED[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFAppendLog( ISAPI_CONTEXT * pIsapiContext, LPSTR szExtraParam ) /*++ Routine Description: Appends the string passed to the QueryString that will be logged Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. szExtraParam - The extra parameter to be logged Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_APPEND_LOG_PARAMETER[%p]: Function Entry\r\n" " Extra Param: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szExtraParam )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_APPEND_LOG_PARAMETER[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate parameters // if ( szExtraParam == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_APPEND_LOG_PARAMETER[%p]: Parameter validation failure\r\n" " Extra Param: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->AppendLog( szExtraParam, 0 ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_APPEND_LOG_PARAMETER[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFExecuteUrl( ISAPI_CONTEXT * pIsapiContext, VOID * pOrigExecUrlInfo, BOOL fIsUnicode ) /*++ Routine Description: Execute a child request Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pOrigExecUrlInfo - Description of child request to execute fIsUnicode - Are we passing unicode data? Return Value: HRESULT --*/ { EXEC_URL_USER_INFO UserName; EXEC_URL_ENTITY_INFO Entity; EXEC_URL_INFO UrlInfo; IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { HSE_EXEC_URL_ENTITY_INFO *pEntityInfo = NULL; if ( fIsUnicode ) { HSE_EXEC_UNICODE_URL_INFO *pInfo = (HSE_EXEC_UNICODE_URL_INFO *)pOrigExecUrlInfo; HSE_EXEC_UNICODE_URL_USER_INFO *pUserInfo = NULL; if ( pInfo ) { pUserInfo = pInfo->pUserInfo; pEntityInfo = pInfo->pEntity; } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Function Entry\r\n" " URL: '%S'\r\n" " Method: '%s'\r\n" " Child Headers: '%s'\r\n" " Flags: 0x%08x (%d)\r\n" " Impersonation Token: %p\r\n" " Custom User Name: '%S'\r\n" " Custom Auth Type: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pInfo ? pInfo->pszUrl : NULL, pInfo ? pInfo->pszMethod : NULL, pInfo ? pInfo->pszChildHeaders : NULL, pInfo ? pInfo->dwExecUrlFlags : 0, pInfo ? pInfo->dwExecUrlFlags : 0, pUserInfo ? pUserInfo->hImpersonationToken : NULL, pUserInfo ? pUserInfo->pszCustomUserName : NULL, pUserInfo ? pUserInfo->pszCustomAuthType : NULL )); } else { HSE_EXEC_URL_INFO *pInfo = (HSE_EXEC_URL_INFO *)pOrigExecUrlInfo; HSE_EXEC_URL_USER_INFO *pUserInfo = NULL; if ( pInfo ) { pUserInfo = pInfo->pUserInfo; pEntityInfo = pInfo->pEntity; } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Function Entry\r\n" " URL: '%s'\r\n" " Method: '%s'\r\n" " Child Headers: '%s'\r\n" " Flags: 0x%08x (%d)\r\n" " Impersonation Token: %p\r\n" " Custom User Name: '%s'\r\n" " Custom Auth Type: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pInfo ? pInfo->pszUrl : NULL, pInfo ? pInfo->pszMethod : NULL, pInfo ? pInfo->pszChildHeaders : NULL, pInfo ? pInfo->dwExecUrlFlags : 0, pInfo ? pInfo->dwExecUrlFlags : 0, pUserInfo ? pUserInfo->hImpersonationToken : NULL, pUserInfo ? pUserInfo->pszCustomUserName : NULL, pUserInfo ? pUserInfo->pszCustomAuthType : NULL )); } IF_DEBUG( ISAPI_DUMP_BUFFERS ) { if ( pEntityInfo ) { STACK_STRA( strBufferDump,512 ); DWORD dwBytesToDump = pEntityInfo->cbAvailable; if ( dwBytesToDump > MAX_DEBUG_DUMP ) { dwBytesToDump = MAX_DEBUG_DUMP; } if ( FAILED( strBufferDump.CopyBinary( pEntityInfo->lpbData, dwBytesToDump ) ) ) { strBufferDump.Copy( "" ); } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Dump of up to %d bytes of entity\r\n" "%s" " <END>\r\n\r\n", pIsapiContext, MAX_DEBUG_DUMP, strBufferDump.QueryStr() )); } } } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pOrigExecUrlInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " ExecUrl Info: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // This is an async call, make sure a completion routine is set // if ( pIsapiContext->QueryPfnIoCompletion() == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Failed\r\n" " No I/O completion has been set: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pIsapiContext->TryInitAsyncIo( AsyncExecPending ) == FALSE ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Failed\r\n" " An async operation is already pending: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // If any of the optional parameters are not NULL, then ensure they are // not empty. Also, copy parameters to the marshallable structure // // Note that any failures from here on down need to goto Done so // that we properly uninitialize async IO. // if (fIsUnicode) { HSE_EXEC_UNICODE_URL_INFO *pExecUnicodeUrlInfo = (HSE_EXEC_UNICODE_URL_INFO *)pOrigExecUrlInfo; if ( pExecUnicodeUrlInfo->pszUrl != NULL ) { if ( pExecUnicodeUrlInfo->pszUrl[ 0 ] == L'\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " URL is an empty string.\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } UrlInfo.fIsUrlUnicode = TRUE; UrlInfo.pszUrl = (BYTE *)pExecUnicodeUrlInfo->pszUrl; UrlInfo.cbUrl = (DWORD)(wcslen(pExecUnicodeUrlInfo->pszUrl) + 1)*sizeof(WCHAR); } else { UrlInfo.pszUrl = NULL; UrlInfo.cbUrl = 0; } if ( pExecUnicodeUrlInfo->pszMethod != NULL ) { if ( pExecUnicodeUrlInfo->pszMethod[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " Method is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } UrlInfo.pszMethod = pExecUnicodeUrlInfo->pszMethod; if ( pExecUnicodeUrlInfo->pszChildHeaders != NULL ) { if ( pExecUnicodeUrlInfo->pszChildHeaders[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " ChildHeaders is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } UrlInfo.pszChildHeaders = pExecUnicodeUrlInfo->pszChildHeaders; if ( pExecUnicodeUrlInfo->pUserInfo != NULL ) { if ( pExecUnicodeUrlInfo->pUserInfo->pszCustomUserName == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " Custom User Name: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } if ( pExecUnicodeUrlInfo->pUserInfo->pszCustomAuthType == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " Custom Auth Type: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } UserName.fIsUserNameUnicode = TRUE; UserName.pszUserName = (BYTE *)pExecUnicodeUrlInfo->pUserInfo->pszCustomUserName; UserName.cbUserName = (DWORD)(wcslen(pExecUnicodeUrlInfo->pUserInfo->pszCustomUserName) + 1)*sizeof(WCHAR); UserName.pszAuthType = pExecUnicodeUrlInfo->pUserInfo->pszCustomAuthType; UserName.hImpersonationToken = (DWORD_PTR)pExecUnicodeUrlInfo->pUserInfo->hImpersonationToken; UrlInfo.pUserInfo = &UserName; } else { UrlInfo.pUserInfo = NULL; } // // If we are being told that there is available entity, ensure // that the buffer is not NULL // if ( pExecUnicodeUrlInfo->pEntity != NULL ) { if ( pExecUnicodeUrlInfo->pEntity->cbAvailable != 0 && pExecUnicodeUrlInfo->pEntity->lpbData == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_UNICODE_URL[%p]: Parameter validation failure\r\n" " Available Entity bytes: %d\r\n" " Available Entity Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pExecUnicodeUrlInfo->pEntity->cbAvailable, pExecUnicodeUrlInfo->pEntity->lpbData )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } Entity.cbAvailable = pExecUnicodeUrlInfo->pEntity->cbAvailable; Entity.lpbData = (BYTE *)pExecUnicodeUrlInfo->pEntity->lpbData; } else { // // If no entity body was set for this child execute, then // we should duplicate the original entity body. This means // we will need to bring over the preloaded entity for the // ISAPI which calls this routine. // Entity.cbAvailable = pIsapiContext->QueryECB()->cbAvailable; Entity.lpbData = pIsapiContext->QueryECB()->lpbData; } UrlInfo.pEntity = &Entity; UrlInfo.dwExecUrlFlags = pExecUnicodeUrlInfo->dwExecUrlFlags; } else { HSE_EXEC_URL_INFO *pExecAnsiUrlInfo = (HSE_EXEC_URL_INFO *)pOrigExecUrlInfo; if ( pExecAnsiUrlInfo->pszUrl != NULL ) { if ( pExecAnsiUrlInfo->pszUrl[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " URL is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } UrlInfo.fIsUrlUnicode = FALSE; UrlInfo.pszUrl = (BYTE *)pExecAnsiUrlInfo->pszUrl; UrlInfo.cbUrl = (DWORD)strlen(pExecAnsiUrlInfo->pszUrl) + 1; } else { UrlInfo.pszUrl = NULL; UrlInfo.cbUrl = 0; } if ( pExecAnsiUrlInfo->pszMethod != NULL ) { if ( pExecAnsiUrlInfo->pszMethod[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " Method is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } UrlInfo.pszMethod = pExecAnsiUrlInfo->pszMethod; if ( pExecAnsiUrlInfo->pszChildHeaders != NULL ) { if ( pExecAnsiUrlInfo->pszChildHeaders[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " ChildHeaders is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } } UrlInfo.pszChildHeaders = pExecAnsiUrlInfo->pszChildHeaders; if ( pExecAnsiUrlInfo->pUserInfo != NULL ) { if ( pExecAnsiUrlInfo->pUserInfo->pszCustomUserName == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " Custom User Name: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } if ( pExecAnsiUrlInfo->pUserInfo->pszCustomAuthType == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " Custom Auth Type: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } UserName.fIsUserNameUnicode = FALSE; UserName.pszUserName = (BYTE *)pExecAnsiUrlInfo->pUserInfo->pszCustomUserName; UserName.cbUserName = (DWORD)strlen(pExecAnsiUrlInfo->pUserInfo->pszCustomUserName) + 1; UserName.pszAuthType = pExecAnsiUrlInfo->pUserInfo->pszCustomAuthType; UserName.hImpersonationToken = (DWORD_PTR)pExecAnsiUrlInfo->pUserInfo->hImpersonationToken; UrlInfo.pUserInfo = &UserName; } else { UrlInfo.pUserInfo = NULL; } // // If we are being told that there is available entity, ensure // that the buffer is not NULL // if ( pExecAnsiUrlInfo->pEntity != NULL ) { if ( pExecAnsiUrlInfo->pEntity->cbAvailable != 0 && pExecAnsiUrlInfo->pEntity->lpbData == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Parameter validation failure\r\n" " Available Entity Bytes: %d\r\n" " Available Entity Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pExecAnsiUrlInfo->pEntity->cbAvailable, pExecAnsiUrlInfo->pEntity->lpbData )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Done; } Entity.cbAvailable = pExecAnsiUrlInfo->pEntity->cbAvailable; Entity.lpbData = (BYTE *)pExecAnsiUrlInfo->pEntity->lpbData; } else { // // If no entity body was set for this child execute, then // we should duplicate the original entity body. This means // we will need to bring over the preloaded entity for the // ISAPI which calls this routine. // Entity.cbAvailable = pIsapiContext->QueryECB()->cbAvailable; Entity.lpbData = pIsapiContext->QueryECB()->lpbData; } UrlInfo.pEntity = &Entity; UrlInfo.dwExecUrlFlags = pExecAnsiUrlInfo->dwExecUrlFlags; } // // All the heavy lifting is in W3CORE.DLL // hr = pIsapiCore->ExecuteUrl( reinterpret_cast<DWORD64>( pIsapiContext ), &UrlInfo ); Done: if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_EXEC_URL[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } pIsapiContext->UninitAsyncIo(); } return hr; } HRESULT SSFGetExecuteUrlStatus( ISAPI_CONTEXT * pIsapiContext, HSE_EXEC_URL_STATUS* pExecUrlStatus ) /*++ Routine Description: Get status of last child execute Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pExecUrlStatus - Filled with status Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_EXEC_URL_STATUS[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_EXEC_URL_STATUS[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pExecUrlStatus == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_EXEC_URL_STATUS[%p]: Parameter validation failure\r\n" " EXEC_URL Status Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetExecuteUrlStatus( &(pExecUrlStatus->uHttpStatusCode), &(pExecUrlStatus->uHttpSubStatus), &(pExecUrlStatus->dwWin32Error) ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_EXEC_URL_STATUS[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFSendCustomError( ISAPI_CONTEXT * pIsapiContext, HSE_CUSTOM_ERROR_INFO * pCustomErrorInfo ) /*++ Routine Description: Send custom error to client Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pCustomErrorInfo - Describes the custom error to send Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr = NOERROR; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Function Entry\r\n" " Status: '%s'\r\n" " SubError Code: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pCustomErrorInfo ? pCustomErrorInfo->pszStatus : NULL, pCustomErrorInfo ? pCustomErrorInfo->uHttpSubError : 0 )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ( pCustomErrorInfo == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Parameter validation failure\r\n" " Custom Error Info Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Ensure status is not empty // if ( pCustomErrorInfo->pszStatus != NULL ) { if ( pCustomErrorInfo->pszStatus[ 0 ] == '\0' ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Parameter validation failure\r\n" " Status is an empty string\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } } // // If this is an async call, then make sure a completion routine is set // if ( pCustomErrorInfo->fAsync ) { if ( pIsapiContext->TryInitAsyncIo( AsyncExecPending ) == FALSE ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Failed\r\n" " Another async operation is already pending\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } } hr = pIsapiCore->SendCustomError( pCustomErrorInfo->fAsync ? reinterpret_cast<DWORD64>( pIsapiContext ) : NULL, pCustomErrorInfo->pszStatus, pCustomErrorInfo->uHttpSubError ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_SEND_CUSTOM_ERROR[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } if ( pCustomErrorInfo->fAsync ) { pIsapiContext->UninitAsyncIo(); } return hr; } return hr; } HRESULT SSFVectorSendDeprecated( ISAPI_CONTEXT * pIsapiContext, HSE_RESPONSE_VECTOR_DEPRECATED * pResponseVector ) /*++ Routine Description: The old deprecated vector-send Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pResponseVector - The vector to be sent Return Value: HRESULT --*/ { HSE_RESPONSE_VECTOR RealResponseVector; STACK_BUFFER( buffResp, 512); HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND_DEPRECATED[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } if ( pResponseVector == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND_DEPRECATED[%p]: Parameter validation failure\r\n" " Response Vector Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } RealResponseVector.dwFlags = pResponseVector->dwFlags; RealResponseVector.pszStatus = pResponseVector->pszStatus; RealResponseVector.pszHeaders = pResponseVector->pszHeaders; RealResponseVector.nElementCount = pResponseVector->nElementCount; if (!buffResp.Resize(pResponseVector->nElementCount * sizeof(HSE_VECTOR_ELEMENT))) { return HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); } RealResponseVector.lpElementArray = (HSE_VECTOR_ELEMENT *)buffResp.QueryPtr(); for (DWORD i=0; i<pResponseVector->nElementCount; i++) { if (pResponseVector->lpElementArray[i].pBuffer != NULL) { RealResponseVector.lpElementArray[i].ElementType = HSE_VECTOR_ELEMENT_TYPE_MEMORY_BUFFER; RealResponseVector.lpElementArray[i].pvContext = pResponseVector->lpElementArray[i].pBuffer; RealResponseVector.lpElementArray[i].cbSize = pResponseVector->lpElementArray[i].cbSize; } else { RealResponseVector.lpElementArray[i].ElementType = HSE_VECTOR_ELEMENT_TYPE_FILE_HANDLE; RealResponseVector.lpElementArray[i].pvContext = pResponseVector->lpElementArray[i].hFile; RealResponseVector.lpElementArray[i].cbOffset = pResponseVector->lpElementArray[i].cbOffset; RealResponseVector.lpElementArray[i].cbSize = pResponseVector->lpElementArray[i].cbSize; } } hr = SSFVectorSend(pIsapiContext, &RealResponseVector); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND_DEPRECATED[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFVectorSend( ISAPI_CONTEXT * pIsapiContext, HSE_RESPONSE_VECTOR * pResponseVector ) /*++ Routine Description: Send an array of memory/file-handle/fragment-cache chunks Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pResponseVector - The vector to be sent Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; ULONGLONG cbTotalSend = 0; STACK_BUFFER( buffResp, 512); HRESULT hr = NOERROR; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Function Entry (%s)\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " Element Count: %d\r\n" " Flags: 0x%08x (%d)\r\n" " <END>\r\n\r\n", pIsapiContext, pResponseVector ? pResponseVector->dwFlags & HSE_IO_ASYNC ? "Asynchronous" : "Synchronous" : "", pResponseVector ? pResponseVector->pszStatus : NULL, pResponseVector ? pResponseVector->pszHeaders : NULL, pResponseVector ? pResponseVector->nElementCount : 0, pResponseVector ? pResponseVector->dwFlags : 0, pResponseVector ? pResponseVector->dwFlags : 0 )); IF_DEBUG( ISAPI_DUMP_BUFFERS ) { if ( pResponseVector && pResponseVector->nElementCount ) { STACK_STRA( strBufferDump,512 ); DWORD dwBytesToDump; DWORD i; for ( i = 0; i < pResponseVector->nElementCount; i++ ) { if ( pResponseVector->lpElementArray[i].ElementType == HSE_VECTOR_ELEMENT_TYPE_MEMORY_BUFFER ) { dwBytesToDump = pResponseVector->lpElementArray[i].cbSize; if ( dwBytesToDump > MAX_DEBUG_DUMP ) { dwBytesToDump = MAX_DEBUG_DUMP; } if ( FAILED( strBufferDump.CopyBinary( pResponseVector->lpElementArray[i].pvContext, dwBytesToDump ) ) ) { strBufferDump.Copy( "" ); } DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Dump of up to %d bytes of element %d\r\n" "%s" " <END>\r\n\r\n", pIsapiContext, MAX_DEBUG_DUMP, i, strBufferDump.QueryStr() )); } else if ( pResponseVector->lpElementArray[i].ElementType == HSE_VECTOR_ELEMENT_TYPE_FILE_HANDLE ) { DBGPRINTF(( DBG_CONTEXT, "\r\n", " HSE_REQ_VECTOR_SEND[%p]: Element %d\r\n" " File Handle: %p\r\n" " Offset: %d\r\n" " Bytes To Send: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pResponseVector->lpElementArray[i].pvContext, pResponseVector->lpElementArray[i].cbOffset, pResponseVector->lpElementArray[i].cbSize )); } } } } } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // verify the data passed in // if ( pResponseVector == NULL || ( ( pResponseVector->dwFlags & HSE_IO_ASYNC ) != 0 && pIsapiContext->TryInitAsyncIo( AsyncVectorPending ) == FALSE ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Failed\r\n" " Another async operation is already pending\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } if ((pResponseVector->dwFlags & HSE_IO_SYNC) && (pResponseVector->dwFlags & HSE_IO_ASYNC)) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Both HSE_IO_SYNC and HSE_IO_ASYNC were specified\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } if (pResponseVector->dwFlags & HSE_IO_SEND_HEADERS) { if ((pResponseVector->pszStatus == NULL) || (pResponseVector->pszHeaders == NULL)) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " HSE_IO_SEND_HEADERS was specified, but some required info is missing\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pResponseVector->pszStatus, pResponseVector->pszHeaders )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } } else { if ((pResponseVector->pszStatus != NULL) || (pResponseVector->pszHeaders != NULL)) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " HSE_IO_SEND_HEADERS was not specified, yet status or header info was provided\r\n" " Status: '%s'\r\n" " Headers: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pResponseVector->pszStatus, pResponseVector->pszHeaders )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } } if (!buffResp.Resize(pResponseVector->nElementCount * sizeof(VECTOR_ELEMENT))) { hr = HRESULT_FROM_WIN32( ERROR_NOT_ENOUGH_MEMORY ); goto Failed; } ZeroMemory(buffResp.QueryPtr(), pResponseVector->nElementCount * sizeof(VECTOR_ELEMENT)); VECTOR_ELEMENT *pVectorElement = (VECTOR_ELEMENT *)buffResp.QueryPtr(); HSE_VECTOR_ELEMENT *pHseVectorElement; for (DWORD i=0; i<pResponseVector->nElementCount; i++) { pHseVectorElement = &pResponseVector->lpElementArray[i]; if (pHseVectorElement->pvContext == NULL) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Context: NULL on element %d in the array\r\n" " <END>\r\n\r\n", pIsapiContext, i )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } switch (pHseVectorElement->ElementType) { case HSE_VECTOR_ELEMENT_TYPE_MEMORY_BUFFER: if (pHseVectorElement->cbSize > MAXULONG) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Invalid memory buffer size on element %d in the array\r\n" " Size: %d\r\n" " <END>\r\n\r\n", pIsapiContext, i, pHseVectorElement->cbSize )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } pVectorElement[i].pBuffer = (BYTE *)pHseVectorElement->pvContext; cbTotalSend += ( pVectorElement[i].cbBufSize = (DWORD)pHseVectorElement->cbSize ); break; case HSE_VECTOR_ELEMENT_TYPE_FILE_HANDLE: if (pHseVectorElement->pvContext == INVALID_HANDLE_VALUE) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Handle on file handle element %d in the array is invalid\r\n" " File Handle: %p\r\n" " <END>\r\n\r\n", pIsapiContext, i, pHseVectorElement->pvContext )); } hr = HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); goto Failed; } // // Treat 0 as "send the rest of the file" - same as TransmitFile // if (pHseVectorElement->cbSize == 0) { pHseVectorElement->cbSize = HTTP_BYTE_RANGE_TO_EOF; } pVectorElement[i].hFile = (DWORD_PTR)pHseVectorElement->pvContext; pVectorElement[i].cbOffset = pHseVectorElement->cbOffset; cbTotalSend += ( pVectorElement[i].cbFileSize = pHseVectorElement->cbSize ); break; case HSE_VECTOR_ELEMENT_TYPE_FRAGMENT: pVectorElement[i].pszFragmentName = (WCHAR *)pHseVectorElement->pvContext; break; default: IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Parameter validation failure\r\n" " Unknown type on element %d in the array\r\n" " Element Type: %d\r\n" " <END>\r\n\r\n", pIsapiContext, i, pHseVectorElement->ElementType )); } hr = HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); goto Failed; } } // // Set up the total number of bytes we are trying to send so that ISAPIs // are not confused // pIsapiContext->SetLastAsyncIo( (cbTotalSend > MAXULONG) ? MAXULONG : (DWORD)cbTotalSend ); // // In general, VECTOR_SEND shouldn't touch the connection flags // in the ISAPI_CONTEXT, since ISAPI tries to do the right thing // automatically. // // There are couple of scenarios, though, where we might have a // bit of connection management housekeeping to do. // // If the caller specified the HSE_IO_DISCONNECT_AFTER_SEND flag, // then we need to force the connection closed. // // Otherwise, there are two scenarios where we may need to force // the connection to stay open. // // First, if all of the below are true, we should set the // connection to be open: // // - The client requested keep-alive // - This call is sending headers (HSE_IO_SEND_HEADERS is set) // - The disconnect flag has not been set // // Second, if all of the below are true, we should set the // connection to be open. // // - The client requested keep-alive // - The ISAPI has not already sent headers // - The disconnect flag has not been set // - This is the final send // // One final note: This logic does not account for the case where // this call is sending headers, and the call fails for some reason. // In the asynchronous case, this would be somewhat complicated to // handle, since the completion routine would need to know both if // the caller was sending headers, and also that the I/O failed. // Presumably, if such a failure occurs, the most likely reason is // that the client already disconnected, or it would otherwise be // unlikely for the caller to do something to try and recover and // redo this send in a way that would succeed, which makes all of this // moot. // if ( pResponseVector->dwFlags & HSE_IO_DISCONNECT_AFTER_SEND ) { pIsapiContext->SetKeepConn( FALSE ); } else { if ( pIsapiContext->QueryClientKeepConn() ) { if ( (pResponseVector->dwFlags & HSE_IO_SEND_HEADERS) || ( pIsapiContext->QueryHeadersSent() == FALSE && (pResponseVector->dwFlags & HSE_IO_FINAL_SEND) ) ) { pIsapiContext->SetKeepConn( TRUE ); } } } hr = pIsapiCore->VectorSend( pResponseVector->dwFlags & HSE_IO_ASYNC ? reinterpret_cast<DWORD64>( pIsapiContext ) : NULL, !pIsapiContext->QueryKeepConn(), pResponseVector->pszStatus, pResponseVector->pszHeaders, pVectorElement, pResponseVector->nElementCount, !!(pResponseVector->dwFlags & HSE_IO_FINAL_SEND), !!(pResponseVector->dwFlags & HSE_IO_CACHE_RESPONSE) ); if ( FAILED( hr ) ) { goto Failed; } return hr; Failed: DBG_ASSERT( FAILED( hr ) ); IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_VECTOR_SEND[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } if ( pResponseVector->dwFlags & HSE_IO_ASYNC ) { pIsapiContext->SetLastAsyncIo( 0 ); pIsapiContext->UninitAsyncIo(); } return hr; } HRESULT SSFGetCustomErrorPage( ISAPI_CONTEXT * pIsapiContext, HSE_CUSTOM_ERROR_PAGE_INFO * pInfo ) { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CUSTOM_ERROR_PAGE[%p]: Function Entry\r\n" " Error: %d\r\n" " SubError: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pInfo ? pInfo->dwError : 0, pInfo ? pInfo->dwSubError : 0 )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CUSTOM_ERROR_PAGE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Validate arguments // if ( pInfo == NULL || ( pInfo->dwBufferSize != 0 && pInfo->pBuffer == NULL ) || pInfo->pdwBufferRequired == NULL || pInfo->pfIsFileError == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CUSTOM_ERROR_PAGE[%p]: Parameter validation failure\r\n" " Info Ptr: %p\r\n" " Buffer Size: %d\r\n" " Buffer Ptr: %p\r\n" " Buffer Required Ptr: %p\r\n" " IsFileError Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pInfo, pInfo ? pInfo->dwBufferSize : 0, pInfo ? pInfo->pBuffer : NULL, pInfo ? pInfo->pdwBufferRequired : NULL, pInfo ? pInfo->pfIsFileError : NULL )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetCustomError( pInfo->dwError, pInfo->dwSubError, pInfo->dwBufferSize, reinterpret_cast<BYTE*>( pInfo->pBuffer ), pInfo->pdwBufferRequired, pInfo->pfIsFileError, pInfo->pfSendErrorBody ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CUSTOM_ERROR_PAGE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFIsInProcess( ISAPI_CONTEXT * pIsapiContext, DWORD * pdwAppFlag ) { LPWSTR szClsid; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_IN_PROCESS[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } if ( pdwAppFlag == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_IS_IN_PROCESS[%p]: Parameter validation failure\r\n" " AppFlag Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } szClsid = pIsapiContext->QueryClsid(); DBG_ASSERT( szClsid != NULL ); if ( wcslen( szClsid ) == 0 ) { *pdwAppFlag = HSE_APP_FLAG_IN_PROCESS; } else if ( _wcsicmp( szClsid, W3_OOP_POOL_WAM_CLSID ) == NULL ) { *pdwAppFlag = HSE_APP_FLAG_POOLED_OOP; } else { *pdwAppFlag = HSE_APP_FLAG_ISOLATED_OOP; } return NO_ERROR; } HRESULT SSFGetSspiInfo( ISAPI_CONTEXT * pIsapiContext, CtxtHandle * pCtxtHandle, CredHandle * pCredHandle ) { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_SSPI_INFO[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } // // The CtxtHandle and CredHandle are only valid in their // local process. There is no way to duplicate them into // a dllhost. As a result, this function is inproc only. // if ( pIsapiContext->QueryIsOop() ) { return HRESULT_FROM_WIN32( ERROR_INVALID_FUNCTION ); } // // Validate parameters // if ( pCtxtHandle == NULL || pCredHandle == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_SSPI_INFO[%p]: Parameter validation Failure\r\n" " Context Handle Ptr: %p\r\n" " Credential Handle Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pCtxtHandle, pCredHandle )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetSspiInfo( reinterpret_cast<BYTE*>( pCredHandle ), sizeof( CredHandle ), reinterpret_cast<BYTE*>( pCtxtHandle ), sizeof( CtxtHandle ) ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_SSPI_INFO[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFGetVirtualPathToken( ISAPI_CONTEXT * pIsapiContext, LPSTR szUrl, HANDLE * pToken, BOOL fUnicode ) { IIsapiCore * pIsapiCore; HRESULT hr = S_OK; DWORD64 dwToken; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { if ( fUnicode ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_UNICODE_VIRTUAL_PATH_TOKEN[%p]: Function Entry\r\n" " URL: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } else { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_VIRTUAL_PATH_TOKEN[%p]: Function Entry\r\n" " URL: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } } // // Validate parameters // if ( szUrl == NULL || pToken == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { if ( fUnicode ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_UNICODE_VIRTUAL_PATH_TOKEN[%p]: Parameter validation failure\r\n" " URL: '%S'\r\n" " Token Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pToken )); } else { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_VIRTUAL_PATH_TOKEN[%p]: Parameter validation failure\r\n" " URL: '%s'\r\n" " Token Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pToken )); } } } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->QueryToken( reinterpret_cast<BYTE*>( szUrl ), (DWORD)( fUnicode ? (wcslen( (LPWSTR)szUrl ) + 1 ) * sizeof(WCHAR) : strlen( szUrl ) + 1 ), TOKEN_VR_TOKEN, &dwToken, fUnicode ); if (FAILED(hr)) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_%sVIRTUAL_PATH_TOKEN[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", fUnicode ? "UNICODE_" : "", pIsapiContext, hr )); } return hr; } *pToken = (HANDLE)dwToken; return hr; } HRESULT SSFGetAnonymousToken( ISAPI_CONTEXT * pIsapiContext, LPSTR szUrl, HANDLE * pToken, BOOL fUnicode ) { IIsapiCore * pIsapiCore; DWORD64 dwToken; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { if ( fUnicode ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_UNICODE_ANONYMOUS_TOKEN[%p]: Function Entry\r\n" " URL: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } else { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_ANONYMOUS_TOKEN[%p]: Function Entry\r\n" " URL: '%s\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl )); } } // // Validate parameters // if ( szUrl == NULL || pToken == NULL ) { if ( fUnicode ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_UNICODE_ANONYMOUS_TOKEN[%p]: Parameter validation failure\r\n" " URL: '%S'\r\n" " Token Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pToken )); } } else { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_ANONYMOUS_TOKEN[%p]: Parameter validation failure\r\n" " URL: '%s'\r\n" " Token Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, szUrl, pToken )); } } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->QueryToken( reinterpret_cast<BYTE*>( szUrl ), (DWORD)( fUnicode ? (wcslen( (LPWSTR)szUrl ) + 1 ) * sizeof(WCHAR) : strlen( szUrl ) + 1 ), TOKEN_ANONYMOUS_TOKEN, &dwToken, fUnicode ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_%sANONYMOUS_TOKEN[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", fUnicode ? "UNICODE_" : "", pIsapiContext, hr )); } return hr; } *pToken = (HANDLE)dwToken; return hr; } HRESULT SSFReportUnhealthy( ISAPI_CONTEXT * pIsapiContext, LPSTR szReason ) { IIsapiCore * pIsapiCore; LPWSTR szImage; STACK_STRU( strReason, 512 ); DWORD cbImage; DWORD cbReason; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); DBG_REQUIRE( ( szImage = pIsapiContext->QueryGatewayImage() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REPORT_UNHEALTHY[%p]: Function Entry\r\n" " Reason: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, szReason )); } cbImage = (DWORD)( wcslen( szImage ) + 1 ) * sizeof( WCHAR ); // // If the ISAPI has given a reason, we need to send it // as UNICODE. // if ( szReason == NULL ) { cbReason = 0; } else { hr = strReason.CopyA( szReason ); if ( FAILED( hr ) ) { return hr; } cbReason = ( strReason.QueryCCH() + 1 ) * sizeof( WCHAR ); } hr = pIsapiCore->ReportAsUnhealthy( reinterpret_cast<BYTE*>( szImage ), cbImage, cbReason ? reinterpret_cast<BYTE*>( strReason.QueryStr() ) : NULL, cbReason ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REPORT_UNHEALTHY[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFNormalizeUrl( LPSTR pszURL ) /*++ Routine Description: Normalize URL Arguments: pszURL - On entry, contains not normalized URL. On return, contains normalized URL. Return Value: HRESULT --*/ { HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_NORMALIZE_URL[]: Function Entry\r\n" " URL: '%s'\r\n" " <END>\r\n\r\n", pszURL )); } // // Validate parameters // if ( pszURL == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_NORMALIZE_URL[]: Parameter validation failure\r\n" " URL: NULL\r\n" " <END>\r\n\r\n" )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = NormalizeUrl( pszURL ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_NORMALIZE_URL[]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", hr )); } return hr; } return hr; } HRESULT SSFAddFragmentToCache( ISAPI_CONTEXT * pIsapiContext, HSE_VECTOR_ELEMENT * pHseVectorElement, WCHAR * pszFragmentName ) /*++ Routine Description: Add the given fragment to the fragment-cache Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pVectorElement - The fragment to be added pszFragmentName - The name of the fragment Return Value: HRESULT --*/ { IIsapiCore *pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Function Entry\r\n" " Fragment Name: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName )); } if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // verify the data passed in // if ( pHseVectorElement == NULL || pszFragmentName == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Vector Element Ptr: %p\r\n" " Fragment Name: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pHseVectorElement, pszFragmentName )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } VECTOR_ELEMENT VectorElement; ZeroMemory(&VectorElement, sizeof VectorElement); if (pHseVectorElement->pvContext == NULL) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Vector Element Context: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } switch (pHseVectorElement->ElementType) { case HSE_VECTOR_ELEMENT_TYPE_MEMORY_BUFFER: if (pHseVectorElement->cbSize > MAXULONG) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Memory buffer size element invalid\r\n" " Size: %d\r\n" " <END>\r\n\r\n", pIsapiContext, pHseVectorElement->cbSize )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } VectorElement.pBuffer = (BYTE *)pHseVectorElement->pvContext; VectorElement.cbBufSize = (DWORD)pHseVectorElement->cbSize; break; case HSE_VECTOR_ELEMENT_TYPE_FILE_HANDLE: if (pHseVectorElement->pvContext == INVALID_HANDLE_VALUE) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Element file handle invalid\r\n" " File Handle: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pHseVectorElement->pvContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // Treat 0 as "send the rest of the file" - same as TransmitFile/VectorSend // if (pHseVectorElement->cbSize == 0) { pHseVectorElement->cbSize = HTTP_BYTE_RANGE_TO_EOF; } VectorElement.hFile = (DWORD_PTR)pHseVectorElement->pvContext; VectorElement.cbOffset = pHseVectorElement->cbOffset; VectorElement.cbFileSize = pHseVectorElement->cbSize; break; case HSE_VECTOR_ELEMENT_TYPE_FRAGMENT: default: IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Parameter validation failure\r\n" " Unknown element type: %d\r\n" " Fragment Name: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pHseVectorElement->ElementType )); } return HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER); } hr = pIsapiCore->AddFragmentToCache(&VectorElement, pszFragmentName); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_ADD_FRAGMENT_TO_CACHE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFReadFragmentFromCache( ISAPI_CONTEXT * pIsapiContext, WCHAR * pszFragmentName, BYTE * pvBuffer, DWORD * pcbSize ) /*++ Routine Description: Read the given fragment from the fragment-cache Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pszFragmentName - The name of the fragment pvBuffer - The buffer to read the fragment in pcbSize - On entry, the size of the buffer and on exit, the number of bytes copied Return Value: HRESULT --*/ { IIsapiCore *pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_READ_FRAGMENT_FROM_CACHE[%p]: Function Entry\r\n" " Fragment Name: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName )); } if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_READ_FRAGMENT_FROM_CACHE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // verify the data passed in // if ( pszFragmentName == NULL || pcbSize == NULL || (pvBuffer == NULL && *pcbSize != 0 ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_READ_FRAGMENT_FROM_CACHE[%p]: Parameter validation failure\r\n" " Fragment Name: '%s'\r\n" " Size Ptr: %p\r\n" " Size: %d\r\n" " Buffer Ptr: %p\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName, pcbSize, pcbSize ? *pcbSize : 0, pvBuffer )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->ReadFragmentFromCache(pszFragmentName, pvBuffer, *pcbSize, pcbSize); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_READ_FRAGMENT_FROM_CACHE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFRemoveFragmentFromCache( ISAPI_CONTEXT * pIsapiContext, WCHAR * pszFragmentName ) /*++ Routine Description: Remove the given fragment from the fragment-cache Arguments: pIsapiContext - The ISAPI_CONTEXT associated with this command. pszFragmentName - The name of the fragment Return Value: HRESULT --*/ { IIsapiCore *pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); HRESULT hr; IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REMOVE_FRAGMENT_FROM_CACHE[%p]: Function Entry\r\n" " Fragment Name: '%S'\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName )); } if ( pIsapiCore == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REMOVE_FRAGMENT_FROM_CACHE[%p]: Failed to get interface to server core\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } // // verify the data passed in // if ( pszFragmentName == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REMOVE_FRAGMENT_FROM_CACHE[%p]: Parameter validation failure\r\n" " Fragment Name: '%s'\r\n" " <END>\r\n\r\n", pIsapiContext, pszFragmentName )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->RemoveFragmentFromCache(pszFragmentName); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_REMOVE_FRAGMENT_FROM_CACHE[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFGetMetadataProperty( ISAPI_CONTEXT * pIsapiContext, DWORD_PTR dwPropertyId, BYTE * pbBuffer, DWORD * pcbBuffer ) /*++ Routine Description: Retrieve a property from the UT_FILE metadata associated with the URL of this request Arguments: pIsapiContext - ISAPI_CONTEXT dwPropertyId - MD_* metabase property ID pbBuffer - Points to buffer pcbBuffer - On input size of buffer, on output size needed/used Return Value: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; METADATA_RECORD * pRecord; DBG_ASSERT( pIsapiContext != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_METADATA_PROPERTY[%p]: Function Entry\r\n" " PropertyID: 0x%08x (%d)\r\n" " <END>\r\n\r\n", pIsapiContext, dwPropertyId, dwPropertyId )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); DBG_ASSERT( pIsapiCore != NULL ); if ( pcbBuffer == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_METADATA_PROPERTY[%p]: Parameter validation failure\r\n" " Buffer Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetMetadataProperty( (DWORD) dwPropertyId, pbBuffer, *pcbBuffer, pcbBuffer ); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_METADATA_PROPERTY[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } else { // // OK. Before we return the METADATA_RECORD back to caller, set the // pbMDData buffer pointer (since for OOP the pointer can only be // calculated on this side // DBG_ASSERT( *pcbBuffer >= sizeof( METADATA_RECORD ) ); pRecord = (METADATA_RECORD*) pbBuffer; pRecord->pbMDData = (BYTE*) (pRecord + 1); } return hr; } HRESULT SSFGetCacheInvalidationCallback( ISAPI_CONTEXT * pIsapiContext, PFN_HSE_CACHE_INVALIDATION_CALLBACK * pfnCallback ) /*++ Routine description: Get the callback function to use to flush a response from the http.sys cache Arguments: pIsapiContext - The ISAPI_CONTEXT corresponding to the request pfnCallback - On successful return, the address of the callback function Return: HRESULT --*/ { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CACHE_INVALIDATION_CALLBACK[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } pIsapiCore = pIsapiContext->QueryIsapiCoreInterface(); DBG_ASSERT( pIsapiCore != NULL ); if ( pfnCallback == NULL ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CACHE_INVALIDATION_CALLBACK[%p]: Parameter validation failure\r\n" " Callback Ptr: NULL\r\n" " <END>\r\n\r\n", pIsapiContext )); } return HRESULT_FROM_WIN32( ERROR_INVALID_PARAMETER ); } hr = pIsapiCore->GetCacheInvalidationCallback((DWORD64 *)pfnCallback); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_GET_CACHE_INVALIDATION_CALLBACK[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } HRESULT SSFCloseConnection( ISAPI_CONTEXT * pIsapiContext ) { IIsapiCore * pIsapiCore; HRESULT hr; DBG_ASSERT( pIsapiContext ); DBG_ASSERT( pIsapiContext->CheckSignature() ); DBG_REQUIRE( ( pIsapiCore = pIsapiContext->QueryIsapiCoreInterface() ) != NULL ); IF_DEBUG( ISAPI_SSF_DETAILS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_CLOSE_CONNECTION[%p]: Function Entry\r\n" " <END>\r\n\r\n", pIsapiContext )); } hr = pIsapiCore->CloseConnection(); if ( FAILED( hr ) ) { IF_DEBUG( ISAPI_ERROR_RETURNS ) { DBGPRINTF(( DBG_CONTEXT, "\r\n" " HSE_REQ_CLOSE_CONNECTION[%p]: Failed\r\n" " Error: 0x%08x\r\n" " <END>\r\n\r\n", pIsapiContext, hr )); } return hr; } return hr; } // stristr (stolen from fts.c, wickn) // // case-insensitive version of strstr. // stristr returns a pointer to the first occurrence of // pszSubString in pszString. The search does not include // terminating nul characters. // // BUGBUG: is this DBCS-safe? const char* stristr2( const char* pszString, const char* pszSubString ) { const char *cp1 = (const char*) pszString, *cp2, *cp1a; char first; // get the first char in string to find first = pszSubString[0]; // first char often won't be alpha if (isalpha(first)) { first = (char) tolower(first); for ( ; *cp1 != '\0'; cp1++) { if (tolower(*cp1) == first) { for (cp1a = &cp1[1], cp2 = (const char*) &pszSubString[1]; ; cp1a++, cp2++) { if (*cp2 == '\0') return cp1; if (tolower(*cp1a) != tolower(*cp2)) break; } } } } else { for ( ; *cp1 != '\0' ; cp1++) { if (*cp1 == first) { for (cp1a = &cp1[1], cp2 = (const char*) &pszSubString[1]; ; cp1a++, cp2++) { if (*cp2 == '\0') return cp1; if (tolower(*cp1a) != tolower(*cp2)) break; } } } } return NULL; }
137,676
45,764
#include "dotted.h" #include "Component.h" #include "File.h" #include "Toolset.h" #include "Project.h" #include <algorithm> #include <set> #include <boost/test/unit_test.hpp> BOOST_AUTO_TEST_CASE(clang_compile) { Component c("hello", true); Project p("./"); File *input = p.CreateFile(c, "hello/src/gretting.cpp"); const std::set<std::string> includes {"hello/include"}; ClangToolset clang; auto cmd = clang.getCompileCommand("clang++", "-std=c++17", "obj/hello/src/gretting.cpp.obj", input, includes, false); BOOST_TEST(cmd == "clang++ -c -std=c++17 -o obj/hello/src/gretting.cpp.obj hello/src/gretting.cpp -Ihello/include"); } BOOST_AUTO_TEST_CASE(clang_archive) { Component c("mylib", true); Project p("./"); File *input = p.CreateFile(c, "obj/mylib/src/mylib.cpp.obj"); ClangToolset clang; auto cmd = clang.getArchiverCommand("ar", "lib/libmylib.lib", {input}); BOOST_TEST(cmd == "ar rcs lib/libmylib.lib obj/mylib/src/mylib.cpp.obj"); } BOOST_AUTO_TEST_CASE(clang_link) { Component c("mylib", true); c.type = "library"; c.buildSuccess = true; Project p("./"); File *input1 = p.CreateFile(c, "obj/hello/src/gretting.cpp.obj"); File *input2 = p.CreateFile(c, "obj/hello/src/main.cpp.obj"); ClangToolset clang; auto cmd = clang.getLinkerCommand("clang++", "bin/hello.exe", {input1, input2}, {{&c}}); BOOST_TEST(cmd == "clang++ -o bin/hello.exe obj/hello/src/gretting.cpp.obj obj/hello/src/main.cpp.obj -Lbuild/clang/lib -lmylib"); }
1,526
605
#include "PlatformUtils.h" #include <Windows.h> #include <psapi.h> #include <TCHAR.h> #include <pdh.h> //total CPU usage static PDH_HQUERY cpuQuery; static PDH_HCOUNTER cpuTotal; //Process CPU time static ULARGE_INTEGER lastCPU, lastSysCPU, lastUserCPU; static int numProcessors; static HANDLE self; void PlatformUtils::Init() { PdhOpenQuery(NULL, NULL, &cpuQuery); PdhAddEnglishCounter(cpuQuery, "\\Processor(_Total)\\% Processor Time", NULL, &cpuTotal); PdhCollectQueryData(cpuQuery); SYSTEM_INFO sysInfo; FILETIME ftime, fsys, fuser; GetSystemInfo(&sysInfo); numProcessors = sysInfo.dwNumberOfProcessors; GetSystemTimeAsFileTime(&ftime); memcpy(&lastCPU, &ftime, sizeof(FILETIME)); self = GetCurrentProcess(); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&lastSysCPU, &fsys, sizeof(FILETIME)); memcpy(&lastUserCPU, &fuser, sizeof(FILETIME)); } void GetMemInfo(MEMORYSTATUSEX* memInfo) { memInfo->dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(memInfo); } unsigned long long PlatformUtils::GetTotalMachineVirtualMemory() { MEMORYSTATUSEX memInfo; GetMemInfo(&memInfo); DWORDLONG totalVirtualMem = memInfo.ullTotalPageFile; return totalVirtualMem; } unsigned long long PlatformUtils::GetSystemVirtualMemoryUsage() { MEMORYSTATUSEX memInfo; GetMemInfo(&memInfo); DWORDLONG virtualMemUsed = memInfo.ullTotalPageFile - memInfo.ullAvailPageFile; return virtualMemUsed; } unsigned long long PlatformUtils::GetProcessVirtualMemoryUsage() { PROCESS_MEMORY_COUNTERS_EX pmc; GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); SIZE_T virtualMemUsedByMe = pmc.PrivateUsage; return virtualMemUsedByMe; } //stats for physical memory unsigned long long PlatformUtils::GetTotalMachinePhysicalMemory() { MEMORYSTATUSEX memInfo; GetMemInfo(&memInfo); DWORDLONG totalPhysMem = memInfo.ullTotalPhys; return totalPhysMem; } unsigned long long PlatformUtils::GetSystemPhysicalMemoryUsage() { MEMORYSTATUSEX memInfo; GetMemInfo(&memInfo); DWORDLONG physMemUsed = memInfo.ullTotalPhys - memInfo.ullAvailPhys; return physMemUsed; } unsigned long long PlatformUtils::GetProcessPhysicalMemoryUsage() { PROCESS_MEMORY_COUNTERS_EX pmc; GetProcessMemoryInfo(GetCurrentProcess(), (PROCESS_MEMORY_COUNTERS*)&pmc, sizeof(pmc)); SIZE_T physMemUsedByMe = pmc.WorkingSetSize; return physMemUsedByMe; } float PlatformUtils::GetSystemCPUUsagePercent() { PDH_FMT_COUNTERVALUE counterVal; PdhCollectQueryData(cpuQuery); PdhGetFormattedCounterValue(cpuTotal, PDH_FMT_DOUBLE, NULL, &counterVal); return (float) counterVal.doubleValue; } float PlatformUtils::GetProcessCPUUsagePercent() { FILETIME ftime, fsys, fuser; ULARGE_INTEGER now, sys, user; double percent; GetSystemTimeAsFileTime(&ftime); memcpy(&now, &ftime, sizeof(FILETIME)); GetProcessTimes(self, &ftime, &ftime, &fsys, &fuser); memcpy(&sys, &fsys, sizeof(FILETIME)); memcpy(&user, &fuser, sizeof(FILETIME)); percent = (sys.QuadPart - lastSysCPU.QuadPart) + (user.QuadPart - lastUserCPU.QuadPart); percent /= (now.QuadPart - lastCPU.QuadPart); percent /= numProcessors; lastCPU = now; lastUserCPU = user; lastSysCPU = sys; return (float) (percent * 100.0); } int PlatformUtils::GetProcessorCount() { return numProcessors; }
3,300
1,220
#pragma once #include <CreateCoin/chain/CreateCoin_object_types.hpp> #ifndef CreateCoin_WITNESS_SPACE_ID #define CreateCoin_WITNESS_SPACE_ID 19 #endif namespace CreateCoin { namespace chain { struct by_account; } } namespace CreateCoin { namespace plugins { namespace witness { using namespace CreateCoin::chain; enum witness_object_types { witness_custom_op_object_type = ( CreateCoin_WITNESS_SPACE_ID << 8 ) }; class witness_custom_op_object : public object< witness_custom_op_object_type, witness_custom_op_object > { public: template< typename Constructor, typename Allocator > witness_custom_op_object( Constructor&& c, allocator< Allocator > a ) { c( *this ); } id_type id; account_name_type account; }; typedef multi_index_container< witness_custom_op_object, indexed_by< ordered_unique< tag< by_id >, member< witness_custom_op_object, witness_custom_op_object::id_type, &witness_custom_op_object::id > >, ordered_unique< tag< by_account >, member< witness_custom_op_object, account_name_type, &witness_custom_op_object::account > > >, allocator< witness_custom_op_object > > witness_custom_op_index; } } } FC_REFLECT( CreateCoin::plugins::witness::witness_custom_op_object, (id) (account) ) CHAINBASE_SET_INDEX_TYPE( CreateCoin::plugins::witness::witness_custom_op_object, CreateCoin::plugins::witness::witness_custom_op_index )
1,459
507
#include<iostream> using namespace std; class node { public: int data; node* next; node() { next=NULL; } node(int d) { data=d; next=NULL; } }; class Graph { public: node **relation; int vertex_count; void initialise(int element[]) { for(int i=0;i<vertex_count;i++) { node* newnode=new node(element[i]); relation[i]=newnode; ///here all the link list have first node as parent } } ///THESE FUNCTION ARE UTLITY FOR TOPOLOGICAL SORT************************* int incoming_edge(int index) { int count=0; int key=relation[index]->data; for(int i=0;i<vertex_count;i++) { if(relation[i]!=NULL &&i!=index) ///skipping the index that is passed { node* temp; temp=relation[i]; temp=temp->next; ///skipping the parent while(temp!=NULL){ if(temp->data==key) count++; ///one incoming edge to the node passed temp=temp->next; } } } return count; } int find_zero_value_index(int in_degree[]) { for(int i=0;i<vertex_count;i++) { if(in_degree[i]==0) return i; } return -1; } void reduce_indegree(int index,int in_degree[]) { node* temp=relation[index]; while(temp!=NULL) { int i=find_index(temp->data); in_degree[i]--; temp=temp->next; } } ///******************************************************************* public: Graph(int count,int ele[]) { vertex_count=count; relation=new node*[count]; initialise(ele); } int find_index(int ele) { for(int i=0;i<vertex_count;i++) { if(relation[i]->data==ele) return i; } return -1; } bool insert_edge(int parent,int child) { int p,c; p=find_index(parent); c=find_index(child); if(p==-1 | c==-1) return false; node* temp=relation[p]; while(temp->next!=NULL) { temp=temp->next; } node* newnode=new node(child); temp->next=newnode; return true; } void Topological_util(int in_degree[],int result[]) { int i=0; while(i<vertex_count) { int index=find_zero_value_index(in_degree); if(index==-1) result[i]=INT_MIN; else{ result[i]=relation[index]->data; reduce_indegree(index,in_degree); } i++; } } bool DetectCycle() { int in_degree[vertex_count]; int result[vertex_count]; for(int i=0;i<vertex_count;i++) { in_degree[i]=incoming_edge(i); } Topological_util(in_degree,result); for(int i=0;i<vertex_count;i++) { if(result[i]==INT_MIN) return true; } return false; } void print() { bool flag=false; for(int i=0;i<vertex_count;i++) { flag=false; if(relation[i]!=NULL) { node* temp; temp=relation[i]; cout<<"Element:-"<<temp->data<<endl; ///printing the parent temp=temp->next; ///skipping the parent while(temp!=NULL){ flag=true; cout<<"\thas an edge to:- "<<temp->data<<endl; temp=temp->next; } if(!flag) cout<<"\tdoesn't have any edge"<<endl; } } cout<<endl; } }; int main() { int b[]={0,1,2,3,4}; ///the elements in the graph int countele=5; ///total elements in graph Graph G(countele,b); G.insert_edge(0,1); G.insert_edge(0,4); G.insert_edge(1,2); G.insert_edge(2,3); G.insert_edge(2,4); G.insert_edge(4,3); G.print(); cout<<"Cycle-:"; cout<<G.DetectCycle(); }
4,798
1,401
/* * Copyright (c) 2022, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "functional.cuh" #include <raft/linalg/binary_op.hpp> #include <raft/linalg/unary_op.hpp> namespace raft { namespace linalg { namespace detail { template <typename InType, typename IdxType, typename OutType = InType> void scalarAdd(OutType* out, const InType* in, InType scalar, IdxType len, cudaStream_t stream) { raft::linalg::unaryOp(out, in, len, adds_scalar<InType, OutType>(scalar), stream); } template <typename InType, typename IdxType, typename OutType = InType> void scalarMultiply(OutType* out, const InType* in, InType scalar, IdxType len, cudaStream_t stream) { raft::linalg::unaryOp(out, in, len, multiplies_scalar<InType, OutType>(scalar), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseAdd( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, thrust::plus<InType>(), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseSub( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, thrust::minus<InType>(), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseMultiply( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, thrust::multiplies<InType>(), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseDivide( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, thrust::divides<InType>(), stream); } template <typename InType, typename IdxType, typename OutType = InType> void eltwiseDivideCheckZero( OutType* out, const InType* in1, const InType* in2, IdxType len, cudaStream_t stream) { raft::linalg::binaryOp(out, in1, in2, len, divides_check_zero<InType, OutType>(), stream); } }; // end namespace detail }; // end namespace linalg }; // end namespace raft
2,734
966
/* * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "asm/assembler.hpp" #include "assembler_arm.inline.hpp" #include "code/icBuffer.hpp" #include "gc/shared/collectedHeap.inline.hpp" #include "interpreter/bytecodes.hpp" #include "memory/resourceArea.hpp" #include "nativeInst_arm.hpp" #include "oops/oop.inline.hpp" #define __ masm-> int InlineCacheBuffer::ic_stub_code_size() { return (AARCH64_ONLY(8) NOT_AARCH64(4)) * Assembler::InstructionSize; } void InlineCacheBuffer::assemble_ic_buffer_code(address code_begin, void* cached_value, address entry_point) { ResourceMark rm; CodeBuffer code(code_begin, ic_stub_code_size()); MacroAssembler* masm = new MacroAssembler(&code); InlinedAddress oop_literal((address) cached_value); __ ldr_literal(Ricklass, oop_literal); // FIXME: OK to remove reloc here? __ patchable_jump(entry_point, relocInfo::runtime_call_type, Rtemp); __ bind_literal(oop_literal); __ flush(); } address InlineCacheBuffer::ic_buffer_entry_point(address code_begin) { address jump_address; jump_address = code_begin + NativeInstruction::instruction_size; NativeJump* jump = nativeJump_at(jump_address); return jump->jump_destination(); } void* InlineCacheBuffer::ic_buffer_cached_value(address code_begin) { NativeMovConstReg* move = nativeMovConstReg_at(code_begin); return (void*)move->data(); } #undef __
2,413
823
/****************************************************/ /* breeze Engine Scene Module (c) Tobias Zirr 2011 */ /****************************************************/ #include "beSceneInternal/stdafx.h" #include "beScene/beSerializationParameters.h" #include <beEntitySystem/beSerializationParameters.h> namespace beScene { // Gets the serialization parameter IDs. const SceneParameterIDs& GetSceneParameterIDs() { beCore::ParameterLayout &layout = beEntitySystem::GetSerializationParameters(); static SceneParameterIDs parameterIDs( layout.Add("beScene.ResourceManager"), layout.Add("beScene.Renderer"), layout.Add("beScene.RenderingController") ); return parameterIDs; } // Sets the given scene parameters in the given parameter set. void SetSceneParameters(beCore::ParameterSet &parameters, const SceneParameters &sceneParameters) { const beCore::ParameterLayout &layout = beEntitySystem::GetSerializationParameters(); const SceneParameterIDs& parameterIDs = GetSceneParameterIDs(); parameters.SetValue(layout, parameterIDs.ResourceManager, sceneParameters.ResourceManager); parameters.SetValue(layout, parameterIDs.Renderer, sceneParameters.Renderer); parameters.SetValue(layout, parameterIDs.RenderingController, sceneParameters.RenderingController); } // Sets the given scene parameters in the given parameter set. SceneParameters GetSceneParameters(const beCore::ParameterSet &parameters) { SceneParameters sceneParameters; const beCore::ParameterLayout &layout = beEntitySystem::GetSerializationParameters(); const SceneParameterIDs& parameterIDs = GetSceneParameterIDs(); sceneParameters.ResourceManager = parameters.GetValueChecked< beScene::ResourceManager* >(layout, parameterIDs.ResourceManager); sceneParameters.Renderer = parameters.GetValueChecked< EffectDrivenRenderer* >(layout, parameterIDs.Renderer); sceneParameters.RenderingController = parameters.GetValueChecked< RenderingController* >(layout, parameterIDs.RenderingController); return sceneParameters; } } // namespace
2,084
560
#include <vnl/vnl_vector_fixed.hxx> VNL_VECTOR_FIXED_INSTANTIATE(double,4);
77
39
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2020 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include <boost/assign.hpp> //#include <Core/Datatypes/Mesh/MeshFactory.h> #include <Core/Datatypes/Legacy/Field/FieldInformation.h> #include <Core/Datatypes/Legacy/Field/LatVolMesh.h> using namespace SCIRun; using namespace SCIRun::Core::Datatypes; using namespace SCIRun::Core::Geometry; using ::testing::_; using ::testing::NiceMock; using ::testing::DefaultValue; using ::testing::Return; using namespace boost::assign; class LatticeVolumeMeshTests : public ::testing::Test { protected: void SetUp() override { int basisOrder = 1; FieldInformation lfi("LatVolMesh", basisOrder, "double"); int sizex,sizey,sizez; sizex = sizey = sizez = 2; Point minb(0,0,0); Point maxb(1,1,1); mesh_ = CreateMesh(lfi, sizex, sizey, sizez, minb, maxb); } MeshHandle mesh_; }; namespace { template <typename T> std::string join(const T& list) { std::ostringstream oss; const int SIZE = list.size(); for (int i = 0; i < SIZE; ++i) { oss << list[i]; if (i < SIZE - 1) oss << ", "; } return oss.str(); } } TEST_F(LatticeVolumeMeshTests, BasicCubeTest) { ASSERT_TRUE(mesh_.get() != nullptr); auto latVolVMesh = mesh_->vmesh(); ASSERT_TRUE(latVolVMesh != nullptr); VMesh::dimension_type dims; latVolVMesh->get_dimensions(dims); VMesh::dimension_type expectedDims; expectedDims += 2,2,2; EXPECT_EQ(expectedDims, dims); EXPECT_EQ(8, latVolVMesh->num_nodes()); EXPECT_EQ(12, latVolVMesh->num_edges()); EXPECT_EQ(6, latVolVMesh->num_faces()); EXPECT_EQ(1, latVolVMesh->num_elems()); #ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER ASSERT_TRUE(latVolVMesh->is_linearmesh()); ASSERT_FALSE(latVolVMesh->has_normals()); #endif } TEST_F(LatticeVolumeMeshTests, CubeIterationTest) { auto latVolVMesh = mesh_->vmesh(); { VMesh::Edge::iterator meshEdgeIter; VMesh::Edge::iterator meshEdgeEnd; VMesh::Node::array_type nodesFromEdge(2); latVolVMesh->end(meshEdgeEnd); std::ostringstream ostr; for (latVolVMesh->begin(meshEdgeIter); meshEdgeIter != meshEdgeEnd; ++meshEdgeIter) { // get nodes from edge VMesh::Edge::index_type edgeID = *meshEdgeIter; latVolVMesh->get_nodes(nodesFromEdge, edgeID); Point p0, p1; latVolVMesh->get_point(p0, nodesFromEdge[0]); latVolVMesh->get_point(p1, nodesFromEdge[1]); ostr << "Edge " << edgeID << " nodes=[" << nodesFromEdge[0] << " point=" << p0.get_string() << ", " << nodesFromEdge[1] << " point=" << p1.get_string() << "]" << std::endl; } EXPECT_EQ( "Edge 0 nodes=[0 point=[0, 0, 0], 1 point=[1, 0, 0]]\n" "Edge 1 nodes=[2 point=[0, 1, 0], 3 point=[1, 1, 0]]\n" "Edge 2 nodes=[4 point=[0, 0, 1], 5 point=[1, 0, 1]]\n" "Edge 3 nodes=[6 point=[0, 1, 1], 7 point=[1, 1, 1]]\n" "Edge 4 nodes=[0 point=[0, 0, 0], 2 point=[0, 1, 0]]\n" "Edge 5 nodes=[4 point=[0, 0, 1], 6 point=[0, 1, 1]]\n" "Edge 6 nodes=[1 point=[1, 0, 0], 3 point=[1, 1, 0]]\n" "Edge 7 nodes=[5 point=[1, 0, 1], 7 point=[1, 1, 1]]\n" "Edge 8 nodes=[0 point=[0, 0, 0], 4 point=[0, 0, 1]]\n" "Edge 9 nodes=[1 point=[1, 0, 0], 5 point=[1, 0, 1]]\n" "Edge 10 nodes=[2 point=[0, 1, 0], 6 point=[0, 1, 1]]\n" "Edge 11 nodes=[3 point=[1, 1, 0], 7 point=[1, 1, 1]]\n" , ostr.str()); } { VMesh::Face::iterator meshFaceIter; VMesh::Face::iterator meshFaceEnd; VMesh::Edge::array_type edgesFromFace(4); VMesh::Node::array_type nodesFromFace(4); latVolVMesh->end(meshFaceEnd); std::ostringstream ostr; for (latVolVMesh->begin(meshFaceIter); meshFaceIter != meshFaceEnd; ++meshFaceIter) { // get edges and nodes from face VMesh::Face::index_type faceID = *meshFaceIter; latVolVMesh->get_edges(edgesFromFace, faceID); ostr << "Face " << faceID << " edges=[" << join(edgesFromFace) << "]" << std::endl; latVolVMesh->get_nodes(nodesFromFace, faceID); ostr << "Face " << faceID << " nodes=[" << join(nodesFromFace) << "]" << std::endl; } EXPECT_EQ("Face 0 edges=[0, 1, 4, 6]\n" "Face 0 nodes=[0, 1, 3, 2]\n" "Face 1 edges=[2, 3, 5, 7]\n" "Face 1 nodes=[4, 6, 7, 5]\n" "Face 2 edges=[4, 5, 8, 10]\n" "Face 2 nodes=[0, 2, 6, 4]\n" "Face 3 edges=[6, 7, 9, 11]\n" "Face 3 nodes=[1, 5, 7, 3]\n" "Face 4 edges=[0, 2, 8, 9]\n" "Face 4 nodes=[0, 4, 5, 1]\n" "Face 5 edges=[1, 3, 10, 11]\n" "Face 5 nodes=[2, 3, 7, 6]\n" ,ostr.str()); } { VMesh::Cell::iterator meshCellIter; VMesh::Cell::iterator meshCellEnd; VMesh::Edge::array_type edgesFromCell(12); VMesh::Node::array_type nodesFromCell(8); latVolVMesh->end(meshCellEnd); std::ostringstream ostr; for (latVolVMesh->begin(meshCellIter); meshCellIter != meshCellEnd; ++meshCellIter) { // get edges and nodes from mesh element VMesh::Cell::index_type elemID = *meshCellIter; latVolVMesh->get_edges(edgesFromCell, elemID); ostr << "Cell " << elemID << " edges=[" << join(edgesFromCell) << "]" << std::endl; latVolVMesh->get_nodes(nodesFromCell, elemID); ostr << "Cell " << elemID << " nodes=["<< join(nodesFromCell) << "]" << std::endl; } EXPECT_EQ( "Cell 0 edges=[0, 1, 2, 3, 4, 6, 5, 7, 8, 9, 10, 11]\n" "Cell 0 nodes=[0, 1, 3, 2, 4, 5, 7, 6]\n", ostr.str()); } { VMesh::Node::iterator meshNodeIter; VMesh::Node::iterator meshNodeEnd; VMesh::Edge::array_type edgesFromNode(3); latVolVMesh->end(meshNodeEnd); std::ostringstream ostr; for (latVolVMesh->begin(meshNodeIter); meshNodeIter != meshNodeEnd; ++meshNodeIter) { // get edges and point from mesh node VMesh::Node::index_type nodeID = *meshNodeIter; Point p; latVolVMesh->get_point(p, nodeID); ostr << "Node " << nodeID << " point=" << p.get_string(); latVolVMesh->get_edges(edgesFromNode, nodeID); ostr << " edges=[" << join(edgesFromNode) << "]" << std::endl; } EXPECT_EQ("Node 0 point=[0, 0, 0] edges=[0, 4, 8]\n" "Node 1 point=[1, 0, 0] edges=[0, 6, 9]\n" "Node 2 point=[0, 1, 0] edges=[1, 6, 10]\n" "Node 3 point=[1, 1, 0] edges=[1, 8, 11]\n" "Node 4 point=[0, 0, 1] edges=[2, 5, 9]\n" "Node 5 point=[1, 0, 1] edges=[2, 7, 10]\n" "Node 6 point=[0, 1, 1] edges=[3, 7, 11]\n" "Node 7 point=[1, 1, 1] edges=[3, 9, 12]\n", ostr.str()); } }
7,790
3,198
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <_TBBUTTON.hpp> #include <tagNMHDR.hpp> #include <tagRECT.hpp> START_ATF_NAMESPACE struct tagNMTOOLBARA { tagNMHDR hdr; int iItem; _TBBUTTON tbButton; int cchText; char *pszText; tagRECT rcButton; }; END_ATF_NAMESPACE
439
165
/* MIT License Copyright (c) 2021 Ivan Gagis 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. */ /* ================ LICENSE END ================ */ #pragma once #include <string> #include <mutex> #include "suite.hpp" #include "application.hpp" #include "util.hxx" namespace tst{ class reporter{ private: std::mutex mutex; const application& app; const size_t num_tests; size_t num_failed = 0; size_t num_passed = 0; size_t num_disabled = 0; size_t num_errors = 0; // thread safe void report( const full_id& id, suite::status result, uint32_t dt, std::string&& message = std::string() ); public: uint32_t time_ms = 0; reporter(const application& app) : app(app), num_tests(app.num_tests()) {} // thread safe void report_pass(const full_id& id, uint32_t dt) { this->report(id, suite::status::passed, dt); } // thread safe void report_failure( const full_id& id, uint32_t dt, std::string&& message ) { this->report(id, suite::status::failed, dt, std::move(message)); } // thread safe void report_error( const full_id& id, uint32_t dt, std::string&& message ) { this->report(id, suite::status::errored, dt, std::move(message)); } // thread safe void report_skipped( const full_id& id, std::string&& message ) { this->report(id, suite::status::not_run, 0, std::move(message)); } // thread safe void report_disabled_test(const full_id& id){ this->report(id, suite::status::disabled, 0); } size_t num_unsuccessful()const noexcept{ return this->num_failed + this->num_errors; } size_t num_not_run()const noexcept{ return this->num_disabled + this->num_skipped(); } size_t num_ran()const noexcept{ return this->num_unsuccessful() + this->num_passed + this->num_disabled; } size_t num_skipped()const noexcept{ ASSERT(this->num_tests >= this->num_ran()) return this->num_tests - this->num_ran(); } void print_num_tests_run(std::ostream& o)const; void print_num_tests_about_to_run(std::ostream& o)const; void print_num_tests_passed(std::ostream& o)const; void print_num_tests_disabled(std::ostream& o)const; void print_num_tests_failed(std::ostream& o)const; void print_num_tests_skipped(std::ostream& o)const; void print_num_warnings(std::ostream& o)const; void print_outcome(std::ostream& o)const; bool is_failed()const noexcept{ return this->num_failed != 0 || this->num_errors != 0; } bool is_semi_passed()const noexcept{ return !this->is_failed() && this->num_skipped() == 0 && this->num_not_run() == 0; } void write_junit_report(const std::string& file_name)const; }; }
3,594
1,377
#include <stdio.h> struct A { int a; virtual void foo() = 0; void bar() { printf("A::bar(): a=%x\n", a); } }; struct B { int b; virtual void foo() = 0; void bar() { printf("B::bar(): b=%x\n", b); } }; struct C : A, B { int c; virtual void foo() { printf("C::foo(), c=%x\n", c); } void bar() { printf("C::bar(), c=%x\n", c); } }; template <class T> void invoke(C &c, void (T::*fn)()) { (c.*fn)(); } int main() { C c; c.a = 0xff; c.b = 0xf0f; c.c = 0xf00f; invoke(c, &A::foo); invoke(c, &A::bar); invoke(c, &B::foo); invoke(c, &B::bar); invoke(c, &C::foo); invoke(c, &C::bar); }
623
303
// ------------------------------------------------------------------------ // Copyright (C) // Universitat Politecnica de Catalunya BarcelonaTech (UPC) - Spain // University of California Berkeley (UCB) - USA // // Jordi Pont-Tuset <jordi.pont@upc.edu> // Pablo Arbelaez <arbelaez@berkeley.edu> // June 2014 // ------------------------------------------------------------------------ // This file is part of the MCG package presented in: // Arbelaez P, Pont-Tuset J, Barron J, Marques F, Malik J, // "Multiscale Combinatorial Grouping," // Computer Vision and Pattern Recognition (CVPR) 2014. // Please consider citing the paper if you use this code. // ------------------------------------------------------------------------ #include "mex.h" #include <iostream> #include <set> #include <map> #include <list> #include "matlab_multiarray.hpp" using namespace std; void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray*prhs[] ) { /* Check for proper number of arguments */ if (nrhs != 3) { mexErrMsgTxt("Three input arguments required."); } else if (nlhs > 3) { mexErrMsgTxt("Too many output arguments."); } /* Input as a Multiarray */ ConstMatlabMultiArray<double> lp(prhs[0]); /* Leaves partition */ ConstMatlabMultiArray<double> ms(prhs[1]); /* Merging sequence */ ConstMatlabMultiArray<double> cands(prhs[2]); /* Candidates */ /* Input sizes and checks */ size_t sm = lp.shape()[0]; size_t sn = lp.shape()[1]; size_t n_sons_max= ms.shape()[1]-1; size_t n_merges = ms.shape()[0]; size_t n_leaves = ms[0][n_sons_max]-1; // n_merges+1; --> Not valid for non-binary trees size_t n_regs = n_leaves+n_merges; size_t n_cands = cands.shape()[0]; size_t n_regs_max= cands.shape()[1]; /* Create the list of activated pixels in each leave region */ vector<list<size_t> > x_coords(n_regs); vector<list<size_t> > y_coords(n_regs); for (size_t xx=0; xx<sm; ++xx) { for (size_t yy=0; yy<sn; ++yy) { size_t curr_leave = lp[xx][yy]-1; x_coords[curr_leave].push_back(xx); y_coords[curr_leave].push_back(yy); } } /* Bottom-up expansion of the lists of pixels */ for (size_t ii=0; ii<n_merges; ++ii) { for (size_t jj=0; jj<n_sons_max; ++jj) { if (ms[ii][jj]==0) break; x_coords[n_leaves+ii].insert(x_coords[n_leaves+ii].end(), x_coords[ms[ii][jj]-1].begin(), x_coords[ms[ii][jj]-1].end()); y_coords[n_leaves+ii].insert(y_coords[n_leaves+ii].end(), y_coords[ms[ii][jj]-1].begin(), y_coords[ms[ii][jj]-1].end()); } } /* Allocate out masks */ size_t ndim = 3; mwSize dims[3]; dims[0] = sm; dims[1] = sn; dims[2] = n_cands; plhs[0] = mxCreateLogicalArray(3, dims); MatlabMultiArray3<bool> out_masks(plhs[0]); for (size_t ii=0; ii<n_cands; ++ii) { for (size_t jj=0; jj<n_regs_max; ++jj) { if (cands[ii][jj]==0) break; list<size_t>::iterator itx = x_coords[cands[ii][jj]-1].begin(); list<size_t>::iterator ity = y_coords[cands[ii][jj]-1].begin(); for( ; itx!=x_coords[cands[ii][jj]-1].end(); ++itx, ++ity) { out_masks[*itx][*ity][ii] = true; } } } }
3,625
1,345
#include <iostream> #include "mysql/mysql.h" int main() { MYSQL* mysql = mysql_init(nullptr); mysql_close(mysql); #ifdef TEST_OPTION std::cout << "[ok] Test option enabled\n"; return 0; #else std::cout << "[error] Test option disabled\n"; return 1; #endif }
283
105
#include <sstream> #include <iomanip> #include <grpcpp/grpcpp.h> #include <grpcpp/security/server_credentials.h> #include <grpcpp/server.h> #include <grpcpp/server_builder.h> #include <grpcpp/server_context.h> #include "muta/mutation.grpc.pb.h" template <typename T> static void to_string (std::ostream& out, const google::protobuf::RepeatedField<T>& vec) { if (vec.size() > 0) { out << std::setprecision(std::numeric_limits<T>::digits10 + 1) << vec.at(0); } for (size_t i = 1, n = vec.size(); i < n; ++i) { out << "," << vec.at(i); } } static void to_string (std::ostream& out, const google::protobuf::RepeatedPtrField<std::string>& vec) { if (vec.size() > 0) { out << vec.at(0); } for (size_t i = 1, n = vec.size(); i < n; ++i) { out << "," << vec.at(i); } } static void print_entry (std::ostream& out, const std::string& name, const muta::MutatorEntry& entry) { std::string type; std::stringstream ss; switch (entry.type()) { case muta::EntryType::INT: type = "int64_t"; to_string(ss, entry.is()); break; case muta::EntryType::DOUBLE: type = "double"; to_string(ss, entry.ds()); break; case muta::EntryType::STRING: type = "std::string"; to_string(ss, entry.ss()); break; default: break; } out << "std::vector<" << type << "> " << name << " = {" << ss.str() << "};"; } class MutationErrorStorageImpl final : public muta::MutationErrorStorage::Service { grpc::Status SaveSessions (grpc::ServerContext* context, const muta::SaveSessionsRequest* request, muta::SaveSessionsResponse* response) override { auto& sessions = request->sessions(); for (auto& session : sessions) { std::cout << "// failed " << session.id() << "\n"; auto& entries = session.entries(); for (auto& entry : entries) { print_entry(std::cout, entry.first, entry.second); std::cout << "\n"; } std::cout << std::endl; } return grpc::Status::OK; } }; void RunServer (void) { std::string server_address("0.0.0.0:50051"); MutationErrorStorageImpl service; grpc::ServerBuilder builder; builder.AddListeningPort(server_address, grpc::InsecureServerCredentials()); builder.RegisterService(&service); std::unique_ptr<grpc::Server> server(builder.BuildAndStart()); std::cout << "Server listening on " << server_address << std::endl; server->Wait(); } int main (int argc, char** argv) { RunServer(); return 0; }
2,397
967
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated by code_generator_v8.py. DO NOT MODIFY! #include "config.h" #include "V8HTMLTableRowElement.h" #include "HTMLNames.h" #include "bindings/core/v8/V8HTMLCollection.h" #include "bindings/core/v8/V8HTMLElement.h" #include "bindings/v8/ExceptionState.h" #include "bindings/v8/V8DOMConfiguration.h" #include "bindings/v8/V8HiddenValue.h" #include "bindings/v8/V8ObjectConstructor.h" #include "core/dom/ClassCollection.h" #include "core/dom/ContextFeatures.h" #include "core/dom/Document.h" #include "core/dom/TagCollection.h" #include "core/dom/custom/CustomElementCallbackDispatcher.h" #include "core/html/HTMLCollection.h" #include "core/html/HTMLFormControlsCollection.h" #include "core/html/HTMLTableRowsCollection.h" #include "platform/RuntimeEnabledFeatures.h" #include "platform/TraceEvent.h" #include "wtf/GetPtr.h" #include "wtf/RefPtr.h" namespace WebCore { static void initializeScriptWrappableForInterface(HTMLTableRowElement* object) { if (ScriptWrappable::wrapperCanBeStoredInObject(object)) ScriptWrappable::fromObject(object)->setTypeInfo(&V8HTMLTableRowElement::wrapperTypeInfo); else ASSERT_NOT_REACHED(); } } // namespace WebCore void webCoreInitializeScriptWrappableForInterface(WebCore::HTMLTableRowElement* object) { WebCore::initializeScriptWrappableForInterface(object); } namespace WebCore { const WrapperTypeInfo V8HTMLTableRowElement::wrapperTypeInfo = { gin::kEmbedderBlink, V8HTMLTableRowElement::domTemplate, V8HTMLTableRowElement::derefObject, 0, V8HTMLTableRowElement::toEventTarget, 0, V8HTMLTableRowElement::installPerContextEnabledMethods, &V8HTMLElement::wrapperTypeInfo, WrapperTypeObjectPrototype, WillBeGarbageCollectedObject }; namespace HTMLTableRowElementV8Internal { template <typename T> void V8_USE(T) { } static void rowIndexAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(holder); v8SetReturnValueInt(info, impl->rowIndex()); } static void rowIndexAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::rowIndexAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void sectionRowIndexAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(holder); v8SetReturnValueInt(info, impl->sectionRowIndex()); } static void sectionRowIndexAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::sectionRowIndexAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void cellsAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(holder); v8SetReturnValueFast(info, WTF::getPtr(impl->cells()), impl); } static void cellsAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::cellsAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void alignAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::alignAttr), info.GetIsolate()); } static void alignAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::alignAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void alignAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<>, cppValue, v8Value); impl->setAttribute(HTMLNames::alignAttr, cppValue); } static void alignAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::alignAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void bgColorAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::bgcolorAttr), info.GetIsolate()); } static void bgColorAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::bgColorAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void bgColorAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<WithNullCheck>, cppValue, v8Value); impl->setAttribute(HTMLNames::bgcolorAttr, cppValue); } static void bgColorAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::bgColorAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void chAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::charAttr), info.GetIsolate()); } static void chAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::chAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void chAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<>, cppValue, v8Value); impl->setAttribute(HTMLNames::charAttr, cppValue); } static void chAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::chAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void chOffAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::charoffAttr), info.GetIsolate()); } static void chOffAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::chOffAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void chOffAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<>, cppValue, v8Value); impl->setAttribute(HTMLNames::charoffAttr, cppValue); } static void chOffAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::chOffAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void vAlignAttributeGetter(const v8::PropertyCallbackInfo<v8::Value>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); v8SetReturnValueString(info, impl->fastGetAttribute(HTMLNames::valignAttr), info.GetIsolate()); } static void vAlignAttributeGetterCallback(v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMGetter"); HTMLTableRowElementV8Internal::vAlignAttributeGetter(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void vAlignAttributeSetter(v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { v8::Handle<v8::Object> holder = info.Holder(); Element* impl = V8Element::toNative(holder); TOSTRING_VOID(V8StringResource<>, cppValue, v8Value); impl->setAttribute(HTMLNames::valignAttr, cppValue); } static void vAlignAttributeSetterCallback(v8::Local<v8::String>, v8::Local<v8::Value> v8Value, const v8::PropertyCallbackInfo<void>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMSetter"); CustomElementCallbackDispatcher::CallbackDeliveryScope deliveryScope; HTMLTableRowElementV8Internal::vAlignAttributeSetter(v8Value, info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void insertCellMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "insertCell", "HTMLTableRowElement", info.Holder(), info.GetIsolate()); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(info.Holder()); int index; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); if (UNLIKELY(info.Length() <= 0)) { RefPtrWillBeRawPtr<HTMLElement> result = impl->insertCell(exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } v8SetReturnValueFast(info, WTF::getPtr(result.release()), impl); return; } TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(index, toInt32(info[0], exceptionState), exceptionState); } RefPtrWillBeRawPtr<HTMLElement> result = impl->insertCell(index, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } v8SetReturnValueFast(info, WTF::getPtr(result.release()), impl); } static void insertCellMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); HTMLTableRowElementV8Internal::insertCellMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } static void deleteCellMethod(const v8::FunctionCallbackInfo<v8::Value>& info) { ExceptionState exceptionState(ExceptionState::ExecutionContext, "deleteCell", "HTMLTableRowElement", info.Holder(), info.GetIsolate()); HTMLTableRowElement* impl = V8HTMLTableRowElement::toNative(info.Holder()); int index; { v8::TryCatch block; V8RethrowTryCatchScope rethrow(block); TONATIVE_VOID_EXCEPTIONSTATE_INTERNAL(index, toInt32(info[0], exceptionState), exceptionState); } impl->deleteCell(index, exceptionState); if (exceptionState.hadException()) { exceptionState.throwIfNeeded(); return; } } static void deleteCellMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) { TRACE_EVENT_SET_SAMPLING_STATE("Blink", "DOMMethod"); HTMLTableRowElementV8Internal::deleteCellMethod(info); TRACE_EVENT_SET_SAMPLING_STATE("V8", "V8Execution"); } } // namespace HTMLTableRowElementV8Internal static const V8DOMConfiguration::AttributeConfiguration V8HTMLTableRowElementAttributes[] = { {"rowIndex", HTMLTableRowElementV8Internal::rowIndexAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"sectionRowIndex", HTMLTableRowElementV8Internal::sectionRowIndexAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"cells", HTMLTableRowElementV8Internal::cellsAttributeGetterCallback, 0, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"align", HTMLTableRowElementV8Internal::alignAttributeGetterCallback, HTMLTableRowElementV8Internal::alignAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"bgColor", HTMLTableRowElementV8Internal::bgColorAttributeGetterCallback, HTMLTableRowElementV8Internal::bgColorAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"ch", HTMLTableRowElementV8Internal::chAttributeGetterCallback, HTMLTableRowElementV8Internal::chAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"chOff", HTMLTableRowElementV8Internal::chOffAttributeGetterCallback, HTMLTableRowElementV8Internal::chOffAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, {"vAlign", HTMLTableRowElementV8Internal::vAlignAttributeGetterCallback, HTMLTableRowElementV8Internal::vAlignAttributeSetterCallback, 0, 0, 0, static_cast<v8::AccessControl>(v8::DEFAULT), static_cast<v8::PropertyAttribute>(v8::None), 0 /* on instance */}, }; static const V8DOMConfiguration::MethodConfiguration V8HTMLTableRowElementMethods[] = { {"insertCell", HTMLTableRowElementV8Internal::insertCellMethodCallback, 0, 0}, {"deleteCell", HTMLTableRowElementV8Internal::deleteCellMethodCallback, 0, 0}, }; static void configureV8HTMLTableRowElementTemplate(v8::Handle<v8::FunctionTemplate> functionTemplate, v8::Isolate* isolate) { functionTemplate->ReadOnlyPrototype(); v8::Local<v8::Signature> defaultSignature; defaultSignature = V8DOMConfiguration::installDOMClassTemplate(functionTemplate, "HTMLTableRowElement", V8HTMLElement::domTemplate(isolate), V8HTMLTableRowElement::internalFieldCount, V8HTMLTableRowElementAttributes, WTF_ARRAY_LENGTH(V8HTMLTableRowElementAttributes), 0, 0, V8HTMLTableRowElementMethods, WTF_ARRAY_LENGTH(V8HTMLTableRowElementMethods), isolate); v8::Local<v8::ObjectTemplate> instanceTemplate ALLOW_UNUSED = functionTemplate->InstanceTemplate(); v8::Local<v8::ObjectTemplate> prototypeTemplate ALLOW_UNUSED = functionTemplate->PrototypeTemplate(); // Custom toString template functionTemplate->Set(v8AtomicString(isolate, "toString"), V8PerIsolateData::from(isolate)->toStringTemplate()); } v8::Handle<v8::FunctionTemplate> V8HTMLTableRowElement::domTemplate(v8::Isolate* isolate) { return V8DOMConfiguration::domClassTemplate(isolate, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), configureV8HTMLTableRowElementTemplate); } bool V8HTMLTableRowElement::hasInstance(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->hasInstance(&wrapperTypeInfo, v8Value); } v8::Handle<v8::Object> V8HTMLTableRowElement::findInstanceInPrototypeChain(v8::Handle<v8::Value> v8Value, v8::Isolate* isolate) { return V8PerIsolateData::from(isolate)->findInstanceInPrototypeChain(&wrapperTypeInfo, v8Value); } HTMLTableRowElement* V8HTMLTableRowElement::toNativeWithTypeCheck(v8::Isolate* isolate, v8::Handle<v8::Value> value) { return hasInstance(value, isolate) ? fromInternalPointer(v8::Handle<v8::Object>::Cast(value)->GetAlignedPointerFromInternalField(v8DOMWrapperObjectIndex)) : 0; } EventTarget* V8HTMLTableRowElement::toEventTarget(v8::Handle<v8::Object> object) { return toNative(object); } v8::Handle<v8::Object> wrap(HTMLTableRowElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8HTMLTableRowElement>(impl, isolate)); return V8HTMLTableRowElement::createWrapper(impl, creationContext, isolate); } v8::Handle<v8::Object> V8HTMLTableRowElement::createWrapper(PassRefPtrWillBeRawPtr<HTMLTableRowElement> impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { ASSERT(impl); ASSERT(!DOMDataStore::containsWrapper<V8HTMLTableRowElement>(impl.get(), isolate)); if (ScriptWrappable::wrapperCanBeStoredInObject(impl.get())) { const WrapperTypeInfo* actualInfo = ScriptWrappable::fromObject(impl.get())->typeInfo(); // Might be a XXXConstructor::wrapperTypeInfo instead of an XXX::wrapperTypeInfo. These will both have // the same object de-ref functions, though, so use that as the basis of the check. RELEASE_ASSERT_WITH_SECURITY_IMPLICATION(actualInfo->derefObjectFunction == wrapperTypeInfo.derefObjectFunction); } v8::Handle<v8::Object> wrapper = V8DOMWrapper::createWrapper(creationContext, &wrapperTypeInfo, toInternalPointer(impl.get()), isolate); if (UNLIKELY(wrapper.IsEmpty())) return wrapper; installPerContextEnabledProperties(wrapper, impl.get(), isolate); V8DOMWrapper::associateObjectWithWrapper<V8HTMLTableRowElement>(impl, &wrapperTypeInfo, wrapper, isolate, WrapperConfiguration::Dependent); return wrapper; } void V8HTMLTableRowElement::derefObject(void* object) { #if !ENABLE(OILPAN) fromInternalPointer(object)->deref(); #endif // !ENABLE(OILPAN) } template<> v8::Handle<v8::Value> toV8NoInline(HTMLTableRowElement* impl, v8::Handle<v8::Object> creationContext, v8::Isolate* isolate) { return toV8(impl, creationContext, isolate); } } // namespace WebCore
18,857
6,178
/* * Copyright (C) 2021 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/HttpError> namespace cc { HttpBadRequest::HttpBadRequest(): HttpError{HttpStatus::BadRequest, "Bad Request"} {} HttpForbidden::HttpForbidden(): HttpError{HttpStatus::Forbidden, "Forbidden"} {} HttpNotFound::HttpNotFound(): HttpError{HttpStatus::NotFound, "Not Found"} {} HttpRequestTimeout::HttpRequestTimeout(): HttpError{HttpStatus::RequestTimeout, "Request Timeout"} {} HttpPayloadTooLarge::HttpPayloadTooLarge(): HttpError{HttpStatus::PayloadTooLarge, "Payload Too Large"} {} HttpInternalServerError::HttpInternalServerError(): HttpError{HttpStatus::InternalServerError, "Internal Server Error"} {} HttpUnsupportedVersion::HttpUnsupportedVersion(): HttpError{HttpStatus::UnsupportedVersion, "HTTP Version Not Supported"} {} HttpNotImplemented::HttpNotImplemented(): HttpError{HttpStatus::NotImplemented, "Not Implemented"} {} } // namespace cc
1,051
331
#include "RendererApiEnum.h" namespace vanadium { std::string_view rendererApiToString(RendererApi rendererApi) { switch (rendererApi) { case RendererApi::Direct3D11: return "Direct3D11"; case RendererApi::Direct3D9: return "Direct3D9"; case RendererApi::Direct3D12: return "Direct3D12"; case RendererApi::Gnm: return "Gnm"; case RendererApi::Metal: return "Metal"; case RendererApi::Nvn: return "Nvn"; case RendererApi::OpenGLES: return "OpenGLES"; case RendererApi::OpenGL: return "OpenGL"; case RendererApi::Vulkan: return "Vulkan"; case RendererApi::WebGPU: return "WebGPU"; case RendererApi::Noop: return "Noop"; case RendererApi::Any: return "Any"; default: return "Undefined"; } } RendererApi bgfxTypeToRendererApi(bgfx::RendererType::Enum rendererType) { using namespace bgfx; switch (rendererType) { case RendererType::Enum::Direct3D9: return RendererApi::Direct3D9; case RendererType::Noop: return RendererApi::Noop; case RendererType::Direct3D11: return RendererApi::Direct3D11; case RendererType::Direct3D12: return RendererApi::Direct3D12; case RendererType::Gnm: return RendererApi::Gnm; case RendererType::Metal: return RendererApi::Metal; case RendererType::Nvn: return RendererApi::Nvn; case RendererType::OpenGLES: return RendererApi::OpenGLES; case RendererType::OpenGL: return RendererApi::OpenGL; case RendererType::Vulkan: return RendererApi::Vulkan; case RendererType::WebGPU: return RendererApi::WebGPU; case RendererType::Count: return RendererApi::Noop; default: return RendererApi::Undefined; } } bgfx::RendererType::Enum rendererApiToBgfxType(RendererApi rendererApi) { using namespace bgfx; switch (rendererApi) { case RendererApi::Direct3D11: return RendererType::Enum::Direct3D11; case RendererApi::Direct3D9: return RendererType::Enum::Direct3D9; case RendererApi::Direct3D12: return RendererType::Enum::Direct3D12; case RendererApi::Gnm: return RendererType::Enum::Gnm; case RendererApi::Metal: return RendererType::Enum::Metal; case RendererApi::Nvn: return RendererType::Enum::Nvn; case RendererApi::OpenGLES: return RendererType::Enum::OpenGLES; case RendererApi::OpenGL: return RendererType::Enum::OpenGL; case RendererApi::Vulkan: return RendererType::Enum::Vulkan; case RendererApi::WebGPU: return RendererType::Enum::WebGPU; default: return RendererType::Enum::Noop; } } } // namespace vanadium
2,842
924
/** * This file is part of the "libterminal" project * Copyright (c) 2019-2020 Christian Parpart <christian@parpart.family> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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 <terminal/pty/ConPty.h> #include <Windows.h> #include <utility> using namespace std; namespace { string GetLastErrorAsString() { DWORD errorMessageID = GetLastError(); if (errorMessageID == 0) return ""; LPSTR messageBuffer = nullptr; size_t size = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr, errorMessageID, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR) &messageBuffer, 0, nullptr); string message(messageBuffer, size); LocalFree(messageBuffer); return message; } } // anonymous namespace namespace terminal { ConPty::ConPty(PageSize const& _windowSize): size_ { _windowSize } { master_ = INVALID_HANDLE_VALUE; input_ = INVALID_HANDLE_VALUE; output_ = INVALID_HANDLE_VALUE; HANDLE hPipePTYIn { INVALID_HANDLE_VALUE }; HANDLE hPipePTYOut { INVALID_HANDLE_VALUE }; // Create the pipes to which the ConPty will connect to if (!CreatePipe(&hPipePTYIn, &output_, NULL, 0)) throw runtime_error { GetLastErrorAsString() }; if (!CreatePipe(&input_, &hPipePTYOut, NULL, 0)) { CloseHandle(hPipePTYIn); throw runtime_error { GetLastErrorAsString() }; } // Create the Pseudo Console of the required size, attached to the PTY-end of the pipes HRESULT hr = CreatePseudoConsole({ unbox<SHORT>(_windowSize.columns), unbox<SHORT>(_windowSize.lines) }, hPipePTYIn, hPipePTYOut, 0, &master_); if (hPipePTYIn != INVALID_HANDLE_VALUE) CloseHandle(hPipePTYIn); if (hPipePTYOut != INVALID_HANDLE_VALUE) CloseHandle(hPipePTYOut); if (hr != S_OK) throw runtime_error { GetLastErrorAsString() }; buffer_.resize(10240); } ConPty::~ConPty() { close(); } bool ConPty::isClosed() const { return master_ == INVALID_HANDLE_VALUE; } void ConPty::close() { auto const _ = std::lock_guard { mutex_ }; if (master_ != INVALID_HANDLE_VALUE) { ClosePseudoConsole(master_); master_ = INVALID_HANDLE_VALUE; } if (input_ != INVALID_HANDLE_VALUE) { CloseHandle(input_); input_ = INVALID_HANDLE_VALUE; } if (output_ != INVALID_HANDLE_VALUE) { CloseHandle(output_); output_ = INVALID_HANDLE_VALUE; } } void ConPty::prepareParentProcess() { } void ConPty::prepareChildProcess() { } optional<string_view> ConPty::read(size_t _size, std::chrono::milliseconds _timeout) { // TODO: wait for _timeout time at most AND got woken up upon wakeupReader() invokcation. (void) _timeout; auto const n = static_cast<DWORD>(min(_size, buffer_.size())); DWORD nread {}; if (!ReadFile(input_, buffer_.data(), n, &nread, nullptr)) return nullopt; return string_view { buffer_.data(), nread }; } void ConPty::wakeupReader() { // TODO: Windows ConPTY does *NOT* support non-blocking / overlapped I/O. // How can we make ReadFile() return early? We could maybe WriteFile() to it? } int ConPty::write(char const* buf, size_t size) { DWORD nwritten {}; if (WriteFile(output_, buf, static_cast<DWORD>(size), &nwritten, nullptr)) return static_cast<int>(nwritten); else return -1; } PageSize ConPty::pageSize() const noexcept { return size_; } void ConPty::resizeScreen(PageSize _cells, std::optional<ImageSize> _pixels) { (void) _pixels; // TODO Can we pass that information, too? COORD coords; coords.X = unbox<unsigned short>(_cells.columns); coords.Y = unbox<unsigned short>(_cells.lines); HRESULT const result = ResizePseudoConsole(master_, coords); if (result != S_OK) throw runtime_error { GetLastErrorAsString() }; size_ = _cells; } } // namespace terminal
4,749
1,560
// // 113_path_sum_3.cpp // leetcode_tree // // Created by Hadley on 11.07.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include <algorithm> #include <iostream> #include <vector> #include <string> #include <unordered_map> #include <stack> #include <cstring> #include <queue> #include <functional> #include <numeric> using namespace std; /** * Definition for a binary tree node.*/ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; //better solution// //*https://leetcode.com/problems/path-sum-ii/discuss/723689/C%2B%2B-96-Faster-Easytounderstand-With-Explanation*// class Solution { public: vector<vector<int>> path(TreeNode* root){ if(!root)return{}; if(!root->left&&!root->right) return {{root->val}}; vector<vector<int>> a=path(root->left); for(auto &x:a) x.push_back(root->val); vector<vector<int>> b=path(root->right); for(auto &x:b) x.push_back(root->val); a.insert(a.end(), b.begin(),b.end()); return a; } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; for(auto &x:path(root)){ int s=0; for(auto &y:x){ s+=y; } if(s==sum){ reverse(x.begin(), x.end()); res.push_back(x); } } return res; } };
1,691
604
//-*-mode:c++; mode:font-lock;-*- /*! \file VSLaserData.hpp Simple pedestal data \author Stephen Fegan \n UCLA \n sfegan@astro.ucla.edu \n \version 1.0 \date 05/18/2005 $Id: VSLaserData.hpp,v 3.8 2009/11/24 01:11:45 matthew Exp $ */ #ifndef VSLASERDATA_HPP #define VSLASERDATA_HPP #include<string> #include<vector> #include<VSOctaveIO.hpp> #include<VSSimpleHist.hpp> namespace VERITAS { class VSLaserData { public: struct CrateData { CrateData(): l2chan(), l2time(), cratetime_mean(), cratetime_dev() {} // Data ----------------------------------------------------------------- unsigned l2chan; // L2 channel double l2time; // L2 arrival time double cratetime_mean; // Crate arrival time - L2 time double cratetime_dev; // Crate arrival time dev static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,CrateData,l2chan); H5_ADDMEMBER(c,CrateData,l2time); H5_ADDMEMBER(c,CrateData,cratetime_mean); H5_ADDMEMBER(c,CrateData,cratetime_dev); } }; struct ChanData { ChanData(): nflash(), l2chan(), crate(), uncalibrated(), excluded(), chantime(), cratetime(), l2time(), gain(), gain_err(), absgain(), absgain_err(), eff(), eff_err(), signal_mean(), signal_dev(), signal_corr_mean(), signal_corr_dev(), signal_hist(0) { } // Data ----------------------------------------------------------------- unsigned nflash; // Number of flashes recorded unsigned l2chan; // L2 channel unsigned crate; // Crate number bool uncalibrated; // Has less than required # of laser flashes bool excluded; // Excluded from mean/median calculations double chantime; // Channel arrival time - L2 time double cratetime; // Crate arrival time - L2 time double l2time; // L2 arrival time for crate double gain; // Total gain relative to median double gain_err; double absgain; // Absolute single PE gain in DC double absgain_err; double eff; // Efficiency relative to median double eff_err; double signal_mean; // Laser amplitude mean double signal_dev; // Laser amplitude dev double signal_corr_mean; // Corrected laser amplitude mean double signal_corr_dev; // Corrected laser amplitude dev // Histograms ----------------------------------------------------------- VSSimpleHist<double> signal_hist; // Histogram of signal_mean static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,ChanData,nflash); H5_ADDMEMBER(c,ChanData,l2chan); H5_ADDMEMBER(c,ChanData,crate); H5_ADDMEMBER(c,ChanData,uncalibrated); H5_ADDMEMBER(c,ChanData,excluded); H5_ADDMEMBER(c,ChanData,chantime); H5_ADDMEMBER(c,ChanData,cratetime); H5_ADDMEMBER(c,ChanData,l2time); H5_ADDMEMBER(c,ChanData,gain); H5_ADDMEMBER(c,ChanData,gain_err); H5_ADDMEMBER(c,ChanData,absgain); H5_ADDMEMBER(c,ChanData,absgain_err); H5_ADDMEMBER(c,ChanData,eff); H5_ADDMEMBER(c,ChanData,eff_err); H5_ADDMEMBER(c,ChanData,signal_mean); H5_ADDMEMBER(c,ChanData,signal_dev); H5_ADDMEMBER(c,ChanData,signal_corr_mean); H5_ADDMEMBER(c,ChanData,signal_corr_dev); } }; struct ScopeData { ScopeData(): runno(), nchan(0), nevents(0), nflash(0), absgain_mean(), absgain_median(), npe_mean(), npe_median(), nchan_mean(), nchan_dev(), signal_mean(), signal_dev(), signal_hist(0), nchan_flash_hist(0), nchan_logain_hist(0), nchan_higain_hist(0), chan(), crate() {} // Data ----------------------------------------------------------------- unsigned runno; unsigned nchan; // Number channels in this telescope unsigned nevents; // Number events in laser run unsigned nflash; // Number events passing laser criteria double absgain_mean; // Mean absolute gain double absgain_median; // Median absolute gain double npe_mean; // Mean number of PEs per pixel double npe_median; // Median number of PEs per pixel double nchan_mean; // Number of channels in each flash mean double nchan_dev; // Number of channels in each flash dev double signal_mean; // Average telescope laser amplitude mean double signal_dev; // Average telescope laser amplitude dev // Histograms ----------------------------------------------------------- VSSimpleHist<double> signal_hist; VSSimpleHist<unsigned> nchan_flash_hist; VSSimpleHist<unsigned> nchan_logain_hist; VSSimpleHist<unsigned> nchan_higain_hist; // Vectors of structures ------------------------------------------------ std::vector<ChanData> chan; std::vector<CrateData> crate; static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,ScopeData,runno); H5_ADDMEMBER(c,ScopeData,nchan); H5_ADDMEMBER(c,ScopeData,nevents); H5_ADDMEMBER(c,ScopeData,nflash); H5_ADDMEMBER(c,ScopeData,absgain_mean); H5_ADDMEMBER(c,ScopeData,absgain_median); H5_ADDMEMBER(c,ScopeData,npe_mean); H5_ADDMEMBER(c,ScopeData,npe_median); H5_ADDMEMBER(c,ScopeData,nchan_mean); H5_ADDMEMBER(c,ScopeData,nchan_dev); H5_ADDMEMBER(c,ScopeData,signal_mean); H5_ADDMEMBER(c,ScopeData,signal_dev); } }; // Data ------------------------------------------------------------------- unsigned m_runno; // Settings --------------------------------------------------------------- unsigned m_threshold_nchan; double m_threshold_dc; double m_singlepe_dev; // Vectors of structures -------------------------------------------------- std::vector<ScopeData> scope; VSLaserData(): m_runno(), m_threshold_nchan(), m_threshold_dc(), m_singlepe_dev(), scope() { /* nothing to see here */ } bool load(const std::string& filename); void suppress(const double lo, const double hi); void clear(); void load(VSOctaveH5ReaderStruct* reader); bool load(unsigned iscope,VSOctaveH5ReaderStruct* reader); void save(VSOctaveH5WriterStruct* writer) const; static void _compose(VSOctaveH5CompositeDefinition& c) { H5_ADDMEMBER(c,VSLaserData,m_runno); H5_ADDMEMBER(c,VSLaserData,m_threshold_nchan); H5_ADDMEMBER(c,VSLaserData,m_threshold_dc); H5_ADDMEMBER(c,VSLaserData,m_singlepe_dev); } private: VSLaserData(const VSLaserData&); VSLaserData& operator= (const VSLaserData&); }; }; #endif // VSLASERDATA_HPP
6,884
2,406
#include <bits/stdc++.h> #define int long long #define double long double using namespace std; // Easy O(1) solution, who needs general solutions anyways bool isPrim(int n){ return n == 2 || n == 3 || n == 5 || n == 7 || n == 11 || n == 13 || n == 17 || n == 19 || n == 23; } signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int counter = 0; vector<int>perm(9); for (int i = 0; i < 9; ++i) { cin >> perm[i]; } for (int i = 1; i < 100001; ++i) { perm[0]=i; perm[4]=perm[0]+perm[1]+perm[2]-perm[3]-perm[5]; perm[8]=perm[0]+perm[1]+perm[2]-perm[6]-perm[7]; int sum=perm[0]+perm[1]+perm[2]; vector<int>sums; for (int j = 0; j < 3; ++j) { sums.push_back(perm[3*j]+perm[3*j+1]+perm[3*j+2]); sums.push_back(perm[j]+perm[j+3]+perm[j+6]); } sums.push_back(perm[0]+perm[4]+perm[8]); sums.push_back(perm[2]+perm[4]+perm[6]); if(sums.size() == count(sums.begin(), sums.end(), sum)){ for (int j = 0; j < 3; ++j) { for (int k = 0; k < 3; ++k) { cout << perm[j*3+k] << " "; } cout << "\n"; } break; } } }
1,405
556
#include "SetSkyboxModifier.h" #include "Utils/StringHelper.h" SetSkyboxModifier::SetSkyboxModifier(ZFile* nParent) : ZRoomCommand(nParent) { } void SetSkyboxModifier::ParseRawData() { ZRoomCommand::ParseRawData(); disableSky = parent->GetRawData().at(rawDataIndex + 0x04); disableSunMoon = parent->GetRawData().at(rawDataIndex + 0x05); } std::string SetSkyboxModifier::GetBodySourceCode() const { std::string sky = StringHelper::BoolStr(disableSky); std::string soonMoon = StringHelper::BoolStr(disableSunMoon); return StringHelper::Sprintf("SCENE_CMD_SKYBOX_DISABLES(%s, %s)", sky.c_str(), soonMoon.c_str()); } std::string SetSkyboxModifier::GetCommandCName() const { return "SCmdSkyboxDisables"; } RoomCommand SetSkyboxModifier::GetRoomCommand() const { return RoomCommand::SetSkyboxModifier; }
842
317
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include <ostream> #include <string> #include <vector> #include <ngraph/ngraph.hpp> namespace ngraph { namespace builder { namespace subgraph { class Constant { public: Constant(); Constant(const float value); Constant(const std::vector<float>& values); Constant(const std::vector<float>& values, const ngraph::element::Type outPrecision); Constant(const std::vector<float>& values, const ngraph::element::Type outPrecision, const ngraph::Shape& shape); bool empty() const noexcept; std::vector<float> values; ngraph::element::Type outPrecision; ngraph::Shape shape; bool shapeIsDefined; private: bool isEmpty; }; inline std::ostream& operator<<(std::ostream& out, const Constant& constant) { auto toStream = [](const std::vector<float>& values) -> std::string { std::stringstream os; os << "{"; for (size_t i = 0; i < values.size(); ++i) { const float& value = values[i]; if (i > 0) { os << value; } else { os << ", " << value; } } os << "}"; return os.str(); }; return out << "_" << toStream(constant.values) << "_" << constant.outPrecision << "_" << constant.shape; } } // namespace subgraph } // namespace builder } // namespace ngraph
1,431
438
/*! * @file at.cpp * * BSD 3-Clause License * Copyright (c) 2021, Giulio Berti * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <AtParser.h> #include <lora.h> AtParser at = AtParser(); String inputString = ""; // a string to hold incoming data void setupAtCommands(){ inputString.reserve(200); // reserve 200 bytes for the inputString: Serial.println("# Arduino AT command Control 1.0. RUNNING #"); at.AddCommand(new AtCommand("version", [](std::vector<String> p){ Serial.println("Helium Mapper Version 1.0.0"); })); at.AddCommand(new AtCommand("get_config=device", [](std::vector<String> p){ Serial.println("Get Config Command"); })); at.AddCommand(new AtCommand("set_config=lora", [](std::vector<String> p){ if (p.size() < 1) { Serial.println("ERROR: 2"); return;} // for (auto &&i : p) // { // Serial.print(i); // } // Serial.println(); String var = p.at(0); if(var == "join_mode") { if (p.size() < 2) { Serial.println("ERROR: 2"); return;} if (p.at(1) == "0"){ Serial.println("join_mode:OTAA"); } else if (p.at(1) == "1"){ Serial.println("join_mode:ABP not supported"); } else{ Serial.print(p.at(1)); Serial.println("ERROR: 2"); return; } } else if(var == "region") { if (p.size() < 2) { Serial.println("ERROR: 2"); return;} if (p.at(1) == "eu868"){ #ifdef CFG_eu868 Serial.println("Selected LoRaWAN 1.0.2 Region: EU868\r\nOK"); #else Serial.println("ERROR: Program needs to be recompiled using define CFG_eu868"); #endif } else if (p.at(1) == "us915"){ #ifdef CFG_us915 Serial.println("Selected LoRaWAN 1.0.2 Region: US915\r\nOK"); #else Serial.println("ERROR: Program needs to be recompiled using define CFG_us915"); #endif } else{ Serial.println("ERROR: 2"); return; } } else if(var == "dev_eui") { if (p.size() < 2) { Serial.println("ERROR: 2"); return;} String devEui = p.at(1); if (devEui.length() != 16) { Serial.println("ERROR: 2"); return;} for (int16_t i = 0; i <8; i++) { uint8_t b = (uint8_t)std::strtoul(devEui.substring(2*i,2*i+2).c_str(), NULL, 16); DEVEUI[7-i] = b; } dev.nvWrite(NV_DEVEUI, DEVEUI, 8); Serial.println("OK"); } else if(var == "app_eui") { if (p.size() < 2) { Serial.println("ERROR: 2"); return;} String appEui = p.at(1); if (appEui.length() != 16) { Serial.println("ERROR: 2"); return;} for (int16_t i = 0; i < 8 ; i++) { uint8_t b = (uint8_t)std::strtoul(appEui.substring(2*i,2*i+2).c_str(), NULL, 16); APPEUI[7-i] = b; } dev.nvWrite(NV_APPEUI, APPEUI, 8); Serial.println("OK"); } else if(var == "app_key") { if (p.size() < 2) { Serial.println("ERROR: 2"); return;} String appKey = p.at(1); if (appKey.length() != 32) { Serial.println("ERROR: 2"); return;} for (int16_t i = 0; i < 16; i++) { uint8_t b = (uint8_t)std::strtoul(appKey.substring(2*i,2*i+2).c_str(), NULL, 16); APPKEY[i] = b; } dev.nvWrite(NV_APPKEY, APPKEY, 16); Serial.println("OK"); } else if(var == "send_interval") { Serial.print("send_interval"); } })); at.AddCommand(new AtCommand("send", [](std::vector<String> p){ Serial.println("Send Command"); })); at.AddCommand(new AtCommand("join", [](std::vector<String> p){ Serial.println("Join Command"); })); at.AddCommand(new AtCommand("doh", [](std::vector<String> p){ pinMode(p.at(0).toInt(),OUTPUT); digitalWrite(p.at(0).toInt(),HIGH); Serial.println("OK"); })); at.AddCommand(new AtCommand("dol", [](std::vector<String> p){ pinMode(p.at(0).toInt(),OUTPUT); digitalWrite(p.at(0).toInt(),LOW); Serial.println("OK"); })); at.AddCommand(new AtCommand("dot", [](std::vector<String> p){ pinMode(p.at(0).toInt(),OUTPUT); digitalToggle(p.at(0).toInt()); Serial.println("OK"); })); } void readAtCommands(){ while (Serial.available()) { // get the new byte: char inChar = (char)Serial.read(); // add it to the inputString: inputString += inChar; // if the incoming character is a newline, set a flag // so the main loop can do something about it: if (inChar == '\n') { if(at.Parse(inputString) != 0) { Serial.println("Parse Error."); } // clear the string: inputString = ""; } } }
6,858
2,330
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef ARY_ESTACK_HXX #define ARY_ESTACK_HXX // USED SERVICES // BASE CLASSES #include <slist> // COMPONENTS // PARAMETERS template <class ELEM> class EStack : private std::slist<ELEM> { private: typedef std::slist<ELEM> base; const base & Base() const { return *this; } base & Base() { return *this; } public: typedef ELEM value_type; typedef typename std::slist<ELEM>::size_type size_type; // LIFECYCLE EStack() {} EStack( const EStack & i_rStack ) : base( (const base &)(i_rStack) ) {} ~EStack() {} // OPERATORS EStack & operator=( const EStack & i_rStack ) { base::operator=( i_rStack.Base() ); return *this; } bool operator==( const EStack<ELEM> & i_r2 ) const { return std::operator==( Base(), this->i_rStack.Base() ); } bool operator<( const EStack<ELEM> & i_r2 ) const { return std::operator<( Base(), this->i_rStack.Base() ); } // OPERATIONS void push( const value_type & i_rElem ) { base::push_front(i_rElem); } void pop() { base::pop_front(); } void erase_all() { while (NOT empty()) pop(); } // INQUIRY const value_type & top() const { return base::front(); } bool empty() const { return base::empty(); } // ACCESS value_type & top() { return base::front(); } }; // IMPLEMENTATION #endif
3,017
855
#include "bin_heap.h" template<typename dataT, typename countT> BinHeap<dataT, countT>::BinHeap(bool (*cmp)(const dataT &, const dataT &)) { trees_list = nullptr; top_node = nullptr; // tree_num = 0; node_num = 0; this->cmp = cmp; } template<typename dataT, typename countT> void BinHeap<dataT, countT>::display() { if (this->empty()) { puts(" Empty heap."); return; } countT tree_count = 1; BinNode<dataT, countT> * current_tree = this->trees_list; while (current_tree != nullptr) { printf("tree %u: ", tree_count); current_tree->display_node(); if (current_tree->child != nullptr) { std::cout << "["; current_tree->child->display_tree(); std::cout << "]"; } current_tree = current_tree->sibling; puts(" "); ++tree_count; } } template<typename dataT, typename countT> BinNode<dataT, countT> * BinHeap<dataT, countT>::push(dataT & data) { BinNode<dataT, countT> * node = new BinNode<dataT, countT>(data); node->sibling = this->trees_list; this->trees_list = this->consolidate(node); ++this->node_num; if (this->top_node == nullptr || cmp_node(this->top_node, node)) top_node = node; return node; } template<typename dataT, typename countT> BinNode<dataT, countT> * BinHeap<dataT, countT>::push(dataT && data) { BinNode<dataT, countT> * node = new BinNode<dataT, countT>(data); node->sibling = this->trees_list; this->trees_list = this->consolidate(node); ++this->node_num; if (this->top_node == nullptr || cmp_node(this->top_node, node)) top_node = node; // std::cout << "here"; return node; } template<typename dataT, typename countT> BinNode<dataT, countT> * BinHeap<dataT, countT>::consolidate(BinNode<dataT, countT> * head) { BinNode<dataT, countT> * current = head; BinNode<dataT, countT> * next = current->sibling; BinNode<dataT, countT> * prev = nullptr; while (next != nullptr) { if ((current->children_num != next->children_num) || (next->sibling != nullptr && current->children_num == next->sibling->children_num)) { prev = current; current = next; } else if (cmp_node(next, current)) { current->sibling = next->sibling; current->merge_tree(next); } else { if (prev == nullptr) head = next; else prev->sibling = next; next->merge_tree(current); current = next; } next = current->sibling; } // std::cout << "here"; return head; } template<typename dataT, typename countT> void BinHeap<dataT, countT>::merge(BinHeap<dataT, countT> & heap) { if (heap.empty()) return; BinNode<dataT, countT> * current = heap.trees_list->merge_trees_list(this->trees_list); current = consolidate(current); this->trees_list = current; this->node_num += heap.node_num; if (this->cmp_node(this->top_node, heap.top_node)) this->top_node = heap.top_node; } template<typename dataT, typename countT> void BinHeap<dataT, countT>::pop() { if (this->empty()) return; BinNode<dataT, countT> * current = this->trees_list; // remove top_node from trees_list if (current == this->top_node) { this->trees_list = this->top_node->sibling; } else { //find prev of top_node while (current->sibling != this->top_node) current = current->sibling; // remove top_node from trees_list current->sibling = this->top_node->sibling; } // merge children of top_node to trees_list if (top_node->children_num > 0) { // reverse children_list of top_node BinNode<dataT, countT> * child = this->top_node->child; BinNode<dataT, countT> * temp; current = nullptr; while (child != nullptr) { child->parent = nullptr; temp = child->sibling; child->sibling = current; current = child; child = temp; } // merge children of top_node to trees_list current = current->merge_trees_list(this->trees_list); current = consolidate(current); this->trees_list = current; } --this->node_num; delete this->top_node; // update top node; this->top_node = this->trees_list; current = this->trees_list; while (current != nullptr) { if (cmp_node(this->top_node, current)) this->top_node = current; current = current->sibling; } } template<typename dataT, typename countT> void BinHeap<dataT, countT>::change_value(BinNode<dataT, countT> * node, dataT & new_data) { node->data = &new_data; BinNode<dataT, countT> * parent = node->parent; while (parent != nullptr && cmp_node(parent, node)) { // swap data dataT * temp = node->data; node->data = parent->data; parent->data = temp; node = parent; parent = node->parent; } } template<typename dataT, typename countT> void BinHeap<dataT, countT>::change_value(BinNode<dataT, countT> * node, dataT && new_data) { node->data = &new_data; BinNode<dataT, countT> * parent = node->parent; while (parent != nullptr && cmp_node(parent, node)) { // swap data dataT * temp = node->data; node->data = parent->data; parent->data = temp; // std::cout << "here"; node = parent; parent = node->parent; } }
5,710
1,916
#pragma once #include <glm/glm.hpp> namespace Colors { inline glm::vec3 hsvToRgb(glm::vec3 hsv) { glm::vec3 rgb; int i = (int)floorf(hsv[0] * 6.0f); float f = hsv[0] * 6 - i; float p = hsv[2] * (1 - hsv[1]); float q = hsv[2] * (1 - f * hsv[1]); float t = hsv[2] * (1 - (1 - f) * hsv[1]); switch (i % 6) { case 0: rgb[0] = hsv[2], rgb[1] = t, rgb[2] = p; break; case 1: rgb[0] = q, rgb[1] = hsv[2], rgb[2] = p; break; case 2: rgb[0] = p, rgb[1] = hsv[2], rgb[2] = t; break; case 3: rgb[0] = p, rgb[1] = q, rgb[2] = hsv[2]; break; case 4: rgb[0] = t, rgb[1] = p, rgb[2] = hsv[2]; break; case 5: rgb[0] = hsv[2], rgb[1] = p, rgb[2] = q; break; } return rgb; } static inline glm::vec4 black = glm::vec4(0.0, 0.0, 0.0, 1.0); static inline glm::vec4 white = glm::vec4(1.0, 1.0, 1.0, 1.0); static inline glm::vec4 darkGrey = glm::vec4(.05, .05, .05, 1.0); static inline glm::vec4 red = glm::vec4(1.0, 0.0, 0.0, 1.0); static inline glm::vec4 green = glm::vec4(0.0, 1.0, 0.0, 1.0); static inline glm::vec4 blue = glm::vec4(0.0, 0.0, 1.0, 1.0); }
1,078
626
#include <bits/stdc++.h> using namespace std; bool isLetter(char l){ return (l>='a'&&l<='z') || (l>='A'&&l<='Z'); } int main(){ string input; cin >> input; long long ans = 0; for(int i = 0; i < input.size(); i++){ if(input[i] == '@'){ long long before = 0, after = 0; for(int j = i - 1; j >= 0; j--){ if(input[j] == '@' || input[j] == '.') break; if(isLetter(input[j])) before++; } for(int j = i + 1; j < input.size(); j++){ if(input[j] == '@' || input[j] == '_'){ i = j - 1; break; } if(input[j] == '.'){ if(j == i + 1) break; for(int k = j + 1; k < input.size(); k++){ if(!isLetter(input[k])) { i = k - 1; break; } i = k - 1; after++; } break; } } /* Multiplicar para obtener las multiples parejas (mini emails) que se forman con esos caracteres consecutivos. */ ans+=before*after; } } cout << ans << endl; return 0; }
1,368
424
//////////////////////////////////////////////////////////////////////////////////// //// This code is written by Ho Yub Jung //// //////////////////////////////////////////////////////////////////////////////////// #include "float4d.h" std::mt19937 float4d::n_random_seed = std::mt19937(0); void float4d::set(float min, float max, float cmin, float cmax, float multi, float add) { float4d r; r.resize(n_size); if (cmin >= cmax) { cmax = *max_element(p_v.begin(), p_v.end()); cmin = *min_element(p_v.begin(), p_v.end()); } for (int n = 0; n < n_size.n; n++) { for (int c = 0; c < n_size.c; c++) { for (int h = 0; h < n_size.h; h++) { for (int w = 0; w < n_size.w; w++) { float v = this->operator()(n, c, h, w); r(n, c, h, w) = ((v / (cmax - cmin))*(max - min) + min)*multi + add; } } } } *this = r; } void float4d::set(string init_method, std::mt19937 &rng) { if (init_method == "xavier" || init_method == "Xavier") { ////http://deepdish.io/2015/02/24/network-initialization/ //// X.Glorot and Y.Bengio, “Understanding the difficulty of training deep feedforward neural networks, ” in International conference on artificial intelligence and statistics, 2010, pp. 249–256. //// Xavier initialization float d = sqrt(12 / double(chw())) / 2; float max = d; float min = -d; set(min, max,rng); } else if (init_method == "pass") { set("xavier"); int ch = n_size.h / 2; int cw = n_size.w / 2; set(0, 0); this->operator()(0, 0, ch, cw) = 1; } } void float4d::set_borders(int border_width, float border_value) { for (int n = 0; n < n_size.n; n++) { for (int c = 0; c < n_size.c; c++) { for (int h = 0; h < n_size.h; h++) { for (int w = 0; w < n_size.w; w++) { if (h < border_width || h >= n_size.h - border_width || w < border_width || w >= n_size.w - border_width) { this->operator()(n, c, h, w) = border_value; } } } } } } void float4d::print(bool print_values) { cout << "size_NCHW " << n_size.n << " " << n_size.c << " " << n_size.h << " " << n_size.w << endl; if (print_values) { for (int ps = 0; ps < n_size.n; ps++) { // per each image for (int pc = 0; pc < n_size.c; pc++) { // per each channel for (int py = 0; py < n_size.h; py++) { // per each y for (int px = 0; px < n_size.w; px++) { // per each x cout << setw(4) << at(ps, pc, py, px) << " "; //if (at(ps, pc, py, px) >= 0) { cout << " "; } } cout << endl; } cout << endl; } } } } void float4d::rotate(int cy, int cx, int angle_degree, float out_bound_value) { float cosangle = std::cos(float(-angle_degree * PI / 180.0)); float sinangle = std::sin(float(-angle_degree * PI / 180.0)); float4d r; r.resize(this->size()); r.set(out_bound_value); for (int ps = 0; ps < n_size.n; ps++) { // per each image for (int pc = 0; pc < n_size.c; pc++) { // per each channel for (int py = 0; py < n_size.h; py++) { // per each y for (int px = 0; px < n_size.w; px++) { // per each x float y, x, ry, rx; y = cy - py; x = px - cx; rx = cosangle*x - sinangle*y; ry = sinangle*x + cosangle*y; int rpy, rpx; rpy = int(cy - ry + 0.5f); rpx = int(rx + cx + 0.5f); if (rpy >= 0 && rpy < n_size.h && rpx >= 0 && rpx < n_size.w) { r(ps, pc, py, px) = this->p_v[nchw2idx(ps, pc, rpy, rpx)]; } } } } } this->p_v = r.p_v; } void float4d::translate(int th, int tw, float out_bound_value ) { float4d r; r.resize(this->size()); r.set(out_bound_value); for (int ps = 0; ps < n_size.n; ps++) { // per each image for (int pc = 0; pc < n_size.c; pc++) { // per each channel for (int py = 0; py < n_size.h; py++) { // per each y for (int px = 0; px < n_size.w; px++) { // per each x int ny, nx; ny = py + th; nx = px + tw; if (ny >= 0 && nx >= 0 && ny < n_size.h && nx < n_size.w) { r(ps, pc, py, px) = this->p_v[nchw2idx(ps, pc, ny, nx)]; } } } } } this->p_v = r.p_v; }
4,161
1,974
// ***************************************************************************** // Module..: Leddar // /// \file LdBoolProperty.cpp /// /// \brief Definition of LdBoolProperty class. /// /// \author Patrick Boulay /// /// \since January 2016 // // Copyright (c) 2016 LeddarTech Inc. All rights reserved. // ***************************************************************************** #include "LdBoolProperty.h" #include "LtStringUtils.h" #include "LtScope.h" #include <string> // ***************************************************************************** // Function: LdBoolProperty::LdBoolProperty // /// \brief Constructor. /// /// \param aCategory See LdProperty. /// \param aFeatures See LdProperty. /// \param aId See LdProperty. /// \param aDeviceId See LdProperty. /// \param aDescription See LdProperty. /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** LeddarCore::LdBoolProperty::LdBoolProperty( LdProperty::eCategories aCategory, uint32_t aFeatures, uint32_t aId, uint16_t aDeviceId, const std::string &aDescription ) : LdProperty( LdProperty::TYPE_BOOL, aCategory, aFeatures, aId, aDeviceId, sizeof( bool ), sizeof( bool ), aDescription ) { } // ***************************************************************************** // Function: LdBoolProperty::SetValue // /// \brief Change the value at the given index. /// /// \param aIndex Index in array of value to change. /// \param aValue New value to write. /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** void LeddarCore::LdBoolProperty::SetValue( size_t aIndex, bool aValue ) { CanEdit(); // Initialize the count to 1 on the fist SetValue if not done before. if( Count() == 0 && aIndex == 0 ) { SetCount( 1 ); } if( aIndex >= Count() ) { throw std::out_of_range( "Index not valid, verify property count. Property id: " + LeddarUtils::LtStringUtils::IntToString( GetId(), 16 ) ); } bool *lValues = reinterpret_cast<bool *>( Storage() ); if( !IsInitialized() || lValues[ aIndex ] != aValue ) { SetInitialized( true ); lValues[ aIndex ] = aValue; EmitSignal( LdObject::VALUE_CHANGED ); } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void LeddarCore::LdBoolProperty::ForceValue( size_t aIndex, bool aValue ) /// /// \brief Force value /// /// \param aIndex Index in array of value to change. /// \param aValue New value to write. /// /// \author David Levy /// \date March 2019 //////////////////////////////////////////////////////////////////////////////////////////////////// void LeddarCore::LdBoolProperty::ForceValue( size_t aIndex, bool aValue ) { LeddarUtils::LtScope<bool> lForceEdit( &mCheckEditable, true ); mCheckEditable = false; SetValue( aIndex, aValue ); } // ***************************************************************************** // Function: LdBoolProperty::GetStringValue // /// \brief Display the value in string format /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** std::string LeddarCore::LdBoolProperty::GetStringValue( size_t aIndex ) const { return ( Value( aIndex ) == true ? "true" : "false" ); } // ***************************************************************************** // Function: LdBoolProperty::SetStringValue // /// \brief Property writer for the value as text. Possible value: true and false (lower case) /// /// \param aIndex Index of value to write. /// \param aValue The new value. /// /// \exception std::invalid_argument If the string is not valid. /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** void LeddarCore::LdBoolProperty::SetStringValue( size_t aIndex, const std::string &aValue ) { bool lNewValue = false; if( LeddarUtils::LtStringUtils::ToLower( aValue ) == "true" ) { lNewValue = true; } else if( LeddarUtils::LtStringUtils::ToLower( aValue ) == "false" ) { lNewValue = false; } else { throw( std::invalid_argument( "Invalid string value (use \"true\" or \"false\"." ) ); } SetValue( aIndex, lNewValue ); return; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void LeddarCore::LdBoolProperty::ForceStringValue( size_t aIndex, const std::string &aValue ) /// /// \brief Force the value /// /// \param aIndex Index of value to write. /// \param aValue The new value. /// /// \author David Levy /// \date March 2019 //////////////////////////////////////////////////////////////////////////////////////////////////// void LeddarCore::LdBoolProperty::ForceStringValue( size_t aIndex, const std::string &aValue ) { LeddarUtils::LtScope<bool> lForceEdit( &mCheckEditable, true ); mCheckEditable = false; SetStringValue( aIndex, aValue ); } // ***************************************************************************** // Function: LdBoolProperty::Value // /// \brief Return the property value /// /// \param aIndex Index of value. /// /// \exception std::out_of_range Value out of range ( from std::stoi ) /// /// \author Patrick Boulay /// /// \since January 2016 // ***************************************************************************** bool LeddarCore::LdBoolProperty::Value( size_t aIndex ) const { VerifyInitialization(); if( aIndex >= Count() ) { throw std::out_of_range( "Index not valid, verify property count. Property id: " + LeddarUtils::LtStringUtils::IntToString( GetId(), 16 ) ); } return reinterpret_cast<const bool *>( CStorage() )[ aIndex ]; }
6,029
1,734
// Copyright (c) 2021 DNV AS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include "gtest/gtest.h" #include "Units/Runtime/DynamicQuantity.h" #include "Units/Runtime/Unit.h" #include "Units/Length.h" #include "Units/Mass.h" #include "Units/ForAllDimensions.h" #include "Units/Reflection/ReflectQuantities.h" #include "Reflection/Classes/Class.h" #include "Reflection/TypeLibraries/TypeLibraryFactory.h" #include "Reflection/Objects/Object.h" #include "Units/Reflection/Details/ReflectLength.h" using namespace DNVS::MoFa::Reflection::Classes; using namespace DNVS::MoFa::Reflection::Objects; using namespace DNVS::MoFa::Reflection::TypeLibraries; using namespace DNVS::MoFa::Reflection::TypeConversions; using namespace DNVS::MoFa::Reflection; using namespace DNVS::MoFa::Units; using namespace DNVS::MoFa::Units::Runtime; struct ConverterFromDynamicQuantityToStaticQuantity { public: ConverterFromDynamicQuantityToStaticQuantity(const Variants::Variant& dynamicQuantity) : m_dynamicQuantity(Variants::VariantService::Unreflect<DynamicQuantity>(dynamicQuantity)) , m_staticQuantity(dynamicQuantity) { } template<typename DimensionT> void Apply() { typedef Quantity<DimensionT> StaticQuantity; if(DynamicDimension(DimensionT()) == m_dynamicQuantity.GetSimplifiedUnit().GetDimension()) m_staticQuantity = Variants::VariantService::Reflect<StaticQuantity>(StaticQuantity(m_dynamicQuantity.GetNeutralValue())); } Variants::Variant GetStaticQuantity() const { return m_staticQuantity; } private: Variants::Variant m_staticQuantity; DynamicQuantity m_dynamicQuantity; }; struct FallbackUnitConverter : public IConversion { virtual Variants::Variant Convert(const Variants::Variant& other) { ConverterFromDynamicQuantityToStaticQuantity converter(other); ForAllUsedDimensions(converter); return converter.GetStaticQuantity(); } virtual void IntrusiveConvert( Variants::Variant& variable ) { ConverterFromDynamicQuantityToStaticQuantity converter(variable); ForAllUsedDimensions(converter); variable = converter.GetStaticQuantity(); } }; TEST(DynamicReflectQuantityTests, ReflectDynamicQuantities_AddLengths) { ConversionGraphPointer conversionGraph( TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph()); TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph)); Reflection::ReflectDynamicQuantities(typeLibrary); Reflection::ReflectLength(typeLibrary); Object a(typeLibrary, DynamicQuantity(5.2, _m)); Object b(typeLibrary, DynamicQuantity(4.2, _m)); Object c = a + b; EXPECT_EQ(DynamicQuantity(5.2 + 4.2, _m), c.As<DynamicQuantity>()); } TEST(DynamicReflectQuantityTests, ReflectDynamicQuantities_ConvertToLength) { ConversionGraphPointer conversionGraph( TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph()); TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph)); Reflection::ReflectDynamicQuantities(typeLibrary); Reflection::ReflectLength(typeLibrary); Object a(typeLibrary, DynamicQuantity(5.2, _m)); Object b(typeLibrary, DynamicQuantity(4.2, _m)); Object c = a + b; EXPECT_EQ(Length(5.2 + 4.2), c.As<Length>()); EXPECT_THROW(c.As<Mass>(), std::runtime_error); } TEST(DynamicReflectQuantityTests, TestInvalidConversionFromDynamicQuantity_NoCrash) { ConversionGraphPointer conversionGraph( TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph()); TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph)); Reflection::ReflectDynamicQuantities(typeLibrary); Reflection::ReflectLength(typeLibrary); Object a(typeLibrary, DynamicQuantity(5.2, Unit("DummyUnit", 1.0, DynamicDimension(4, 4, 4, 4, 4)))); EXPECT_NO_FATAL_FAILURE( EXPECT_THROW(a.As<Length>(), std::runtime_error) ); } TEST(DynamicReflectQuantityTests, TestConversionOfNonDimensionalToDouble) { ConversionGraphPointer conversionGraph( TypeLibraries::TypeLibraryFactory::CreateDefaultTypeLibrary()->GetConversionGraph()); TypeLibraryPointer typeLibrary(new TypeLibrary(conversionGraph)); Reflection::ReflectDynamicQuantities(typeLibrary); Object a(typeLibrary, DynamicQuantity(5.2, Unit("DummyUnit", 1.0, DynamicDimension(0, 0, 0, 0, 0)))); EXPECT_DOUBLE_EQ(5.2, a.As<double>()); }
4,659
1,457
/* Copyright (c) 2010-2015, Delft University of Technology * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * - Neither the name of the Delft University of Technology nor the names of its contributors * may be used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Changelog * YYMMDD Author Comment * 140106 J. Geul File creatad, copied from unitTestOrbitalStateDerivativeModel. * * * References * * Notes: * Test tolerance was set at 5.0e-15 instead of epsilon due to rounding errors in Eigen types * with entries over a number of orders of magnitude, presumably causing the observed larger * than epsilon relative differences between expected and computed values. * */ #define BOOST_TEST_MAIN #include <boost/assign/list_of.hpp> #include <boost/bind.hpp> #include <boost/function.hpp> #include <boost/make_shared.hpp> #include <boost/shared_ptr.hpp> #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #include <Eigen/Core> #include <Eigen/Geometry> #include "Tudat/Basics/testMacros.h" #include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testAccelerationModels.h" #include "Tudat/Astrodynamics/BasicAstrodynamics/UnitTests/testBody.h" #include "Tudat/Astrodynamics/StateDerivativeModels/orbitalStateDerivativeModel.h" #include "Tudat/Mathematics/BasicMathematics/linearAlgebraTypes.h" namespace tudat { namespace unit_tests { using boost::assign::list_of; using basic_mathematics::Vector6d; //! Rotate vector over arbitrary angles. /*! * This function computes a composite rotation of the input vector over arbitrary angles about the * unit x-, y-, and z-axes. This is used in conjunction with rotateOverOtherArbitraryAngles() to * test the frame transformation features provided by the orbitalStateDerivativeModel. * \param inputVector Input vector before rotation. * \return Rotated vector. * \sa orbitalStateDerivativeModel, rotateOverOtherArbitraryAngles(). */ Eigen::Vector3d rotateOverArbitraryAngles( const Eigen::Vector3d& inputVector ) { // Declare rotation matrix. Eigen::Matrix3d rotationMatrix; rotationMatrix = Eigen::AngleAxisd( -1.15, Eigen::Vector3d::UnitX( ) ) * Eigen::AngleAxisd( 0.23, Eigen::Vector3d::UnitY( ) ) * Eigen::AngleAxisd( 2.56, Eigen::Vector3d::UnitZ( ) ); // Compute rotated matrix and return. return rotationMatrix * inputVector; } //! Rotate vector over other arbitrary angles. /*! * This function computes another composite rotation of the input vector over different arbitrary * angles (compared to the rotateOverArbitraryAngles() function) about the unit x-, y-, and z-axes. * This is used in conjunction with rotateOverArbitraryAngles() to test the frame transformation * features provided by the OrbitalStateDerivativeModel. * \param inputVector Input vector before rotation. * \return Rotated vector. * \sa orbitalStateDerivativeModel, rotateOverArbitraryAngles(). */ Eigen::Vector3d rotateOverOtherArbitraryAngles( const Eigen::Vector3d& inputVector ) { // Declare rotation matrix. Eigen::Matrix3d rotationMatrix; rotationMatrix = Eigen::AngleAxisd( 0.24, Eigen::Vector3d::UnitX( ) ) * Eigen::AngleAxisd( -1.55, Eigen::Vector3d::UnitY( ) ) * Eigen::AngleAxisd( 2.13, Eigen::Vector3d::UnitZ( ) ); // Compute rotated matrix and return. return rotationMatrix * inputVector; } //! Perform Mapping from Acceleration to Cartesian State Derivative /*! * This function is implemented in order to not use any external * mapping functions. The function was build completely from pieces of * code of the old cartesianStateDerivativeModel in order to use * completely different, but also verified methods of constructing a * stateDerivative from the total accelerations. * \param currentState The current state. * \param accelerations Total sum of accelerations. * \return stateDerivative */ Vector6d mapCartesian( const Vector6d& cartesianState, const Eigen::Vector3d& acceleration ) { // {{{ Snippets from cartesianStateDerivativeModel.h typedef Vector6d CartesianStateDerivativeType; // Declare Cartesian state derivative size. unsigned int stateDerivativeSize = cartesianState.rows( ); // Declare Cartesian state derivative of the same size as Cartesian state. CartesianStateDerivativeType cartesianStateDerivative = CartesianStateDerivativeType::Zero( stateDerivativeSize ); // Set derivative of position components to current Cartesian velocity. cartesianStateDerivative.segment( 0, stateDerivativeSize / 2 ) = cartesianState.segment( stateDerivativeSize / 2, stateDerivativeSize / 2 ); // Add transformed acceleration to state derivative. cartesianStateDerivative.segment( stateDerivativeSize / 2, stateDerivativeSize / 2 ) += acceleration; // Return assembled state derivative. return cartesianStateDerivative; // }}} End Snippets from cartesianStateDerivativeModel.h } BOOST_AUTO_TEST_SUITE( test_orbital_state_derivative_model ) //! Test whether 6D Cartesian state derivative model works correctly without frame transformations. BOOST_AUTO_TEST_CASE( test_OrbitalStateDerivativeModelWithoutFrameTransformations ) { using basic_astrodynamics::AccelerationModel3dPointer; using state_derivative_models::OrbitalStateDerivativeModelType; using state_derivative_models::OrbitalStateDerivativeModelPointer; // Shortcuts. typedef TestBody< 3, double > TestBody3d; typedef boost::shared_ptr< TestBody3d > TestBody3dPointer; typedef DerivedAccelerationModel< > DerivedAccelerationModel3d; typedef AnotherDerivedAccelerationModel< > AnotherDerivedAccelerationModel3d; // Set current state. const Vector6d currentState = ( basic_mathematics::Vector6d( ) << Eigen::Vector3d( -1.1, 2.2, -3.3 ), Eigen::Vector3d( 0.23, 1.67, -0.11 ) ).finished( ); // Set current time. const double currentTime = 5.6; // Set current position. const Eigen::Vector3d currentPosition = currentState.segment( 0, 3 ); // Set current velocity. const Eigen::Vector3d currentVelocity = currentState.segment( 3, 3 ); // Create body with zombie time and state. TestBody3dPointer body = boost::make_shared< TestBody3d >( Eigen::VectorXd::Zero( 6 ), 0.0 ); // Create acceleration models. AccelerationModel3dPointer firstAccelerationModel3d = boost::make_shared< DerivedAccelerationModel3d >( boost::bind( &TestBody3d::getCurrentPosition, body ), boost::bind( &TestBody3d::getCurrentTime, body ) ); AccelerationModel3dPointer secondAccelerationModel3d = boost::make_shared< AnotherDerivedAccelerationModel3d >( boost::bind( &TestBody3d::getCurrentPosition, body ), boost::bind( &TestBody3d::getCurrentVelocity, body ), boost::bind( &TestBody3d::getCurrentTime, body ) ); // Create list of acceleration models to provide to state derivative model. OrbitalStateDerivativeModelType::AccelerationModelPointerVector listOfAccelerations = list_of( firstAccelerationModel3d )( secondAccelerationModel3d ); // Declare Cartesian state derivative model. OrbitalStateDerivativeModelPointer cartesianStateDerivativeModel = boost::make_shared< OrbitalStateDerivativeModelType >( listOfAccelerations, boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ), boost::bind( &mapCartesian, _1, _2 ) ); // // Set Earth gravitational parameter [m^3 s^-2]. // const double earthGravitationalParameter = 3.986004415e14; // // Declare Keplerian state derivative model. // OrbitalStateDerivativeModelPointer keplerianStateDerivativeModel // = boost::make_shared< OrbitalStateDerivativeModelType >( // listOfAccelerations, // boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ), // boost::bind( &stateDerivativeMapKeplerian, _1, _2, // earthGravitationalParameter ) ); // // Declare Modified Equinoctial state derivative model. // OrbitalStateDerivativeModelPointer modifiedEquinoctialStateDerivativeModel // = boost::make_shared< OrbitalStateDerivativeModelType >( // listOfAccelerations, // boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ), // boost::bind( &stateDerivativeMapModifiedEquinoctial, _1, _2, // earthGravitationalParameter ) ); // Set expected accelerations. const Eigen::Vector3d expectedAccelerationFirstModel = currentPosition / ( currentTime * currentTime ); const Eigen::Vector3d expectedAccelerationSecondModel = 0.5 * currentPosition / ( 3.2 * ( currentTime + 3.4 ) * currentTime ) + currentVelocity / currentTime; // Set expected (cumulative) Cartesian state derivative. const Vector6d expectedCartesianStateDerivative = ( basic_mathematics::Vector6d( ) << currentVelocity, expectedAccelerationFirstModel + expectedAccelerationSecondModel ).finished( ); // Compute Cartesian state derivative. const Vector6d computedCartesianStateDerivative = cartesianStateDerivativeModel->computeStateDerivative( currentTime, currentState ); // Check that computed Cartesian state derivative matches expected values. TUDAT_CHECK_MATRIX_BASE( computedCartesianStateDerivative, expectedCartesianStateDerivative ) BOOST_CHECK_SMALL( computedCartesianStateDerivative.coeff( row, col ) - expectedCartesianStateDerivative.coeff( row, col ), 5.0e-15 ); } //! Test whether 6D Cartesian state derivative model works correctly with frame transformations. BOOST_AUTO_TEST_CASE( test_OrbitalStateDerivativeModelWithFrameTransformations ) { using basic_astrodynamics::AccelerationModel3dPointer; using state_derivative_models::OrbitalStateDerivativeModelType; using state_derivative_models::OrbitalStateDerivativeModelPointer; // Shortcuts. typedef TestBody< 3, double > TestBody3d; typedef boost::shared_ptr< TestBody3d > TestBody3dPointer; typedef DerivedAccelerationModel< > DerivedAccelerationModel3d; typedef AnotherDerivedAccelerationModel< > AnotherDerivedAccelerationModel3d; // Set current state. const Vector6d currentState = ( basic_mathematics::Vector6d( ) << Eigen::Vector3d( -1.1, 2.2, -3.3 ), Eigen::Vector3d( 0.23, 1.67, -0.11 ) ).finished( ); // Set current time. const double currentTime = 5.6; // Set current position. const Eigen::Vector3d currentPosition = currentState.segment( 0, 3 ); // Set current velocity. const Eigen::Vector3d currentVelocity = currentState.segment( 3, 3 ); // Create body with zombie time and state. TestBody3dPointer body = boost::make_shared< TestBody3d >( Eigen::VectorXd::Zero( 6 ), 0.0 ); // Create acceleration models. AccelerationModel3dPointer firstAccelerationModel3d = boost::make_shared< DerivedAccelerationModel3d >( boost::bind( &TestBody3d::getCurrentPosition, body ), boost::bind( &TestBody3d::getCurrentTime, body ) ); AccelerationModel3dPointer secondAccelerationModel3d = boost::make_shared< AnotherDerivedAccelerationModel3d >( boost::bind( &TestBody3d::getCurrentPosition, body ), boost::bind( &TestBody3d::getCurrentVelocity, body ), boost::bind( &TestBody3d::getCurrentTime, body ) ); // Create list of reference frame transformations for first acceleration model. // NB: The order of this list is VERY important! The order of transformations executed is from // the beginning of the vector to the end sequentially. OrbitalStateDerivativeModelType::ListOfReferenceFrameTransformations listOfFrameTransformations = list_of( &rotateOverArbitraryAngles )( &rotateOverOtherArbitraryAngles ); // Create list to pass to constructor of acceleration model/frame transformation list pairs. // In this case, there are two frame transformations executed for the first acceleration model, // and none for the second. OrbitalStateDerivativeModelType::ListOfAccelerationFrameTransformationPairs listOfAccelerationFrameTransformations = list_of( std::make_pair( firstAccelerationModel3d, listOfFrameTransformations ) ) ( std::make_pair( secondAccelerationModel3d, OrbitalStateDerivativeModelType:: ListOfReferenceFrameTransformations( ) ) ); // Declare Cartesian state derivative model. OrbitalStateDerivativeModelPointer stateDerivativeModel = boost::make_shared< OrbitalStateDerivativeModelType >( listOfAccelerationFrameTransformations, boost::bind( &TestBody3d::setCurrentTimeAndState, body, _1, _2 ), boost::bind( &mapCartesian, _1, _2 ) ); // Set expected accelerations. const Eigen::Vector3d expectedAccelerationFirstModel = rotateOverOtherArbitraryAngles( rotateOverArbitraryAngles( currentPosition / ( currentTime * currentTime ) ) ); const Eigen::Vector3d expectedAccelerationSecondModel = 0.5 * currentPosition / ( 3.2 * ( currentTime + 3.4 ) * currentTime ) + currentVelocity / currentTime; // Set expected (cumulative) Cartesian state derivative. const Vector6d expectedCartesianStateDerivative = ( basic_mathematics::Vector6d( ) << currentVelocity, expectedAccelerationFirstModel + expectedAccelerationSecondModel ).finished( ); // Compute Cartesian state derivative. const Vector6d computedCartesianStateDerivative = stateDerivativeModel->computeStateDerivative( currentTime, currentState ); // Check that computed Cartesian state derivative matches expected values. TUDAT_CHECK_MATRIX_BASE( computedCartesianStateDerivative, expectedCartesianStateDerivative ) BOOST_CHECK_CLOSE_FRACTION( computedCartesianStateDerivative.coeff( row, col ), expectedCartesianStateDerivative.coeff( row, col ), 5.0e-15 ); } BOOST_AUTO_TEST_SUITE_END( ) } // namespace unit_tests } // namespace tudat
16,075
4,719
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2017-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include <time.h> #include <string> #include "hphp/runtime/ext/vsdebug/logging.h" namespace HPHP { namespace VSDEBUG { // Linkage for the log file pointer, this is a singleton for the extension. FILE* VSDebugLogger::s_logFile {nullptr}; void VSDebugLogger::InitializeLogging(std::string& logFilePath) { if (logFilePath.empty()) { return; } // This is only expected to be invoked once, when the extension is loaded. assert(s_logFile == nullptr); // TODO: (Ericblue) Add logic for max file size, log file rotation, etc. const char* path = logFilePath.c_str(); s_logFile = fopen(path, "a"); if (s_logFile == nullptr) { return; } // Start with a visual delimiter so it's easy to see where // the session started. Log(VSDebugLogger::LogLevelInfo, "-------------------------------"); } void VSDebugLogger::FinalizeLogging() { if (s_logFile == nullptr) { return; } Log(VSDebugLogger::LogLevelInfo, "VSDebugExtension shutting down."); Log(VSDebugLogger::LogLevelInfo, "-------------------------------"); LogFlush(); fclose(s_logFile); s_logFile = nullptr; } void VSDebugLogger::Log(const char* level, const char* fmt, ...) { if (s_logFile == nullptr) { return; } time_t t = time(NULL); struct tm tm = *localtime(&t); fprintf(s_logFile, "[%d-%d-%d %d:%d:%d]", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec ); fprintf(s_logFile, "[%s]\t", level); va_list args; va_start(args, fmt); vfprintf(s_logFile, fmt, args); va_end(args); fprintf(s_logFile, "\n"); } void VSDebugLogger::LogFlush() { if (s_logFile == nullptr) { return; } fflush(s_logFile); } } }
2,702
886
// Copyright 2008-2009 Deutsches Forschungszentrum fuer Kuenstliche Intelligenz // or its licensors, as applicable. // // You may not use this file except under the terms of the accompanying license. // // 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. // // Project: // File: ocrofst-impl.h // Purpose: OcroFST class implementation // Responsible: mezhirov // Reviewer: // Primary Repository: // Web Sites: www.iupr.org, www.dfki.de, www.ocropus.org #include "ocr-pfst.h" #include "fst-io.h" #include "a-star.h" namespace ocropus { struct OcroFSTImpl : OcroFST { objlist<intarray> m_targets; objlist<intarray> m_inputs; objlist<intarray> m_outputs; objlist<floatarray> m_costs; floatarray m_heuristics; floatarray accept_costs; int start; virtual intarray &targets(int vertex) { return m_targets[vertex]; } virtual intarray &inputs(int vertex) { return m_inputs[vertex]; } virtual intarray &outputs(int vertex) { return m_outputs[vertex]; } virtual floatarray &costs(int vertex) { return m_costs[vertex]; } virtual float acceptCost(int vertex) { return accept_costs[vertex]; } virtual void setAcceptCost(int vertex, float new_value) { accept_costs[vertex] = new_value; } virtual const char *description() { return "Lattice"; } // reading virtual int nStates() { return accept_costs.length(); } virtual int getStart() { return start; } virtual float getAcceptCost(int node) { return accept_costs[node]; } virtual void arcs(intarray &out_inputs, intarray &out_targets, intarray &out_outputs, floatarray &out_costs, int from) { copy(out_inputs, m_inputs[from]); copy(out_targets, m_targets[from]); copy(out_outputs, m_outputs[from]); copy(out_costs, m_costs[from]); } virtual void clear() { start = 0; m_targets.clear(); m_inputs.clear(); m_outputs.clear(); m_costs.clear(); accept_costs.clear(); } // writing virtual int newState() { accept_costs.push() = INFINITY; m_targets.push(); m_inputs.push(); m_outputs.push(); m_costs.push(); return accept_costs.length() - 1; } virtual void addTransition(int from,int to,int output,float cost,int input) { m_targets[from].push(to); m_outputs[from].push(output); m_inputs[from].push(input); m_costs[from].push(cost); } virtual void rescore(int from,int to,int output,float cost,int input) { intarray &t = m_targets[from]; intarray &i = m_inputs[from]; intarray &o = m_outputs[from]; for(int j = 0; j < t.length(); j++) { if(t[j] == to && i[j] == input && o[j] == output) { m_costs[from][j] = cost; break; } } } virtual void setStart(int node) { start = node; } virtual void setAccept(int node,float cost=0.0) { accept_costs[node] = cost; } virtual int special(const char *s) { return 0; } virtual void bestpath(colib::ustrg &result) { a_star(result, *this); } virtual void save(const char *path) { fst_write(path, *this); } virtual void load(const char *path) { fst_read(*this, path); } private: int flags; void achieve(int flag) { CHECK_ARG(flag == SORTED_BY_INPUT || flag == SORTED_BY_OUTPUT || flag == HAS_HEURISTICS); if(flags & flag) return; if(flag == HAS_HEURISTICS) { a_star_backwards(m_heuristics, *this); return; } for(int node = 0; node < nStates(); node++) { intarray permutation; if(flag == OcroFST::SORTED_BY_INPUT) quicksort(permutation, m_inputs[node]); else quicksort(permutation, m_outputs[node]); permute(m_inputs[node], permutation); permute(m_outputs[node], permutation); permute(m_targets[node], permutation); permute(m_costs[node], permutation); } flags |= flag; } public: virtual void sortByInput() { achieve(SORTED_BY_INPUT); } virtual void sortByOutput() { achieve(SORTED_BY_OUTPUT); } virtual bool hasFlag(int flag) { return flags & flag; } virtual floatarray &heuristics() { return m_heuristics; } virtual void calculateHeuristics() { achieve(HAS_HEURISTICS); } OcroFSTImpl(int max_size=0) : m_targets(max_size), m_inputs(max_size), m_outputs(max_size), m_costs(max_size), accept_costs(max_size), start(0), flags(0) { } virtual void clearFlags() { flags = 0; } }; OcroFST *make_OcroFST() { return new OcroFSTImpl(); }; void scale_fst(OcroFST &fst,float scale) { using namespace narray_ops; if(fabs(scale-1.0)<1e-6) return; for(int i=0;i<fst.nStates();i++) { fst.costs(i) *= scale; float accept = fst.acceptCost(i); if(accept>=0 && accept<1e37) fst.setAcceptCost(i,accept*scale); } } static void make_neg(intarray &a) { for(int i=0;i<a.length();i++) if(a[i]>0&&a[i]<=4) a[i] = -a[i]; } static void make_pos(intarray &a) { for(int i=0;i<a.length();i++) if(a[i]>=-40&&a[i]<0) a[i] = -a[i]; } void make_specials_neg(OcroFST &fst,bool input,bool output) { using namespace narray_ops; for(int i=0;i<fst.nStates();i++) { if(input) make_neg(fst.inputs(i)); if(output) make_neg(fst.outputs(i)); } } void make_specials_pos(OcroFST &fst,bool input,bool output) { using namespace narray_ops; for(int i=0;i<fst.nStates();i++) { if(input) make_pos(fst.inputs(i)); if(output) make_pos(fst.outputs(i)); } } }
7,392
2,336
/* ************************************************************************ * Copyright 2016-2020 Advanced Micro Devices, Inc. * ************************************************************************ */ #pragma once #ifndef _GEMM_HOST_HPP_ #define _GEMM_HOST_HPP_ #include "handle.hpp" #ifdef USE_TENSILE_HOST #include "tensile_host.hpp" #else // USE_TENSILE_HOST /******************************************************************************* * Helper enumeration over different transpose combinations ******************************************************************************/ typedef enum { // First letter refers to A, second letter refers to B NN, NT, TN, TT, NC, CN, TC, CT, CC, } transpose_mode; constexpr transpose_mode GetTransposeMode(rocblas_operation trans_a, rocblas_operation trans_b) { if(trans_a == rocblas_operation_none) { if(trans_b == rocblas_operation_none) return NN; if(trans_b == rocblas_operation_conjugate_transpose) return NC; return NT; } else if(trans_a == rocblas_operation_conjugate_transpose) { if(trans_b == rocblas_operation_none) return CN; if(trans_b == rocblas_operation_conjugate_transpose) return CC; return CT; } else { if(trans_b == rocblas_operation_none) return TN; if(trans_b == rocblas_operation_conjugate_transpose) return TC; return TT; } } #include "Tensile.h" /******************************************************************************* * Tensile Helper Function call ******************************************************************************/ template <typename T> rocblas_status tensile_helper(const T& alpha_h, const T& beta_h, const T* A, const T* B, T* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle); #define TENSILE_ARGS(T) \ (T*)C, (const T*)C, (const T*)A, (const T*)B, *((const T*)&alpha_h), *((const T*)&beta_h), \ strideC1, strideC2, strideC1, strideC2, strideA1, strideA2, strideB1, strideB2, sizeI, \ sizeJ, sizeK, sizeL, handle->rocblas_stream, 0, nullptr, nullptr, nullptr template <> inline rocblas_status tensile_helper(const rocblas_half& alpha_h, const rocblas_half& beta_h, const rocblas_half* A, const rocblas_half* B, rocblas_half* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_HB(TENSILE_ARGS(rocblas_half)); break; case NT: case NC: status = tensile_Cijk_Ailk_Bjlk_HB(TENSILE_ARGS(rocblas_half)); break; case TN: case CN: status = tensile_Cijk_Alik_Bljk_HB(TENSILE_ARGS(rocblas_half)); break; case TT: case TC: case CT: case CC: status = tensile_Cijk_Alik_Bjlk_HB(TENSILE_ARGS(rocblas_half)); break; } return get_rocblas_status_for_hip_status(status); } template <> inline rocblas_status tensile_helper(const float& alpha_h, const float& beta_h, const float* A, const float* B, float* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_SB(TENSILE_ARGS(float)); break; case NT: case NC: status = tensile_Cijk_Ailk_Bjlk_SB(TENSILE_ARGS(float)); break; case TN: case CN: status = tensile_Cijk_Alik_Bljk_SB(TENSILE_ARGS(float)); break; case TT: case TC: case CT: case CC: status = tensile_Cijk_Alik_Bjlk_SB(TENSILE_ARGS(float)); break; } return get_rocblas_status_for_hip_status(status); } template <> inline rocblas_status tensile_helper(const double& alpha_h, const double& beta_h, const double* A, const double* B, double* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_DB(TENSILE_ARGS(double)); break; case NT: case NC: status = tensile_Cijk_Ailk_Bjlk_DB(TENSILE_ARGS(double)); break; case TN: case CN: status = tensile_Cijk_Alik_Bljk_DB(TENSILE_ARGS(double)); break; case TT: case TC: case CT: case CC: status = tensile_Cijk_Alik_Bjlk_DB(TENSILE_ARGS(double)); break; } return get_rocblas_status_for_hip_status(status); } template <> inline rocblas_status tensile_helper(const rocblas_float_complex& alpha_h, const rocblas_float_complex& beta_h, const rocblas_float_complex* A, const rocblas_float_complex* B, rocblas_float_complex* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { static_assert(std::is_standard_layout<TensileComplexFloat>{}, "TensileComplexFloat is not a standard layout type, and thus is " "incompatible with C."); static_assert(std::is_trivial<TensileComplexFloat>{}, "TensileComplexFloat is not a trivial type, and thus is " "incompatible with C."); static_assert(sizeof(rocblas_float_complex) == sizeof(TensileComplexFloat), "TensileComplexFloat does not match rocblas_float_complex"); hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case NT: status = tensile_Cijk_Ailk_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case TN: status = tensile_Cijk_Alik_Bljk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case TT: status = tensile_Cijk_Alik_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case NC: status = tensile_Cijk_Ailk_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat)); break; case CN: status = tensile_Cijk_AlikC_Bljk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case TC: status = tensile_Cijk_Alik_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat)); break; case CT: status = tensile_Cijk_AlikC_Bjlk_CB(TENSILE_ARGS(TensileComplexFloat)); break; case CC: status = tensile_Cijk_AlikC_BjlkC_CB(TENSILE_ARGS(TensileComplexFloat)); break; } return get_rocblas_status_for_hip_status(status); } template <> inline rocblas_status tensile_helper(const rocblas_double_complex& alpha_h, const rocblas_double_complex& beta_h, const rocblas_double_complex* A, const rocblas_double_complex* B, rocblas_double_complex* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_stride strideC1, rocblas_stride strideC2, rocblas_stride strideA1, rocblas_stride strideA2, rocblas_stride strideB1, rocblas_stride strideB2, rocblas_int sizeI, rocblas_int sizeJ, rocblas_int sizeK, rocblas_int sizeL, rocblas_handle handle) { static_assert(std::is_standard_layout<TensileComplexDouble>{}, "TensileComplexDouble is not a standard layout type, and thus is " "incompatible with C."); static_assert(std::is_trivial<TensileComplexDouble>{}, "TensileComplexDouble is not a trivial type, and thus is " "incompatible with C."); static_assert(sizeof(rocblas_double_complex) == sizeof(TensileComplexDouble), "TensileComplexDouble does not match rocblas_double_complex"); hipError_t status = hipErrorInvalidValue; switch(GetTransposeMode(trans_a, trans_b)) { case NN: status = tensile_Cijk_Ailk_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case NT: status = tensile_Cijk_Ailk_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case TN: status = tensile_Cijk_Alik_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case TT: status = tensile_Cijk_Alik_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case NC: status = tensile_Cijk_Ailk_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case CN: status = tensile_Cijk_AlikC_Bljk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case TC: status = tensile_Cijk_Alik_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case CT: status = tensile_Cijk_AlikC_Bjlk_ZB(TENSILE_ARGS(TensileComplexDouble)); break; case CC: status = tensile_Cijk_AlikC_BjlkC_ZB(TENSILE_ARGS(TensileComplexDouble)); break; } return get_rocblas_status_for_hip_status(status); } #undef TENSILE_ARGS #endif // USE_TENSILE_HOST /********************************************************************************* * Right now Tensile requires alpha and beta to be passed by value on host. * * If in device pointer mode, copy alpha and beta to host. * * If k == 0, we set alpha = 0 instead of copying from device. * * TODO: Make this asynchronous, putting synchronization closer to Tensile call. * *********************************************************************************/ template <typename T, typename Tc> rocblas_status copy_alpha_beta_to_host_if_on_device( rocblas_handle handle, const T*& alpha, const T*& beta, Tc& alpha_h, Tc& beta_h, rocblas_int k) { if(handle->pointer_mode == rocblas_pointer_mode_device) { if(alpha) { if(k == 0) alpha_h = 0; else RETURN_IF_HIP_ERROR(hipMemcpy(&alpha_h, alpha, sizeof(Tc), hipMemcpyDeviceToHost)); alpha = &alpha_h; } if(beta) { RETURN_IF_HIP_ERROR(hipMemcpy(&beta_h, beta, sizeof(Tc), hipMemcpyDeviceToHost)); beta = &beta_h; } } return rocblas_status_success; } /******************************************************************************* * Tensile Function call ******************************************************************************/ template <typename T> inline rocblas_status call_tensile(rocblas_handle handle, const T* alpha, const T* beta, const T* A, const T* B, T* C, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_int ld_c, rocblas_stride stride_c, rocblas_int ld_a, rocblas_stride stride_a, rocblas_int ld_b, rocblas_stride stride_b, rocblas_int m, rocblas_int n, rocblas_int k, rocblas_int batch_count = 1) { #ifdef USE_TENSILE_HOST RocblasContractionProblem<T> problem{handle, trans_a, trans_b, m, n, k, alpha, A, ld_a, stride_a, B, ld_b, stride_b, beta, C, ld_c, stride_c, batch_count}; return runContractionProblem(problem); #else // USE_TENSILE_HOST return tensile_helper(*alpha, *beta, A, B, C, trans_a, trans_b, ld_c, stride_c, ld_a, stride_a, ld_b, stride_b, m, n, batch_count, k, handle); #endif // USE_TENSILE_HOST } /******************************************************************************* * Validate Arguments ******************************************************************************/ template <typename T> inline rocblas_status validateArgs(rocblas_handle handle, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_int m, rocblas_int n, rocblas_int k, const T* alpha, const void* a, rocblas_int ld_a, const void* b, rocblas_int ld_b, const T* beta, const void* c, rocblas_int ld_c, rocblas_int batch_count = 1) { // handle must be valid if(!handle) return rocblas_status_invalid_handle; // sizes must not be negative if(m < 0 || n < 0 || k < 0 || batch_count < 0) return rocblas_status_invalid_size; rocblas_int num_rows_a = trans_a == rocblas_operation_none ? m : k; rocblas_int num_rows_b = trans_b == rocblas_operation_none ? k : n; rocblas_int num_rows_c = m; // leading dimensions must be valid if(num_rows_a > ld_a || num_rows_b > ld_b || num_rows_c > ld_c) return rocblas_status_invalid_size; // quick return 0 is valid in BLAS // Note: k==0 is not a quick return, because C must still be multiplied by beta if(!m || !n || !batch_count) return rocblas_status_success; if(!beta) return rocblas_status_invalid_pointer; if(handle->pointer_mode == rocblas_pointer_mode_host && *beta == 1) { if(!k) return rocblas_status_success; if(!alpha) return rocblas_status_invalid_pointer; if(!*alpha) return rocblas_status_success; } // pointers must be valid if((k && (!a || !b || !alpha)) || !c) return rocblas_status_invalid_pointer; return rocblas_status_continue; } /* * =========================================================================== * template interface * =========================================================================== */ template <bool BATCHED, typename T, typename U, typename V> ROCBLAS_EXPORT_NOINLINE rocblas_status rocblas_gemm_template(rocblas_handle handle, rocblas_operation trans_a, rocblas_operation trans_b, rocblas_int m, rocblas_int n, rocblas_int k, const T* alpha, const U* A, rocblas_int offset_a, rocblas_int ld_a, rocblas_stride stride_a, const U* B, rocblas_int offset_b, rocblas_int ld_b, rocblas_stride stride_b, const T* beta, V* C, rocblas_int offset_c, rocblas_int ld_c, rocblas_stride stride_c, rocblas_int batch_count) { // Early exit. Note: k==0 is not an early exit, since C still needs to be multiplied by beta. if(m == 0 || n == 0 || batch_count == 0) return rocblas_status_success; // Temporarily change the thread's default device ID to the handle's device ID auto saved_device_id = handle->push_device_id(); T alpha_h, beta_h; RETURN_IF_ROCBLAS_ERROR( copy_alpha_beta_to_host_if_on_device(handle, alpha, beta, alpha_h, beta_h, k)); // When beta == 1 and either k == 0 or alpha == 0, the operation is a no-op if(*beta == 1 && (k == 0 || *alpha == 0)) return rocblas_status_success; rocblas_status status = rocblas_status_success; // TODO: Use C++17 constexpr if if(BATCHED) { // We cannot do this with a device array, so array of pointers must be on host for now // Host arrays of device pointers. auto hostA = std::make_unique<T*[]>(batch_count); auto hostB = std::make_unique<T*[]>(batch_count); auto hostC = std::make_unique<T*[]>(batch_count); RETURN_IF_HIP_ERROR( hipMemcpy(&hostA[0], A, sizeof(T*) * batch_count, hipMemcpyDeviceToHost)); RETURN_IF_HIP_ERROR( hipMemcpy(&hostB[0], B, sizeof(T*) * batch_count, hipMemcpyDeviceToHost)); RETURN_IF_HIP_ERROR( hipMemcpy(&hostC[0], C, sizeof(T*) * batch_count, hipMemcpyDeviceToHost)); for(rocblas_int b = 0; b < batch_count; b++) { status = call_tensile(handle, alpha, beta, hostA[b] + offset_a, hostB[b] + offset_b, hostC[b] + offset_c, trans_a, trans_b, ld_c, stride_c, ld_a, stride_a, ld_b, stride_b, m, n, k); if(status != rocblas_status_success) break; } } else { // The (T*) casts are to prevent template deduction errors when BATCHED==true and the A, B, C // pointers are pointers to arrays of pointers. constexpr if(BATCHED) above could avoid this. status = call_tensile(handle, alpha, beta, (T*)A + offset_a, (T*)B + offset_b, (T*)C + offset_c, trans_a, trans_b, ld_c, stride_c, ld_a, stride_a, ld_b, stride_b, m, n, k, batch_count); } return status; } #endif // _GEMM_HOST_HPP_
26,273
7,290
// [!output WTL_FRAME_FILE].cpp : implmentation of the [!output WTL_FRAME_CLASS] class // ///////////////////////////////////////////////////////////////////////////// #include "stdafx.h" [!if WTL_USE_RIBBON] #include "Ribbon.h" [!endif] #include "resource.h" #include "aboutdlg.h" [!if WTL_USE_VIEW] #include "[!output WTL_VIEW_FILE].h" [!endif] [!if WTL_APPTYPE_MDI] #include "[!output WTL_CHILD_FRAME_FILE].h" [!endif] #include "[!output WTL_FRAME_FILE].h" BOOL [!output WTL_FRAME_CLASS]::PreTranslateMessage(MSG* pMsg) { [!if WTL_APPTYPE_MDI] if([!output WTL_FRAME_BASE_CLASS]<[!output WTL_FRAME_CLASS]>::PreTranslateMessage(pMsg)) return TRUE; HWND hWnd = MDIGetActive(); if(hWnd != NULL) return (BOOL)::SendMessage(hWnd, WM_FORWARDMSG, 0, (LPARAM)pMsg); return FALSE; [!else] [!if WTL_USE_VIEW] if([!output WTL_FRAME_BASE_CLASS]<[!output WTL_FRAME_CLASS]>::PreTranslateMessage(pMsg)) return TRUE; return m_view.PreTranslateMessage(pMsg); [!else] return [!output WTL_FRAME_BASE_CLASS]<[!output WTL_FRAME_CLASS]>::PreTranslateMessage(pMsg); [!endif] [!endif] } BOOL [!output WTL_FRAME_CLASS]::OnIdle() { [!if WTL_USE_TOOLBAR] UIUpdateToolBar(); [!endif] return FALSE; } LRESULT [!output WTL_FRAME_CLASS]::OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { [!if WTL_RIBBON_DUAL_UI] bool bRibbonUI = RunTimeHelper::IsRibbonUIAvailable(); if (bRibbonUI) UIAddMenu(GetMenu(), true); else CMenuHandle(GetMenu()).DeleteMenu(ID_VIEW_RIBBON, MF_BYCOMMAND); [!else] [!if WTL_RIBBON_SINGLE_UI] UIAddMenu(GetMenu(), true); [!endif] [!endif] [!if WTL_USE_RIBBON && !WTL_USE_CMDBAR] m_CmdBar.Create(m_hWnd, rcDefault, NULL, WS_CHILD); m_CmdBar.AttachMenu(GetMenu()); m_CmdBar.LoadImages(IDR_MAINFRAME); [!endif] [!if WTL_USE_TOOLBAR] [!if WTL_USE_REBAR] [!if WTL_USE_CMDBAR] // create command bar window HWND hWndCmdBar = m_CmdBar.Create(m_hWnd, rcDefault, NULL, ATL_SIMPLE_CMDBAR_PANE_STYLE); // attach menu m_CmdBar.AttachMenu(GetMenu()); // load command bar images m_CmdBar.LoadImages(IDR_MAINFRAME); // remove old menu SetMenu(NULL); [!endif] HWND hWndToolBar = CreateSimpleToolBarCtrl(m_hWnd, IDR_MAINFRAME, FALSE, ATL_SIMPLE_TOOLBAR_PANE_STYLE); CreateSimpleReBar(ATL_SIMPLE_REBAR_NOBORDER_STYLE); [!if WTL_USE_CMDBAR] AddSimpleReBarBand(hWndCmdBar); AddSimpleReBarBand(hWndToolBar, NULL, TRUE); [!else] AddSimpleReBarBand(hWndToolBar); [!endif] [!else] CreateSimpleToolBar(); [!endif] [!endif] [!if WTL_USE_STATUSBAR] CreateSimpleStatusBar(); [!endif] [!if WTL_APPTYPE_MDI] CreateMDIClient(); [!if WTL_USE_CMDBAR] m_CmdBar.SetMDIClient(m_hWndMDIClient); [!endif] [!endif] [!if WTL_APPTYPE_SDI || WTL_APPTYPE_MTSDI] [!if WTL_USE_VIEW] [!if WTL_VIEWTYPE_FORM] m_hWndClient = m_view.Create(m_hWnd); [!else] [!if WTL_VIEWTYPE_HTML] //TODO: Replace with a URL of your choice m_hWndClient = m_view.Create(m_hWnd, rcDefault, _T("http://www.microsoft.com"), [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!else] m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!endif] [!if WTL_VIEWTYPE_LISTBOX || WTL_VIEWTYPE_EDIT || WTL_VIEWTYPE_RICHEDIT] m_font = AtlCreateControlFont(); m_view.SetFont(m_font); [!endif] [!if WTL_VIEWTYPE_SCROLL] // replace with appropriate values for the app m_view.SetScrollSize(2000, 1000); [!endif] [!endif] [!endif] [!endif] [!if WTL_APPTYPE_TABVIEW] m_hWndClient = m_view.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, WS_EX_CLIENTEDGE); [!endif] [!if WTL_APPTYPE_EXPLORER] m_hWndClient = m_splitter.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN); m_pane.SetPaneContainerExtendedStyle(PANECNT_NOBORDER); m_pane.Create(m_splitter, _T("Tree"), WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN); m_treeview.Create(m_pane, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | TVS_HASLINES | TVS_LINESATROOT | TVS_HASBUTTONS | TVS_SHOWSELALWAYS, WS_EX_CLIENTEDGE); m_pane.SetClient(m_treeview); [!if WTL_VIEWTYPE_FORM] m_view.Create(m_splitter); [!else] [!if WTL_VIEWTYPE_HTML] //TODO: Replace with a URL of your choice m_view.Create(m_splitter, rcDefault, _T("http://www.microsoft.com"), [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!else] m_view.Create(m_splitter, rcDefault, NULL, [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!endif] [!if WTL_VIEWTYPE_LISTBOX || WTL_VIEWTYPE_EDIT || WTL_VIEWTYPE_RICHEDIT] m_font = AtlCreateControlFont(); m_view.SetFont(m_font); [!endif] [!if WTL_VIEWTYPE_SCROLL] // replace with appropriate values for the app m_view.SetScrollSize(2000, 1000); [!endif] [!endif] m_splitter.SetSplitterPanes(m_pane, m_view); UpdateLayout(); m_splitter.SetSplitterPosPct(25); [!endif] [!if WTL_USE_TOOLBAR] [!if WTL_USE_REBAR] UIAddToolBar(hWndToolBar); [!else] UIAddToolBar(m_hWndToolBar); [!endif] UISetCheck(ID_VIEW_TOOLBAR, 1); [!endif] [!if WTL_USE_STATUSBAR] UISetCheck(ID_VIEW_STATUS_BAR, 1); [!endif] [!if WTL_APPTYPE_EXPLORER] UISetCheck(ID_VIEW_TREEPANE, 1); [!endif] // register object for message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->AddMessageFilter(this); pLoop->AddIdleHandler(this); [!if WTL_USE_RIBBON] [!if WTL_RIBBON_SINGLE_UI] ShowRibbonUI(true); [!else] ShowRibbonUI(bRibbonUI); UISetCheck(ID_VIEW_RIBBON, bRibbonUI); [!endif] [!endif] [!if WTL_APPTYPE_TABVIEW] [!if WTL_USE_CMDBAR] CMenuHandle menuMain = m_CmdBar.GetMenu(); [!else] CMenuHandle menuMain = GetMenu(); [!endif] m_view.SetWindowMenu(menuMain.GetSubMenu(WINDOW_MENU_POSITION)); [!endif] return 0; } [!if WTL_COM_SERVER] LRESULT [!output WTL_FRAME_CLASS]::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/) { [!if WTL_APPTYPE_MDI] [!if WTL_USE_CMDBAR] m_CmdBar.AttachMenu(NULL); [!endif] [!endif] // unregister message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->RemoveMessageFilter(this); pLoop->RemoveIdleHandler(this); // if UI is the last thread, no need to wait if(_Module.GetLockCount() == 1) { _Module.m_dwTimeOut = 0L; _Module.m_dwPause = 0L; } _Module.Unlock(); [!if WTL_APPTYPE_MTSDI] ::PostQuitMessage(1); [!endif] return 0; } [!else] LRESULT [!output WTL_FRAME_CLASS]::OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled) { [!if WTL_APPTYPE_MDI] [!if WTL_USE_CMDBAR] m_CmdBar.AttachMenu(NULL); [!endif] [!endif] // unregister message filtering and idle updates CMessageLoop* pLoop = _Module.GetMessageLoop(); ATLASSERT(pLoop != NULL); pLoop->RemoveMessageFilter(this); pLoop->RemoveIdleHandler(this); bHandled = FALSE; return 1; } [!endif] LRESULT [!output WTL_FRAME_CLASS]::OnFileExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { PostMessage(WM_CLOSE); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnFileNew(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { [!if WTL_APPTYPE_TABVIEW] [!output WTL_VIEW_CLASS]* pView = new [!output WTL_VIEW_CLASS]; [!if WTL_VIEWTYPE_FORM] pView->Create(m_view); [!else] [!if WTL_VIEWTYPE_HTML] //TODO: Replace with a URL of your choice pView->Create(m_view, rcDefault, _T("http://www.microsoft.com"), [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!else] pView->Create(m_view, rcDefault, NULL, [!output WTL_VIEW_STYLES], [!output WTL_VIEW_EX_STYLES]); [!endif] [!if WTL_VIEWTYPE_LISTBOX || WTL_VIEWTYPE_EDIT || WTL_VIEWTYPE_RICHEDIT] pView->SetFont(m_font); [!endif] [!if WTL_VIEWTYPE_SCROLL] // replace with appropriate values for the app pView->SetScrollSize(2000, 1000); [!endif] [!endif] m_view.AddPage(pView->m_hWnd, _T("Document")); [!endif] [!if WTL_APPTYPE_MDI] [!output WTL_CHILD_FRAME_CLASS]* pChild = new [!output WTL_CHILD_FRAME_CLASS]; pChild->CreateEx(m_hWndClient); [!endif] // TODO: add code to initialize document return 0; } [!if WTL_APPTYPE_MTSDI] LRESULT [!output WTL_FRAME_CLASS]::OnFileNewWindow(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { ::PostThreadMessage(_Module.m_dwMainThreadID, WM_USER, 0, 0L); return 0; } [!endif] [!if WTL_USE_TOOLBAR] LRESULT [!output WTL_FRAME_CLASS]::OnViewToolBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { [!if WTL_USE_REBAR] static BOOL bVisible = TRUE; // initially visible bVisible = !bVisible; CReBarCtrl rebar = m_hWndToolBar; [!if WTL_USE_CMDBAR] int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST + 1); // toolbar is 2nd added band [!else] int nBandIndex = rebar.IdToIndex(ATL_IDW_BAND_FIRST); // toolbar is first 1st band [!endif] rebar.ShowBand(nBandIndex, bVisible); [!else] BOOL bVisible = !::IsWindowVisible(m_hWndToolBar); ::ShowWindow(m_hWndToolBar, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE); [!endif] UISetCheck(ID_VIEW_TOOLBAR, bVisible); UpdateLayout(); return 0; } [!endif] [!if WTL_USE_STATUSBAR] LRESULT [!output WTL_FRAME_CLASS]::OnViewStatusBar(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { BOOL bVisible = !::IsWindowVisible(m_hWndStatusBar); ::ShowWindow(m_hWndStatusBar, bVisible ? SW_SHOWNOACTIVATE : SW_HIDE); UISetCheck(ID_VIEW_STATUS_BAR, bVisible); UpdateLayout(); return 0; } [!endif] [!if WTL_RIBBON_DUAL_UI] LRESULT [!output WTL_FRAME_CLASS]::OnViewRibbon(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { ShowRibbonUI(!IsRibbonUI()); UISetCheck(ID_VIEW_RIBBON, IsRibbonUI()); [!if !WTL_USE_CMDBAR] if (!IsRibbonUI()) SetMenu(AtlLoadMenu(IDR_MAINFRAME)); [!endif] return 0; } [!endif] LRESULT [!output WTL_FRAME_CLASS]::OnAppAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { CAboutDlg dlg; dlg.DoModal(); return 0; } [!if WTL_APPTYPE_MDI] LRESULT [!output WTL_FRAME_CLASS]::OnWindowCascade(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDICascade(); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnWindowTile(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDITile(); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnWindowArrangeIcons(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { MDIIconArrange(); return 0; } [!endif] [!if WTL_APPTYPE_TABVIEW] LRESULT [!output WTL_FRAME_CLASS]::OnWindowClose(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { int nActivePage = m_view.GetActivePage(); if(nActivePage != -1) m_view.RemovePage(nActivePage); else ::MessageBeep((UINT)-1); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnWindowCloseAll(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { m_view.RemoveAllPages(); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnWindowActivate(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { int nPage = wID - ID_WINDOW_TABFIRST; m_view.SetActivePage(nPage); return 0; } [!endif] [!if WTL_APPTYPE_EXPLORER] LRESULT [!output WTL_FRAME_CLASS]::OnViewTreePane(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/) { bool bShow = (m_splitter.GetSinglePaneMode() != SPLIT_PANE_NONE); m_splitter.SetSinglePaneMode(bShow ? SPLIT_PANE_NONE : SPLIT_PANE_RIGHT); UISetCheck(ID_VIEW_TREEPANE, bShow); return 0; } LRESULT [!output WTL_FRAME_CLASS]::OnTreePaneClose(WORD /*wNotifyCode*/, WORD /*wID*/, HWND hWndCtl, BOOL& /*bHandled*/) { if(hWndCtl == m_pane.m_hWnd) { m_splitter.SetSinglePaneMode(SPLIT_PANE_RIGHT); UISetCheck(ID_VIEW_TREEPANE, 0); } return 0; } [!endif]
12,185
5,894
#include "platform.h" #include <time.h> #include <stdlib.h> #include <string.h> #include "dmetaphone.hpp" #include "metaphone.h" #define DMETAPHONE_VERSION "DMETAPHONE 1.1.05" static const char * compatibleVersions[] = { "DMETAPHONE 1.1.05 [0e64c86ec1d5771d4ce0abe488a98a2a]", "DMETAPHONE 1.1.05", NULL }; DMETAPHONE_API bool getECLPluginDefinition(ECLPluginDefinitionBlock *pb) { if (pb->size == sizeof(ECLPluginDefinitionBlockEx)) { ECLPluginDefinitionBlockEx * pbx = (ECLPluginDefinitionBlockEx *) pb; pbx->compatibleVersions = compatibleVersions; } else if (pb->size != sizeof(ECLPluginDefinitionBlock)) return false; pb->magicVersion = PLUGIN_VERSION; pb->version = DMETAPHONE_VERSION; pb->moduleName = "lib_metaphone"; pb->ECL = NULL; // Definition is in lib_metaphone.ecllib pb->flags = PLUGIN_IMPLICIT_MODULE; pb->description = "Metaphone library"; return true; } namespace nsDmetaphone { IPluginContext * parentCtx = NULL; } using namespace nsDmetaphone; DMETAPHONE_API void setPluginContext(IPluginContext * _ctx) { parentCtx = _ctx; } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone1(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); __ret_len = strlen((char*) metaph); __ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1); strcpy(__ret_str, (char*) metaph); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone2(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); __ret_len = strlen((char*) metaph2); __ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1); strcpy(__ret_str, (char*) metaph2); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphoneBoth(size32_t & __ret_len,char * & __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); __ret_len = strlen((char*) metaph) + strlen((char*) metaph2); __ret_str = (char *) CTXMALLOC(parentCtx, __ret_len+1); strcpy(__ret_str, (char*) metaph); strcat(__ret_str, (char*) metaph2); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone1_20(char * __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); memset(__ret_str, ' ', 20); size32_t metaph_len = strlen((char*) metaph); strncpy(__ret_str, (char*) metaph, (metaph_len > 20)?20:metaph_len); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphone2_20(char * __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); memset(__ret_str, ' ', 20); size32_t metaph2_len = strlen((char*) metaph2); strncpy(__ret_str, (char*) metaph2, (metaph2_len > 20)?20:metaph2_len); } DMETAPHONE_API void DMETAPHONE_CALL mpDMetaphoneBoth_40(char * __ret_str,unsigned _len_instr,const char * instr) { cString metaph; cString metaph2; MString ms; ms.Set(instr, _len_instr); ms.DoubleMetaphone(metaph, metaph2); memset(__ret_str, ' ', 40); size32_t metaph_len = strlen((char*) metaph); strncpy(__ret_str, (char*) metaph, (metaph_len > 20)?20:metaph_len); size32_t metaph2_len = strlen((char*) metaph2); strncpy(__ret_str+metaph_len, (char*) metaph2, (metaph2_len > 20)?20:metaph2_len); }
3,761
1,592
const char* const asserter_abi = R"=====( { "version": "eosio::abi/1.0", "types": [], "structs": [ { "name": "assertdef", "base": "", "fields": [ { "name": "condition", "type": "int8" },{ "name": "message", "type": "string" } ] }, { "name": "nothing", "base": "", "fields": [] } ], "actions": [ { "name": "procassert", "type": "assertdef", "ricardian_contract": "" }, { "name": "provereset", "type": "nothing", "ricardian_contract": "" } ], "tables": [], "ricardian_clauses": [], "abi_extensions": [] } )=====";
788
257
#ifndef AST_VAR_DECL_H #define AST_VAR_DECL_H #include <memory> #include "ast.hpp" #include "../common/typedefs.hpp" #include "../typing/substitution.hpp" namespace splicpp { class ast_type; class ast_exp; class ast_id; class symboltable; class varcontext; class typecontext; class ltypecontext; class sl_type; class ir_stmt; class ircontext; class ast_var_decl : public ast { public: const s_ptr<ast_type> t; const s_ptr<ast_id> id; const s_ptr<ast_exp> exp; ast_var_decl(__decltype(t) t, __decltype(id) id, __decltype(exp) exp, const sloc sl) : ast(sl) , t(t) , id(id) , exp(exp) {} void assign(sid i); std::string fetch_name() const; sid fetch_id() const; void assign_ids(const varcontext& c); void register_types(symboltable& s, varcontext& c); s_ptr<const sl_type> fetch_assigned_type(const typecontext& c) const; substitution declare_type(ltypecontext& c) const; s_ptr<const ir_stmt> translate(const ircontext& c) const; virtual void pretty_print(std::ostream& s, const uint tab) const; }; } #endif
1,078
457
#include "gtest/gtest.h" #include "test_macro.cpp" #include "localPRG.h" #include "minimizer.h" #include "minirecord.h" #include "minihit.h" #include "interval.h" #include "prg/path.h" #include "localgraph.h" #include "localnode.h" #include "index.h" #include "inthash.h" #include "pangenome/pannode.h" #include "pangenome/panread.h" #include "utils.h" #include "seq.h" #include "kmergraph.h" #include "kmernode.h" #include <stdint.h> #include <iostream> using namespace std; TEST(LocalPRGTest, create) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); uint32_t j = 0; EXPECT_EQ(j, l0.id); EXPECT_EQ("empty", l0.name); EXPECT_EQ("", l0.seq); j = 1; EXPECT_EQ(j, l1.id); EXPECT_EQ("simple", l1.name); EXPECT_EQ("AGCT", l1.seq); j = 2; EXPECT_EQ(j, l2.id); EXPECT_EQ("varsite", l2.name); EXPECT_EQ("A 5 GC 6 G 5 T", l2.seq); j = 3; EXPECT_EQ(j, l3.id); EXPECT_EQ("nested varsite", l3.name); EXPECT_EQ("A 5 G 7 C 8 T 7 6 G 5 T", l3.seq); } TEST(LocalPRGTest, isalphaEmptyString) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); bool a0 = l0.isalpha_string(""); bool a1 = l1.isalpha_string(""); bool a2 = l2.isalpha_string(""); bool a3 = l3.isalpha_string(""); EXPECT_EQ(a0, 1) << "isalpha_string thinks the empty string is not alphabetic for l0"; EXPECT_EQ(a1, 1) << "isalpha_string thinks the empty string is not alphabetic for l1"; EXPECT_EQ(a2, 1) << "isalpha_string thinks the empty string is not alphabetic for l2"; EXPECT_EQ(a3, 1) << "isalpha_string thinks the empty string is not alphabetic for l3"; } TEST(LocalPRGTest, isalphaSpaceString) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); bool a0 = l0.isalpha_string("AGCT T"); bool a1 = l1.isalpha_string("AGCT T"); bool a2 = l2.isalpha_string("AGCT T"); bool a3 = l3.isalpha_string("AGCT T"); EXPECT_EQ(a0, 0) << "isalpha_string thinks a string containing a space is alphabetic for l0"; EXPECT_EQ(a1, 0) << "isalpha_string thinks a string containing a space is alphabetic for l1"; EXPECT_EQ(a2, 0) << "isalpha_string thinks a string containing a space is alphabetic for l2"; EXPECT_EQ(a3, 0) << "isalpha_string thinks a string containing a space is alphabetic for l3"; } TEST(LocalPRGTest, isalphaNumberString) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); bool a0 = l0.isalpha_string("AGCT 8 T"); bool a1 = l1.isalpha_string("AGCT 8 T"); bool a2 = l2.isalpha_string("AGCT 8 T"); bool a3 = l3.isalpha_string("AGCT 8 T"); EXPECT_EQ(a0, 0) << "isalpha_string thinks a string containing a number is alphabetic for l0"; EXPECT_EQ(a1, 0) << "isalpha_string thinks a string containing a number is alphabetic for l1"; EXPECT_EQ(a2, 0) << "isalpha_string thinks a string containing a number is alphabetic for l2"; EXPECT_EQ(a3, 0) << "isalpha_string thinks a string containing a number is alphabetic for l3"; } TEST(LocalPRGTest, string_along_path) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); // empty interval deque<Interval> d = {Interval(0, 0)}; Path p; p.initialize(d); EXPECT_EQ("", l0.string_along_path(p)); EXPECT_EQ("", l1.string_along_path(p)); EXPECT_EQ("", l2.string_along_path(p)); EXPECT_EQ("", l3.string_along_path(p)); // positive length interval d = {Interval(1, 3)}; p.initialize(d); EXPECT_EQ("GC", l1.string_along_path(p)); EXPECT_EQ(" 5", l2.string_along_path(p)); EXPECT_EQ(" 5", l3.string_along_path(p)); // multiple intervals d = {Interval(0, 1), Interval(2, 3)}; p.initialize(d); EXPECT_EQ("AC", l1.string_along_path(p)); EXPECT_EQ("A5", l2.string_along_path(p)); EXPECT_EQ("A5", l3.string_along_path(p)); // including empty interval d = {Interval(0, 1), Interval(2, 2)}; p.initialize(d); EXPECT_EQ("A", l1.string_along_path(p)); EXPECT_EQ("A", l2.string_along_path(p)); EXPECT_EQ("A", l3.string_along_path(p)); // forbidden paths d = {Interval(2, 3), Interval(13, 25)}; p.initialize(d); EXPECT_DEATH(l1.string_along_path(p), ""); EXPECT_DEATH(l1.string_along_path(p), ""); EXPECT_DEATH(l2.string_along_path(p), ""); EXPECT_DEATH(l3.string_along_path(p), ""); } TEST(LocalPRGTest, string_along_localpath) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); // empty interval vector<LocalNodePtr> p = {l0.prg.nodes[0]}; EXPECT_EQ("", l0.string_along_path(p)); p = {l1.prg.nodes[0]}; EXPECT_EQ("AGCT", l1.string_along_path(p)); // extract from intervals p = {l2.prg.nodes[0], l2.prg.nodes[1]}; EXPECT_EQ("AGC", l2.string_along_path(p)); p = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]}; EXPECT_EQ("AGT", l2.string_along_path(p)); } TEST(LocalPRGTest, nodes_along_path) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); // empty interval expects no nodes along deque<Interval> d = {Interval(0, 0)}; Path p; p.initialize(d); vector<LocalNodePtr> v; //EXPECT_EQ(v, l0.nodes_along_path(p)); EXPECT_EQ(v, l1.nodes_along_path(p)); EXPECT_EQ(v, l2.nodes_along_path(p)); EXPECT_EQ(v, l3.nodes_along_path(p)); // positive length interval d = {Interval(1, 3)}; p.initialize(d); uint32_t j = 1; EXPECT_EQ(j, l1.nodes_along_path(p).size()); j = 0; EXPECT_EQ(j, l1.nodes_along_path(p)[0]->id); EXPECT_EQ(j, l2.nodes_along_path(p).size()); // no nodes in this interval EXPECT_EQ(j, l3.nodes_along_path(p).size()); // different interval d = {Interval(4, 5)}; p.initialize(d); j = 1; EXPECT_EQ(j, l2.nodes_along_path(p).size()); EXPECT_EQ(j, l3.nodes_along_path(p).size()); EXPECT_EQ(j, l2.nodes_along_path(p)[0]->id); EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); // multiple intervals d = {Interval(0, 1), Interval(4, 5)}; p.initialize(d); j = 1; EXPECT_EQ(j, l1.nodes_along_path(p).size()); j = 2; EXPECT_EQ(j, l2.nodes_along_path(p).size()); EXPECT_EQ(j, l3.nodes_along_path(p).size()); j = 0; EXPECT_EQ(j, l1.nodes_along_path(p)[0]->id); EXPECT_EQ(j, l2.nodes_along_path(p)[0]->id); EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 1; EXPECT_EQ(j, l2.nodes_along_path(p)[1]->id); EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); // including empty interval d = {Interval(12, 13), Interval(16, 16), Interval(23, 24)}; p.initialize(d); j = 3; vector<LocalNodePtr> w = l3.nodes_along_path(p); EXPECT_EQ(j, w.size()); EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 4; EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); j = 6; EXPECT_EQ(j, l3.nodes_along_path(p)[2]->id); // a path with an empty node at end d = {Interval(12, 13), Interval(16, 16), Interval(23, 23)}; p.initialize(d); j = 3; w = l3.nodes_along_path(p); EXPECT_EQ(j, w.size()); EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 4; EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); j = 6; EXPECT_EQ(j, l3.nodes_along_path(p)[2]->id); // and a path which ends on a null node d = {Interval(12, 13), Interval(16, 16)}; p.initialize(d); j = 2; w = l3.nodes_along_path(p); EXPECT_EQ(j, w.size()); j = 3; EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 4; EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); // and a path that can't really exist still works d = {Interval(12, 13), Interval(19, 20)}; p.initialize(d); j = 2; EXPECT_EQ(j, l3.nodes_along_path(p).size()); j = 3; EXPECT_EQ(j, l3.nodes_along_path(p)[0]->id); j = 5; EXPECT_EQ(j, l3.nodes_along_path(p)[1]->id); } TEST(LocalPRGTest, split_by_siteNoSites) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); vector<Interval> v0, v1; v0.push_back(Interval(0, 0)); EXPECT_ITERABLE_EQ(vector<Interval>, v0, l0.split_by_site(Interval(0, 0)));// << "Failed to split empty string with input Interval"; v1.push_back(Interval(0, 4)); EXPECT_ITERABLE_EQ(vector<Interval>, v1, l1.split_by_site(Interval(0, 4)));// << "Failed to split string with input Interval"; v1.clear(); v1.push_back(Interval(0, 2)); EXPECT_ITERABLE_EQ(vector<Interval>, v1, l1.split_by_site(Interval(0, 2)));// << "Failed to split string with short input Interval"; v1.clear(); v1.push_back(Interval(1, 3)); EXPECT_ITERABLE_EQ(vector<Interval>, v1, l1.split_by_site(Interval(1, 3)));// << "Failed to split string with middle input Interval"; } TEST(LocalPRGTest, split_by_siteSite) { LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); vector<Interval> v2; v2.push_back(Interval(0, 1)); l2.next_site = 5; EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 3)));// << "Failed to split string in Interval" << Interval(0,3); //EXPECT_ITERABLE_EQ( vector< Interval >,v2, l2.split_by_site(Interval(0,4)));// << "Failed to split string in Interval" << Interval(0,4); v2.push_back(Interval(4, 6)); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 6)));// << "Failed to split string in Interval" << Interval(0,6); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 7)));// << "Failed to split string in Interval" << Interval(0,7); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 8)));// << "Failed to split string in Interval" << Interval(0,8); v2.push_back(Interval(9, 10)); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 10)));// << "Failed to split string in Interval" << Interval(0,10); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 11)));// << "Failed to split string in Interval" << Interval(0,11); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 12)));// << "Failed to split string in Interval" << Interval(0,12); v2.push_back(Interval(13, 14)); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site(Interval(0, 14)));// << "Failed to split string in Interval" << Interval(0,14); v2.clear(); v2.push_back(Interval(5, 6)); EXPECT_ITERABLE_EQ(vector<Interval>, v2, l2.split_by_site( Interval(5, 8)));// << "Failed to split string in mid Interval" << Interval(5,8); } TEST(LocalPRGTest, split_by_siteNestedSite) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "nested varsite start immediately", " 5 G 7 C 8 T 7 6 G 5 "); vector<Interval> v3; v3.push_back(Interval(0, 1)); l3.next_site = 5; EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 3)));// << "Failed to split string in Interval" << Interval(0,3); //EXPECT_ITERABLE_EQ( vector< Interval >,v3, l3.split_by_site(Interval(0,4)));// << "Failed to split string in Interval" << Interval(0,4); v3.push_back(Interval(4, 16)); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 16)));// << "Failed to split string in Interval" << Interval(0,6); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 17)));// << "Failed to split string in Interval" << Interval(0,7); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 18)));// << "Failed to split string in Interval" << Interval(0,8); v3.push_back(Interval(19, 20)); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 20)));// << "Failed to split string in Interval" << Interval(0,10); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 21)));// << "Failed to split string in Interval" << Interval(0,11); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 22)));// << "Failed to split string in Interval" << Interval(0,12); v3.push_back(Interval(23, 24)); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site(Interval(0, 24)));// << "Failed to split string in Interval" << Interval(0,14); l3.next_site = 7; v3.clear(); v3.push_back(Interval(4, 5)); v3.push_back(Interval(8, 9)); v3.push_back(Interval(12, 13)); v3.push_back(Interval(16, 16)); EXPECT_ITERABLE_EQ(vector<Interval>, v3, l3.split_by_site( Interval(4, 16)));// << "Failed to split string in mid Interval" << Interval(5,8); vector<Interval> v4; v4.push_back(Interval(0, 0)); l4.next_site = 5; EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 1)));// << "Failed to split string in Interval" << Interval(0,1); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 2)));// << "Failed to split string in Interval" << Interval(0,2); v4.push_back(Interval(3, 15)); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 15)));// << "Failed to split string in Interval" << Interval(0,6); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 16)));// << "Failed to split string in Interval" << Interval(0,7); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 17)));// << "Failed to split string in Interval" << Interval(0,8); v4.push_back(Interval(18, 19)); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 19)));// << "Failed to split string in Interval" << Interval(0,10); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site(Interval(0, 20)));// << "Failed to split string in Interval" << Interval(0,11); l4.next_site = 7; v4.clear(); v4.push_back(Interval(0, 4)); v4.push_back(Interval(7, 8)); v4.push_back(Interval(11, 12)); v4.push_back(Interval(15, 22)); EXPECT_ITERABLE_EQ(vector<Interval>, v4, l4.split_by_site( Interval(0, 22)));// << "Failed to split string in mid Interval" << Interval(5,8); } TEST(LocalPRGTest, build_graph) { LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalGraph lg0; lg0.add_node(0, "", Interval(0, 0)); EXPECT_EQ(lg0, l0.prg); LocalGraph lg1; lg1.add_node(0, "AGCT", Interval(0, 4)); EXPECT_EQ(lg1, l1.prg); LocalGraph lg2; lg2.add_node(0, "A", Interval(0, 1)); lg2.add_node(1, "GC", Interval(4, 6)); lg2.add_node(2, "G", Interval(9, 10)); lg2.add_node(3, "T", Interval(13, 14)); lg2.add_edge(0, 1); lg2.add_edge(0, 2); lg2.add_edge(1, 3); lg2.add_edge(2, 3); EXPECT_EQ(lg2, l2.prg); LocalGraph lg3; lg3.add_node(0, "A", Interval(0, 1)); lg3.add_node(1, "G", Interval(4, 5)); lg3.add_node(2, "C", Interval(8, 9)); lg3.add_node(3, "T", Interval(12, 13)); lg3.add_node(4, "", Interval(16, 16)); lg3.add_node(5, "G", Interval(19, 20)); lg3.add_node(6, "T", Interval(23, 24)); lg3.add_edge(0, 1); lg3.add_edge(0, 5); lg3.add_edge(1, 2); lg3.add_edge(1, 3); lg3.add_edge(2, 4); lg3.add_edge(3, 4); lg3.add_edge(4, 6); lg3.add_edge(5, 6); EXPECT_EQ(lg3, l3.prg); } TEST(LocalPRGTest, shift) { LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "AT 5 G 7 C 8 T 7 6 G 5 T"); //LocalPRG l4(4, "much more complex", "TCATTC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AGCTG"); LocalPRG l5(5, "one with lots of null at start and end, and a long stretch in between", " 5 7 9 11 AGTTCTGAAACATTGCGCGTGAGATCTCTG 12 T 11 10 A 9 8 C 7 6 G 5 "); LocalPRG l6(6, "one representing a possible deletion at end", "GATCTCTAG 5 TTATG 6 5 "); deque<Interval> d = {Interval(0, 3)}; Path p, q; p.initialize(d); d = {Interval(1, 4)}; q.initialize(d); vector<Path> v_exp = {q}; EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l1.shift(p)); v_exp.clear(); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l1.shift(q)); // there are no shifts over end of prg d = {Interval(0, 1), Interval(4, 6)}; p.initialize(d); d = {Interval(4, 6), Interval(13, 14)}; q.initialize(d); v_exp = {q}; EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l2.shift(p)); v_exp.clear(); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l2.shift(q)); v_exp.clear(); d = {Interval(0, 2)}; p.initialize(d); d = {Interval(1, 2), Interval(5, 6)}; q.initialize(d); v_exp.push_back(q); d = {Interval(1, 2), Interval(20, 21)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l3.shift(p)); v_exp.clear(); d = {Interval(1, 2), Interval(5, 6)}; p.initialize(d); d = {Interval(5, 6), Interval(9, 10)}; q.initialize(d); v_exp.push_back(q); d = {Interval(5, 6), Interval(13, 14)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l3.shift(p)); v_exp.clear(); d = {Interval(0, 0), Interval(3, 3), Interval(6, 6), Interval(9, 9), Interval(13, 18)}; p.initialize(d); d = {Interval(14, 19)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l5.shift(p)); v_exp.clear(); d = {Interval(3, 8)}; p.initialize(d); d = {Interval(4, 9), Interval(20, 20), Interval(23, 23)}; q.initialize(d); v_exp.push_back(q); d = {Interval(4, 9)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l6.shift(p)); v_exp.clear(); d = {Interval(4, 9)}; p.initialize(d); d = {Interval(5, 9), Interval(12, 13)}; q.initialize(d); v_exp.push_back(q); EXPECT_ITERABLE_EQ(vector<Path>, v_exp, l6.shift(p)); } TEST(LocalPRGTest, minimizer_sketch) { // note this is a bad test LocalPRG l0(0, "empty", ""); LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "much more complex", "TCATTC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AGCTG"); LocalPRG l5(5, "one with lots of null at start and end, and a long stretch in between", " 5 7 9 11 AGTTCTGAAACATTGCGCGTGAGATCTCTG 12 T 11 10 A 9 8 C 7 6 G 5 "); Index *idx; idx = new Index(); KmerHash hash; l0.minimizer_sketch(idx, 1, 3); uint32_t j = 0; EXPECT_EQ(j, idx->minhash.size()); l1.minimizer_sketch(idx, 2, 3); j = 1; EXPECT_EQ(j, idx->minhash.size()); l1.minimizer_sketch(idx, 1, 3); EXPECT_EQ(j, idx->minhash.size()); j = 2; pair<uint64_t, uint64_t> kh = hash.kmerhash("AGC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l2.minimizer_sketch(idx, 2, 3); j = 1; EXPECT_EQ(j, idx->minhash.size()); l2.minimizer_sketch(idx, 1, 3); j = 2; EXPECT_EQ(j, idx->minhash.size()); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 1; kh = hash.kmerhash("AGT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l3.minimizer_sketch(idx, 2, 3); j = 2; EXPECT_EQ(j, idx->minhash.size()); l3.minimizer_sketch(idx, 1, 3); j = 3; EXPECT_EQ(j, idx->minhash.size()); j = 2; kh = hash.kmerhash("AGC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); //AGC kh = hash.kmerhash("AGT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); //AGTx2 j = 1; kh = hash.kmerhash("GTT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l4.minimizer_sketch(idx, 1, 3); j = 16; EXPECT_EQ(j, idx->minhash.size()); j = 5; kh = hash.kmerhash("TCA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 4; kh = hash.kmerhash("CTA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 3; kh = hash.kmerhash("ACT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CAA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("AAG", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("TCT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("AGC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 2; kh = hash.kmerhash("TTC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CAC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CTC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 1; kh = hash.kmerhash("CAT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("ATT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("GTC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("GTT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("TGT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CTG", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l4.minimizer_sketch(idx, 3, 3); j = 10; EXPECT_EQ(j, idx->minhash.size()); j = 4; kh = hash.kmerhash("CTA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 3; kh = hash.kmerhash("CTT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 2; kh = hash.kmerhash("CAC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); j = 1; kh = hash.kmerhash("ATT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("ACT", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("TCA", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("AAC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("GTC", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("GAG", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); kh = hash.kmerhash("CTG", 3); EXPECT_EQ(j, idx->minhash[min(kh.first, kh.second)]->size()); idx->clear(); l5.minimizer_sketch(idx, 4, 5); EXPECT_EQ((idx->minhash.size() > 2), true); idx->clear(); delete idx; } struct MiniPos { bool operator()(Minimizer lhs, Minimizer rhs) { return (lhs.pos.start) < (rhs.pos.start); } }; TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw1) { string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT"; Index *idx; idx = new Index(); LocalPRG l(0, "prg", st); l.minimizer_sketch(idx, 1, 15); Seq s = Seq(0, "read", st, 1, 15); //cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl; EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2); set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end()); l.kmer_prg.sort_topologically(); vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin(); lit++; for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) { EXPECT_EQ((*sit).pos, (*lit)->path.path[0]); ++lit; } } TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw5) { string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT"; Index *idx; idx = new Index(); LocalPRG l(0, "prg", st); l.minimizer_sketch(idx, 5, 15); Seq s = Seq(0, "read", st, 5, 15); //cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl; EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2); set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end()); l.kmer_prg.sort_topologically(); vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin(); lit++; for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) { EXPECT_EQ((*sit).pos, (*lit)->path.path[0]); ++lit; } } TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw10) { string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT"; Index *idx; idx = new Index(); LocalPRG l(0, "prg", st); l.minimizer_sketch(idx, 10, 15); Seq s = Seq(0, "read", st, 10, 15); //cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl; EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2); set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end()); l.kmer_prg.sort_topologically(); vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin(); lit++; for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) { EXPECT_EQ((*sit).pos, (*lit)->path.path[0]); ++lit; } } TEST(LocalPRGTest, minimizer_sketch_SameAsSeqw15) { string st = "ATGGCAATCCGAATCTTCGCGATACTTTTCTCCATTTTTTCTCTTGCCACTTTCGCGCATGCGCAAGAAGGCACGCTAGAACGTTCTGACTGGAGGAAGTTTTTCAGCGAATTTCAAGCCAAAGGCACGATAGTTGTGGCAGACGAACGCCAAGCGGATCGTGCCATGTTGGTTTTTGATCCTGTGCGATCGAAGAAACGCTACTCGCCTGCATCGACATTCAAGATACCTCATACACTTTTTGCACTTGATGCAGGCGCTGTTCGTGATGAGTTCCAGATTTTTCGATGGGACGGCGTTAACAGGGGCTTTGCAGGCCACAATCAAGACCAAGATTTGCGATCAGCAATGCGGAATTCTACTGTTTGGGTGTATGAGCTATTTGCAAAGGAAATTGGTGATGACAAAGCTCGGCGCTATTTGAAGAAAATCGACTATGGCAACGCCGATCCTTCGACAAGTAATGGCGATTACTGTATAGAAGGCAGCCTTGCAATCTCGGCGCAGGAGCAAATTGCATTTCTCAGGAAGCTCTATCGTAACGAGCTGCCCTTTCGGGTAGAACATCAGCGCTTGGTCAAGGATCTCATGATTGTGGAAGCCGGTCGCAACTGGATACTGCGTGCAAAGACGGGCTGGGAAGGCCGTATGGGTTGGTGGGTAGGATGGGTTGAGTGGCCGACTGGCTCCGTATTCTTCGCACTGAATATTGATACGCCAAACAGAATGGATGATCTTTTCAAGAGGGAGGCAATCGTGCGGGCAATCCTT"; Index *idx; idx = new Index(); LocalPRG l(0, "prg", st); l.minimizer_sketch(idx, 15, 15); Seq s = Seq(0, "read", st, 15, 15); //cout << l.kmer_prg.nodes.size() << " " << s.sketch.size() << endl; EXPECT_EQ(l.kmer_prg.nodes.size(), s.sketch.size() + 2); set<Minimizer, MiniPos> sketch(s.sketch.begin(), s.sketch.end()); l.kmer_prg.sort_topologically(); vector<KmerNodePtr>::iterator lit = l.kmer_prg.sorted_nodes.begin(); lit++; for (auto sit = sketch.begin(); sit != sketch.end(); ++sit) { EXPECT_EQ((*sit).pos, (*lit)->path.path[0]); ++lit; } } TEST(LocalPRGTest, localnode_path_from_kmernode_path) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG"); Index *idx; idx = new Index(); KmerHash hash; l3.minimizer_sketch(idx, 2, 3); //vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[1], l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp); vector<LocalNodePtr> lmp_exp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6]}; EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp); lmp = l3.localnode_path_from_kmernode_path(kmp, 2); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp); idx->clear(); l4.minimizer_sketch(idx, 3, 3); //kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7], l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[11], l4.kmer_prg.nodes[13]}; kmp = {l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7]}; lmp = l4.localnode_path_from_kmernode_path(kmp, 2); lmp_exp = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6]}; EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp); lmp = l4.localnode_path_from_kmernode_path(kmp, 3); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, lmp_exp, lmp); delete idx; } TEST(LocalPRGTest, kmernode_path_from_localnode_path) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG"); LocalPRG l5(5, "nested varsite", "A 5 G 7 C 8 T 7 T 9 CCG 10 CGG 9 6 G 5 TAT"); Index *idx; idx = new Index(); KmerHash hash; l3.minimizer_sketch(idx, 2, 3); l3.kmer_prg.sort_topologically(); vector<LocalNodePtr> lmp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6]}; vector<KmerNodePtr> kmp = l3.kmernode_path_from_localnode_path(lmp); sort(kmp.begin(), kmp.end()); vector<KmerNodePtr> kmp_exp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[1], l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; sort(kmp_exp.begin(), kmp_exp.end()); EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp); idx->clear(); l4.minimizer_sketch(idx, 3, 3); l4.kmer_prg.sort_topologically(); lmp = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6]}; kmp = l4.kmernode_path_from_localnode_path(lmp); sort(kmp.begin(), kmp.end()); kmp_exp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[7], l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[11], l4.kmer_prg.nodes[13]}; sort(kmp_exp.begin(), kmp_exp.end()); EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp); // case where we don't have start and end point in localpath, so need to consider whether kmer overlaps idx->clear(); l5.minimizer_sketch(idx, 2, 3); l5.kmer_prg.sort_topologically(); lmp = {l5.prg.nodes[1], l5.prg.nodes[2], l5.prg.nodes[4], l5.prg.nodes[6], l5.prg.nodes[7]}; kmp = l5.kmernode_path_from_localnode_path(lmp); sort(kmp.begin(), kmp.end()); cout << l5.kmer_prg << endl; kmp_exp = {l5.kmer_prg.nodes[1], l5.kmer_prg.nodes[2], l5.kmer_prg.nodes[6], l5.kmer_prg.nodes[8], l5.kmer_prg.nodes[10], l5.kmer_prg.nodes[12], l5.kmer_prg.nodes[13]}; sort(kmp_exp.begin(), kmp_exp.end()); EXPECT_ITERABLE_EQ(vector<KmerNodePtr>, kmp_exp, kmp); delete idx; } TEST(LocalPRGTest, get_covgs_along_localnode_path) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); LocalPRG l4(4, "much more complex", "TC 5 ACTC 7 TAGTCA 8 TTGTGA 7 6 AACTAG 5 AG"); Index *idx; idx = new Index(); KmerHash hash; l3.minimizer_sketch(idx, 2, 3); vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp, 2); shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "3")); pn3->kmer_prg = l3.kmer_prg; for (const auto &n : pn3->kmer_prg.nodes) { n->covg[0] += 1; } vector<uint> covgs = get_covgs_along_localnode_path(pn3, lmp, kmp); vector<uint> covgs_exp = {0, 1, 1, 1}; EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs); idx->clear(); l4.minimizer_sketch(idx, 1, 3); kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[1], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[5], l4.kmer_prg.nodes[7], l4.kmer_prg.nodes[9], l4.kmer_prg.nodes[12], l4.kmer_prg.nodes[15], l4.kmer_prg.nodes[18], l4.kmer_prg.nodes[21], l4.kmer_prg.nodes[23], l4.kmer_prg.nodes[25], l4.kmer_prg.nodes[27], l4.kmer_prg.nodes[29]}; lmp = l4.localnode_path_from_kmernode_path(kmp, 1); shared_ptr<pangenome::Node> pn4(make_shared<pangenome::Node>(4, 4, "4")); pn4->kmer_prg = l4.kmer_prg; for (const auto &n : pn4->kmer_prg.nodes) { n->covg[0] += 1; } covgs = get_covgs_along_localnode_path(pn4, lmp, kmp); //covgs_exp = {1,2,3,3,3,3,3,3,3,3,3,3,2,1}; covgs_exp = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs); kmp = {l4.kmer_prg.nodes[0], l4.kmer_prg.nodes[3], l4.kmer_prg.nodes[5], l4.kmer_prg.nodes[12], l4.kmer_prg.nodes[15], l4.kmer_prg.nodes[18], l4.kmer_prg.nodes[25]}; lmp = l4.localnode_path_from_kmernode_path(kmp, 2); covgs = get_covgs_along_localnode_path(pn4, lmp, kmp); //covgs_exp = {0,1,2,2,1,1,2,3,2,1,1,1,1,0}; covgs_exp = {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}; EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs); delete idx; } TEST(LocalPRGTest, write_covgs_to_file) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 T"); Index *idx; idx = new Index(); KmerHash hash; l3.minimizer_sketch(idx, 2, 3); vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[4]}; vector<LocalNodePtr> lmp = l3.localnode_path_from_kmernode_path(kmp, 2); shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "3")); pn3->kmer_prg = l3.kmer_prg; for (const auto &n : pn3->kmer_prg.nodes) { n->covg[0] += 1; } vector<uint> covgs = get_covgs_along_localnode_path(pn3, lmp, kmp); vector<uint> covgs_exp = {0, 1, 1, 1}; EXPECT_ITERABLE_EQ(vector<uint>, covgs_exp, covgs); l3.write_covgs_to_file("localPRG_test.covgs", covgs); delete idx; } TEST(LocalPRGTest, write_path_to_fasta) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); Index *idx; idx = new Index(); l3.minimizer_sketch(idx, 1, 3); vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.write_path_to_fasta("localPRG_test.maxpath.fa", lmp3, 0.00); delete idx; } TEST(LocalPRGTest, append_path_to_fasta) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); Index *idx; idx = new Index(); l3.minimizer_sketch(idx, 1, 3); vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.append_path_to_fasta("localPRG_test.maxpath.fa", lmp3, 0.00); delete idx; } TEST(LocalPRGTest, write_aligned_path_to_fasta) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); Index *idx; idx = new Index(); l3.minimizer_sketch(idx, 1, 3); vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.write_aligned_path_to_fasta("localPRG_test.alignedpath.fa", lmp3, 0.00); delete idx; } TEST(LocalPRGTest, build_vcf) { LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); LocalPRG l4(4, "small real PRG", "ATGACAAAACGAAGTGGAAGTAATACGCGCAGGCGGGCTATCAGTCGCCCTGTTCGTCTGACGGCAGAAGAAGACCAGG" "AAATCAGAAAAAGGGCTGCTGAATGCGGCAAGACCGTTTC 5 T 6 C 5 GGTTTTTTACGGGCGGCAGCTCTCGGTAAGAAAGTTAA 7 TTCACTGACTGA" "TGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG 8 CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA 7 CAGAAA" "AAACTCTTTATCGACGGCAAGCGTGTCGGGGACAG 9 A 10 G 9 GAGTATGCGGAGGTGCTGAT 11 A 12 C 11 GCTATTACGGAGTATCACCG 13" " G 14 T 13 GCCCTGTTATCCAGGCTTATGGCAGATTAG"); LocalPRG l5(5, "another real PRG", "ATGACAAAGGTTACACCGT 5 C 6 T 5 TGACGTGCTACGCCTGTCAGGCCTATTCGACTCCTGCAAT 7 G 8 A 7 TATTGAATTTGCATAGTTTT 9 G 10 A 9 TAGGTCGA 11 G 12 A 11 TAAGGCGTTCACGCCGCATCCGGCGTGAACAAA 13 G 14 T 13 TACTCTTTTT 15 17 19 C 20 T 19 GCACAATCCAA 18 CGCACAAACCAA 17 16 21 CGCACAATCCAA 22 23 CGT 24 CGC 23 ACAAACCA 25 A 26 T 25 21 TATGTGCAAATTATTACTTTTTCCAGAAATCATCGAAAACGG 15 "); VCF vcf; l1.build_vcf(vcf, l1.prg.top_path()); uint j = 0; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ(j, vcf.samples.size()); vcf.clear(); l2.build_vcf(vcf, l2.prg.top_path()); j = 1; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("GC", vcf.records[0].ref); EXPECT_EQ("G", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info); vcf.clear(); vector<LocalNodePtr> lmp = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]}; l2.build_vcf(vcf, lmp); j = 1; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("G", vcf.records[0].ref); EXPECT_EQ("GC", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info); vcf.clear(); l3.build_vcf(vcf, l3.prg.top_path()); vcf.sort_records(); j = 2; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("nested varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("GC", vcf.records[0].ref); EXPECT_EQ("G", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=NESTED", vcf.records[0].info); EXPECT_EQ((uint) 2, vcf.records[1].pos); EXPECT_EQ("C", vcf.records[1].ref); EXPECT_EQ("T", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=NESTED", vcf.records[1].info); vcf.clear(); lmp = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.build_vcf(vcf, lmp); vcf.sort_records(); EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("nested varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("GT", vcf.records[0].ref); EXPECT_EQ("G", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=NESTED", vcf.records[0].info); EXPECT_EQ((uint) 2, vcf.records[1].pos); EXPECT_EQ("T", vcf.records[1].ref); EXPECT_EQ("C", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=NESTED", vcf.records[1].info); vcf.clear(); lmp = {l3.prg.nodes[0], l3.prg.nodes[5], l3.prg.nodes[6]}; l3.build_vcf(vcf, lmp); vcf.sort_records(); EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("nested varsite", vcf.records[0].chrom); EXPECT_EQ((uint) 1, vcf.records[0].pos); EXPECT_EQ("G", vcf.records[0].ref); EXPECT_EQ("GC", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[0].info); EXPECT_EQ((uint) 1, vcf.records[1].pos); EXPECT_EQ("G", vcf.records[1].ref); EXPECT_EQ("GT", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=INDEL;GRAPHTYPE=SIMPLE", vcf.records[1].info); vcf.clear(); l4.build_vcf(vcf, l4.prg.top_path()); vcf.sort_records(); j = 5; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("small real PRG", vcf.records[0].chrom); EXPECT_EQ((uint) 119, vcf.records[0].pos); EXPECT_EQ("T", vcf.records[0].ref); EXPECT_EQ("C", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[0].info); EXPECT_EQ((uint) 158, vcf.records[1].pos); EXPECT_EQ("TTCACTGACTGATGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG", vcf.records[1].ref); EXPECT_EQ("CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=PH_SNPs;GRAPHTYPE=SIMPLE", vcf.records[1].info); EXPECT_EQ((uint) 251, vcf.records[2].pos); EXPECT_EQ("A", vcf.records[2].ref); EXPECT_EQ("G", vcf.records[2].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[2].info); EXPECT_EQ((uint) 272, vcf.records[3].pos); EXPECT_EQ("A", vcf.records[3].ref); EXPECT_EQ("C", vcf.records[3].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[3].info); EXPECT_EQ((uint) 293, vcf.records[4].pos); EXPECT_EQ("G", vcf.records[4].ref); EXPECT_EQ("T", vcf.records[4].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[4].info); vcf.clear(); lmp = {l4.prg.nodes[0], l4.prg.nodes[2], l4.prg.nodes[3], l4.prg.nodes[4], l4.prg.nodes[6], l4.prg.nodes[8], l4.prg.nodes[9], l4.prg.nodes[10], l4.prg.nodes[12], l4.prg.nodes[14], l4.prg.nodes[15]}; l4.build_vcf(vcf, lmp); vcf.sort_records(); j = 5; EXPECT_EQ(j, vcf.records.size()); EXPECT_EQ("small real PRG", vcf.records[0].chrom); EXPECT_EQ((uint) 119, vcf.records[0].pos); EXPECT_EQ("C", vcf.records[0].ref); EXPECT_EQ("T", vcf.records[0].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[0].info); EXPECT_EQ((uint) 158, vcf.records[1].pos); EXPECT_EQ("TTCACTGACTGATGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG", vcf.records[1].ref); EXPECT_EQ("CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA", vcf.records[1].alt[0]); EXPECT_EQ("SVTYPE=PH_SNPs;GRAPHTYPE=SIMPLE", vcf.records[1].info); EXPECT_EQ((uint) 251, vcf.records[2].pos); EXPECT_EQ("G", vcf.records[2].ref); EXPECT_EQ("A", vcf.records[2].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[2].info); EXPECT_EQ((uint) 272, vcf.records[3].pos); EXPECT_EQ("A", vcf.records[3].ref); EXPECT_EQ("C", vcf.records[3].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[3].info); EXPECT_EQ((uint) 293, vcf.records[4].pos); EXPECT_EQ("T", vcf.records[4].ref); EXPECT_EQ("G", vcf.records[4].alt[0]); EXPECT_EQ("SVTYPE=SNP;GRAPHTYPE=SIMPLE", vcf.records[4].info); vcf.clear(); l5.build_vcf(vcf, l5.prg.top_path()); vcf.sort_records(); } TEST(LocalPRGTest, add_sample_gt_to_vcf) { LocalPRG l1(1, "simple", "AGCT"); LocalPRG l2(2, "varsite", "A 5 GC 6 G 5 T"); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); LocalPRG l4(4, "small real PRG", "ATGACAAAACGAAGTGGAAGTAATACGCGCAGGCGGGCTATCAGTCGCCCTGTTCGTCTGACGGCAGAAGAAGACCAGG" "AAATCAGAAAAAGGGCTGCTGAATGCGGCAAGACCGTTTC 5 T 6 C 5 GGTTTTTTACGGGCGGCAGCTCTCGGTAAGAAAGTTAA 7 TTCACTGACTGA" "TGACCGAGTGCTGAAAGAAGTCATGCGACTGGGGGCGTTG 8 CTCACTGACTGATGATCGGGTACTGAAAGAAGTTATGAGACTGGGGGCGTTA 7 CAGAAA" "AAACTCTTTATCGACGGCAAGCGTGTCGGGGACAG 9 A 10 G 9 GAGTATGCGGAGGTGCTGAT 11 A 12 C 11 GCTATTACGGAGTATCACCG 13" " G 14 T 13 GCCCTGTTATCCAGGCTTATGGCAGATTAG"); LocalPRG l5(5, "another real PRG", " 5 ATGCTTATTGGCTATGT 7 9 ACGCGTA 10 TCGCGTA 10 ACGTGTG 9 TCAACAAATGACCAGAACA" "C 11 A 12 C 11 8 ACGCGTATCAACAAATGATCAGAACACA 7 GATCTACAACGTAATGCG 6 AAGT 5 "); VCF vcf; vector<LocalNodePtr> lmp1 = {l1.prg.nodes[0]}; l1.build_vcf(vcf, l1.prg.top_path()); l1.add_sample_gt_to_vcf(vcf, l1.prg.top_path(), lmp1, "sample"); uint j = 1; EXPECT_EQ(j, vcf.samples.size()); vcf.clear(); vector<LocalNodePtr> lmp2 = {l2.prg.nodes[0], l2.prg.nodes[2], l2.prg.nodes[3]}; l2.build_vcf(vcf, l2.prg.top_path()); l2.add_sample_gt_to_vcf(vcf, l2.prg.top_path(), lmp2, "sample"); j = 1; EXPECT_EQ(j, vcf.samples.size()); EXPECT_EQ(j, vcf.records[0].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[0].samples[0]["GT"][0]); vcf.clear(); vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.build_vcf(vcf, l3.prg.top_path()); vcf.sort_records(); l3.add_sample_gt_to_vcf(vcf, l3.prg.top_path(), lmp3, "sample"); EXPECT_EQ(j, vcf.samples.size()); EXPECT_EQ(j, vcf.records[0].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); vcf.clear(); vector<LocalNodePtr> lmp4 = {l4.prg.nodes[0], l4.prg.nodes[1], l4.prg.nodes[3], l4.prg.nodes[5], l4.prg.nodes[6], l4.prg.nodes[8], l4.prg.nodes[9], l4.prg.nodes[10], l4.prg.nodes[12], l4.prg.nodes[13], l4.prg.nodes[15]}; l4.build_vcf(vcf, l4.prg.top_path()); vcf.sort_records(); l4.add_sample_gt_to_vcf(vcf, l4.prg.top_path(), lmp4, "sample"); EXPECT_EQ(j, vcf.samples.size()); EXPECT_EQ(j, vcf.records[0].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[0].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[1].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[2].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[2].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[3].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[3].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[4].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[4].samples[0]["GT"][0]); vcf.clear(); vector<LocalNodePtr> lmp5 = {l5.prg.nodes[0], l5.prg.nodes[1], l5.prg.nodes[10], l5.prg.nodes[11], l5.prg.nodes[13]}; l5.build_vcf(vcf, l5.prg.top_path()); vcf.sort_records(); l5.add_sample_gt_to_vcf(vcf, l5.prg.top_path(), lmp5, "sample"); EXPECT_EQ(j, vcf.samples.size()); EXPECT_EQ((uint) 5, vcf.records.size()); EXPECT_EQ(j, vcf.records[0].samples.size()); EXPECT_TRUE(vcf.records[0].samples[0].find("GT") == vcf.records[0].samples[0].end()); EXPECT_EQ(j, vcf.records[1].samples.size()); EXPECT_TRUE(vcf.records[1].samples[0].find("GT") == vcf.records[1].samples[0].end()); EXPECT_EQ(j, vcf.records[2].samples.size()); EXPECT_TRUE(vcf.records[2].samples[0].find("GT") == vcf.records[2].samples[0].end()); EXPECT_EQ(j, vcf.records[3].samples.size()); EXPECT_EQ((uint8_t) 1, vcf.records[3].samples[0]["GT"][0]); EXPECT_EQ(j, vcf.records[4].samples.size()); EXPECT_TRUE(vcf.records[4].samples[0].find("GT") == vcf.records[4].samples[0].end()); // add the ref path l5.add_sample_gt_to_vcf(vcf, l5.prg.top_path(), l5.prg.top_path(), "sample2"); EXPECT_EQ((uint) 2, vcf.samples.size()); EXPECT_EQ((uint) 5, vcf.records.size()); EXPECT_EQ((uint) 2, vcf.records[0].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[0].samples[1]["GT"][0]); EXPECT_EQ((uint) 2, vcf.records[1].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[1]["GT"][0]); EXPECT_EQ((uint) 2, vcf.records[2].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[2].samples[1]["GT"][0]); EXPECT_EQ((uint) 2, vcf.records[3].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[3].samples[1]["GT"][0]); EXPECT_EQ((uint) 2, vcf.records[4].samples.size()); EXPECT_EQ((uint8_t) 0, vcf.records[4].samples[1]["GT"][0]); } TEST(LocalPRGTest, moreupdateVCF) { // load PRGs from file std::vector<std::shared_ptr<LocalPRG>> prgs; read_prg_file(prgs, "../../test/test_cases/updatevcf_test.fa"); EXPECT_EQ((uint) 3, prgs.size()); VCF vcf; prgs[0]->build_vcf(vcf, prgs[0]->prg.top_path()); prgs[1]->build_vcf(vcf, prgs[1]->prg.top_path()); prgs[2]->build_vcf(vcf, prgs[2]->prg.top_path()); vcf.sort_records(); //for (uint i=0; i!=prgs[2]->vcf.records.size(); ++i) //{ //cout << prgs[2]->vcf.records[i]; //} vector<LocalNodePtr> lmp1 = {prgs[1]->prg.nodes[0], prgs[1]->prg.nodes[11], prgs[1]->prg.nodes[12], prgs[1]->prg.nodes[17], prgs[1]->prg.nodes[65], prgs[1]->prg.nodes[67]}; //cout << "PRG 1 has " << prgs[1]->prg.nodes.size() << " nodes" << endl; prgs[1]->add_sample_gt_to_vcf(vcf, prgs[1]->prg.top_path(), lmp1, "sample"); vector<LocalNodePtr> lmp2 = {prgs[2]->prg.nodes[0], prgs[2]->prg.nodes[1], prgs[2]->prg.nodes[3], prgs[2]->prg.nodes[4], prgs[2]->prg.nodes[6], prgs[2]->prg.nodes[7], prgs[2]->prg.nodes[9], prgs[2]->prg.nodes[10], prgs[2]->prg.nodes[11], prgs[2]->prg.nodes[13], prgs[2]->prg.nodes[14], prgs[2]->prg.nodes[16], prgs[2]->prg.nodes[17], prgs[2]->prg.nodes[19], prgs[2]->prg.nodes[44], prgs[2]->prg.nodes[45], prgs[2]->prg.nodes[47], prgs[2]->prg.nodes[118], prgs[2]->prg.nodes[119], prgs[2]->prg.nodes[121], prgs[2]->prg.nodes[123], prgs[2]->prg.nodes[125], prgs[2]->prg.nodes[126], prgs[2]->prg.nodes[130], prgs[2]->prg.nodes[131], prgs[2]->prg.nodes[133], prgs[2]->prg.nodes[135], prgs[2]->prg.nodes[141], prgs[2]->prg.nodes[142], prgs[2]->prg.nodes[144], prgs[2]->prg.nodes[145], prgs[2]->prg.nodes[160]}; //cout << "PRG 2 has " << prgs[2]->prg.nodes.size() << " nodes" << endl; prgs[2]->add_sample_gt_to_vcf(vcf, prgs[2]->prg.top_path(), lmp2, "sample"); } TEST(LocalPRGTest, find_alt_path) { LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT 9 T 10 9 ATG"); vector<LocalNodePtr> top = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6]}; vector<LocalNodePtr> middle = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; vector<LocalNodePtr> bottom = {l3.prg.nodes[0], l3.prg.nodes[5], l3.prg.nodes[6]}; vector<LocalNodePtr> alt_path = l3.find_alt_path(top, 2, "C", "T"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, middle, alt_path); alt_path = l3.find_alt_path(top, 1, "GC", "G"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3.find_alt_path(middle, 2, "T", "C"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); alt_path = l3.find_alt_path(top, 1, "GT", "G"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3.find_alt_path(bottom, 1, "G", "GT"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, middle, alt_path); alt_path = l3.find_alt_path(bottom, 1, "G", "GC"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); // and now for the one where the alt or ref is "." top = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6], l3.prg.nodes[7], l3.prg.nodes[9]}; bottom = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[2], l3.prg.nodes[4], l3.prg.nodes[6], l3.prg.nodes[8], l3.prg.nodes[9]}; alt_path = l3.find_alt_path(top, 6, "T", "."); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3.find_alt_path(bottom, 6, ".", "T"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); // if the site is at the start and alt is "." LocalPRG l3_(3, "nested varsite", " 5 G 7 C 8 T 7 6 5 TAT 9 T 10 9 "); top = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4], l3_.prg.nodes[6]}; bottom = {l3_.prg.nodes[0], l3_.prg.nodes[5], l3_.prg.nodes[6]}; alt_path = l3_.find_alt_path(top, 0, "GC", "."); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3_.find_alt_path(bottom, 0, ".", "GC"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); // if the site at the end has ref/alt as "." top = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4], l3_.prg.nodes[6], l3_.prg.nodes[7], l3_.prg.nodes[9]}; bottom = {l3_.prg.nodes[0], l3_.prg.nodes[1], l3_.prg.nodes[2], l3_.prg.nodes[4], l3_.prg.nodes[6], l3_.prg.nodes[8], l3_.prg.nodes[9]}; alt_path = l3_.find_alt_path(top, 5, "T", "."); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, bottom, alt_path); alt_path = l3_.find_alt_path(bottom, 5, ".", "T"); EXPECT_ITERABLE_EQ(vector<LocalNodePtr>, top, alt_path); } TEST(LocalPRGTest, append_kmer_covgs_in_range) { Index *idx; idx = new Index(); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); l3.minimizer_sketch(idx, 1, 3); l3.kmer_prg.nodes[2]->covg[0] = 4; l3.kmer_prg.nodes[2]->covg[1] = 3; l3.kmer_prg.nodes[5]->covg[0] = 4; l3.kmer_prg.nodes[5]->covg[1] = 5; l3.kmer_prg.nodes[7]->covg[0] = 2; l3.kmer_prg.nodes[7]->covg[1] = 3; l3.kmer_prg.nodes[8]->covg[0] = 4; l3.kmer_prg.nodes[8]->covg[1] = 6; for (const auto &n : l3.kmer_prg.nodes) { cout << *n; } vector<LocalNodePtr> lmp = {}; vector<KmerNodePtr> kmp = {l3.kmer_prg.nodes[0], l3.kmer_prg.nodes[2], l3.kmer_prg.nodes[5], l3.kmer_prg.nodes[8], l3.kmer_prg.nodes[10], l3.kmer_prg.nodes[11]}; vector<uint32_t> fwd, rev, exp_fwd, exp_rev; l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 0, fwd, rev); exp_fwd = {}; exp_rev = {}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 1, fwd, rev); exp_fwd = {4}; exp_rev = {3}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); fwd.clear(); rev.clear(); l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 2, fwd, rev); exp_fwd = {4, 4}; exp_rev = {3, 5}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); fwd.clear(); rev.clear(); l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 0, 3, fwd, rev); exp_fwd = {4, 4, 4}; exp_rev = {3, 5, 6}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); fwd.clear(); rev.clear(); l3.append_kmer_covgs_in_range(l3.kmer_prg, kmp, lmp, 1, 2, fwd, rev); exp_fwd = {4, 4}; exp_rev = {3, 5}; EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_fwd, fwd); EXPECT_ITERABLE_EQ(vector<uint32_t>, exp_rev, rev); } TEST(LocalPRGTest, add_sample_covgs_to_vcf) { Index *idx; idx = new Index(); vector<string> short_formats = {"GT"}; vector<string> formats = {"GT", "MEAN_FWD_COVG", "MEAN_REV_COVG", "MED_FWD_COVG", "MED_REV_COVG", "SUM_FWD_COVG", "SUM_REV_COVG"}; LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); l3.minimizer_sketch(idx, 1, 3); l3.kmer_prg.sort_topologically(); VCF vcf; vector<LocalNodePtr> lmp3 = {l3.prg.nodes[0], l3.prg.nodes[1], l3.prg.nodes[3], l3.prg.nodes[4], l3.prg.nodes[6]}; l3.build_vcf(vcf, l3.prg.top_path()); vcf.sort_records(); l3.add_sample_gt_to_vcf(vcf, l3.prg.top_path(), lmp3, "sample"); EXPECT_EQ((uint) 1, vcf.samples.size()); EXPECT_EQ((uint) 1, vcf.records[0].samples.size()); EXPECT_ITERABLE_EQ(vector<string>, short_formats, vcf.records[0].format); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); l3.add_sample_covgs_to_vcf(vcf, l3.kmer_prg, l3.prg.top_path(), "sample"); EXPECT_EQ((uint) 1, vcf.samples.size()); EXPECT_EQ((uint) 1, vcf.records[0].samples.size()); EXPECT_ITERABLE_EQ(vector<string>, formats, vcf.records[0].format); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][1]); // ref l3.kmer_prg.nodes[1]->covg[0] = 1; l3.kmer_prg.nodes[1]->covg[1] = 0; l3.kmer_prg.nodes[4]->covg[0] = 1; l3.kmer_prg.nodes[4]->covg[1] = 0; l3.kmer_prg.nodes[7]->covg[0] = 1; l3.kmer_prg.nodes[7]->covg[1] = 0; // alt l3.kmer_prg.nodes[2]->covg[0] = 6; l3.kmer_prg.nodes[2]->covg[1] = 8; l3.kmer_prg.nodes[5]->covg[0] = 5; l3.kmer_prg.nodes[5]->covg[1] = 5; l3.kmer_prg.nodes[8]->covg[0] = 4; l3.kmer_prg.nodes[8]->covg[1] = 5; l3.add_sample_covgs_to_vcf(vcf, l3.kmer_prg, l3.prg.top_path(), "sample"); EXPECT_EQ((uint) 1, vcf.samples.size()); EXPECT_EQ((uint) 1, vcf.records[0].samples.size()); EXPECT_ITERABLE_EQ(vector<string>, formats, vcf.records[0].format); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["GT"][0]); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["MEAN_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MEAN_REV_COVG"][0]); EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MEAN_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 6, vcf.records[1].samples[0]["MEAN_REV_COVG"][1]); EXPECT_EQ((uint8_t) 1, vcf.records[1].samples[0]["MED_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["MED_REV_COVG"][0]); EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MED_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 5, vcf.records[1].samples[0]["MED_REV_COVG"][1]); EXPECT_EQ((uint8_t) 3, vcf.records[1].samples[0]["SUM_FWD_COVG"][0]); EXPECT_EQ((uint8_t) 0, vcf.records[1].samples[0]["SUM_REV_COVG"][0]); EXPECT_EQ((uint8_t) 15, vcf.records[1].samples[0]["SUM_FWD_COVG"][1]); EXPECT_EQ((uint8_t) 18, vcf.records[1].samples[0]["SUM_REV_COVG"][1]); delete idx; } TEST(LocalPRGTest, add_consensus_path_to_fastaq_bin) { Index *idx; idx = new Index(); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); l3.minimizer_sketch(idx, 1, 3); shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "three")); pn3->kmer_prg = l3.kmer_prg; pn3->kmer_prg.nodes[2]->covg[0] = 4; pn3->kmer_prg.nodes[2]->covg[1] = 3; pn3->kmer_prg.nodes[5]->covg[0] = 4; pn3->kmer_prg.nodes[5]->covg[0] = 5; pn3->kmer_prg.nodes[7]->covg[0] = 2; pn3->kmer_prg.nodes[7]->covg[1] = 3; pn3->kmer_prg.nodes[8]->covg[0] = 4; pn3->kmer_prg.nodes[8]->covg[0] = 6; pn3->kmer_prg.num_reads = 6; pn3->kmer_prg.set_p(0.0001); shared_ptr<pangenome::Read> pr(make_shared<pangenome::Read>(0)); pn3->reads.insert(pr); Fastaq fq(false, true); vector<KmerNodePtr> kmp; vector<LocalNodePtr> lmp; l3.add_consensus_path_to_fastaq(fq, pn3, kmp, lmp, 1, true, 8); EXPECT_EQ("AGTTAT", l3.string_along_path(lmp)); bool added_to_fq = find(fq.names.begin(), fq.names.end(), "three") != fq.names.end(); EXPECT_TRUE(added_to_fq); bool added_to_seqs = fq.sequences.find("three") != fq.sequences.end(); EXPECT_TRUE(added_to_seqs); bool added_to_scores = fq.scores.find("three") != fq.scores.end(); EXPECT_TRUE(added_to_scores); bool added_to_headers = fq.headers.find("three") != fq.headers.end(); EXPECT_TRUE(added_to_headers); EXPECT_EQ("AGTTAT", fq.sequences["three"]); EXPECT_EQ(fq.scores["three"], "DDD\?\?!"); cout << fq << endl; } TEST(LocalPRGTest, add_consensus_path_to_fastaq_nbin) { Index *idx; idx = new Index(); LocalPRG l3(3, "nested varsite", "A 5 G 7 C 8 T 7 6 G 5 TAT"); l3.minimizer_sketch(idx, 1, 3); shared_ptr<pangenome::Node> pn3(make_shared<pangenome::Node>(3, 3, "three")); pn3->kmer_prg = l3.kmer_prg; pn3->kmer_prg.nodes[2]->covg[0] = 4; pn3->kmer_prg.nodes[2]->covg[1] = 3; pn3->kmer_prg.nodes[5]->covg[0] = 4; pn3->kmer_prg.nodes[5]->covg[0] = 5; pn3->kmer_prg.nodes[7]->covg[0] = 2; pn3->kmer_prg.nodes[7]->covg[1] = 3; pn3->kmer_prg.nodes[8]->covg[0] = 4; pn3->kmer_prg.nodes[8]->covg[0] = 6; pn3->kmer_prg.num_reads = 6; pn3->kmer_prg.set_nb(0.05, 2.0); shared_ptr<pangenome::Read> pr(make_shared<pangenome::Read>(0)); pn3->reads.insert(pr); Fastaq fq(false, true); vector<KmerNodePtr> kmp; vector<LocalNodePtr> lmp; l3.add_consensus_path_to_fastaq(fq, pn3, kmp, lmp, 1, false, 8); EXPECT_EQ("AGTTAT", l3.string_along_path(lmp)); bool added_to_fq = find(fq.names.begin(), fq.names.end(), "three") != fq.names.end(); EXPECT_TRUE(added_to_fq); bool added_to_seqs = fq.sequences.find("three") != fq.sequences.end(); EXPECT_TRUE(added_to_seqs); bool added_to_scores = fq.scores.find("three") != fq.scores.end(); EXPECT_TRUE(added_to_scores); bool added_to_headers = fq.headers.find("three") != fq.headers.end(); EXPECT_TRUE(added_to_headers); EXPECT_EQ("AGTTAT", fq.sequences["three"]); EXPECT_EQ(fq.scores["three"], "DDD\?\?!"); cout << fq << endl; }
64,921
30,841
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #define N 100010 #define mp make_pair #define pa pair<ll,ll> #define fi first #define se second using namespace std ; typedef long long ll; ll p,n,m,w[N]; ll prime[N],mod[N],cnt[N],a[N]; int tot; ll quick_my(ll a,ll b,ll M) { ll ret=1; while(b) { if(b&1)ret=(ret*a)%M; a=(a*a)%M; b>>=1; } return ret; } void exgcd(ll a,ll b,ll &x,ll &y,ll &gcd) { if(!b) { x=1,y=0,gcd=a; return ; } exgcd(b,a%b,x,y,gcd); ll t=y; y=x-a/b*y;x=t; } void get_factor(ll x) { for(int i=2;i*i<=x;i++) { if(x%i==0) { prime[++tot]=i,cnt[tot]=0,mod[tot]=1; while(x%i==0){x/=i,cnt[tot]++,mod[tot]*=i;} } } if(x>1)prime[++tot]=x,cnt[tot]=1,mod[tot]=x; } ll inverse(ll a,ll b) { ll xx,yy,d; exgcd(a,b,xx,yy,d); return (xx+b)%b; } pa fact(ll k,ll n) { if(n==0)return mp(0,1); int x=n/prime[k],y=n/mod[k]; ll ans=1; if(y) { for(int i=2;i<mod[k];i++) { if(i%prime[k]!=0)ans=(ans*i)%mod[k]; } ans=quick_my(ans,y,mod[k]); } for(int i=y*mod[k]+1;i<=n;i++) { if(i%prime[k]!=0)ans=ans*i%mod[k]; } pa tmp=fact(k,x); return mp(x+tmp.fi,ans*tmp.se%mod[k]); } ll calc(int k,ll n,ll m) { if(n<m)return 0; pa a=fact(k,n),b=fact(k,m),c=fact(k,n-m); return a.se%mod[k]*inverse(b.se,mod[k])%mod[k]*inverse(c.se,mod[k])%mod[k]*quick_my(prime[k],a.fi-b.fi-c.fi,mod[k])%mod[k]; } ll china() { ll gcd,y,x=0; for(int i=1;i<=tot;i++) { ll r=p/mod[i]; exgcd(mod[i],r,gcd,y,gcd); x=(x+r*y*a[i])%p; } return (x+p)%p; } ll work(ll n,ll m) { for(int i=1;i<=tot;i++) a[i]=calc(i,n,m); return china(); } int main() { freopen("code.in","r",stdin);freopen("std.out","w",stdout); scanf("%lld%lld%lld",&p,&n,&m); get_factor(p); int sum=0; for(int i=1;i<=m;i++)scanf("%lld",&w[i]),sum+=w[i]; if(sum>n){printf("Impossible\n");return 0;} ll ans=work(n,sum)%p; for(int i=1;i<=m;i++) { ans=ans*work(sum,w[i])%p; sum-=w[i]; } printf("%lld\n",ans); }
2,238
1,157
// //////////////////////////////////////////////////////// // # Title // Tours on a 4 x n playing board // // # URL // https://projecteuler.net/problem=237 // http://euler.stephan-brumme.com/237/ // // # Problem // Let `T(n)` be the number of tours over a `4 * n` playing board such that: // - The tour starts in the top left corner. // - The tour consists of moves that are up, down, left, or right one square. // - The tour visits each square exactly once. // - The tour ends in the bottom left corner. // // The diagram shows one tour over a `4 * 10` board: // // ![tour](p237.gif) // // `T(10)` is 2329. What is `T(10^12) mod 10^8`? // // # Solved by // Stephan Brumme // October 2017 // // # Algorithm // A nice problem that you can easily understand within a few seconds. But it took a few days to come up with a solution ... // // Of course I immediately wrote a ''bruteForce'' algorithm and it solves the `T(10)` case. Anything beyond that is impossible. // // The main realization was to split the whole board in its columns. // I identified 15 different columns (A - O) which can have a unique "flow" on their left and right border. // The term "flow" means the chronological way how a piece moves across the board. // // The arrows symbolize the "flow" in and out of a column while hash signs stand for "no border crossing": // // || 4 || 4 || 4 || 4 || 4 || // ||! A ++ B ++ C ++ D ++ E || // || ==> ==> ++ ==> ==> ++ ==> ==> ++ ==> ==> ++ ==> ## || // || <== <== ++ <== ## ++ ## <== ++ <== <== ++ <== ## || // || ==> ==> ++ ==> ## ++ ## ==> ++ ==> ## ++ ==> ==> || // || <== <== ++ <== <== ++ <== <== ++ <== ## ++ <== <== || // // || 4 || 4 || 4 || 4 || 4 || // ||! F ++ G ++ H ++ I ++ J || // || ==> ==> ++ ## ==> ++ ==> ## ++ ## ==> ++ ==> ==> || // || <== <== ++ ## <== ++ ## ==> ++ ==> ## ++ <== ## || // || ## ==> ++ ==> ==> ++ ## <== ++ <== ## ++ ## ## || // || ## <== ++ <== <== ++ <== ## ++ ## <== ++ ## <== || // // || 4 || 4 || 4 || 4 || 4 || // ||! K ++ L ++ M ++ N ++ O || // || ==> ## ++ ==> ==> ++ ## ==> ++ ==> ## ++ ==> ## || // || ## ## ++ ## <== ++ ## ## ++ <== ## ++ ## ## || // || ## ==> ++ ## ## ++ ==> ## ++ ==> ## ++ ## ## || // || <== <== ++ <== ## ++ <== <== ++ <== ## ++ <== ## || // // Columns N and O can only be found at the right edge of the board. // // Unfortunately it's not sufficient to represent the flow by arrows because they are still ambigious: // there are three different chronological orders how the "flow" can pass through column A. // // If I look at each column's left and right border then there are just 6 patterns for these borders. // With a proper labelling of the flow's chronological order (indicated by 1,2,3,4 and a hash means "no crossing") I get 8 different borders: // // || 2 || 2 || 2 || 2 || 2 || 2 || 2 || 2 || // || 1 ++ 1 ++ 1 ++ # ++ # ++ 1 ++ 3 ++ # || // || # ++ 2 ++ 2 ++ 1 ++ # ++ 4 ++ 2 ++ # || // || # ++ # ++ 3 ++ 2 ++ 1 ++ 3 ++ 1 ++ # || // || 2 ++ # ++ 4 ++ # ++ 2 ++ 2 ++ 4 ++ # || // // The function ''fill()'' stores the borders of each column, e.g. column C is // ''neighbors.insert( { "1##2", "1234" } );'' // Trust me, getting all this stuff right was a lot of work: I made tons of mistakes ! // // I wrote two algorithms: a simple one that verifies `T(10)` and a much faster one to solve `T(10^12)`. // ''slow()'' linearly goes through all borders that are allowed on the right side of the current border and stops if it reaches the right side of the board. // Assuming that there are about 3 borders that are compatible in such a way, the routine analyzes `3^width` combinations. // There's no way it can solve `T(10^12)` - but I really needed this algorithm to get my borders right. // When the output finally matched the results of ''bruteForce'' I went on to write a faster (and more complex) algorithm. // // ''fast()'' is a divide-and-conquer approach: // - I treat a group of columns as a blackbox where I only knows its left and right border // - if I cut through this blackbox at an arbitrary point then any of the 8 borders could be found // - well, that's not quite right, since the 8th border is reserved for the right-most border of the board ==> only 7 borders "inside" the blackbox // - then the number of combinations of a blackbox is the product of its left and right half // - if I keep doing this until the blackbox contains only a single column then I check whether this type of column is valid // // This isn't much faster than what ''slow()'' does ... but when the blackbox becomes smaller, I process the same kinds of blackboxes over and over again. // Thus memoization drastically reduced the number of __different__ blackboxes. At the end, ''cache'' contains 3417 values. // // # Note // Even though the result is found within about 0.02 seconds, I felt that dividing each blackbox in the middle isn't optimal: // if I try to divide the blackbox in such a way that at least one half's size is a power of two (that means `2^i`) then ''cache'' contains only 2031 values. // Moreover, the program runs about 50% faster. // // Replacing the ''std::string'' by plain integers would be still faster but I think it would be much harder to understand the code. // // # Alternative // I was blown away by the simple solutions found by others: they discovered a relationship between `T(n)` and `T(n-1)`, ..., `T(n-4)`. // Incredible stuff - or maybe just looked up in OEIS A181688. #include <iostream> #include <set> #include <map> #include <vector> #include <tuple> // assuming that the route could exceed the left border I get these states for the left-most and right-most borders: typedef std::string Border; const Border LeftBorder = "1##2"; const Border RightBorder = "####"; // all possible borders that can be found inside the grid std::set<Border> borders; // define which borders can be next to each other std::set<std::pair<Border, Border>> neighbors; // set up the containers "borders" and "neighbors" void fill() { // the following lines are derived from my drawings above // left right column neighbors.insert( { "1234", "1234" } ); // A neighbors.insert( { "1432", "1432" } ); // A neighbors.insert( { "3214", "3214" } ); // A neighbors.insert( { "1432", "1##2" } ); // B neighbors.insert( { "3214", "1##2" } ); // B neighbors.insert( { "1##2", "1234" } ); // C neighbors.insert( { "1234", "12##" } ); // D neighbors.insert( { "1234", "##12" } ); // E neighbors.insert( { "12##", "1432" } ); // F neighbors.insert( { "##12", "3214" } ); // G neighbors.insert( { "1##2", "#12#" } ); // H neighbors.insert( { "#12#", "1##2" } ); // I neighbors.insert( { "12##", "1##2" } ); // J neighbors.insert( { "1##2", "##12" } ); // K neighbors.insert( { "1##2", "12##" } ); // L neighbors.insert( { "##12", "1##2" } ); // M neighbors.insert( { "1234", RightBorder } ); // N neighbors.insert( { "1##2", RightBorder } ); // O for (auto x : neighbors) borders.insert(x.first); } // fast search in O(log n) unsigned long long search(const Border& left, const Border& right, unsigned long long length, unsigned int modulo) { // reduced to a single column ? if (length == 1) // can these two borders be next to each other ? return neighbors.count(std::make_pair(left, right)); // memoize auto id = std::make_tuple(left, right, length); // I don't add "modulo" to the key to keep it simple static std::map<std::tuple<Border, Border, unsigned long long>, unsigned long long> cache; auto lookup = cache.find(id); if (lookup != cache.end()) return lookup->second; // split region into two parts: every possible border can be at the splitting point unsigned long long result = 0; for (const auto& next : borders) { // prefer a "power of two"-splitting, causes less states than splitting 50:50 unsigned long long pow2 = 1; while (pow2 < length / 2) pow2 *= 2; //pow2 = length / 2; // alternatively: less efficient 50:50 method // process left half auto leftHalf = search(left, next, pow2, modulo); // process right half auto rightHalf = search(next, right, length - pow2, modulo); // each left half can be combined with each right half auto combined = (leftHalf * rightHalf) % modulo; result += combined; } result %= modulo; cache[id] = result; return result; } // slow search, no caching whatsoever unsigned long long slow(const std::string& border, unsigned int length, unsigned int width, unsigned int modulo) { // walked across the whole board ? if (length == width) return (border == RightBorder) ? 1 : 0; // proceed with each border that is compatible to the current one unsigned long long result = 0; for (auto x : neighbors) if (x.first == border) result += slow(x.second, length + 1, width, modulo); return result % modulo; } // backtracking of possible paths, doesn't need the information about borders etc. typedef std::vector<std::vector<unsigned int>> Grid; unsigned int bruteForce(Grid& grid, unsigned int x, unsigned int y, unsigned int step) { // reached final position ? if (x == 0 && y == 3) return (step == grid.size() * grid[0].size()) ? 1 : 0; // take a step grid[x][y] = step; // try to search deeper in each direction unsigned int result = 0; if (x > 0 && grid[x - 1][y] == 0) result += bruteForce(grid, x - 1, y, step + 1); if (x + 1 < grid.size() && grid[x + 1][y] == 0) result += bruteForce(grid, x + 1, y, step + 1); if (y > 0 && grid[x][y - 1] == 0) result += bruteForce(grid, x, y - 1, step + 1); if (y < 3 && grid[x][y + 1] == 0) result += bruteForce(grid, x, y + 1, step + 1); // undo step grid[x][y] = 0; return result; } int main() { // set up borders and their relationships fill(); unsigned int modulo = 100000000; unsigned long long limit = 1000000000000; std::cin >> limit; //#define BRUTEFORCE #ifdef BRUTEFORCE // allocate memory Grid grid(limit); for (auto& column : grid) column.resize(4, 0); // start in upper left corner (0,0), that's the first step std::cout << bruteForce(grid, 0, 0, 1) << std::endl; #endif //#define SLOW #ifdef SLOW std::cout << slow(LeftBorder, 0, limit, modulo) << std::endl; #endif #define FAST #ifdef FAST std::cout << search(LeftBorder, RightBorder, limit, modulo) << std::endl; #endif return 0; }
10,606
3,601
#include "LevelGenerationCarver.h" FLevelGenerationCarver::FLevelGenerationCarver() { this->MeshCarver = NULL; this->ConvexCarver = NULL; this->StaticMeshCarver = NULL; this->ConvexExpensiveNoise = 0.00f; this->CarveCellSize = CarveOptionsCellSize::CARVE_CELL_SIZE_25; this->TerrainMaterial = NULL; this->Filter = ECarveFilterType::ReplaceAll; this->ToBeDiscarded = false; }
409
150
// Copyright (C) 2016-2019 Internet Systems Consortium, Inc. ("ISC") // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #include <config.h> #include <dhcp/dhcp6.h> #include <dhcp/option.h> #include <dhcp/option_int.h> #include <dhcp/option_int_array.h> #include <dhcp/pkt6.h> #include <dhcp/tests/iface_mgr_test_config.h> #include <dhcp/opaque_data_tuple.h> #include <dhcp/option_string.h> #include <dhcp/option_vendor_class.h> #include <dhcp/option6_addrlst.h> #include <dhcp/tests/pkt_captures.h> #include <dhcpsrv/cfgmgr.h> #include <dhcp6/tests/dhcp6_test_utils.h> #include <dhcp6/tests/dhcp6_client.h> #include <asiolink/io_address.h> #include <stats/stats_mgr.h> #include <boost/pointer_cast.hpp> #include <string> using namespace isc; using namespace isc::asiolink; using namespace isc::dhcp; using namespace isc::dhcp::test; namespace { /// @brief Set of JSON configurations used by the classification unit tests. /// /// - Configuration 0: /// - Specifies 3 classes: 'router', 'reserved-class1' and 'reserved-class2'. /// - 'router' class is assigned when the client sends option 1234 (string) /// equal to 'foo'. /// - The other two classes are reserved for the client having /// DUID '01:02:03:04' /// - Class 'router' includes option 'ipv6-forwarding'. /// - Class 'reserved-class1' includes option DNS servers. /// - Class 'reserved-class2' includes option NIS servers. /// - All three options are sent when client has reservations for the /// 'reserved-class1', 'reserved-class2' and sends option 1234 with /// the 'foo' value. /// - There is one subnet specified 2001:db8:1::/48 with pool of /// IPv6 addresses. /// /// - Configuration 1: /// - Used for complex membership (example taken from HA) /// - 1 subnet: 2001:db8:1::/48 /// - 4 pools: 2001:db8:1:1::/64, 2001:db8:1:2::/64, /// 2001:db8:1:3::/64 and 2001:db8:1:4::/64 /// - 4 classes to compose: /// server1 and server2 for each HA server /// option 1234 'foo' aka telephones /// option 1234 'bar' aka computers /// /// - Configuration 2: /// - Used for complex membership (example taken from HA) and pd-pools /// - 1 subnet: 2001:db8::/32 /// - 4 pd-pools: 2001:db8:1::/48, 2001:db8:2::/48, /// 2001:db8:3::/48 and 2001:db8:4::/48 /// - 4 classes to compose: /// server1 and server2 for each HA server /// option 1234 'foo' aka telephones /// option 1234 'bar' aka computers /// /// - Configuration 3: /// - Used for the DROP class /// - 1 subnet: 2001:db8:1::/48 /// - 2 pool: 2001:db8:1:1::/64 /// - the following class defined: option 1234 'foo', DROP /// const char* CONFIGS[] = { // Configuration 0 "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"option-def\": [ " "{" " \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\"" "}," "{" " \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\"" "} ]," "\"client-classes\": [" "{" " \"name\": \"router\"," " \"test\": \"option[host-name].text == 'foo'\"," " \"option-data\": [" " {" " \"name\": \"ipv6-forwarding\", " " \"data\": \"true\"" " } ]" "}," "{" " \"name\": \"reserved-class1\"," " \"option-data\": [" " {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::50\"" " }" " ]" "}," "{" " \"name\": \"reserved-class2\"," " \"option-data\": [" " {" " \"name\": \"nis-servers\"," " \"data\": \"2001:db8:1::100\"" " }" " ]" "}" "]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\"," " \"reservations\": [" " {" " \"duid\": \"01:02:03:04\"," " \"client-classes\": [ \"reserved-class1\", \"reserved-class2\" ]" " } ]" " } ]," "\"valid-lifetime\": 4000 }", // Configuration 1 "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"option-def\": [ " "{" " \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\"" "} ]," "\"client-classes\": [" "{" " \"name\": \"server1\"" "}," "{" " \"name\": \"server2\"" "}," "{" " \"name\": \"telephones\"," " \"test\": \"option[host-name].text == 'foo'\"" "}," "{" " \"name\": \"computers\"," " \"test\": \"option[host-name].text == 'bar'\"" "}," "{" " \"name\": \"server1_and_telephones\"," " \"test\": \"member('server1') and member('telephones')\"" "}," "{" " \"name\": \"server1_and_computers\"," " \"test\": \"member('server1') and member('computers')\"" "}," "{" " \"name\": \"server2_and_telephones\"," " \"test\": \"member('server2') and member('telephones')\"" "}," "{" " \"name\": \"server2_and_computers\"," " \"test\": \"member('server2') and member('computers')\"" "}" "]," "\"subnet6\": [ " "{ \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\"," " \"pools\": [ " " { \"pool\": \"2001:db8:1:1::/64\"," " \"client-class\": \"server1_and_telephones\" }," " { \"pool\": \"2001:db8:1:2::/64\"," " \"client-class\": \"server1_and_computers\" }," " { \"pool\": \"2001:db8:1:3::/64\"," " \"client-class\": \"server2_and_telephones\" }," " { \"pool\": \"2001:db8:1:4::/64\"," " \"client-class\": \"server2_and_computers\" } ]" " } ]," "\"valid-lifetime\": 4000 }", // Configuration 2 "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"option-def\": [ " "{" " \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\"" "} ]," "\"client-classes\": [" "{" " \"name\": \"server1\"" "}," "{" " \"name\": \"server2\"" "}," "{" " \"name\": \"telephones\"," " \"test\": \"option[host-name].text == 'foo'\"" "}," "{" " \"name\": \"computers\"," " \"test\": \"option[host-name].text == 'bar'\"" "}," "{" " \"name\": \"server1_and_telephones\"," " \"test\": \"member('server1') and member('telephones')\"" "}," "{" " \"name\": \"server1_and_computers\"," " \"test\": \"member('server1') and member('computers')\"" "}," "{" " \"name\": \"server2_and_telephones\"," " \"test\": \"member('server2') and member('telephones')\"" "}," "{" " \"name\": \"server2_and_computers\"," " \"test\": \"member('server2') and member('computers')\"" "}" "]," "\"subnet6\": [ " "{ \"subnet\": \"2001:db8::/32\", " " \"interface\": \"eth1\"," " \"pd-pools\": [ " " { \"prefix\": \"2001:db8:1::\"," " \"prefix-len\": 48, \"delegated-len\": 64," " \"client-class\": \"server1_and_telephones\" }," " { \"prefix\": \"2001:db8:2::\"," " \"prefix-len\": 48, \"delegated-len\": 64," " \"client-class\": \"server1_and_computers\" }," " { \"prefix\": \"2001:db8:3::\"," " \"prefix-len\": 48, \"delegated-len\": 64," " \"client-class\": \"server2_and_telephones\" }," " { \"prefix\": \"2001:db8:4::\"," " \"prefix-len\": 48, \"delegated-len\": 64," " \"client-class\": \"server2_and_computers\" } ]" " } ]," "\"valid-lifetime\": 4000 }", // Configuration 3 "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"option-def\": [ " "{" " \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\"" "}," "{" " \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\"" "} ]," "\"client-classes\": [" "{" " \"name\": \"DROP\"," " \"test\": \"option[host-name].text == 'foo'\"" "}" "]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\"" " } ]," "\"valid-lifetime\": 4000 }" }; /// @brief Test fixture class for testing client classification by the /// DHCPv6 server. /// /// @todo There are numerous tests not using Dhcp6Client class. They should be /// migrated to use it one day. class ClassifyTest : public Dhcpv6SrvTest { public: /// @brief Constructor. /// /// Sets up fake interfaces. ClassifyTest() : Dhcpv6SrvTest(), iface_mgr_test_config_(true) { } /// @brief Verify values of options returned by the server when the server /// uses configuration with index 0. /// /// @param config Reference to DHCP client's configuration received. /// @param ip_forwarding Expected value of IP forwarding option. This option /// is expected to always be present. /// @param dns_servers String holding an address carried within DNS /// servers option. If this value is empty, the option is expected to not /// be included in the response. /// @param nis_servers String holding an address carried within NIS /// servers option. If this value is empty, the option is expected to not /// be included in the response. void verifyConfig0Options(const Dhcp6Client::Configuration& config, const uint8_t ip_forwarding = 1, const std::string& dns_servers = "", const std::string& nis_servers = "") { // IP forwarding option should always exist. OptionPtr ip_forwarding_opt = config.findOption(2345); ASSERT_TRUE(ip_forwarding_opt); // The option comprises 2 bytes of option code, 2 bytes of option length, // and a single 1 byte value. This makes it 5 bytes of a total length. ASSERT_EQ(5, ip_forwarding_opt->len()); ASSERT_EQ(static_cast<int>(ip_forwarding), static_cast<int>(ip_forwarding_opt->getUint8())); // DNS servers. Option6AddrLstPtr dns_servers_opt = boost::dynamic_pointer_cast< Option6AddrLst>(config.findOption(D6O_NAME_SERVERS)); if (!dns_servers.empty()) { ASSERT_TRUE(dns_servers_opt); Option6AddrLst::AddressContainer addresses = dns_servers_opt->getAddresses(); // For simplicity, we expect only a single address. ASSERT_EQ(1, addresses.size()); EXPECT_EQ(dns_servers, addresses[0].toText()); } else { EXPECT_FALSE(dns_servers_opt); } // NIS servers. Option6AddrLstPtr nis_servers_opt = boost::dynamic_pointer_cast< Option6AddrLst>(config.findOption(D6O_NIS_SERVERS)); if (!nis_servers.empty()) { ASSERT_TRUE(nis_servers_opt); Option6AddrLst::AddressContainer addresses = nis_servers_opt->getAddresses(); // For simplicity, we expect only a single address. ASSERT_EQ(1, addresses.size()); EXPECT_EQ(nis_servers, addresses[0].toText()); } else { EXPECT_FALSE(nis_servers_opt); } } /// @brief Create a solicit Pkt6Ptr createSolicit(std::string remote_addr = "fe80::abcd") { OptionPtr clientid = generateClientId(); Pkt6Ptr query(new Pkt6(DHCPV6_SOLICIT, 1234)); query->setRemoteAddr(IOAddress(remote_addr)); query->addOption(clientid); query->setIface("eth1"); query->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000)); return (query); } /// @brief Interface Manager's fake configuration control. IfaceMgrTestConfig iface_mgr_test_config_; }; // Checks if DOCSIS client packets are classified properly TEST_F(ClassifyTest, docsisClientClassification) { NakedDhcpv6Srv srv(0); // Let's create a relayed SOLICIT. This particular relayed SOLICIT has // vendor-class set to docsis3.0 Pkt6Ptr sol1; ASSERT_NO_THROW(sol1 = PktCaptures::captureDocsisRelayedSolicit()); ASSERT_NO_THROW(sol1->unpack()); srv.classifyPacket(sol1); // It should belong to docsis3.0 class. It should not belong to eRouter1.0 EXPECT_TRUE(sol1->inClass("VENDOR_CLASS_docsis3.0")); EXPECT_FALSE(sol1->inClass("eRouter1.0")); // Let's get a relayed SOLICIT. This particular relayed SOLICIT has // vendor-class set to eRouter1.0 Pkt6Ptr sol2; ASSERT_NO_THROW(sol2 = PktCaptures::captureeRouterRelayedSolicit()); ASSERT_NO_THROW(sol2->unpack()); srv.classifyPacket(sol2); EXPECT_TRUE(sol2->inClass(srv.VENDOR_CLASS_PREFIX + "eRouter1.0")); EXPECT_FALSE(sol2->inClass(srv.VENDOR_CLASS_PREFIX + "docsis3.0")); } // Checks if client packets are classified properly using match expressions. // Note option names and definitions are used. TEST_F(ClassifyTest, matchClassification) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\" } ]," "\"client-classes\": [ " "{ \"name\": \"router\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[host-name].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create packets with enough to select the subnet Pkt6Ptr query1 = createSolicit(); Pkt6Ptr query2 = createSolicit(); Pkt6Ptr query3 = createSolicit(); // Create and add an ORO option to the first 2 queries OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query1->addOption(oro); query2->addOption(oro); // Create and add a host-name option to the first and last queries OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query1->addOption(hostname); query3->addOption(hostname); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // Packets with the exception of the second should be in the router class EXPECT_TRUE(query1->inClass("router")); EXPECT_FALSE(query2->inClass("router")); EXPECT_TRUE(query3->inClass("router")); // Process queries AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); // Classification processing should add an ip-forwarding option OptionPtr opt1 = response1->getOption(2345); EXPECT_TRUE(opt1); // But only for the first query: second was not classified OptionPtr opt2 = response2->getOption(2345); EXPECT_FALSE(opt2); // But only for the first query: third has no ORO OptionPtr opt3 = response3->getOption(2345); EXPECT_FALSE(opt3); } // Check that only-if-required classes are not evaluated by classifyPacket TEST_F(ClassifyTest, required) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\" } ]," "\"client-classes\": [ " "{ \"name\": \"router\", " " \"only-if-required\": true, " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[host-name].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create packets with enough to select the subnet OptionPtr clientid = generateClientId(); Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234)); query1->setRemoteAddr(IOAddress("fe80::abcd")); query1->addOption(clientid); query1->setIface("eth1"); query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000)); Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234)); query2->setRemoteAddr(IOAddress("fe80::abcd")); query2->addOption(clientid); query2->setIface("eth1"); query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234)); query3->setRemoteAddr(IOAddress("fe80::abcd")); query3->addOption(clientid); query3->setIface("eth1"); query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000)); // Create and add an ORO option to the first 2 queries OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query1->addOption(oro); query2->addOption(oro); // Create and add a host-name option to the first and last queries OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query1->addOption(hostname); query3->addOption(hostname); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // No packet is in the router class EXPECT_FALSE(query1->inClass("router")); EXPECT_FALSE(query2->inClass("router")); EXPECT_FALSE(query3->inClass("router")); // Process queries AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); // Classification processing should do nothing OptionPtr opt1 = response1->getOption(2345); EXPECT_FALSE(opt1); OptionPtr opt2 = response2->getOption(2345); EXPECT_FALSE(opt2); OptionPtr opt3 = response3->getOption(2345); EXPECT_FALSE(opt3); } // Checks that when only-if-required classes are still evaluated TEST_F(ClassifyTest, requiredClassification) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"require-client-classes\": [ \"router\" ], " " \"interface\": \"eth1\" } ]," "\"client-classes\": [ " "{ \"name\": \"router\", " " \"only-if-required\": true, " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[host-name].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create packets with enough to select the subnet OptionPtr clientid = generateClientId(); Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234)); query1->setRemoteAddr(IOAddress("fe80::abcd")); query1->addOption(clientid); query1->setIface("eth1"); query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000)); Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234)); query2->setRemoteAddr(IOAddress("fe80::abcd")); query2->addOption(clientid); query2->setIface("eth1"); query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234)); query3->setRemoteAddr(IOAddress("fe80::abcd")); query3->addOption(clientid); query3->setIface("eth1"); query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000)); // Create and add an ORO option to the first 2 queries OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query1->addOption(oro); query2->addOption(oro); // Create and add a host-name option to the first and last queries OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query1->addOption(hostname); query3->addOption(hostname); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // No packet is in the router class yet EXPECT_FALSE(query1->inClass("router")); EXPECT_FALSE(query2->inClass("router")); EXPECT_FALSE(query3->inClass("router")); // Process queries AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); // Classification processing should add an ip-forwarding option OptionPtr opt1 = response1->getOption(2345); EXPECT_TRUE(opt1); // But only for the first query: second was not classified OptionPtr opt2 = response2->getOption(2345); EXPECT_FALSE(opt2); // But only for the first query: third has no ORO OptionPtr opt3 = response3->getOption(2345); EXPECT_FALSE(opt3); } // Checks subnet options have the priority over class options TEST_F(ClassifyTest, subnetClassPriority) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // Subnet sets an ipv6-forwarding option in the response. // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ] } ], " "\"client-classes\": [ " "{ \"name\": \"router\"," " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[1234].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create a packet with enough to select the subnet and go through // the SOLICIT processing Pkt6Ptr query = createSolicit(); // Create and add an ORO option to the query OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query->addOption(oro); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify the packet srv.classifyPacket(query); // The packet should be in the router class EXPECT_TRUE(query->inClass("router")); // Process the query AllocEngine::ClientContext6 ctx; bool drop = false; srv.initContext(query, ctx, drop); ASSERT_FALSE(drop); Pkt6Ptr response = srv.processSolicit(ctx); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(2345); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Classification sets the value to true/1, subnet to false/0 // Here subnet has the priority EXPECT_EQ(0, opt->getUint8()); } // Checks subnet options have the priority over global options TEST_F(ClassifyTest, subnetGlobalPriority) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // Subnet sets an ipv6-forwarding option in the response. // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ], " "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ] } ] }"; ASSERT_NO_THROW(configure(config)); // Create a packet with enough to select the subnet and go through // the SOLICIT processing Pkt6Ptr query = createSolicit(); // Create and add an ORO option to the query OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query->addOption(oro); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Process the query AllocEngine::ClientContext6 ctx; bool drop = false; srv.initContext(query, ctx, drop); ASSERT_FALSE(drop); Pkt6Ptr response = srv.processSolicit(ctx); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(2345); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Global sets the value to true/1, subnet to false/0 // Here subnet has the priority EXPECT_EQ(0, opt->getUint8()); } // Checks class options have the priority over global options TEST_F(ClassifyTest, classGlobalPriority) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // A global ipv6-forwarding option is set in the response. // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\" } ]," "\"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ], " "\"client-classes\": [ " "{ \"name\": \"router\"," " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"option[1234].text == 'foo'\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create a packet with enough to select the subnet and go through // the SOLICIT processing Pkt6Ptr query = createSolicit(); // Create and add an ORO option to the query OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query->addOption(oro); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Classify the packet srv.classifyPacket(query); // The packet should be in the router class EXPECT_TRUE(query->inClass("router")); // Process the query AllocEngine::ClientContext6 ctx; bool drop = false; srv.initContext(query, ctx, drop); ASSERT_FALSE(drop); Pkt6Ptr response = srv.processSolicit(ctx); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(2345); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Classification sets the value to true/1, global to false/0 // Here class has the priority EXPECT_NE(0, opt->getUint8()); } // Checks class options have the priority over global persistent options TEST_F(ClassifyTest, classGlobalPersistency) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // Subnet sets an ipv6-forwarding option in the response. // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. // Note the persistency flag follows a "OR" semantic so to set // it to false (or to leave the default) has no effect. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\", " " \"always-send\": true } ], " "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\", " " \"always-send\": false } ] } ] }"; ASSERT_NO_THROW(configure(config)); // Create a packet with enough to select the subnet and go through // the SOLICIT processing Pkt6Ptr query = createSolicit(); // Do not add an ORO. OptionPtr oro = query->getOption(D6O_ORO); EXPECT_FALSE(oro); // Create and add a host-name option to the query OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); query->addOption(hostname); // Process the query AllocEngine::ClientContext6 ctx; bool drop = false; srv.initContext(query, ctx, drop); ASSERT_FALSE(drop); Pkt6Ptr response = srv.processSolicit(ctx); // Processing should add an ip-forwarding option OptionPtr opt = response->getOption(2345); ASSERT_TRUE(opt); ASSERT_GT(opt->len(), opt->getHeaderLen()); // Global sets the value to true/1, subnet to false/0 // Here subnet has the priority EXPECT_EQ(0, opt->getUint8()); } // Checks if the client-class field is indeed used for subnet selection. // Note that packet classification is already checked in ClassifyTest // .*Classification above. TEST_F(ClassifyTest, clientClassifySubnet) { // This test configures 2 subnets. We actually only need the // first one, but since there's still this ugly hack that picks // the pool if there is only one, we must use more than one // subnet. That ugly hack will be removed in #3242, currently // under review. // The second subnet does not play any role here. The client's // IP address belongs to the first subnet, so only that first // subnet is being tested. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet6\": [ " " { \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ]," " \"subnet\": \"2001:db8:1::/48\", " " \"client-class\": \"foo\" " " }, " " { \"pools\": [ { \"pool\": \"2001:db8:2::/64\" } ]," " \"subnet\": \"2001:db8:2::/48\", " " \"client-class\": \"xyzzy\" " " } " "]," "\"valid-lifetime\": 4000 }"; ASSERT_NO_THROW(configure(config)); Pkt6Ptr sol = createSolicit("2001:db8:1::3"); // This discover does not belong to foo class, so it will not // be serviced bool drop = false; EXPECT_FALSE(srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); // Let's add the packet to bar class and try again. sol->addClass("bar"); // Still not supported, because it belongs to wrong class. EXPECT_FALSE(srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); // Let's add it to matching class. sol->addClass("foo"); // This time it should work EXPECT_TRUE(srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); } // Checks if the client-class field is indeed used for pool selection. TEST_F(ClassifyTest, clientClassifyPool) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // This test configures 2 pools. // The second pool does not play any role here. The client's // IP address belongs to the first pool, so only that first // pool is being tested. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"client-classes\": [ " " { " " \"name\": \"foo\" " " }, " " { " " \"name\": \"bar\" " " } " "], " "\"subnet6\": [ " " { \"pools\": [ " " { " " \"pool\": \"2001:db8:1::/64\", " " \"client-class\": \"foo\" " " }, " " { " " \"pool\": \"2001:db8:2::/64\", " " \"client-class\": \"xyzzy\" " " } " " ], " " \"subnet\": \"2001:db8::/40\" " " } " "], " "\"valid-lifetime\": 4000 }"; ASSERT_NO_THROW(configure(config)); Pkt6Ptr query1 = createSolicit("2001:db8:1::3"); Pkt6Ptr query2 = createSolicit("2001:db8:1::3"); Pkt6Ptr query3 = createSolicit("2001:db8:1::3"); // This discover does not belong to foo class, so it will not // be serviced srv.classifyPacket(query1); AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); ASSERT_TRUE(response1); OptionPtr ia_na1 = response1->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na1); EXPECT_TRUE(ia_na1->getOption(D6O_STATUS_CODE)); EXPECT_FALSE(ia_na1->getOption(D6O_IAADDR)); // Let's add the packet to bar class and try again. query2->addClass("bar"); // Still not supported, because it belongs to wrong class. srv.classifyPacket(query2); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); ASSERT_TRUE(response2); OptionPtr ia_na2 = response2->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na2); EXPECT_TRUE(ia_na2->getOption(D6O_STATUS_CODE)); EXPECT_FALSE(ia_na2->getOption(D6O_IAADDR)); // Let's add it to matching class. query3->addClass("foo"); // This time it should work srv.classifyPacket(query3); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); ASSERT_TRUE(response3); OptionPtr ia_na3 = response3->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na3); EXPECT_FALSE(ia_na3->getOption(D6O_STATUS_CODE)); EXPECT_TRUE(ia_na3->getOption(D6O_IAADDR)); } // Checks if the [UN]KNOWN built-in classes is indeed used for pool selection. TEST_F(ClassifyTest, clientClassifyPoolKnown) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // This test configures 2 pools. // The first one requires reservation, the second does the opposite. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet6\": [ " " { \"pools\": [ " " { " " \"pool\": \"2001:db8:1::/64\", " " \"client-class\": \"KNOWN\" " " }, " " { " " \"pool\": \"2001:db8:2::/64\", " " \"client-class\": \"UNKNOWN\" " " } " " ], " " \"subnet\": \"2001:db8::/40\", " " \"reservations\": [ " " { \"duid\": \"01:02:03:04\", \"hostname\": \"foo\" } ] " " } " "], " "\"valid-lifetime\": 4000 }"; ASSERT_NO_THROW(configure(config)); OptionPtr clientid1 = generateClientId(); Pkt6Ptr query1 = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 1234)); query1->setRemoteAddr(IOAddress("2001:db8:1::3")); query1->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); query1->addOption(clientid1); query1->setIface("eth1"); // First pool requires reservation so the second will be used srv.classifyPacket(query1); AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); ASSERT_TRUE(response1); OptionPtr ia_na1 = response1->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na1); EXPECT_FALSE(ia_na1->getOption(D6O_STATUS_CODE)); OptionPtr iaaddr1 = ia_na1->getOption(D6O_IAADDR); ASSERT_TRUE(iaaddr1); boost::shared_ptr<Option6IAAddr> addr1 = boost::dynamic_pointer_cast<Option6IAAddr>(iaaddr1); ASSERT_TRUE(addr1); EXPECT_EQ("2001:db8:2::", addr1->getAddress().toText()); // Try with DUID 01:02:03:04 uint8_t duid[] = { 0x01, 0x02, 0x03, 0x04 }; OptionBuffer buf(duid, duid + sizeof(duid)); OptionPtr clientid2(new Option(Option::V6, D6O_CLIENTID, buf)); Pkt6Ptr query2 = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 2345)); query2->setRemoteAddr(IOAddress("2001:db8:1::3")); query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); query2->addOption(clientid2); query2->setIface("eth1"); // Now the first pool will be used srv.classifyPacket(query2); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); ASSERT_TRUE(response2); OptionPtr ia_na2 = response2->getOption(D6O_IA_NA); ASSERT_TRUE(ia_na2); EXPECT_FALSE(ia_na2->getOption(D6O_STATUS_CODE)); OptionPtr iaaddr2 = ia_na2->getOption(D6O_IAADDR); ASSERT_TRUE(iaaddr2); boost::shared_ptr<Option6IAAddr> addr2 = boost::dynamic_pointer_cast<Option6IAAddr>(iaaddr2); ASSERT_TRUE(addr2); EXPECT_EQ("2001:db8:1::", addr2->getAddress().toText()); } // Tests whether a packet with custom vendor-class (not erouter or docsis) // is classified properly. TEST_F(ClassifyTest, vendorClientClassification2) { NakedDhcpv6Srv srv(0); // Let's create a SOLICIT. Pkt6Ptr sol = Pkt6Ptr(new Pkt6(DHCPV6_SOLICIT, 1234)); sol->setRemoteAddr(IOAddress("2001:db8:1::3")); sol->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); OptionPtr clientid = generateClientId(); sol->addOption(clientid); // Now let's add a vendor-class with id=1234 and content "foo" OptionVendorClassPtr vendor_class(new OptionVendorClass(Option::V6, 1234)); OpaqueDataTuple tuple(OpaqueDataTuple::LENGTH_2_BYTES); tuple = "foo"; vendor_class->addTuple(tuple); sol->addOption(vendor_class); // Now the server classifies the packet. srv.classifyPacket(sol); // The packet should now belong to VENDOR_CLASS_foo. EXPECT_TRUE(sol->inClass(srv.VENDOR_CLASS_PREFIX + "foo")); // It should not belong to "foo" EXPECT_FALSE(sol->inClass("foo")); } // Checks if relay IP address specified in the relay-info structure can be // used together with client-classification. TEST_F(ClassifyTest, relayOverrideAndClientClass) { // This test configures 2 subnets. They both are on the same link, so they // have the same relay-ip address. Furthermore, the first subnet is // reserved for clients that belong to class "foo". std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"subnet6\": [ " " { \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ]," " \"subnet\": \"2001:db8:1::/48\", " " \"client-class\": \"foo\", " " \"relay\": { " " \"ip-address\": \"2001:db8:3::1\"" " }" " }, " " { \"pools\": [ { \"pool\": \"2001:db8:2::/64\" } ]," " \"subnet\": \"2001:db8:2::/48\", " " \"relay\": { " " \"ip-address\": \"2001:db8:3::1\"" " }" " } " "]," "\"valid-lifetime\": 4000 }"; // Use this config to set up the server ASSERT_NO_THROW(configure(config)); // Let's get the subnet configuration objects const Subnet6Collection* subnets = CfgMgr::instance().getCurrentCfg()->getCfgSubnets6()->getAll(); ASSERT_EQ(2, subnets->size()); // Let's get them for easy reference Subnet6Ptr subnet1 = (*subnets)[0]; Subnet6Ptr subnet2 = (*subnets)[1]; ASSERT_TRUE(subnet1); ASSERT_TRUE(subnet2); Pkt6Ptr sol = createSolicit("2001:db8:1::3"); // Now pretend the packet came via one relay. Pkt6::RelayInfo relay; relay.linkaddr_ = IOAddress("2001:db8:3::1"); relay.peeraddr_ = IOAddress("fe80::1"); sol->relay_info_.push_back(relay); // This packet does not belong to class foo, so it should be rejected in // subnet[0], even though the relay-ip matches. It should be accepted in // subnet[1], because the subnet matches and there are no class // requirements. bool drop = false; EXPECT_TRUE(subnet2 == srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); // Now let's add this packet to class foo and recheck. This time it should // be accepted in the first subnet, because both class and relay-ip match. sol->addClass("foo"); EXPECT_TRUE(subnet1 == srv_.selectSubnet(sol, drop)); EXPECT_FALSE(drop); } // This test checks that it is possible to specify static reservations for // client classes. TEST_F(ClassifyTest, clientClassesInHostReservations) { Dhcp6Client client; // Initially use a DUID for which there are no reservations. As a result, // the client should be assigned a single class "router". client.setDUID("01:02:03:05"); client.setInterface("eth1"); client.requestAddress(); // Request all options we may potentially get. Otherwise, the server will // not return them, even when the client is assigned to the classes for // which these options should be sent. client.requestOption(2345); client.requestOption(D6O_NAME_SERVERS); client.requestOption(D6O_NIS_SERVERS); ASSERT_NO_THROW(configure(CONFIGS[0], *client.getServer())); // Adding this option to the client's message will cause the client to // belong to the 'router' class. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Send a message to the server. ASSERT_NO_THROW(client.doSolicit(true)); // IP forwarding should be present, but DNS and NIS servers should not. ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_)); // Modify the DUID of our client to the one for which class reservations // have been made. client.setDUID("01:02:03:04"); ASSERT_NO_THROW(client.doSolicit(true)); // This time, the client should obtain options from all three classes. ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // This should also work for Request case. ASSERT_NO_THROW(client.doSARR()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // Renew case. ASSERT_NO_THROW(client.doRenew()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // Rebind case. ASSERT_NO_THROW(client.doRebind()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // Confirm case. This must be before Information-request because the // client must have an address to confirm from one of the transactions // involving address assignment, i.e. Request, Renew or Rebind. ASSERT_NO_THROW(client.doConfirm()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); // Information-request case. ASSERT_NO_THROW(client.doInfRequest()); ASSERT_NO_FATAL_FAILURE(verifyConfig0Options(client.config_, 1, "2001:db8:1::50", "2001:db8:1::100")); } // Check classification using membership expressions. TEST_F(ClassifyTest, member) { IfaceMgrTestConfig test_config(true); NakedDhcpv6Srv srv(0); // The router class matches incoming packets with foo in a host-name // option (code 1234) and sets an ipv6-forwarding option in the response. std::string config = "{ \"interfaces-config\": {" " \"interfaces\": [ \"*\" ] }, " "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000, " "\"renew-timer\": 1000, " "\"valid-lifetime\": 4000, " "\"option-def\": [ " "{ \"name\": \"host-name\"," " \"code\": 1234," " \"type\": \"string\" }," "{ \"name\": \"ipv6-forwarding\"," " \"code\": 2345," " \"type\": \"boolean\" }]," "\"subnet6\": [ " "{ \"pools\": [ { \"pool\": \"2001:db8:1::/64\" } ], " " \"subnet\": \"2001:db8:1::/48\", " " \"interface\": \"eth1\" } ]," "\"client-classes\": [ " "{ \"name\": \"not-foo\", " " \"test\": \"not (option[host-name].text == 'foo')\"" "}," "{ \"name\": \"foo\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"true\" } ], " " \"test\": \"not member('not-foo')\"" "}," "{ \"name\": \"bar\", " " \"test\": \"option[host-name].text == 'bar'\"" "}," "{ \"name\": \"baz\", " " \"test\": \"option[host-name].text == 'baz'\"" "}," "{ \"name\": \"barz\", " " \"option-data\": [" " { \"name\": \"ipv6-forwarding\", " " \"data\": \"false\" } ], " " \"test\": \"member('bar') or member('baz')\" } ] }"; ASSERT_NO_THROW(configure(config)); // Create packets with enough to select the subnet OptionPtr clientid = generateClientId(); Pkt6Ptr query1(new Pkt6(DHCPV6_SOLICIT, 1234)); query1->setRemoteAddr(IOAddress("fe80::abcd")); query1->addOption(clientid); query1->setIface("eth1"); query1->addOption(generateIA(D6O_IA_NA, 123, 1500, 3000)); Pkt6Ptr query2(new Pkt6(DHCPV6_SOLICIT, 1234)); query2->setRemoteAddr(IOAddress("fe80::abcd")); query2->addOption(clientid); query2->setIface("eth1"); query2->addOption(generateIA(D6O_IA_NA, 234, 1500, 3000)); Pkt6Ptr query3(new Pkt6(DHCPV6_SOLICIT, 1234)); query3->setRemoteAddr(IOAddress("fe80::abcd")); query3->addOption(clientid); query3->setIface("eth1"); query3->addOption(generateIA(D6O_IA_NA, 345, 1500, 3000)); // Create and add an ORO option to queries OptionUint16ArrayPtr oro(new OptionUint16Array(Option::V6, D6O_ORO)); ASSERT_TRUE(oro); oro->addValue(2345); query1->addOption(oro); query2->addOption(oro); query3->addOption(oro); // Create and add a host-name option to the first and last queries OptionStringPtr hostname1(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname1); query1->addOption(hostname1); OptionStringPtr hostname3(new OptionString(Option::V6, 1234, "baz")); ASSERT_TRUE(hostname3); query3->addOption(hostname3); // Classify packets srv.classifyPacket(query1); srv.classifyPacket(query2); srv.classifyPacket(query3); // Check classes EXPECT_FALSE(query1->inClass("not-foo")); EXPECT_TRUE(query1->inClass("foo")); EXPECT_FALSE(query1->inClass("bar")); EXPECT_FALSE(query1->inClass("baz")); EXPECT_FALSE(query1->inClass("barz")); EXPECT_TRUE(query2->inClass("not-foo")); EXPECT_FALSE(query2->inClass("foo")); EXPECT_FALSE(query2->inClass("bar")); EXPECT_FALSE(query2->inClass("baz")); EXPECT_FALSE(query2->inClass("barz")); EXPECT_TRUE(query3->inClass("not-foo")); EXPECT_FALSE(query3->inClass("foo")); EXPECT_FALSE(query3->inClass("bar")); EXPECT_TRUE(query3->inClass("baz")); EXPECT_TRUE(query3->inClass("barz")); // Process queries AllocEngine::ClientContext6 ctx1; bool drop = false; srv.initContext(query1, ctx1, drop); ASSERT_FALSE(drop); Pkt6Ptr response1 = srv.processSolicit(ctx1); AllocEngine::ClientContext6 ctx2; srv.initContext(query2, ctx2, drop); ASSERT_FALSE(drop); Pkt6Ptr response2 = srv.processSolicit(ctx2); AllocEngine::ClientContext6 ctx3; srv.initContext(query3, ctx3, drop); ASSERT_FALSE(drop); Pkt6Ptr response3 = srv.processSolicit(ctx3); // Classification processing should add an ip-forwarding option OptionPtr opt1 = response1->getOption(2345); EXPECT_TRUE(opt1); OptionCustomPtr ipf1 = boost::dynamic_pointer_cast<OptionCustom>(opt1); ASSERT_TRUE(ipf1); EXPECT_TRUE(ipf1->readBoolean()); // But not the second query which was not classified OptionPtr opt2 = response2->getOption(2345); EXPECT_FALSE(opt2); // The third has the option but with another value OptionPtr opt3 = response3->getOption(2345); EXPECT_TRUE(opt3); OptionCustomPtr ipf3 = boost::dynamic_pointer_cast<OptionCustom>(opt3); ASSERT_TRUE(ipf3); EXPECT_FALSE(ipf3->readBoolean()); } // This test checks the precedence order in required evaluation. // This order is: shared-network > subnet > pools TEST_F(ClassifyTest, precedenceNone) { std::string config = "{" "\"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"preferred-lifetime\": 3000," "\"rebind-timer\": 2000," "\"renew-timer\": 1000," "\"client-classes\": [" " {" " \"name\": \"all\"," " \"test\": \"'' == ''\"" " }," " {" " \"name\": \"for-pool\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::1\"" " } ]" " }," " {" " \"name\": \"for-subnet\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::2\"" " } ]" " }," " {" " \"name\": \"for-network\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::3\"" " } ]" " }" "]," "\"shared-networks\": [ {" " \"name\": \"frog\"," " \"interface\": \"eth1\"," " \"subnet6\": [ { " " \"subnet\": \"2001:db8:1::/64\"," " \"id\": 1," " \"pools\": [ { " " \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\"" " } ]" " } ]" "} ]," "\"valid-lifetime\": 600" "}"; // Create a client requesting dns-servers option Dhcp6Client client; client.setInterface("eth1"); client.requestAddress(0xabca, IOAddress("2001:db8:1::28")); client.requestOption(D6O_NAME_SERVERS); // Load the config and perform a SARR configure(config, *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response EXPECT_EQ(1, client.getLeaseNum()); Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // Check dns-servers option OptionPtr opt = resp->getOption(D6O_NAME_SERVERS); EXPECT_FALSE(opt); } // This test checks the precedence order in required evaluation. // This order is: shared-network > subnet > pools TEST_F(ClassifyTest, precedencePool) { std::string config = "{" "\"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"valid-lifetime\": 600," "\"client-classes\": [" " {" " \"name\": \"all\"," " \"test\": \"'' == ''\"" " }," " {" " \"name\": \"for-pool\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::1\"" " } ]" " }," " {" " \"name\": \"for-subnet\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::2\"" " } ]" " }," " {" " \"name\": \"for-network\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::3\"" " } ]" " }" "]," "\"shared-networks\": [ {" " \"name\": \"frog\"," " \"interface\": \"eth1\"," " \"subnet6\": [ { " " \"subnet\": \"2001:db8:1::/64\"," " \"id\": 1," " \"pools\": [ { " " \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\"," " \"require-client-classes\": [ \"for-pool\" ]" " } ]" " } ]" "} ]," "\"valid-lifetime\": 600" "}"; // Create a client requesting dns-servers option Dhcp6Client client; client.setInterface("eth1"); client.requestAddress(0xabca, IOAddress("2001:db8:1::28")); client.requestOption(D6O_NAME_SERVERS); // Load the config and perform a SARR configure(config, *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response EXPECT_EQ(1, client.getLeaseNum()); Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // Check dns-servers option OptionPtr opt = resp->getOption(D6O_NAME_SERVERS); ASSERT_TRUE(opt); Option6AddrLstPtr servers = boost::dynamic_pointer_cast<Option6AddrLst>(opt); ASSERT_TRUE(servers); auto addrs = servers->getAddresses(); ASSERT_EQ(1, addrs.size()); EXPECT_EQ("2001:db8:1::1", addrs[0].toText()); } // This test checks the precedence order in required evaluation. // This order is: shared-network > subnet > pools TEST_F(ClassifyTest, precedenceSubnet) { std::string config = "{" "\"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"valid-lifetime\": 600," "\"client-classes\": [" " {" " \"name\": \"all\"," " \"test\": \"'' == ''\"" " }," " {" " \"name\": \"for-pool\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::1\"" " } ]" " }," " {" " \"name\": \"for-subnet\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::2\"" " } ]" " }," " {" " \"name\": \"for-network\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::3\"" " } ]" " }" "]," "\"shared-networks\": [ {" " \"name\": \"frog\"," " \"interface\": \"eth1\"," " \"subnet6\": [ { " " \"subnet\": \"2001:db8:1::/64\"," " \"id\": 1," " \"require-client-classes\": [ \"for-subnet\" ]," " \"pools\": [ { " " \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\"," " \"require-client-classes\": [ \"for-pool\" ]" " } ]" " } ]" "} ]," "\"valid-lifetime\": 600" "}"; // Create a client requesting dns-servers option Dhcp6Client client; client.setInterface("eth1"); client.requestAddress(0xabca, IOAddress("2001:db8:1::28")); client.requestOption(D6O_NAME_SERVERS); // Load the config and perform a SARR configure(config, *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response EXPECT_EQ(1, client.getLeaseNum()); Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // Check dns-servers option OptionPtr opt = resp->getOption(D6O_NAME_SERVERS); ASSERT_TRUE(opt); Option6AddrLstPtr servers = boost::dynamic_pointer_cast<Option6AddrLst>(opt); ASSERT_TRUE(servers); auto addrs = servers->getAddresses(); ASSERT_EQ(1, addrs.size()); EXPECT_EQ("2001:db8:1::2", addrs[0].toText()); } // This test checks the precedence order in required evaluation. // This order is: shared-network > subnet > pools TEST_F(ClassifyTest, precedenceNetwork) { std::string config = "{" "\"interfaces-config\": {" " \"interfaces\": [ \"*\" ]" "}," "\"valid-lifetime\": 600," "\"client-classes\": [" " {" " \"name\": \"all\"," " \"test\": \"'' == ''\"" " }," " {" " \"name\": \"for-pool\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::1\"" " } ]" " }," " {" " \"name\": \"for-subnet\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::2\"" " } ]" " }," " {" " \"name\": \"for-network\"," " \"test\": \"member('all')\"," " \"only-if-required\": true," " \"option-data\": [ {" " \"name\": \"dns-servers\"," " \"data\": \"2001:db8:1::3\"" " } ]" " }" "]," "\"shared-networks\": [ {" " \"name\": \"frog\"," " \"interface\": \"eth1\"," " \"require-client-classes\": [ \"for-network\" ]," " \"subnet6\": [ { " " \"subnet\": \"2001:db8:1::/64\"," " \"id\": 1," " \"require-client-classes\": [ \"for-subnet\" ]," " \"pools\": [ { " " \"pool\": \"2001:db8:1::1 - 2001:db8:1::64\"," " \"require-client-classes\": [ \"for-pool\" ]" " } ]" " } ]" "} ]," "\"valid-lifetime\": 600" "}"; // Create a client requesting dns-servers option Dhcp6Client client; client.setInterface("eth1"); client.requestAddress(0xabca, IOAddress("2001:db8:1::28")); client.requestOption(D6O_NAME_SERVERS); // Load the config and perform a SARR configure(config, *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response EXPECT_EQ(1, client.getLeaseNum()); Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // Check dns-servers option OptionPtr opt = resp->getOption(D6O_NAME_SERVERS); ASSERT_TRUE(opt); Option6AddrLstPtr servers = boost::dynamic_pointer_cast<Option6AddrLst>(opt); ASSERT_TRUE(servers); auto addrs = servers->getAddresses(); ASSERT_EQ(1, addrs.size()); EXPECT_EQ("2001:db8:1::3", addrs[0].toText()); } // This test checks the complex membership from HA with server1 telephone. TEST_F(ClassifyTest, server1Telephone) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestAddress(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Add server1 client.addClass("server1"); // Load the config and perform a SARR configure(CONFIGS[1], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The address is from the first pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1:1::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server1 computer. TEST_F(ClassifyTest, server1Computer) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestAddress(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar")); client.addExtraOption(hostname); // Add server1 client.addClass("server1"); // Load the config and perform a SARR configure(CONFIGS[1], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The address is from the second pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1:2::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server2 telephone. TEST_F(ClassifyTest, server2Telephone) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestAddress(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Add server2 client.addClass("server2"); // Load the config and perform a SARR configure(CONFIGS[1], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The address is from the third pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1:3::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server2 computer. TEST_F(ClassifyTest, server2Computer) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestAddress(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar")); client.addExtraOption(hostname); // Add server2 client.addClass("server2"); // Load the config and perform a SARR configure(CONFIGS[1], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The address is from the forth pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1:4::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server1 telephone // with prefixes. TEST_F(ClassifyTest, pDserver1Telephone) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestPrefix(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Add server1 client.addClass("server1"); // Load the config and perform a SARR configure(CONFIGS[2], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The prefix is from the first pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:1::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server1 computer // with prefix. TEST_F(ClassifyTest, pDserver1Computer) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestPrefix(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar")); client.addExtraOption(hostname); // Add server1 client.addClass("server1"); // Load the config and perform a SARR configure(CONFIGS[2], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The prefix is from the second pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:2::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server2 telephone // with prefixes. TEST_F(ClassifyTest, pDserver2Telephone) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestPrefix(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); client.addExtraOption(hostname); // Add server2 client.addClass("server2"); // Load the config and perform a SARR configure(CONFIGS[2], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The prefix is from the third pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:3::", lease_client.addr_.toText()); } // This test checks the complex membership from HA with server2 computer // with prefix. TEST_F(ClassifyTest, pDserver2Computer) { // Create a client. Dhcp6Client client; client.setInterface("eth1"); ASSERT_NO_THROW(client.requestPrefix(0xabca0)); // Add option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "bar")); client.addExtraOption(hostname); // Add server2 client.addClass("server2"); // Load the config and perform a SARR configure(CONFIGS[2], *client.getServer()); ASSERT_NO_THROW(client.doSARR()); // Check response Pkt6Ptr resp = client.getContext().response_; ASSERT_TRUE(resp); // The prefix is from the forth pool. ASSERT_EQ(1, client.getLeaseNum()); Lease6 lease_client = client.getLease(0); EXPECT_EQ("2001:db8:4::", lease_client.addr_.toText()); } // This test checks the handling for the DROP special class. TEST_F(ClassifyTest, dropClass) { Dhcp6Client client; client.setDUID("01:02:03:05"); client.setInterface("eth1"); client.requestAddress(); // Configure DHCP server. ASSERT_NO_THROW(configure(CONFIGS[3], *client.getServer())); // Send a message to the server. ASSERT_NO_THROW(client.doSolicit(true)); // No option: no drop. EXPECT_TRUE(client.getContext().response_); // Retry with an option matching the DROP class. Dhcp6Client client2; // Add the host-name option. OptionStringPtr hostname(new OptionString(Option::V6, 1234, "foo")); ASSERT_TRUE(hostname); client2.addExtraOption(hostname); // Send a message to the server. ASSERT_NO_THROW(client2.doSolicit(true)); // Option, dropped. EXPECT_FALSE(client2.getContext().response_); // There should also be pkt6-receive-drop stat bumped up. stats::StatsMgr& mgr = stats::StatsMgr::instance(); stats::ObservationPtr drop_stat = mgr.getObservation("pkt6-receive-drop"); // This statistic must be present and must be set to 1. ASSERT_TRUE(drop_stat); EXPECT_EQ(1, drop_stat->getInteger().first); } } // end of anonymous namespace
74,881
26,670
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { PluginWindowState::PluginWindowState (Edit& e) : edit (e), engine (e.engine), windowLocked (engine.getPluginManager().areGUIsLockedByDefault()) { } void PluginWindowState::deleteWindow() { pluginWindow.reset(); } void PluginWindowState::incRefCount() { TRACKTION_ASSERT_MESSAGE_THREAD ++windowShowerCount; startTimer (100); } void PluginWindowState::decRefCount() { TRACKTION_ASSERT_MESSAGE_THREAD --windowShowerCount; startTimer (100); } void PluginWindowState::showWindowExplicitly() { TRACKTION_ASSERT_MESSAGE_THREAD wasExplicitlyClosed = false; stopTimer(); showWindow(); } void PluginWindowState::closeWindowExplicitly() { TRACKTION_ASSERT_MESSAGE_THREAD if (pluginWindow && pluginWindow->isVisible()) { wasExplicitlyClosed = true; deleteWindow(); stopTimer(); } } bool PluginWindowState::isWindowShowing() const { return pluginWindow != nullptr && pluginWindow->isVisible(); } void PluginWindowState::recreateWindowIfShowing() { deleteWindow(); startTimer (100); } void PluginWindowState::hideWindowForShutdown() { deleteWindow(); stopTimer(); } void PluginWindowState::pickDefaultWindowBounds() { lastWindowBounds = { 100, 100, 600, 500 }; if (auto focused = juce::Component::getCurrentlyFocusedComponent()) lastWindowBounds.setPosition (focused->getTopLevelComponent()->getPosition() + juce::Point<int> (80, 80)); } void PluginWindowState::showWindow() { if (! pluginWindow) { // Ensure at least 40px of the window is on screen const auto displayRects = [] { RectangleList<int> trimmedDisplays; for (auto rect : Desktop::getInstance().getDisplays().getRectangleList (true)) trimmedDisplays.addWithoutMerging (rect.withTrimmedLeft (100).withTrimmedRight (100).withTrimmedBottom (100)); return trimmedDisplays; }(); const bool windowBoundsIsOnScreen = displayRects.intersectsRectangle (lastWindowBounds); if (lastWindowBounds.isEmpty() || ! windowBoundsIsOnScreen) pickDefaultWindowBounds(); WeakReference<Component> oldFocus (Component::getCurrentlyFocusedComponent()); pluginWindow = engine.getUIBehaviour().createPluginWindow (*this); if (oldFocus != nullptr) oldFocus->grabKeyboardFocus(); } if (pluginWindow) { windowOpenTime = Time::getCurrentTime(); pluginWindow->setVisible (true); pluginWindow->toFront (false); } } void PluginWindowState::pluginClicked (const MouseEvent& e) { bool isShowing = isWindowShowing(); if (e.getNumberOfClicks() >= 2) { if ((Time::getCurrentTime() - windowOpenTime).inMilliseconds() < 300) return; if (isShowing) closeWindowExplicitly(); else showWindowExplicitly(); } else if (! (isShowing || engine.getPluginManager().doubleClickToOpenWindows())) { showWindowExplicitly(); } } void PluginWindowState::timerCallback() { stopTimer(); if (windowShowerCount > 0) { if ((pluginWindow == nullptr || ! pluginWindow->isVisible()) && ! (engine.getPluginManager().doubleClickToOpenWindows() || wasExplicitlyClosed)) showWindow(); } else if (! windowLocked) { deleteWindow(); } } }
4,010
1,300
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1999 - 1999 // // File: evtsink.cpp // //-------------------------------------------------------------------------- #include "stdafx.h" #include "winnls.h" #include "AMC.h" #include "AMCDoc.h" #include "AMCView.h" #include "histlist.h" #include "exdisp.h" // for the IE dispatch interfaces. #include "websnk.h" #include "evtsink.h" #include "WebCtrl.h" #include "cstr.h" #include "constatbar.h" #ifdef DBG CTraceTag tagWebEventSink(TEXT("Web View"), TEXT("Web Event Sink")); #endif // DBG CWebEventSink::CWebEventSink() : m_bBrowserBackEnabled(false), m_bBrowserForwardEnabled(false), m_pWebViewControl(NULL), m_pStatusBar(NULL), m_pwndProgressCtrl(NULL), m_pHistoryList(NULL) { } SC CWebEventSink::ScInitialize(CAMCWebViewCtrl *pWebViewControl) { DECLARE_SC(sc, TEXT("CWebEventSink::ScInitialize")); sc = ScCheckPointers(pWebViewControl); if(sc) return sc; m_pWebViewControl = pWebViewControl; CAMCView* pAMCView = dynamic_cast<CAMCView*>(pWebViewControl->GetParent()); CFrameWnd* pwndParentFrame = pWebViewControl->GetParentFrame(); sc = ScCheckPointers(pAMCView, pwndParentFrame); if(sc) return sc; m_pHistoryList = pAMCView->GetHistoryList(); sc = ScCheckPointers(m_pHistoryList); if(sc) return sc; // Create the status bar for this instance of the web control m_pStatusBar = dynamic_cast<CConsoleStatusBar*>(pwndParentFrame); sc = ScCheckPointers(m_pStatusBar, E_UNEXPECTED); if(sc) return sc; // find the progress control on the status bar for the parent frame CAMCStatusBar* pwndStatusBar = reinterpret_cast<CAMCStatusBar*>(pwndParentFrame->GetMessageBar()); sc = ScCheckPointers(pwndStatusBar); if(sc) return sc; ASSERT_KINDOF (CAMCStatusBar, pwndStatusBar); m_pwndProgressCtrl = pwndStatusBar->GetStatusProgressCtrlHwnd(); m_fLastTextWasEmpty = false; return sc; } CWebEventSink::~CWebEventSink() { /* * clear the status bar text */ if (m_pStatusBar != NULL) m_pStatusBar->ScSetStatusText(NULL); } void CWebEventSink::SetActiveTo(BOOL /*bState*/) { } STDMETHODIMP_(void) CWebEventSink::BeforeNavigate(BSTR URL, long Flags, BSTR TargetFrameName, VARIANT* PostData, BSTR Headers, VARIANT_BOOL* Cancel) { Trace(tagWebEventSink, TEXT("BeginNavigate(URL:%s, flags:%0X, targetfrm:%s, headers:%s)\n"), URL, Flags, TargetFrameName, Headers); bool bPageBreak = IsPageBreak(URL); m_pHistoryList->OnPageBreakStateChange(bPageBreak); m_pHistoryList->UpdateWebBar (HB_STOP, TRUE); // turn on "stop" button } STDMETHODIMP_(void) CWebEventSink::CommandStateChange(int Command, VARIANT_BOOL Enable) { if(Command == CSC_NAVIGATEFORWARD) { m_bBrowserForwardEnabled = Enable; } else if(Command == CSC_NAVIGATEBACK) { m_bBrowserBackEnabled = Enable; } } STDMETHODIMP_(void) CWebEventSink::DownloadBegin() { Trace(tagWebEventSink, TEXT("DownloadBegin()")); } STDMETHODIMP_(void) CWebEventSink::DownloadComplete() { Trace(tagWebEventSink, TEXT("DownloadComplete()")); } STDMETHODIMP_(void) CWebEventSink::FrameBeforeNavigate(BSTR URL, long Flags, BSTR TargetFrameName, VARIANT* PostData, BSTR Headers, VARIANT_BOOL* Cancel) { m_pHistoryList->UpdateWebBar (HB_STOP, TRUE); // turn on "stop" button } STDMETHODIMP_(void) CWebEventSink::FrameNavigateComplete(BSTR URL) { } STDMETHODIMP_(void) CWebEventSink::FrameNewWindow(BSTR URL, long Flags, BSTR TargetFrameName, VARIANT* PostData, BSTR Headers, VARIANT_BOOL* Processed) { } bool CWebEventSink::IsPageBreak(BSTR URL) { USES_CONVERSION; CStr strURL = OLE2T(URL); strURL.MakeLower(); bool bPageBreak = (_tcsstr(strURL, PAGEBREAK_URL) != NULL); return bPageBreak; } STDMETHODIMP_(void) CWebEventSink::NavigateComplete(BSTR URL) { Trace(tagWebEventSink, TEXT("NavigateComplete()\n")); // Set progress bar position to 0 m_pwndProgressCtrl->SetPos (0); bool bPageBreak = IsPageBreak(URL); m_pHistoryList->OnPageBreakStateChange(bPageBreak); // send the browser state across AFTER sending the OnPageBreakStateChange and BEFORE // the OnPageBreak. m_pHistoryList->OnBrowserStateChange(m_bBrowserForwardEnabled, m_bBrowserBackEnabled); if(bPageBreak) { // Extract the Page Break ID. Since bPageBreak is true, the URL // is guaranteed to be prefixed with PAGEBREAK_URL USES_CONVERSION; LPCTSTR szPageBreakID = OLE2CT(URL) + _tcslen(PAGEBREAK_URL); int nPageBreakID = _tstoi(szPageBreakID); //PageBreakIDs start with 1; _tstoi returns 0 if it can't convert ASSERT(nPageBreakID != 0); m_pHistoryList->ScOnPageBreak(nPageBreakID); } } STDMETHODIMP_(void) CWebEventSink::NewWindow(BSTR URL, long Flags, BSTR TargetFrameName, VARIANT* PostData, BSTR Headers, BSTR Referrer) { } STDMETHODIMP_(void) CWebEventSink::Progress(long Progress, long ProgressMax) { Trace(tagWebEventSink, TEXT("Progress(Progress:%ld ProgressMax:%ld)\n"), Progress, ProgressMax); // display progress only if the web view is visible. if(m_pWebViewControl && m_pWebViewControl->IsWindowVisible()) { m_pwndProgressCtrl->SetRange (0, ProgressMax); m_pwndProgressCtrl->SetPos (Progress); } // maintain "stop" button m_pHistoryList->UpdateWebBar (HB_STOP, ProgressMax != 0); } STDMETHODIMP_(void) CWebEventSink::PropertyChange(BSTR szProperty) { } STDMETHODIMP_(void) CWebEventSink::Quit(VARIANT_BOOL* pCancel) { Trace(tagWebEventSink, TEXT("Quit()")); } STDMETHODIMP_(void) CWebEventSink::StatusTextChange(BSTR bstrText) { // display progress only if the web view is visible. if(m_pWebViewControl && m_pWebViewControl->IsWindowVisible()) { bool fThisTextIsEmpty = ((bstrText == NULL) || (bstrText[0] == 0)); if (m_fLastTextWasEmpty && fThisTextIsEmpty) return; m_fLastTextWasEmpty = fThisTextIsEmpty; Trace(tagWebEventSink, TEXT("StatusTextChange(%s)"), bstrText); USES_CONVERSION; m_pStatusBar->ScSetStatusText(W2T( bstrText)); } } STDMETHODIMP_(void) CWebEventSink::TitleChange(BSTR Text) { Trace(tagWebEventSink, TEXT("TitleChange(%s)"), Text); } STDMETHODIMP_(void) CWebEventSink::WindowActivate() { } STDMETHODIMP_(void) CWebEventSink::WindowMove() { } STDMETHODIMP_(void) CWebEventSink::WindowResize() { }
6,982
2,566