text
string
size
int64
token_count
int64
/**************************************************************************** ** ** Copyright (C) 2015 The Qt Company Ltd. ** Contact: http://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see http://www.qt.io/terms-conditions. For further ** information use the contact form at http://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** As a special exception, The Qt Company gives you certain additional ** rights. These rights are described in The Qt Company LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <qsize.h> class tst_QSize : public QObject { Q_OBJECT private slots: void getSetCheck(); void scale(); void expandedTo(); void expandedTo_data(); void boundedTo_data(); void boundedTo(); void transpose_data(); void transpose(); }; // Testing get/set functions void tst_QSize::getSetCheck() { QSize obj1; // int QSize::width() // void QSize::setWidth(int) obj1.setWidth(0); QCOMPARE(0, obj1.width()); obj1.setWidth(INT_MIN); QCOMPARE(INT_MIN, obj1.width()); obj1.setWidth(INT_MAX); QCOMPARE(INT_MAX, obj1.width()); // int QSize::height() // void QSize::setHeight(int) obj1.setHeight(0); QCOMPARE(0, obj1.height()); obj1.setHeight(INT_MIN); QCOMPARE(INT_MIN, obj1.height()); obj1.setHeight(INT_MAX); QCOMPARE(INT_MAX, obj1.height()); QSizeF obj2; // qreal QSizeF::width() // void QSizeF::setWidth(qreal) obj2.setWidth(0.0); QCOMPARE(0.0, obj2.width()); obj2.setWidth(1.1); QCOMPARE(1.1, obj2.width()); // qreal QSizeF::height() // void QSizeF::setHeight(qreal) obj2.setHeight(0.0); QCOMPARE(0.0, obj2.height()); obj2.setHeight(1.1); QCOMPARE(1.1, obj2.height()); } void tst_QSize::scale() { QSize t1( 10, 12 ); t1.scale( 60, 60, Qt::IgnoreAspectRatio ); QCOMPARE( t1, QSize(60, 60) ); QSize t2( 10, 12 ); t2.scale( 60, 60, Qt::KeepAspectRatio ); QCOMPARE( t2, QSize(50, 60) ); QSize t3( 10, 12 ); t3.scale( 60, 60, Qt::KeepAspectRatioByExpanding ); QCOMPARE( t3, QSize(60, 72) ); QSize t4( 12, 10 ); t4.scale( 60, 60, Qt::KeepAspectRatio ); QCOMPARE( t4, QSize(60, 50) ); QSize t5( 12, 10 ); t5.scale( 60, 60, Qt::KeepAspectRatioByExpanding ); QCOMPARE( t5, QSize(72, 60) ); // test potential int overflow QSize t6(88473, 88473); t6.scale(141817, 141817, Qt::KeepAspectRatio); QCOMPARE(t6, QSize(141817, 141817)); QSize t7(800, 600); t7.scale(400, INT_MAX, Qt::KeepAspectRatio); QCOMPARE(t7, QSize(400, 300)); QSize t8(800, 600); t8.scale(INT_MAX, 150, Qt::KeepAspectRatio); QCOMPARE(t8, QSize(200, 150)); QSize t9(600, 800); t9.scale(300, INT_MAX, Qt::KeepAspectRatio); QCOMPARE(t9, QSize(300, 400)); QSize t10(600, 800); t10.scale(INT_MAX, 200, Qt::KeepAspectRatio); QCOMPARE(t10, QSize(150, 200)); QSize t11(0, 0); t11.scale(240, 200, Qt::IgnoreAspectRatio); QCOMPARE(t11, QSize(240, 200)); QSize t12(0, 0); t12.scale(240, 200, Qt::KeepAspectRatio); QCOMPARE(t12, QSize(240, 200)); QSize t13(0, 0); t13.scale(240, 200, Qt::KeepAspectRatioByExpanding); QCOMPARE(t13, QSize(240, 200)); } void tst_QSize::expandedTo_data() { QTest::addColumn<QSize>("input1"); QTest::addColumn<QSize>("input2"); QTest::addColumn<QSize>("expected"); QTest::newRow("data0") << QSize(10,12) << QSize(6,4) << QSize(10,12); QTest::newRow("data1") << QSize(0,0) << QSize(6,4) << QSize(6,4); // This should pick the highest of w,h components independently of each other, // thus the results don't have to be equal to neither input1 nor input2. QTest::newRow("data3") << QSize(6,4) << QSize(4,6) << QSize(6,6); } void tst_QSize::expandedTo() { QFETCH( QSize, input1); QFETCH( QSize, input2); QFETCH( QSize, expected); QCOMPARE( input1.expandedTo(input2), expected); } void tst_QSize::boundedTo_data() { QTest::addColumn<QSize>("input1"); QTest::addColumn<QSize>("input2"); QTest::addColumn<QSize>("expected"); QTest::newRow("data0") << QSize(10,12) << QSize(6,4) << QSize(6,4); QTest::newRow("data1") << QSize(0,0) << QSize(6,4) << QSize(0,0); // This should pick the lowest of w,h components independently of each other, // thus the results don't have to be equal to neither input1 nor input2. QTest::newRow("data3") << QSize(6,4) << QSize(4,6) << QSize(4,4); } void tst_QSize::boundedTo() { QFETCH( QSize, input1); QFETCH( QSize, input2); QFETCH( QSize, expected); QCOMPARE( input1.boundedTo(input2), expected); } void tst_QSize::transpose_data() { QTest::addColumn<QSize>("input1"); QTest::addColumn<QSize>("expected"); QTest::newRow("data0") << QSize(10,12) << QSize(12,10); QTest::newRow("data1") << QSize(0,0) << QSize(0,0); QTest::newRow("data3") << QSize(6,4) << QSize(4,6); } void tst_QSize::transpose() { QFETCH( QSize, input1); QFETCH( QSize, expected); // transpose() works only inplace and does not return anything, so we must do the operation itself before the compare. input1.transpose(); QCOMPARE(input1 , expected); } QTEST_APPLESS_MAIN(tst_QSize) #include "tst_qsize.moc"
6,367
2,625
// -*- C++ -*- // Copyright (C) Dmitry Igrishin // For conditions of distribution and use, see files LICENSE.txt or fcgi.hpp #ifndef DMITIGR_FCGI_LISTENER_OPTIONS_HPP #define DMITIGR_FCGI_LISTENER_OPTIONS_HPP #include "dmitigr/fcgi/dll.hpp" #include "dmitigr/fcgi/types_fwd.hpp" #include <dmitigr/misc/filesystem.hpp> #include <dmitigr/net/types_fwd.hpp> #include <memory> #include <optional> #include <string> namespace dmitigr::fcgi { /** * @brief FastCGI Listener options. */ class Listener_options { public: /** * @brief The destructor. */ virtual ~Listener_options() = default; /// @name Constructors /// @{ #ifdef _WIN32 /** * @returns A new instance of the options for listeners of * Windows Named Pipes (WNP). * * @param pipe_name - the pipe name. * * @par Effects * `(endpoint()->communication_mode() == Communication_mode::wnp)`. */ static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::string pipe_name); #else /** * @returns A new instance of the options for listeners of * Unix Domain Sockets (UDS). * * @param path - the path to the socket. * @param backlog - the maximum size of the queue of pending connections. * * @par Effects * `(endpoint()->communication_mode() == Communication_mode::uds)`. */ static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::filesystem::path path, int backlog); #endif /** * @overload * * @returns A new instance of the options for listeners of network. * * @param address - IPv4 or IPv6 address to use for binding on. * @param port - the port number to use for binding on. * @param backlog - the maximum size of the queue of pending connections. * * @par Requires * `(port > 0)`. * * @par Effects * `(endpoint()->communication_mode() == Communication_mode::net)`. */ static DMITIGR_FCGI_API std::unique_ptr<Listener_options> make(std::string address, int port, int backlog); /** * @returns A new instance of the Listener initialized with this instance. * * @see Listener::make(). */ virtual std::unique_ptr<Listener> make_listener() const = 0; /** * @returns The copy of this instance. */ virtual std::unique_ptr<Listener_options> to_listener_options() const = 0; /// @} /** * @returns The endpoint identifier. */ virtual const net::Endpoint& endpoint() const = 0; /** * @returns The value of backlog if the communication mode of the endpoint is * not `Communication_mode::wnp`, or `std::nullopt` otherwise. */ virtual std::optional<int> backlog() const = 0; private: friend detail::iListener_options; Listener_options() = default; }; } // namespace dmitigr::fcgi #ifdef DMITIGR_FCGI_HEADER_ONLY #include "dmitigr/fcgi/listener_options.cpp" #endif #endif // DMITIGR_FCGI_LISTENER_OPTIONS_HPP
2,860
996
#include "listwrapperobjects.h" #include "checkinvitation.h" namespace MoodBox { CheckInvitationData::CheckInvitationData() : QSharedData() { } CheckInvitationData::CheckInvitationData(QString code) : QSharedData() { this->code = code; } CheckInvitationData::~CheckInvitationData() { } CheckInvitation::CheckInvitation() : TransportableObject() { } CheckInvitation::CheckInvitation(QString code) : TransportableObject() { d = new CheckInvitationData(code); } CheckInvitation::~CheckInvitation() { } QString CheckInvitation::getCode() const { Q_ASSERT_X(!isNull(), "CheckInvitation::getCode", "Getter call on object which isNull"); return this->d->code; } void CheckInvitation::setCode(QString value) { Q_ASSERT_X(!isNull(), "CheckInvitation::setCode", "Setter call on object which isNull"); this->d->code = value; } qint32 CheckInvitation::getRepresentedTypeId() { return 10091; } qint32 CheckInvitation::getTypeId() const { return 10091; } void CheckInvitation::writeProperties(PropertyWriter *writer) { TransportableObject::writeProperties(writer); writer->writeProperty(this, 1, this->d->code); } PropertyReadResult CheckInvitation::readProperty(qint32 propertyId, qint32 typeId, PropertyReader *reader) { PropertyReadResult result = TransportableObject::readProperty(propertyId, typeId, reader); if(result.getIsPropertyFound()) return result; switch(propertyId) { case 1: this->d->code = reader->readString(); return PropertyReadResult(true); } return PropertyReadResult(false); } }
1,603
513
#include "execution/compiler/output_checker.h" #include "gtest/gtest.h" #include "spdlog/fmt/fmt.h" #include "storage/index/bplustree_index.h" #include "storage/index/index.h" #include "test_util/end_to_end_test.h" #include "test_util/test_harness.h" namespace noisepage::test { class CreateIndexOptionsTest : public EndToEndTest { public: void SetUp() override { EndToEndTest::SetUp(); auto exec_ctx = MakeExecCtx(); GenerateTestTables(exec_ctx.get()); } }; // NOLINTNEXTLINE TEST_F(CreateIndexOptionsTest, BPlusTreeOptions) { RunQuery("CREATE INDEX test_2_idx_upper ON test_2 (col1) WITH (BPLUSTREE_INNER_NODE_UPPER_THRESHOLD = 256)"); RunQuery("CREATE INDEX test_2_idx_lower ON test_2 (col1) WITH (BPLUSTREE_INNER_NODE_LOWER_THRESHOLD = 4)"); RunQuery( "CREATE INDEX test_2_idx_both ON test_2 (col1) WITH (BPLUSTREE_INNER_NODE_UPPER_THRESHOLD = 256, " "BPLUSTREE_INNER_NODE_LOWER_THRESHOLD = 4)"); auto test_2_idx_upper = accessor_->GetIndex(accessor_->GetIndexOid("test_2_idx_upper")); auto test_2_idx_lower = accessor_->GetIndex(accessor_->GetIndexOid("test_2_idx_lower")); auto test_2_idx_both = accessor_->GetIndex(accessor_->GetIndexOid("test_2_idx_both")); ASSERT_TRUE(test_2_idx_upper); ASSERT_TRUE(test_2_idx_lower); ASSERT_TRUE(test_2_idx_both); ASSERT_EQ(test_2_idx_upper->Type(), storage::index::IndexType::BPLUSTREE); ASSERT_EQ(test_2_idx_lower->Type(), storage::index::IndexType::BPLUSTREE); ASSERT_EQ(test_2_idx_both->Type(), storage::index::IndexType::BPLUSTREE); auto test_2_idx_upper_bpt_index = test_2_idx_upper.CastManagedPointerTo<storage::index::BPlusTreeIndex<storage::index::CompactIntsKey<8>>>(); auto test_2_idx_lower_bpt_index = test_2_idx_lower.CastManagedPointerTo<storage::index::BPlusTreeIndex<storage::index::CompactIntsKey<8>>>(); auto test_2_idx_both_bpt_index = test_2_idx_both.CastManagedPointerTo<storage::index::BPlusTreeIndex<storage::index::CompactIntsKey<8>>>(); ASSERT_EQ(test_2_idx_upper_bpt_index->GetInnerNodeSizeUpperThreshold(), 256); ASSERT_EQ(test_2_idx_lower_bpt_index->GetInnerNodeSizeLowerThreshold(), 4); ASSERT_EQ(test_2_idx_both_bpt_index->GetInnerNodeSizeUpperThreshold(), 256); ASSERT_EQ(test_2_idx_both_bpt_index->GetInnerNodeSizeLowerThreshold(), 4); } } // namespace noisepage::test
2,340
935
#include "PhongDivider/PhongDivider.hpp" using namespace castor3d; namespace Phong { namespace { castor::Point3f barycenter( float u , float v , castor::Point3f const & p1 , castor::Point3f const & p2 , castor::Point3f const & p3 ) { float w = 1 - u - v; CU_Ensure( std::abs( u + v + w - 1.0 ) < 0.0001 ); return castor::Point3f{ p1 * u + p2 * v + p3 * w }; } } Patch::Patch( Plane const & p1 , Plane const & p2 , Plane const & p3 ) : pi( p1 ) , pj( p2 ) , pk( p3 ) { } castor::String const Subdivider::Name = cuT( "Phong Divider" ); castor::String const Subdivider::Type = cuT( "phong" ); Subdivider::Subdivider() : castor3d::MeshSubdivider() , m_occurences( 1 ) { } Subdivider::~Subdivider() { cleanup(); } MeshSubdividerUPtr Subdivider::create() { return std::make_unique< Subdivider >(); } void Subdivider::cleanup() { castor3d::MeshSubdivider::cleanup(); } void Subdivider::subdivide( SubmeshSPtr submesh , int occurences , bool generateBuffers , bool threaded ) { m_occurences = occurences; m_submesh = submesh; m_generateBuffers = generateBuffers; m_submesh->computeContainers(); doInitialise(); m_threaded = threaded; if ( threaded ) { m_thread = std::make_shared< std::thread >( std::bind( &Subdivider::doSubdivideThreaded, this ) ); } else { doSubdivide(); doAddGeneratedFaces(); doSwapBuffers(); } } void Subdivider::doSubdivide() { auto facesArray = m_indexMapping->getFaces(); m_indexMapping->clearFaces(); std::map< uint32_t, Plane > posnml; uint32_t i = 0; for ( auto const & point : m_submesh->getPoints() ) { castor::Point3f position = point.pos; castor::Point3f normal = point.nml; posnml.emplace( i++, Plane{ castor::PlaneEquation( normal, position ), position } ); } for ( auto face : facesArray ) { doComputeFaces( 0.0, 0.0, 1.0, 1.0, m_occurences, Patch( posnml[face[0]], posnml[face[1]], posnml[face[2]] ) ); } for ( auto & point : m_points ) { m_submesh->getPoint( point->m_index ).pos = point->m_vertex.pos; } facesArray.clear(); } void Subdivider::doInitialise() { for ( uint32_t i = 0; i < m_submesh->getPointsCount(); ++i ) { m_points.emplace_back( std::make_unique< SubmeshVertex >( SubmeshVertex{ i, m_submesh->getPoint( i ) } ) ); } castor3d::MeshSubdivider::doInitialise(); m_indexMapping = m_submesh->getComponent< TriFaceMapping >(); } void Subdivider::doAddGeneratedFaces() { for ( auto const & face : m_arrayFaces ) { m_indexMapping->addFace( face[0], face[1], face[2] ); } } void Subdivider::doComputeFaces( float u0 , float v0 , float u2 , float v2 , int occurences , Patch const & patch ) { float u1 = ( u0 + u2 ) / 2.0f; float v1 = ( v0 + v2 ) / 2.0f; if ( occurences > 1 ) { doComputeFaces( u0, v0, u1, v1, occurences - 1, patch ); doComputeFaces( u0, v1, u1, v2, occurences - 1, patch ); doComputeFaces( u1, v0, u2, v1, occurences - 1, patch ); doComputeFaces( u1, v1, u0, v0, occurences - 1, patch ); } else { auto & a = doComputePoint( u0, v0, patch ); auto & b = doComputePoint( u2, v0, patch ); auto & c = doComputePoint( u0, v2, patch ); auto & d = doComputePoint( u1, v0, patch ); auto & e = doComputePoint( u1, v1, patch ); auto & f = doComputePoint( u0, v1, patch ); doSetTextCoords( a, b, c, d, e, f ); } } castor3d::SubmeshVertex & Subdivider::doComputePoint( float u, float v, Patch const & patch ) { castor::Point3f b = barycenter( u, v, patch.pi.point, patch.pj.point, patch.pk.point ); castor::Point3f pi = patch.pi.plane.project( b ); castor::Point3f pj = patch.pj.plane.project( b ); castor::Point3f pk = patch.pk.plane.project( b ); castor::Point3f point( barycenter( u, v, pi, pj, pk ) ); return doTryAddPoint( point ); } }
3,869
1,789
/** Definition for a binary tree node. */ //https://leetcode.com/problems/same-tree/ #include<bits/stdc++.h> using namespace std; 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) {} }; class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if(p==NULL && q==NULL) return true; if(p==NULL || q==NULL) return false; return (p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right)); } };
701
254
/* * Copyright (C) 2005-2019 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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. */ /************************************************************************************************************ * * * ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo * * o * * o * * o * * o * * o ooooooo ooooooo o o oo * * o o o o o o o o o o * * o o o o o o o o o o * * o o o o o o o o o o * * o o o oooo o o o o o o * * o o o o o o o o o * * o o o o o o o o o o * * oo oooooooo o o o oooooo o oooo * * o * * o * * o o * * o o oooo o o oooo * * o o o o o o * * o o ooo o o ooo * * o o o o o * * ooooo oooo o ooooo oooo * * o * * * ************************************************************************************************************ * * * Author: CS Systemes d'Information (France) * * * ************************************************************************************************************ * HISTORIQUE * * * * VERSION : 1-0-0 : <TypeFT> : <NumFT> : 15 nov. 2017 : Creation * * * FIN-HISTORIQUE * * * * $Id$ * * ************************************************************************************************************/ #include "otbWrapperApplication.h" #include "otbWrapperApplicationFactory.h" #include "otbMultiChannelExtractROI.h" #include "otbMultiToMonoChannelExtractROI.h" #include "otbWrapperListViewParameter.h" #include "vnsMacro.h" #define CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(Tin, Tout, image_base) \ { \ Tin* img = dynamic_cast<Tin*>(image_base); \ \ if (img) \ { \ DoExtractVector<Tin, Tout>(img); \ return; \ \ } \ } \ #define CAST_AND_EXTRACT_IMAGE_BASE(Tin, Tout, image_base) \ { \ Tin* img = dynamic_cast<Tin*>(image_base); \ \ if (img) \ { \ DoExtract<Tin, Tout>(img); \ return; \ \ } \ } \ namespace vns { namespace Wrapper { using namespace otb::Wrapper; class ExtractChannels : public Application { public: /** Standard class typedefs. */ typedef ExtractChannels Self; typedef Application Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(ExtractChannels, otb::Application); protected: ExtractChannels() { } private: void DoInit() override { SetName("ExtractChannels"); SetDescription("Extract channels defined by the user."); // Documentation SetDocLongDescription( "This application extracts a list of channels with " "user parameters. "); SetDocLimitations("None"); SetDocAuthors("MAJA-OTB-Team"); SetDocSeeAlso(" "); AddDocTag(Tags::Manip); // Set parameter input AddParameter(ParameterType_InputImage, "in", "Input Image"); SetParameterDescription("in", "Image to be processed."); AddParameter(ParameterType_OutputImage, "out", "Output Image"); SetParameterDescription("out", "Region of interest from the input image"); SetParameterOutputImagePixelType("out",ImagePixelType_double); // Channelist Parameters AddParameter(ParameterType_ListView, "cl", "Output Image channels"); SetParameterDescription("cl", "Channels to write in the output image."); AddRAMParameter(); SetOfficialDocLink(); } void DoUpdateParameters() override { if (HasValue("in")) { ImageBaseType* inImage = GetParameterImageBase("in",0); unsigned int nbComponents = inImage->GetNumberOfComponentsPerPixel(); ListViewParameter* clParam = dynamic_cast<ListViewParameter*>(GetParameterByKey("cl")); // Update the values of the channels to be selected if nbComponents is changed if (clParam != nullptr && clParam->GetNbChoices() != nbComponents) { ClearChoices("cl"); for (unsigned int idx = 0; idx < nbComponents; ++idx) { std::ostringstream key, item; key << "cl.channel" << idx + 1; item << "Channel" << idx + 1; AddChoice(key.str(), item.str()); } } } } template <typename TInputImage, typename TOutputImage> void DoExtractVector(TInputImage* in) { //MultiChannels typedef otb::MultiChannelExtractROI<typename TInputImage::InternalPixelType, typename TOutputImage::InternalPixelType> ExtractROIFilterType; typename ExtractROIFilterType::Pointer extractROIFilter = ExtractROIFilterType::New(); extractROIFilter->SetInput(in); for (unsigned int idx = 0; idx < GetSelectedItems("cl").size(); ++idx) { extractROIFilter->SetChannel(GetSelectedItems("cl")[idx] + 1); } SetParameterOutputImage<TOutputImage>("out", extractROIFilter->GetOutput()); m_ExtractFilter = extractROIFilter; } template <typename TInputImage, typename TOutputImage> void DoExtract(TInputImage* in) { //MonoChannel typedef otb::MultiToMonoChannelExtractROI<typename TInputImage::InternalPixelType, typename TOutputImage::InternalPixelType> MonoChannelExtractROIFilterType; typename MonoChannelExtractROIFilterType::Pointer extractROIFilter = MonoChannelExtractROIFilterType::New(); extractROIFilter->SetInput(in); extractROIFilter->SetChannel(GetSelectedItems("cl")[0] + 1); SetParameterOutputImage<TOutputImage>("out", extractROIFilter->GetOutput()); m_ExtractFilter = extractROIFilter; } void DoExecute() override { // Get input image pointers ImageBaseType* l_inPtr = GetParameterImageBase("in",0); // Guess the image type std::string className(l_inPtr->GetNameOfClass()); vnsLogDebugMacro("Resampling needed"); if (className == "VectorImage") { if (GetSelectedItems("cl").size() == 1) { vnsLogDebugMacro("SingleImage"); CAST_AND_EXTRACT_IMAGE_BASE(DoubleVectorImageType,DoubleImageType,l_inPtr); SetParameterOutputImagePixelType("out",ImagePixelType_float); CAST_AND_EXTRACT_IMAGE_BASE(FloatVectorImageType,FloatImageType,l_inPtr); SetParameterOutputImagePixelType("out",ImagePixelType_uint8); CAST_AND_EXTRACT_IMAGE_BASE(UInt8VectorImageType, UInt8ImageType,l_inPtr); SetParameterOutputImagePixelType("out",ImagePixelType_uint16); CAST_AND_EXTRACT_IMAGE_BASE(UInt16VectorImageType, UInt16ImageType,l_inPtr); } else { vnsLogDebugMacro("VectorImage"); CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(DoubleVectorImageType,DoubleVectorImageType,l_inPtr); SetParameterOutputImagePixelType("out",ImagePixelType_float); CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(FloatVectorImageType,FloatVectorImageType,l_inPtr); SetParameterOutputImagePixelType("out",ImagePixelType_uint8); CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(UInt8VectorImageType, UInt8VectorImageType,l_inPtr); SetParameterOutputImagePixelType("out",ImagePixelType_uint16); CAST_AND_EXTRACT_VECTOR_IMAGE_BASE(UInt16VectorImageType, UInt16VectorImageType,l_inPtr); } } else { vnsExceptionDataMacro("Unsuported image type : only vector supported"); } vnsExceptionDataMacro("Unsuported image type"); } private: itk::ProcessObject::Pointer m_ExtractFilter; }; } } OTB_APPLICATION_EXPORT(vns::Wrapper::ExtractChannels)
11,241
2,937
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // include the required headers #include "EMotionFXConfig.h" #include <MCore/Source/Compare.h> #include <MCore/Source/UnicodeString.h> #include "AnimGraphStateCondition.h" #include "AnimGraph.h" #include "AnimGraphStateMachine.h" #include "AnimGraphExitNode.h" #include "AnimGraphInstance.h" #include "AnimGraphManager.h" #include <MCore/Source/AttributeSettings.h> namespace EMotionFX { // constructor AnimGraphStateCondition::AnimGraphStateCondition(AnimGraph* animGraph) : AnimGraphTransitionCondition(animGraph, TYPE_ID) { mState = nullptr; CreateAttributeValues(); InitInternalAttributesForAllInstances(); } // destructor AnimGraphStateCondition::~AnimGraphStateCondition() { } // create AnimGraphStateCondition* AnimGraphStateCondition::Create(AnimGraph* animGraph) { return new AnimGraphStateCondition(animGraph); } // create unique data AnimGraphObjectData* AnimGraphStateCondition::CreateObjectData() { return new UniqueData(this, nullptr); } // register the attributes void AnimGraphStateCondition::RegisterAttributes() { // register the state name MCore::AttributeSettings* attributeInfo = RegisterAttribute("State", "stateID", "The state to watch.", ATTRIBUTE_INTERFACETYPE_STATESELECTION); attributeInfo->SetDefaultValue(MCore::AttributeString::Create()); // create the function combobox attributeInfo = RegisterAttribute("Test Function", "testFunction", "The type of test function or condition.", MCore::ATTRIBUTE_INTERFACETYPE_COMBOBOX); attributeInfo->ResizeComboValues(6); attributeInfo->SetComboValue(FUNCTION_EXITSTATES, "Trigger When Exit State Reached"); attributeInfo->SetComboValue(FUNCTION_ENTERING, "Started Transitioning Into State"); attributeInfo->SetComboValue(FUNCTION_ENTER, "State Fully Blended In"); attributeInfo->SetComboValue(FUNCTION_EXIT, "Leaving State, Transitioning Out"); attributeInfo->SetComboValue(FUNCTION_END, "State Fully Blended Out"); attributeInfo->SetComboValue(FUNCTION_PLAYTIME, "Has Reached Specified Playtime"); attributeInfo->SetDefaultValue(MCore::AttributeFloat::Create(FUNCTION_EXITSTATES)); // create the max playtime attribute attributeInfo = RegisterAttribute("Play Time", "playtime", "The float value in seconds to test against the current playtime of the state.", MCore::ATTRIBUTE_INTERFACETYPE_FLOATSPINNER); attributeInfo->SetDefaultValue(MCore::AttributeFloat::Create(0.0f)); attributeInfo->SetMinValue(MCore::AttributeFloat::Create(0.0f)); attributeInfo->SetMaxValue(MCore::AttributeFloat::Create(FLT_MAX)); } // get the palette name const char* AnimGraphStateCondition::GetPaletteName() const { return "State Condition"; } // get the type string const char* AnimGraphStateCondition::GetTypeString() const { return "AnimGraphStateCondition"; } // get the category AnimGraphObject::ECategory AnimGraphStateCondition::GetPaletteCategory() const { return AnimGraphObject::CATEGORY_TRANSITIONCONDITIONS; } // test the condition bool AnimGraphStateCondition::TestCondition(AnimGraphInstance* animGraphInstance) const { // add the unique data for the condition to the anim graph UniqueData* uniqueData = static_cast<UniqueData*>(animGraphInstance->FindUniqueObjectData(this)); // in case a event got triggered constantly fire true until the condition gets reset if (uniqueData->mTriggered) { return true; } // update the unique data if (uniqueData->mAnimGraphInstance != animGraphInstance || uniqueData->mAnimGraphInstance->FindEventHandlerIndex(uniqueData->mEventHandler) == MCORE_INVALIDINDEX32) { // create a new event handler for this motion condition and add it to the motion instance uniqueData->mAnimGraphInstance = animGraphInstance; uniqueData->mEventHandler = new AnimGraphStateCondition::EventHandler(const_cast<AnimGraphStateCondition*>(this), uniqueData); uniqueData->mAnimGraphInstance->AddEventHandler(uniqueData->mEventHandler); } // get the condition test function type const int32 functionIndex = GetAttributeFloatAsInt32(ATTRIB_FUNCTION); // check what we want to do switch (functionIndex) { // reached an exit state case FUNCTION_EXITSTATES: { // check if the state is a valid state machine if (mState && mState->GetType() == AnimGraphStateMachine::TYPE_ID) { // type-cast the state to a state machine AnimGraphStateMachine* stateMachine = static_cast<AnimGraphStateMachine*>(mState); // check if we have reached an exit state if (stateMachine->GetExitStateReached(animGraphInstance)) { return true; } } break; } // reached the specified play time case FUNCTION_PLAYTIME: { // get the play time to check against // the has reached play time condition is not part of the event handler, so we have to manually handle it here const float playTime = GetAttributeFloat(ATTRIB_PLAYTIME)->GetValue(); // reached the specified play time if (mState) { const float currentLocalTime = mState->GetCurrentPlayTime(uniqueData->mAnimGraphInstance); if (currentLocalTime > playTime) { return true; } } } break; default: { // check if any event got triggered since we tested the condition the last time if (functionIndex == uniqueData->mLastTriggeredType) { uniqueData->mLastTriggeredType = FUNCTION_NONE; uniqueData->mTriggered = true; return true; } } } ; // no event got triggered, continue playing the state and don't autostart the transition return false; } // clonse the condition AnimGraphObject* AnimGraphStateCondition::Clone(AnimGraph* animGraph) { // create the clone AnimGraphStateCondition* clone = new AnimGraphStateCondition(animGraph); // copy base class settings such as parameter values to the new clone CopyBaseObjectTo(clone); // return a pointer to the clone return clone; } // update the data void AnimGraphStateCondition::OnUpdateAttributes() { // get a pointer to the selected motion node AnimGraphNode* animGraphNode = mAnimGraph->RecursiveFindNode(GetAttributeString(ATTRIB_STATE)->AsChar()); if (animGraphNode && animGraphNode->GetCanActAsState()) { mState = animGraphNode; } else { mState = nullptr; } // disable GUI items that have no influence #ifdef EMFX_EMSTUDIOBUILD // enable all attributes EnableAllAttributes(true); // disable the playtime value const int32 function = GetAttributeFloatAsInt32(ATTRIB_FUNCTION); if (function != FUNCTION_PLAYTIME) { SetAttributeDisabled(ATTRIB_PLAYTIME); } #endif } // reset the motion condition void AnimGraphStateCondition::Reset(AnimGraphInstance* animGraphInstance) { // find the unique data and reset it UniqueData* uniqueData = static_cast<UniqueData*>(animGraphInstance->FindUniqueObjectData(this)); uniqueData->mTriggered = false; uniqueData->mLastTriggeredType = FUNCTION_NONE; } // when attribute values change void AnimGraphStateCondition::OnUpdateUniqueData(AnimGraphInstance* animGraphInstance) { // add the unique data for the condition to the anim graph UniqueData* uniqueData = static_cast<UniqueData*>(animGraphInstance->FindUniqueObjectData(this)); if (uniqueData == nullptr) { uniqueData = (UniqueData*)GetEMotionFX().GetAnimGraphManager()->GetObjectDataPool().RequestNew(TYPE_ID, this, animGraphInstance); //uniqueData = new UniqueData(this, nullptr); animGraphInstance->RegisterUniqueObjectData(uniqueData); } } // get the name of the currently used test function const char* AnimGraphStateCondition::GetTestFunctionString() const { // get access to the combo values and the currently selected function MCore::AttributeSettings* comboAttributeInfo = GetAnimGraphManager().GetAttributeInfo(this, ATTRIB_FUNCTION); const uint32 functionIndex = GetAttributeFloatAsUint32(ATTRIB_FUNCTION); return comboAttributeInfo->GetComboValue(functionIndex); } // construct and output the information summary string for this object void AnimGraphStateCondition::GetSummary(MCore::String* outResult) const { outResult->Format("%s: State='%s', Test Function='%s'", GetTypeString(), GetAttributeString(ATTRIB_STATE)->AsChar(), GetTestFunctionString()); } // construct and output the tooltip for this object void AnimGraphStateCondition::GetTooltip(MCore::String* outResult) const { MCore::String columnName, columnValue; // add the condition type columnName = "Condition Type: "; columnValue = GetTypeString(); outResult->Format("<table border=\"0\"><tr><td width=\"100\"><b>%s</b></td><td>%s</td>", columnName.AsChar(), columnValue.AsChar()); // add the state name columnName = "State Name: "; columnValue = GetAttributeString(ATTRIB_STATE)->AsChar(); outResult->FormatAdd("</tr><tr><td><b>%s</b></td><td>%s</td>", columnName.AsChar(), columnValue.AsChar()); // add the test function columnName = "Test Function: "; columnValue = GetTestFunctionString(); outResult->FormatAdd("</tr><tr><td><b>%s</b></td><td width=\"180\">%s</td></tr></table>", columnName.AsChar(), columnValue.AsChar()); } //-------------------------------------------------------------------------------- // class AnimGraphStateCondition::UniqueData //-------------------------------------------------------------------------------- // constructor AnimGraphStateCondition::UniqueData::UniqueData(AnimGraphObject* object, AnimGraphInstance* animGraphInstance) : AnimGraphObjectData(object, animGraphInstance) { mLastTriggeredType = FUNCTION_NONE; mAnimGraphInstance = animGraphInstance; mEventHandler = nullptr; mTriggered = false; } // destructor AnimGraphStateCondition::UniqueData::~UniqueData() { // get rid of the event handler if (mEventHandler) { if (mAnimGraphInstance) { mAnimGraphInstance->RemoveEventHandler(mEventHandler, false); } mEventHandler->Destroy(); mAnimGraphInstance = nullptr; } } // callback for when we renamed a node void AnimGraphStateCondition::OnRenamedNode(AnimGraph* animGraph, AnimGraphNode* node, const MCore::String& oldName) { MCORE_UNUSED(animGraph); if (GetAttributeString(ATTRIB_STATE)->GetValue().CheckIfIsEqual(oldName)) { GetAttributeString(ATTRIB_STATE)->SetValue(node->GetName()); } } // callback that gets called before a node gets removed void AnimGraphStateCondition::OnRemoveNode(AnimGraph* animGraph, AnimGraphNode* nodeToRemove) { MCORE_UNUSED(animGraph); if (GetAttributeString(ATTRIB_STATE)->GetValue().CheckIfIsEqual(nodeToRemove->GetName())) { GetAttributeString(ATTRIB_STATE)->SetValue(""); } } //-------------------------------------------------------------------------------- // class AnimGraphStateCondition::EventHandler //-------------------------------------------------------------------------------- // constructor AnimGraphStateCondition::EventHandler::EventHandler(AnimGraphStateCondition* condition, UniqueData* uniqueData) : EMotionFX::AnimGraphInstanceEventHandler() { mCondition = condition; mUniqueData = uniqueData; } // destructor AnimGraphStateCondition::EventHandler::~EventHandler() { } void AnimGraphStateCondition::EventHandler::OnStateEnter(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { // check if the state and the anim graph instance are valid and return directly in case one of them is not if (state == nullptr || animGraphInstance == nullptr) { return; } const MCore::String& stateName = mCondition->GetAttributeString(ATTRIB_STATE)->GetValue(); if (stateName.GetIsEmpty() || stateName.CheckIfIsEqual(state->GetName())) { mUniqueData->mLastTriggeredType = FUNCTION_ENTER; } } void AnimGraphStateCondition::EventHandler::OnStateEntering(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { // check if the state and the anim graph instance are valid and return directly in case one of them is not if (state == nullptr || animGraphInstance == nullptr) { return; } // get the condition test function type const int32 functionIndex = mCondition->GetAttributeFloatAsInt32(ATTRIB_FUNCTION); if (functionIndex == FUNCTION_ENTERING) { const MCore::String& stateName = mCondition->GetAttributeString(ATTRIB_STATE)->GetValue(); if (stateName.GetIsEmpty() || stateName.CheckIfIsEqual(state->GetName())) { mUniqueData->mLastTriggeredType = FUNCTION_ENTERING; } } } void AnimGraphStateCondition::EventHandler::OnStateExit(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { // check if the state and the anim graph instance are valid and return directly in case one of them is not if (state == nullptr || animGraphInstance == nullptr) { return; } const MCore::String& stateName = mCondition->GetAttributeString(ATTRIB_STATE)->GetValue(); if (stateName.GetIsEmpty() || stateName.CheckIfIsEqual(state->GetName())) { mUniqueData->mLastTriggeredType = FUNCTION_EXIT; } } void AnimGraphStateCondition::EventHandler::OnStateEnd(AnimGraphInstance* animGraphInstance, AnimGraphNode* state) { // check if the state and the anim graph instance are valid and return directly in case one of them is not if (state == nullptr || animGraphInstance == nullptr) { return; } const MCore::String& stateName = mCondition->GetAttributeString(ATTRIB_STATE)->GetValue(); if (stateName.GetIsEmpty() || stateName.CheckIfIsEqual(state->GetName())) { mUniqueData->mLastTriggeredType = FUNCTION_END; } } } // namespace EMotionFX
16,068
4,245
// // slippy map elements based on example code Copyright (c) 2014 Christopher Baker <https://christopherbaker.net> // SPDX-License-Identifier: MIT // /* Project Title: Signs of Surveillance Description: ©Daniel Buzzo 2019 dan@buzzo.com http://buzzo.com https://github.com/danbz */ #include "ofAppRunner.h" #include "ofApp.h" int main() { ofGLWindowSettings settings; settings.setSize(1280, 768); settings.setGLVersion(3, 2); settings.windowMode = OF_FULLSCREEN; auto window = ofCreateWindow(settings); auto app = std::make_shared<ofApp>(); return ofRunApp(app); }
607
227
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "optimizer/rule/PushFilterDownGetNbrsRule.h" #include "common/expression/BinaryExpression.h" #include "common/expression/ConstantExpression.h" #include "common/expression/Expression.h" #include "common/expression/FunctionCallExpression.h" #include "common/expression/LogicalExpression.h" #include "common/expression/UnaryExpression.h" #include "optimizer/OptGroup.h" #include "planner/PlanNode.h" #include "planner/Query.h" #include "visitor/ExtractFilterExprVisitor.h" using nebula::graph::Filter; using nebula::graph::GetNeighbors; using nebula::graph::PlanNode; using nebula::graph::QueryContext; namespace nebula { namespace opt { std::unique_ptr<OptRule> PushFilterDownGetNbrsRule::kInstance = std::unique_ptr<PushFilterDownGetNbrsRule>(new PushFilterDownGetNbrsRule()); PushFilterDownGetNbrsRule::PushFilterDownGetNbrsRule() { RuleSet::queryRules().addRule(this); } bool PushFilterDownGetNbrsRule::match(const OptGroupExpr *groupExpr) const { auto pair = findMatchedGroupExpr(groupExpr); if (!pair.first) { return false; } return true; } Status PushFilterDownGetNbrsRule::transform(QueryContext *qctx, const OptGroupExpr *groupExpr, TransformResult *result) const { auto pair = findMatchedGroupExpr(groupExpr); auto filter = static_cast<const Filter *>(groupExpr->node()); auto gn = static_cast<const GetNeighbors *>(pair.second->node()); auto condition = filter->condition()->clone(); graph::ExtractFilterExprVisitor visitor; condition->accept(&visitor); if (!visitor.ok()) { result->eraseCurr = false; result->eraseAll = false; return Status::OK(); } auto pool = qctx->objPool(); auto remainedExpr = std::move(visitor).remainedExpr(); OptGroupExpr *newFilterGroupExpr = nullptr; if (remainedExpr != nullptr) { auto newFilter = Filter::make(qctx, nullptr, pool->add(remainedExpr.release())); newFilter->setOutputVar(filter->outputVar()); newFilter->setInputVar(filter->inputVar()); newFilterGroupExpr = OptGroupExpr::create(qctx, newFilter, groupExpr->group()); } auto newGNFilter = condition->encode(); if (!gn->filter().empty()) { auto filterExpr = Expression::decode(gn->filter()); LogicalExpression logicExpr( Expression::Kind::kLogicalAnd, condition.release(), filterExpr.release()); newGNFilter = logicExpr.encode(); } auto newGN = cloneGetNbrs(qctx, gn); newGN->setFilter(newGNFilter); OptGroupExpr *newGroupExpr = nullptr; if (newFilterGroupExpr != nullptr) { // Filter(A&&B)->GetNeighbors(C) => Filter(A)->GetNeighbors(B&&C) auto newGroup = OptGroup::create(qctx); newGroupExpr = OptGroupExpr::create(qctx, newGN, newGroup); newFilterGroupExpr->dependsOn(newGroup); } else { // Filter(A)->GetNeighbors(C) => GetNeighbors(A&&C) newGroupExpr = OptGroupExpr::create(qctx, newGN, groupExpr->group()); newGN->setOutputVar(filter->outputVar()); } for (auto dep : pair.second->dependencies()) { newGroupExpr->dependsOn(dep); } result->newGroupExprs.emplace_back(newFilterGroupExpr ? newFilterGroupExpr : newGroupExpr); result->eraseAll = true; result->eraseCurr = true; return Status::OK(); } std::string PushFilterDownGetNbrsRule::toString() const { return "PushFilterDownGetNbrsRule"; } std::pair<bool, const OptGroupExpr *> PushFilterDownGetNbrsRule::findMatchedGroupExpr( const OptGroupExpr *groupExpr) const { auto node = groupExpr->node(); if (node->kind() != PlanNode::Kind::kFilter) { return std::make_pair(false, nullptr); } for (auto dep : groupExpr->dependencies()) { for (auto expr : dep->groupExprs()) { if (expr->node()->kind() == PlanNode::Kind::kGetNeighbors) { return std::make_pair(true, expr); } } } return std::make_pair(false, nullptr); } GetNeighbors *PushFilterDownGetNbrsRule::cloneGetNbrs(QueryContext *qctx, const GetNeighbors *gn) const { auto newGN = GetNeighbors::make(qctx, nullptr, gn->space()); newGN->setSrc(gn->src()); newGN->setEdgeTypes(gn->edgeTypes()); newGN->setEdgeDirection(gn->edgeDirection()); newGN->setDedup(gn->dedup()); newGN->setRandom(gn->random()); newGN->setLimit(gn->limit()); newGN->setInputVar(gn->inputVar()); newGN->setOutputVar(gn->outputVar()); if (gn->vertexProps()) { auto vertexProps = *gn->vertexProps(); auto vertexPropsPtr = std::make_unique<decltype(vertexProps)>(std::move(vertexProps)); newGN->setVertexProps(std::move(vertexPropsPtr)); } if (gn->edgeProps()) { auto edgeProps = *gn->edgeProps(); auto edgePropsPtr = std::make_unique<decltype(edgeProps)>(std::move(edgeProps)); newGN->setEdgeProps(std::move(edgePropsPtr)); } if (gn->statProps()) { auto statProps = *gn->statProps(); auto statPropsPtr = std::make_unique<decltype(statProps)>(std::move(statProps)); newGN->setStatProps(std::move(statPropsPtr)); } if (gn->exprs()) { auto exprs = *gn->exprs(); auto exprsPtr = std::make_unique<decltype(exprs)>(std::move(exprs)); newGN->setExprs(std::move(exprsPtr)); } return newGN; } } // namespace opt } // namespace nebula
5,744
1,817
#include "model_base.h" #include "util.h" /** @file Example of how to run Bert inference using our implementation. */ int main(int argc, char* argv[]) { std::string model_weights_path = argv[1]; int max_batch_size = 128; auto model = lightseq::cuda::LSModelFactory::GetInstance().CreateModel( "Bert", model_weights_path, max_batch_size); int batch_size = 1; int batch_seq_len = 8; std::vector<int> host_input = {101, 4931, 1010, 2129, 2024, 2017, 102, 0}; void* d_input; lightseq::cuda::CHECK_GPU_ERROR( cudaMalloc(&d_input, sizeof(int) * batch_size * batch_seq_len)); lightseq::cuda::CHECK_GPU_ERROR(cudaMemcpy( d_input, host_input.data(), sizeof(int) * batch_size * batch_seq_len, cudaMemcpyHostToDevice)); model->set_input_ptr(0, d_input); model->set_input_shape(0, {batch_size, batch_seq_len}); for (int i = 0; i < model->get_output_size(); i++) { void* d_output; std::vector<int> shape = model->get_output_max_shape(i); int total_size = 1; for (int j = 0; j < shape.size(); j++) { total_size *= shape[j]; } lightseq::cuda::CHECK_GPU_ERROR( cudaMalloc(&d_output, total_size * sizeof(int))); model->set_output_ptr(i, d_output); } lightseq::cuda::CHECK_GPU_ERROR(cudaStreamSynchronize(0)); std::cout << "infer preprocessing finished" << std::endl; /* ---step5. infer and log--- */ for (int i = 0; i < 10; i++) { auto start = std::chrono::high_resolution_clock::now(); model->Infer(); lightseq::cuda::print_time_duration(start, "one infer time", 0); } for (int i = 0; i < model->get_output_size(); i++) { const float* d_output; d_output = static_cast<const float*>(model->get_output_ptr(i)); std::vector<int> shape = model->get_output_shape(i); std::cout << "output shape: "; for (int j = 0; j < shape.size(); j++) { std::cout << shape[j] << " "; } std::cout << std::endl; lightseq::cuda::print_vec(d_output, "output", 5); } return 0; }
2,007
800
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ // See docs in ../ops/linalg_ops.cc. #include <cmath> #include "third_party/eigen3/Eigen/Cholesky" #include "third_party/eigen3/Eigen/LU" #include "tensorflow/core/framework/kernel_def_builder.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor_shape.h" #include "tensorflow/core/kernels/linalg_ops_common.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/macros.h" #include "tensorflow/core/platform/types.h" namespace tensorflow { template <class Scalar, bool SupportsBatchOperationT> class MatrixInverseOp : public UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT> { public: explicit MatrixInverseOp(OpKernelConstruction* context) : UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT>(context) {} ~MatrixInverseOp() override {} TensorShape GetOutputMatrixShape( const TensorShape& input_matrix_shape) override { return input_matrix_shape; } int64 GetCostPerUnit(const TensorShape& input_matrix_shape) override { const int64 rows = input_matrix_shape.dim_size(0); if (rows > (1LL << 20)) { // A big number to cap the cost in case overflow. return kint64max; } else { return rows * rows * rows; } } typedef UnaryLinearAlgebraOp<Scalar, SupportsBatchOperationT> Base; using Matrix = typename Base::Matrix; using MatrixMap = typename Base::MatrixMap; using ConstMatrixMap = typename Base::ConstMatrixMap; void ComputeMatrix(OpKernelContext* context, const ConstMatrixMap& input, MatrixMap* output) override { OP_REQUIRES(context, input.rows() == input.cols(), errors::InvalidArgument("Input matrix must be square.")); if (input.rows() == 0) { // By definition, an empty matrix's inverse is an empty matrix. return; } Eigen::PartialPivLU<Matrix> lu_decomposition(input); // TODO(rmlarsen): Add check based on condition number estimation. // PartialPivLU cannot give strong guarantees on invertibility, but // we can at least guard against exact zero pivots. This can occur as // a result of basic user mistakes, such as providing integer valued // matrices that are exactly singular, or due to underflow if this // code is run with denormals being flushed to zero. const Scalar min_abs_pivot = lu_decomposition.matrixLU().diagonal().cwiseAbs().minCoeff(); OP_REQUIRES(context, min_abs_pivot > Scalar(0), errors::InvalidArgument("Input is not invertible.")); output->noalias() = lu_decomposition.inverse(); } private: TF_DISALLOW_COPY_AND_ASSIGN(MatrixInverseOp); }; REGISTER_LINALG_OP("MatrixInverse", (MatrixInverseOp<float, false>), float); REGISTER_LINALG_OP("MatrixInverse", (MatrixInverseOp<double, false>), double); REGISTER_LINALG_OP("BatchMatrixInverse", (MatrixInverseOp<float, true>), float); REGISTER_LINALG_OP("BatchMatrixInverse", (MatrixInverseOp<double, true>), double); } // namespace tensorflow
3,733
1,145
// hacky for now, to be cleaned later #include <vector> #include <string> #include <cstdio> #include <set> #include <queue> std::vector< std::vector<int> > gActions = { {2, 0, 1}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}, {0, 2, 1} }; class ProblemState { public: ProblemState() : mState{{3, 3, 1}} { } ProblemState(const ProblemState& pThat) { *this = pThat; } ProblemState& operator=(const ProblemState& pThat) { if (this != &pThat) { mState = pThat.mState; mActions = pThat.mActions; } return *this; } ProblemState applyAction(const std::vector<int>& pAction) { std::vector<int> action = pAction; if (mState[2] == 1) { for (int i = 0; i < 3; i++) { action[i] *= -1; } } ProblemState newState(*this); for (int i = 0; i < 3; i++) { newState.mState[i] += action[i]; } newState.mActions.push_back(actionToString(pAction)); return newState; } bool isValid() const { return validVector(mState) && validVector(complementVector(mState)); } bool validVector(const std::vector<int>& pState) const { return ( (pState[0] == 0 || (pState[0] >= pState[1])) && pState[0] >= 0 && pState[1] >= 0 && pState[0] <= 3 && pState[1] <= 3 ); } bool isSuccess() const { bool success = true; for (auto count : mState) { if (count != 0) { success = false; } } return success; } std::string toString() const { std::string ret; for (auto count : mState) { ret += ((char) count + '0'); } return ret; } std::vector<int> complementVector(const std::vector<int>& pVector) const { std::vector<int> complement; for (auto count : pVector) { complement.push_back(3 - count); } complement[2] = 1 - pVector[2]; return complement; } std::string actionToString(const std::vector<int>& pAction) const { std::string ret(""); ret += (char(pAction[0]) + '0'); ret += " missionaries "; ret += (char(pAction[1]) + '0'); ret += " cannibals"; return ret; } std::vector<int> mState; std::vector<std::string> mActions; }; ProblemState bfs(const ProblemState& pInitialState) { ProblemState currentState; std::set<std::string> encounteredStates; std::queue<ProblemState> statesToBeProcessed; encounteredStates.insert(pInitialState.toString()); statesToBeProcessed.push(pInitialState); while (!statesToBeProcessed.empty()) { currentState = statesToBeProcessed.front(); statesToBeProcessed.pop(); if (currentState.isSuccess()) { return currentState; } else { for (auto operation : gActions) { ProblemState newState = currentState.applyAction(operation); if (newState.isValid()) { if (encounteredStates.find(newState.toString()) == std::end(encounteredStates)) { encounteredStates.insert(newState.toString()); statesToBeProcessed.push(newState); } } } } } throw 666; } int main(int argc, char**argv) { ProblemState initialState; try { ProblemState solution = bfs(initialState); puts("solution"); int i; for (i = 0; i < solution.mActions.size() - 1; i += 2) { printf("Move %s across\n", solution.mActions[i].c_str()); printf("Move %s back\n", solution.mActions[i + 1].c_str()); } printf("Move %s across\n", solution.mActions[i].c_str()); } catch (int e) { puts("no solution..."); } return 0; }
3,304
1,406
/* Copyright (c) 2021, Arvid Norberg All rights reserved. You may use, distribute and modify this code under the terms of the BSD license, see LICENSE file. */ #include "test.hpp" #include "setup_transfer.hpp" // for load_file #include "libtorrent/flags.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/add_torrent_params.hpp" #include "libtorrent/session.hpp" #include "libtorrent/error_code.hpp" #include "libtorrent/aux_/path.hpp" #include <iostream> namespace { using add_torrent_test_flag_t = lt::flags::bitfield_flag<std::uint32_t, struct add_torrent_test_tag>; using lt::operator""_bit; #if TORRENT_ABI_VERSION < 3 add_torrent_test_flag_t const set_info_hash = 0_bit; #endif add_torrent_test_flag_t const set_info_hashes_v1 = 1_bit; add_torrent_test_flag_t const set_info_hashes_v2 = 2_bit; add_torrent_test_flag_t const async_add = 3_bit; add_torrent_test_flag_t const ec_add = 4_bit; add_torrent_test_flag_t const magnet_link = 5_bit; #if TORRENT_ABI_VERSION < 3 add_torrent_test_flag_t const set_invalid_info_hash = 6_bit; #endif add_torrent_test_flag_t const set_invalid_info_hash_v1 = 7_bit; add_torrent_test_flag_t const set_invalid_info_hash_v2 = 8_bit; lt::error_code test_add_torrent(std::string file, add_torrent_test_flag_t const flags) { std::string const root_dir = lt::parent_path(lt::current_working_directory()); std::string const filename = lt::combine_path(lt::combine_path(root_dir, "test_torrents"), file); lt::error_code ec; std::vector<char> data; TEST_CHECK(load_file(filename, data, ec) == 0); auto ti = std::make_shared<lt::torrent_info>(data, ec, lt::from_span); TEST_CHECK(!ec); if (ec) std::printf(" loading(\"%s\") -> failed %s\n", filename.c_str() , ec.message().c_str()); lt::add_torrent_params atp; atp.ti = ti; atp.save_path = "."; #if TORRENT_ABI_VERSION < 3 if (flags & set_info_hash) atp.info_hash = atp.ti->info_hash(); #endif if (flags & set_info_hashes_v1) atp.info_hashes.v1 = atp.ti->info_hashes().v1; if (flags & set_info_hashes_v2) atp.info_hashes.v2 = atp.ti->info_hashes().v2; #if TORRENT_ABI_VERSION < 3 if (flags & set_invalid_info_hash) atp.info_hash = lt::sha1_hash("abababababababababab"); #endif if (flags & set_invalid_info_hash_v1) atp.info_hashes.v1 = lt::sha1_hash("abababababababababab"); if (flags & set_invalid_info_hash_v2) atp.info_hashes.v2 = lt::sha256_hash("abababababababababababababababab"); std::vector<char> info_section; if (flags & magnet_link) { auto const is = atp.ti->info_section(); info_section.assign(is.begin(), is.end()); atp.ti.reset(); } lt::session_params p; p.settings.set_int(lt::settings_pack::alert_mask, lt::alert_category::error | lt::alert_category::status); p.settings.set_str(lt::settings_pack::listen_interfaces, "127.0.0.1:6881"); lt::session ses(p); try { if (flags & ec_add) { ses.add_torrent(atp, ec); if (ec) return ec; } else if (flags & async_add) { ses.async_add_torrent(atp); } else { ses.add_torrent(atp); } } catch (lt::system_error const& e) { return e.code(); } std::vector<lt::alert*> alerts; auto const start_time = lt::clock_type::now(); while (lt::clock_type::now() - start_time < lt::seconds(3)) { ses.wait_for_alert(lt::seconds(1)); alerts.clear(); ses.pop_alerts(&alerts); for (auto const* a : alerts) { std::cout << a->message() << '\n'; if (auto const* te = lt::alert_cast<lt::torrent_error_alert>(a)) { return te->error; } if (auto const* mf = lt::alert_cast<lt::metadata_failed_alert>(a)) { return mf->error; } if (auto const* ta = lt::alert_cast<lt::add_torrent_alert>(a)) { if (ta->error) return ta->error; if (flags & magnet_link) { // if this fails, we'll pick up the metadata_failed_alert TEST_CHECK(ta->handle.is_valid()); ta->handle.set_metadata(info_section); } else { // success! return lt::error_code(); } } if (lt::alert_cast<lt::metadata_received_alert>(a)) { // success! return lt::error_code(); } } } return lt::error_code(); } struct test_case_t { char const* filename; add_torrent_test_flag_t flags; lt::error_code expected_error; }; auto const v2 = "v2.torrent"; auto const hybrid = "v2_hybrid.torrent"; auto const v1 = "base.torrent"; test_case_t const add_torrent_test_cases[] = { {v2, {}, {}}, {v2, set_info_hashes_v1, {}}, {v2, set_info_hashes_v2, {}}, {v2, set_info_hashes_v1 | set_info_hashes_v2, {}}, #if TORRENT_ABI_VERSION < 3 {v2, set_info_hash, {}}, // the info_hash field is ignored when we have an actual torrent_info object {v2, set_invalid_info_hash, {}}, #endif {v2, set_invalid_info_hash_v1, lt::errors::mismatching_info_hash}, {v2, set_invalid_info_hash_v2, lt::errors::mismatching_info_hash}, {hybrid, {}, {}}, {hybrid, set_info_hashes_v1, {}}, {hybrid, set_info_hashes_v2, {}}, {hybrid, set_info_hashes_v1 | set_info_hashes_v2, {}}, #if TORRENT_ABI_VERSION < 3 {hybrid, set_info_hash, {}}, // the info_hash field is ignored when we have an actual torrent_info object {hybrid, set_invalid_info_hash, {}}, #endif {hybrid, set_invalid_info_hash_v1, lt::errors::mismatching_info_hash}, {hybrid, set_invalid_info_hash_v2, lt::errors::mismatching_info_hash}, {v1, {}, {}}, {v1, set_info_hashes_v1, {}}, #if TORRENT_ABI_VERSION < 3 {v1, set_info_hash, {}}, // the info_hash field is ignored when we have an actual torrent_info object {v1, set_invalid_info_hash, {}}, #endif // magnet links {v2, magnet_link, lt::errors::missing_info_hash_in_uri}, {v2, magnet_link | set_info_hashes_v1, {}}, {v2, magnet_link | set_info_hashes_v2, {}}, #if TORRENT_ABI_VERSION < 3 // a v2-only magnet link supports magnet links with a truncated hash {v2, magnet_link | set_info_hash, {}}, {v2, magnet_link | set_invalid_info_hash, lt::errors::mismatching_info_hash}, #endif {v2, magnet_link | set_info_hashes_v1 | set_info_hashes_v2, {}}, {v2, magnet_link | set_invalid_info_hash_v1, lt::errors::mismatching_info_hash}, {v2, magnet_link | set_invalid_info_hash_v2, lt::errors::mismatching_info_hash}, {hybrid, magnet_link, lt::errors::missing_info_hash_in_uri}, {hybrid, magnet_link | set_info_hashes_v1, {}}, {hybrid, magnet_link | set_info_hashes_v2, {}}, #if TORRENT_ABI_VERSION < 3 {hybrid, magnet_link | set_info_hash, {}}, {hybrid, magnet_link | set_invalid_info_hash, lt::errors::mismatching_info_hash}, #endif {hybrid, magnet_link | set_info_hashes_v1 | set_info_hashes_v2, {}}, {hybrid, magnet_link | set_invalid_info_hash_v1, lt::errors::mismatching_info_hash}, {hybrid, magnet_link | set_invalid_info_hash_v2, lt::errors::mismatching_info_hash}, {v1, magnet_link, lt::errors::missing_info_hash_in_uri}, #if TORRENT_ABI_VERSION < 3 {v1, magnet_link | set_info_hash, {}}, {v1, magnet_link | set_invalid_info_hash, lt::errors::mismatching_info_hash}, #endif {v1, magnet_link | set_info_hashes_v1, {}}, {v1, magnet_link | set_invalid_info_hash_v1, lt::errors::mismatching_info_hash}, {v1, magnet_link | set_invalid_info_hash_v2, lt::errors::mismatching_info_hash}, }; } TORRENT_TEST(invalid_file_root) { TEST_CHECK(test_add_torrent("v2_invalid_root_hash.torrent", {}) == lt::error_code(lt::errors::torrent_invalid_piece_layer)); } TORRENT_TEST(add_torrent) { int i = 0; for (auto const& test_case : add_torrent_test_cases) { std::cerr << "idx: " << i << '\n'; auto const e = test_add_torrent(test_case.filename, test_case.flags); if (e != test_case.expected_error) { std::cerr << test_case.filename << '\n'; TEST_ERROR(e.message() + " != " + test_case.expected_error.message()); } ++i; } } TORRENT_TEST(async_add_torrent) { int i = 0; for (auto const& test_case : add_torrent_test_cases) { auto const e = test_add_torrent(test_case.filename, test_case.flags | async_add); if (e != test_case.expected_error) { std::cerr << "idx: " << i << " " << test_case.filename << '\n'; TEST_ERROR(e.message() + " != " + test_case.expected_error.message()); } ++i; } } TORRENT_TEST(ec_add_torrent) { int i = 0; for (auto const& test_case : add_torrent_test_cases) { auto const e = test_add_torrent(test_case.filename, test_case.flags | ec_add); if (e != test_case.expected_error) { std::cerr << "idx: " << i << " " << test_case.filename << '\n'; TEST_ERROR(e.message() + " != " + test_case.expected_error.message()); } ++i; } }
8,415
3,693
#include <imgui.h> #include "core/panels/Profiler.h" namespace ige::creator { Profiler::Profiler(const std::string& name, const Panel::Settings& settings) : Panel(name, settings) { } Profiler::~Profiler() { clear(); } void Profiler::initialize() { clear(); m_timeWidget = createWidget<Label>("Time"); m_fpsWidget = createWidget<Label>("FPS"); } void Profiler::_drawImpl() { // Show FPS m_timeWidget->setLabel("Time: " + std::to_string(static_cast<int>(1000.0f / ImGui::GetIO().Framerate)) + " ms"); m_fpsWidget->setLabel("FPS: " + std::to_string(static_cast<int>(ImGui::GetIO().Framerate)) + " fps"); Panel::_drawImpl(); } void Profiler::clear() { m_timeWidget = nullptr; m_fpsWidget = nullptr; removeAllWidgets(); } }
900
322
#include "trivium.h" #include "../algos/trivium.h" TriviumBox::TriviumBox() : Gtk::Box(Gtk::ORIENTATION_VERTICAL) { pack_start(m_KeyGrid); m_KeyGrid.set_halign(Gtk::ALIGN_CENTER); m_KeyGrid.attach(m_KeyHeader, 1, 1, 2); m_KeyGrid.attach(m_KeywordLabel, 1, 2); m_KeyGrid.attach(m_KeywordEntry, 2, 2); m_KeyGrid.attach(m_InitializationVectorLabel, 1, 3); m_KeyGrid.attach(m_InitializationVectorEntry, 2, 3); pack_start(m_UsageGrid); m_UsageGrid.set_halign(Gtk::ALIGN_CENTER); m_UsageGrid.attach(m_UsageHeader, 1, 1, 2); m_UsageGrid.attach(m_PlainTextLabel, 1, 2, 2); m_UsageGrid.attach(m_PlainTextView, 1, 3, 2); m_UsageGrid.attach(m_EncryptedTextLabel, 1, 4, 2); m_UsageGrid.attach(m_EncryptedTextView, 1, 5, 2); m_KeyHeader.set_markup("<u><b>Key</b></u>"); m_KeyHeader.set_margin_top(10); m_KeyHeader.set_margin_bottom(10); m_KeywordLabel.set_text("Keyword "); m_refKeywordBuffer = m_KeywordEntry.get_buffer(); m_KeywordEntry.set_text("1234567890"); m_KeywordEntry.signal_changed().connect( sigc::mem_fun(*this, TriviumBox::changed_keyword_text) ); m_InitializationVectorLabel.set_text("Initialization Vector "); m_refInitializationVectorBuffer = m_InitializationVectorEntry.get_buffer(); m_InitializationVectorEntry.set_text("1234567890"); m_InitializationVectorEntry.signal_changed().connect( sigc::mem_fun(*this, TriviumBox::changed_ivector_text) ); m_PlainTextLabel.set_text("Plain Message (in base64)"); m_refPlainTextBuffer = Gtk::TextBuffer::create(); m_refPlainTextBuffer->set_text("AAAAAAAAAAAA"); m_refPlainTextBuffer->signal_changed().connect( sigc::mem_fun(*this, TriviumBox::changed_message_text) ); m_PlainTextView.set_buffer(m_refPlainTextBuffer); m_PlainTextView.set_wrap_mode(Gtk::WRAP_WORD_CHAR); m_EncryptedTextLabel.set_text("Encrypted Message (in base64)"); m_refEncryptedTextBuffer = Gtk::TextBuffer::create(); m_refEncryptedTextBuffer->signal_changed().connect( sigc::mem_fun(*this, TriviumBox::changed_encrypted_text) ); m_EncryptedTextView.set_buffer(m_refEncryptedTextBuffer); m_EncryptedTextView.set_wrap_mode(Gtk::WRAP_WORD_CHAR); changed_message_text(); logger_attach(&logger, this); } void TriviumBox::changed_message_text() { if (!m_ignoreTextInput) { m_ignoreTextInput = true; if (!logger.has_errors) encrypt(); m_ignoreTextInput = false; } } void TriviumBox::changed_encrypted_text() { if (!m_ignoreTextInput) { m_ignoreTextInput = true; if (!logger.has_errors) decrypt(); m_ignoreTextInput = false; } } void TriviumBox::changed_ivector_text() { changed_keyword_text(); } void TriviumBox::changed_keyword_text() { if (!m_ignoreTextInput) { m_ignoreTextInput = true; validate(); if (!logger.has_errors) encrypt(); m_ignoreTextInput = false; } } Glib::ustring TriviumBox::crypt(const Glib::ustring& buffer) { auto key_string = m_refKeywordBuffer->get_text(); auto ivector = m_refInitializationVectorBuffer->get_text(); auto base64_decoded = Glib::Base64::decode(buffer); auto num_bytes = base64_decoded.size(); trivium_crypt( (u8*)key_string.data(), (u8*)ivector.data(), (u8*)base64_decoded.data(), num_bytes); return Glib::Base64::encode(base64_decoded); } void TriviumBox::encrypt() { auto buffer = m_refPlainTextBuffer->get_text(); m_refEncryptedTextBuffer->set_text(crypt(buffer)); } void TriviumBox::decrypt() { auto buffer = m_refEncryptedTextBuffer->get_text(); m_refPlainTextBuffer->set_text(crypt(buffer)); } void TriviumBox::validate() { logger_clear(&logger); int num_ivector_bytes = m_refInitializationVectorBuffer->get_bytes(); if (num_ivector_bytes < 10) { logger_format_error(&logger, "Not enough bytes in the initialization vector (%i). Must be at least 10.\n", num_ivector_bytes); } int num_keyword_bytes = m_refKeywordBuffer->get_bytes(); if (num_keyword_bytes < 10) { logger_format_error(&logger, "Not enough bytes in the keyword (%i). Must be at least 10.\n", num_keyword_bytes); } } // Salsa20Box::~Salsa20Box() {}
4,478
1,664
#include "jass_luastate.h" // Use raw function of form "int(lua_State*)" // -- this is called a "raw C function", // and matches the type for lua_CFunction int LoadFileRequire(lua_State* L) { // use sol2 stack API to pull // "first argument" std::string path = sol::stack::get<std::string>(L, 1); if (path == "a") { std::string script = R"( print("Hello from module land!") test = 123 return "bananas" )"; // load "module", but don't run it luaL_loadbuffer( L, script.data(), script.size(), path.c_str()); // returning 1 object left on Lua stack: // a function that, when called, executes the script // (this is what lua_loadX/luaL_loadX functions return return 1; } sol::stack::push( L, "This is not the module you're looking for!"); return 1; } void jass_luastate::init(const std::string& scriptsPath) { luastate.open_libraries( sol::lib::base , sol::lib::package , sol::lib::os , sol::lib::string , sol::lib::math , sol::lib::io ); // https://github.com/ThePhD/sol2/issues/90 /* sol::state lua; lua.open_libraries(sol::lib::base, sol::lib::package); const std::string package_path = lua["package"]["path"]; lua["package"]["path"] = package_path + (!package_path.empty() ? ";" : "") + test::scripts_path("proc/valid/") + "?.lua"; */ //luastate.clear_package_loaders(); //luastate.add_package_loader(LoadFileRequire); const std::string package_path = luastate["package"]["path"]; luastate["package"]["path"] = package_path + (!package_path.empty() ? ";" : "") + "./?.lua;" + scriptsPath +"?.lua"; }
1,572
608
/* * Copyright (C) 2016 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "agent.h" #include "android-base/stringprintf.h" #include "nativehelper/scoped_local_ref.h" #include "nativeloader/native_loader.h" #include "base/logging.h" #include "base/strlcpy.h" #include "jni/java_vm_ext.h" #include "runtime.h" #include "thread-current-inl.h" #include "scoped_thread_state_change-inl.h" namespace art { namespace ti { using android::base::StringPrintf; const char* AGENT_ON_LOAD_FUNCTION_NAME = "Agent_OnLoad"; const char* AGENT_ON_ATTACH_FUNCTION_NAME = "Agent_OnAttach"; const char* AGENT_ON_UNLOAD_FUNCTION_NAME = "Agent_OnUnload"; AgentSpec::AgentSpec(const std::string& arg) { size_t eq = arg.find_first_of('='); if (eq == std::string::npos) { name_ = arg; } else { name_ = arg.substr(0, eq); args_ = arg.substr(eq + 1, arg.length()); } } std::unique_ptr<Agent> AgentSpec::Load(/*out*/jint* call_res, /*out*/LoadError* error, /*out*/std::string* error_msg) { VLOG(agents) << "Loading agent: " << name_ << " " << args_; return DoLoadHelper(nullptr, false, nullptr, call_res, error, error_msg); } // Tries to attach the agent using its OnAttach method. Returns true on success. std::unique_ptr<Agent> AgentSpec::Attach(JNIEnv* env, jobject class_loader, /*out*/jint* call_res, /*out*/LoadError* error, /*out*/std::string* error_msg) { VLOG(agents) << "Attaching agent: " << name_ << " " << args_; return DoLoadHelper(env, true, class_loader, call_res, error, error_msg); } // TODO We need to acquire some locks probably. std::unique_ptr<Agent> AgentSpec::DoLoadHelper(JNIEnv* env, bool attaching, jobject class_loader, /*out*/jint* call_res, /*out*/LoadError* error, /*out*/std::string* error_msg) { ScopedThreadStateChange stsc(Thread::Current(), ThreadState::kNative); DCHECK(call_res != nullptr); DCHECK(error_msg != nullptr); std::unique_ptr<Agent> agent = DoDlOpen(env, class_loader, error, error_msg); if (agent == nullptr) { VLOG(agents) << "err: " << *error_msg; return nullptr; } AgentOnLoadFunction callback = attaching ? agent->onattach_ : agent->onload_; if (callback == nullptr) { *error_msg = StringPrintf("Unable to start agent %s: No %s callback found", (attaching ? "attach" : "load"), name_.c_str()); VLOG(agents) << "err: " << *error_msg; *error = kLoadingError; return nullptr; } // Need to let the function fiddle with the array. std::unique_ptr<char[]> copied_args(new char[args_.size() + 1]); strlcpy(copied_args.get(), args_.c_str(), args_.size() + 1); // TODO Need to do some checks that we are at a good spot etc. *call_res = callback(Runtime::Current()->GetJavaVM(), copied_args.get(), nullptr); if (*call_res != 0) { *error_msg = StringPrintf("Initialization of %s returned non-zero value of %d", name_.c_str(), *call_res); VLOG(agents) << "err: " << *error_msg; *error = kInitializationError; return nullptr; } return agent; } std::unique_ptr<Agent> AgentSpec::DoDlOpen(JNIEnv* env, jobject class_loader, /*out*/LoadError* error, /*out*/std::string* error_msg) { DCHECK(error_msg != nullptr); ScopedLocalRef<jstring> library_path(env, class_loader == nullptr ? nullptr : JavaVMExt::GetLibrarySearchPath(env, class_loader)); bool needs_native_bridge = false; char* nativeloader_error_msg = nullptr; void* dlopen_handle = android::OpenNativeLibrary(env, Runtime::Current()->GetTargetSdkVersion(), name_.c_str(), class_loader, nullptr, library_path.get(), &needs_native_bridge, &nativeloader_error_msg); if (dlopen_handle == nullptr) { *error_msg = StringPrintf("Unable to dlopen %s: %s", name_.c_str(), nativeloader_error_msg); android::NativeLoaderFreeErrorMessage(nativeloader_error_msg); *error = kLoadingError; return nullptr; } if (needs_native_bridge) { // TODO: Consider support? // The result of this call and error_msg is ignored because the most // relevant error is that native bridge is unsupported. android::CloseNativeLibrary(dlopen_handle, needs_native_bridge, &nativeloader_error_msg); android::NativeLoaderFreeErrorMessage(nativeloader_error_msg); *error_msg = StringPrintf("Native-bridge agents unsupported: %s", name_.c_str()); *error = kLoadingError; return nullptr; } std::unique_ptr<Agent> agent(new Agent(name_, dlopen_handle)); agent->PopulateFunctions(); *error = kNoError; return agent; } std::ostream& operator<<(std::ostream &os, AgentSpec const& m) { return os << "AgentSpec { name=\"" << m.name_ << "\", args=\"" << m.args_ << "\" }"; } void* Agent::FindSymbol(const std::string& name) const { CHECK(dlopen_handle_ != nullptr) << "Cannot find symbols in an unloaded agent library " << this; return dlsym(dlopen_handle_, name.c_str()); } // TODO Lock some stuff probably. void Agent::Unload() { if (dlopen_handle_ != nullptr) { if (onunload_ != nullptr) { onunload_(Runtime::Current()->GetJavaVM()); } // Don't actually android::CloseNativeLibrary since some agents assume they will never get // unloaded. Since this only happens when the runtime is shutting down anyway this isn't a big // deal. dlopen_handle_ = nullptr; onload_ = nullptr; onattach_ = nullptr; onunload_ = nullptr; } else { VLOG(agents) << this << " is not currently loaded!"; } } Agent::Agent(Agent&& other) noexcept : dlopen_handle_(nullptr), onload_(nullptr), onattach_(nullptr), onunload_(nullptr) { *this = std::move(other); } Agent& Agent::operator=(Agent&& other) noexcept { if (this != &other) { if (dlopen_handle_ != nullptr) { Unload(); } name_ = std::move(other.name_); dlopen_handle_ = other.dlopen_handle_; onload_ = other.onload_; onattach_ = other.onattach_; onunload_ = other.onunload_; other.dlopen_handle_ = nullptr; other.onload_ = nullptr; other.onattach_ = nullptr; other.onunload_ = nullptr; } return *this; } void Agent::PopulateFunctions() { onload_ = reinterpret_cast<AgentOnLoadFunction>(FindSymbol(AGENT_ON_LOAD_FUNCTION_NAME)); if (onload_ == nullptr) { VLOG(agents) << "Unable to find 'Agent_OnLoad' symbol in " << this; } onattach_ = reinterpret_cast<AgentOnLoadFunction>(FindSymbol(AGENT_ON_ATTACH_FUNCTION_NAME)); if (onattach_ == nullptr) { VLOG(agents) << "Unable to find 'Agent_OnAttach' symbol in " << this; } onunload_ = reinterpret_cast<AgentOnUnloadFunction>(FindSymbol(AGENT_ON_UNLOAD_FUNCTION_NAME)); if (onunload_ == nullptr) { VLOG(agents) << "Unable to find 'Agent_OnUnload' symbol in " << this; } } Agent::~Agent() { if (dlopen_handle_ != nullptr) { Unload(); } } std::ostream& operator<<(std::ostream &os, const Agent* m) { return os << *m; } std::ostream& operator<<(std::ostream &os, Agent const& m) { return os << "Agent { name=\"" << m.name_ << "\", handle=" << m.dlopen_handle_ << " }"; } } // namespace ti } // namespace art
8,826
2,743
#include <IO/WriteHelpers.h> #include <IO/WriteBufferValidUTF8.h> #include <Processors/Formats/Impl/JSONCompactEachRowRowOutputFormat.h> #include <Formats/FormatFactory.h> #include <Formats/registerWithNamesAndTypes.h> namespace DB { JSONCompactEachRowRowOutputFormat::JSONCompactEachRowRowOutputFormat(WriteBuffer & out_, const Block & header_, const RowOutputFormatParams & params_, const FormatSettings & settings_, bool with_names_, bool with_types_, bool yield_strings_) : IRowOutputFormat(header_, out_, params_), settings(settings_), with_names(with_names_), with_types(with_types_), yield_strings(yield_strings_) { } void JSONCompactEachRowRowOutputFormat::writeField(const IColumn & column, const ISerialization & serialization, size_t row_num) { if (yield_strings) { WriteBufferFromOwnString buf; serialization.serializeText(column, row_num, buf, settings); writeJSONString(buf.str(), out, settings); } else serialization.serializeTextJSON(column, row_num, out, settings); } void JSONCompactEachRowRowOutputFormat::writeFieldDelimiter() { writeCString(", ", out); } void JSONCompactEachRowRowOutputFormat::writeRowStartDelimiter() { writeChar('[', out); } void JSONCompactEachRowRowOutputFormat::writeRowEndDelimiter() { writeCString("]\n", out); } void JSONCompactEachRowRowOutputFormat::writeTotals(const Columns & columns, size_t row_num) { writeChar('\n', out); size_t num_columns = columns.size(); writeRowStartDelimiter(); for (size_t i = 0; i < num_columns; ++i) { if (i != 0) writeFieldDelimiter(); writeField(*columns[i], *serializations[i], row_num); } writeRowEndDelimiter(); } void JSONCompactEachRowRowOutputFormat::writeLine(const std::vector<String> & values) { writeRowStartDelimiter(); for (size_t i = 0; i < values.size(); ++i) { writeChar('\"', out); writeString(values[i], out); writeChar('\"', out); if (i != values.size() - 1) writeFieldDelimiter(); } writeRowEndDelimiter(); } void JSONCompactEachRowRowOutputFormat::doWritePrefix() { const auto & header = getPort(PortKind::Main).getHeader(); if (with_names) writeLine(header.getNames()); if (with_types) writeLine(header.getDataTypeNames()); } void JSONCompactEachRowRowOutputFormat::consumeTotals(DB::Chunk chunk) { if (with_names) IRowOutputFormat::consumeTotals(std::move(chunk)); } void registerOutputFormatJSONCompactEachRow(FormatFactory & factory) { for (bool yield_strings : {false, true}) { auto register_func = [&](const String & format_name, bool with_names, bool with_types) { factory.registerOutputFormat(format_name, [yield_strings, with_names, with_types]( WriteBuffer & buf, const Block & sample, const RowOutputFormatParams & params, const FormatSettings & format_settings) { return std::make_shared<JSONCompactEachRowRowOutputFormat>(buf, sample, params, format_settings, with_names, with_types, yield_strings); }); factory.markOutputFormatSupportsParallelFormatting(format_name); }; registerWithNamesAndTypes(yield_strings ? "JSONCompactStringsEachRow" : "JSONCompactEachRow", register_func); } } }
3,476
1,054
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the HiGHS linear optimization suite */ /* */ /* Written and engineered 2008-2021 at the University of Edinburgh */ /* */ /* Available as open-source under the MIT License */ /* */ /* Authors: Julian Hall, Ivet Galabova, Qi Huangfu, Leona Gottwald */ /* and Michael Feldmeier */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file lp_data/HighsUtils.cpp * @brief Class-independent utilities for HiGHS */ #include "lp_data/HighsModelUtils.h" #include <algorithm> #include <vector> #include "HConfig.h" #include "io/HighsIO.h" #include "lp_data/HConst.h" #include "util/HighsUtils.h" HighsStatus assessMatrixDimensions(const HighsLogOptions& log_options, const std::string matrix_name, const HighsInt num_vec, const vector<HighsInt>& matrix_start, const vector<HighsInt>& matrix_index, const vector<double>& matrix_value) { HighsStatus return_status = HighsStatus::kOk; // Use error_found to track whether an error has been found in multiple tests bool error_found = false; // Assess main dimensions bool legal_num_vec = num_vec >= 0; if (!legal_num_vec) { highsLogUser(log_options, HighsLogType::kError, "%s matrix has illegal number of vectors = %" HIGHSINT_FORMAT "\n", matrix_name.c_str(), num_vec); error_found = true; } HighsInt matrix_start_size = matrix_start.size(); bool legal_matrix_start_size = false; // Don't expect the matrix_start_size to be legal if there are no vectors if (num_vec > 0) { legal_matrix_start_size = matrix_start_size >= num_vec + 1; if (!legal_matrix_start_size) { highsLogUser(log_options, HighsLogType::kError, "%s matrix has illegal start vector size = %" HIGHSINT_FORMAT " < %" HIGHSINT_FORMAT "\n", matrix_name.c_str(), matrix_start_size, num_vec + 1); error_found = true; } } if (matrix_start_size > 0) { // Check whether the first start is zero if (matrix_start[0]) { highsLogUser(log_options, HighsLogType::kWarning, "%s matrix start vector begins with %" HIGHSINT_FORMAT " rather than 0\n", matrix_name.c_str(), matrix_start[0]); error_found = true; } } // Possibly check the sizes of the index and value vectors. Can only // do this with the number of nonzeros, and this is only known if // the start vector has a legal size. Setting num_nz = 0 otherwise // means that all tests pass, as they just check that the sizes of // the index and value vectors are non-negative. HighsInt num_nz = 0; if (legal_matrix_start_size) num_nz = matrix_start[num_vec]; bool legal_num_nz = num_nz >= 0; if (!legal_num_nz) { highsLogUser(log_options, HighsLogType::kError, "%s matrix has illegal number of nonzeros = %" HIGHSINT_FORMAT "\n", matrix_name.c_str(), num_nz); error_found = true; } else { HighsInt matrix_index_size = matrix_index.size(); HighsInt matrix_value_size = matrix_value.size(); bool legal_matrix_index_size = matrix_index_size >= num_nz; bool legal_matrix_value_size = matrix_value_size >= num_nz; if (!legal_matrix_index_size) { highsLogUser(log_options, HighsLogType::kError, "%s matrix has illegal index vector size = %" HIGHSINT_FORMAT " < %" HIGHSINT_FORMAT "\n", matrix_name.c_str(), matrix_index_size, num_nz); error_found = true; } if (!legal_matrix_value_size) { highsLogUser(log_options, HighsLogType::kError, "%s matrix has illegal value vector size = %" HIGHSINT_FORMAT " < %" HIGHSINT_FORMAT "\n", matrix_name.c_str(), matrix_value_size, num_nz); error_found = true; } } if (error_found) return_status = HighsStatus::kError; else return_status = HighsStatus::kOk; return return_status; } HighsStatus assessMatrix(const HighsLogOptions& log_options, const std::string matrix_name, const HighsInt vec_dim, const HighsInt num_vec, vector<HighsInt>& matrix_start, vector<HighsInt>& matrix_index, vector<double>& matrix_value, const double small_matrix_value, const double large_matrix_value) { if (assessMatrixDimensions(log_options, matrix_name, num_vec, matrix_start, matrix_index, matrix_value) == HighsStatus::kError) return HighsStatus::kError; const HighsInt num_nz = matrix_start[num_vec]; if (num_vec <= 0) return HighsStatus::kOk; if (num_nz <= 0) return HighsStatus::kOk; HighsStatus return_status = HighsStatus::kOk; bool error_found = false; bool warning_found = false; // Assess the starts // Set up previous_start for a fictitious previous empty packed vector HighsInt previous_start = matrix_start[0]; for (HighsInt ix = 0; ix < num_vec; ix++) { HighsInt this_start = matrix_start[ix]; bool this_start_too_small = this_start < previous_start; if (this_start_too_small) { highsLogUser(log_options, HighsLogType::kError, "%s matrix packed vector %" HIGHSINT_FORMAT " has illegal start of %" HIGHSINT_FORMAT " < %" HIGHSINT_FORMAT " = " "previous start\n", matrix_name.c_str(), ix, this_start, previous_start); return HighsStatus::kError; } bool this_start_too_big = this_start > num_nz; if (this_start_too_big) { highsLogUser(log_options, HighsLogType::kError, "%s matrix packed vector %" HIGHSINT_FORMAT " has illegal start of %" HIGHSINT_FORMAT " > %" HIGHSINT_FORMAT " = " "number of nonzeros\n", matrix_name.c_str(), ix, this_start, num_nz); return HighsStatus::kError; } } // Assess the indices and values // Count the number of acceptable indices/values HighsInt num_new_nz = 0; HighsInt num_small_values = 0; double max_small_value = 0; double min_small_value = kHighsInf; // Set up a zeroed vector to detect duplicate indices vector<HighsInt> check_vector; if (vec_dim > 0) check_vector.assign(vec_dim, 0); for (HighsInt ix = 0; ix < num_vec; ix++) { HighsInt from_el = matrix_start[ix]; HighsInt to_el = matrix_start[ix + 1]; // Account for any index-value pairs removed so far matrix_start[ix] = num_new_nz; for (HighsInt el = from_el; el < to_el; el++) { // Check the index HighsInt component = matrix_index[el]; // Check that the index is non-negative bool legal_component = component >= 0; if (!legal_component) { highsLogUser(log_options, HighsLogType::kError, "%s matrix packed vector %" HIGHSINT_FORMAT ", entry %" HIGHSINT_FORMAT ", is illegal index %" HIGHSINT_FORMAT "\n", matrix_name.c_str(), ix, el, component); return HighsStatus::kError; } // Check that the index does not exceed the vector dimension legal_component = component < vec_dim; if (!legal_component) { highsLogUser(log_options, HighsLogType::kError, "%s matrix packed vector %" HIGHSINT_FORMAT ", entry %" HIGHSINT_FORMAT ", is illegal index " "%12" HIGHSINT_FORMAT " >= %" HIGHSINT_FORMAT " = vector dimension\n", matrix_name.c_str(), ix, el, component, vec_dim); return HighsStatus::kError; } // Check that the index has not already ocurred legal_component = check_vector[component] == 0; if (!legal_component) { highsLogUser(log_options, HighsLogType::kError, "%s matrix packed vector %" HIGHSINT_FORMAT ", entry %" HIGHSINT_FORMAT ", is duplicate index %" HIGHSINT_FORMAT "\n", matrix_name.c_str(), ix, el, component); return HighsStatus::kError; } // Indicate that the index has occurred check_vector[component] = 1; // Check the value double abs_value = fabs(matrix_value[el]); /* // Check that the value is not zero bool zero_value = abs_value == 0; if (zero_value) { highsLogUser(log_options, HighsLogType::kError, "%s matrix packed vector %" HIGHSINT_FORMAT ", entry %" HIGHSINT_FORMAT ", is zero\n", matrix_name.c_str(), ix, el); return HighsStatus::kError; } */ // Check that the value is not too large bool large_value = abs_value > large_matrix_value; if (large_value) { highsLogUser( log_options, HighsLogType::kError, "%s matrix packed vector %" HIGHSINT_FORMAT ", entry %" HIGHSINT_FORMAT ", is large value |%g| >= %g\n", matrix_name.c_str(), ix, el, abs_value, large_matrix_value); return HighsStatus::kError; } bool ok_value = abs_value > small_matrix_value; if (!ok_value) { if (max_small_value < abs_value) max_small_value = abs_value; if (min_small_value > abs_value) min_small_value = abs_value; num_small_values++; } if (ok_value) { // Shift the index and value of the OK entry to the new // position in the index and value vectors, and increment // the new number of nonzeros matrix_index[num_new_nz] = matrix_index[el]; matrix_value[num_new_nz] = matrix_value[el]; num_new_nz++; } else { // Zero the check_vector entry since the small value // _hasn't_ occurred check_vector[component] = 0; } } // Zero check_vector for (HighsInt el = matrix_start[ix]; el < num_new_nz; el++) check_vector[matrix_index[el]] = 0; #ifdef HiGHSDEV // NB This is very expensive so shouldn't be true const bool check_check_vector = false; if (check_check_vector) { // Check zeroing of check vector for (HighsInt component = 0; component < vec_dim; component++) { if (check_vector[component]) error_found = true; } if (error_found) highsLogUser(log_options, HighsLogType::kError, "assessMatrix: check_vector not zeroed\n"); } #endif } if (num_small_values) { highsLogUser(log_options, HighsLogType::kWarning, "%s matrix packed vector contains %" HIGHSINT_FORMAT " |values| in [%g, %g] " "less than %g: ignored\n", matrix_name.c_str(), num_small_values, min_small_value, max_small_value, small_matrix_value); warning_found = true; } matrix_start[num_vec] = num_new_nz; if (error_found) return_status = HighsStatus::kError; else if (warning_found) return_status = HighsStatus::kWarning; else return_status = HighsStatus::kOk; return return_status; } void analyseModelBounds(const HighsLogOptions& log_options, const char* message, HighsInt numBd, const std::vector<double>& lower, const std::vector<double>& upper) { if (numBd == 0) return; HighsInt numFr = 0; HighsInt numLb = 0; HighsInt numUb = 0; HighsInt numBx = 0; HighsInt numFx = 0; for (HighsInt ix = 0; ix < numBd; ix++) { if (highs_isInfinity(-lower[ix])) { // Infinite lower bound if (highs_isInfinity(upper[ix])) { // Infinite lower bound and infinite upper bound: Fr numFr++; } else { // Infinite lower bound and finite upper bound: Ub numUb++; } } else { // Finite lower bound if (highs_isInfinity(upper[ix])) { // Finite lower bound and infinite upper bound: Lb numLb++; } else { // Finite lower bound and finite upper bound: if (lower[ix] < upper[ix]) { // Distinct finite bounds: Bx numBx++; } else { // Equal finite bounds: Fx numFx++; } } } } highsLogDev(log_options, HighsLogType::kInfo, "Analysing %" HIGHSINT_FORMAT " %s bounds\n", numBd, message); if (numFr > 0) highsLogDev(log_options, HighsLogType::kInfo, " Free: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n", numFr, (100 * numFr) / numBd); if (numLb > 0) highsLogDev(log_options, HighsLogType::kInfo, " LB: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n", numLb, (100 * numLb) / numBd); if (numUb > 0) highsLogDev(log_options, HighsLogType::kInfo, " UB: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n", numUb, (100 * numUb) / numBd); if (numBx > 0) highsLogDev(log_options, HighsLogType::kInfo, " Boxed: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n", numBx, (100 * numBx) / numBd); if (numFx > 0) highsLogDev(log_options, HighsLogType::kInfo, " Fixed: %7" HIGHSINT_FORMAT " (%3" HIGHSINT_FORMAT "%%)\n", numFx, (100 * numFx) / numBd); highsLogDev(log_options, HighsLogType::kInfo, "grep_CharMl,%s,Free,LB,UB,Boxed,Fixed\n", message); highsLogDev(log_options, HighsLogType::kInfo, "grep_CharMl,%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT ",%" HIGHSINT_FORMAT "\n", numBd, numFr, numLb, numUb, numBx, numFx); } std::string statusToString(const HighsBasisStatus status, const double lower, const double upper) { switch (status) { case HighsBasisStatus::kLower: if (lower == upper) { return "FX"; } else { return "LB"; } break; case HighsBasisStatus::kBasic: return "BS"; break; case HighsBasisStatus::kUpper: return "UB"; break; case HighsBasisStatus::kZero: return "FR"; break; case HighsBasisStatus::kNonbasic: return "NB"; break; } return ""; } void writeModelBoundSolution(FILE* file, const bool columns, const HighsInt dim, const std::vector<double>& lower, const std::vector<double>& upper, const std::vector<std::string>& names, const std::vector<double>& primal, const std::vector<double>& dual, const std::vector<HighsBasisStatus>& status) { const bool have_names = names.size() > 0; const bool have_primal = primal.size() > 0; const bool have_dual = dual.size() > 0; const bool have_basis = status.size() > 0; if (have_names) assert((int)names.size() >= dim); if (have_primal) assert((int)primal.size() >= dim); if (have_dual) assert((int)dual.size() >= dim); if (have_basis) assert((int)status.size() >= dim); std::string var_status_string; if (columns) { fprintf(file, "Columns\n"); } else { fprintf(file, "Rows\n"); } fprintf( file, " Index Status Lower Upper Primal Dual"); if (have_names) { fprintf(file, " Name\n"); } else { fprintf(file, "\n"); } for (HighsInt ix = 0; ix < dim; ix++) { if (have_basis) { var_status_string = statusToString(status[ix], lower[ix], upper[ix]); } else { var_status_string = ""; } fprintf(file, "%9" HIGHSINT_FORMAT " %4s %12g %12g", ix, var_status_string.c_str(), lower[ix], upper[ix]); if (have_primal) { fprintf(file, " %12g", primal[ix]); } else { fprintf(file, " "); } if (have_dual) { fprintf(file, " %12g", dual[ix]); } else { fprintf(file, " "); } if (have_names) { fprintf(file, " %-s\n", names[ix].c_str()); } else { fprintf(file, "\n"); } } } void writeModelSolution(FILE* file, const HighsOptions& options, double solutionObjective, const HighsInt dim, const std::vector<std::string>& names, const std::vector<double>& primal, const std::vector<HighsVarType>& integrality) { const bool have_names = names.size() > 0; const bool have_primal = primal.size() > 0; const bool have_integrality = integrality.size() > 0; if (!have_names || !have_primal) return; if (have_names) assert((int)names.size() >= dim); if (have_primal) assert((int)primal.size() >= dim); if (have_integrality) assert((int)integrality.size() >= dim); std::array<char, 32> objStr = highsDoubleToString(solutionObjective, 1e-13); fprintf(file, "=obj= %s\n", objStr.data()); for (HighsInt ix = 0; ix < dim; ix++) { std::array<char, 32> valStr = highsDoubleToString(primal[ix], 1e-13); fprintf(file, "%-s %s\n", names[ix].c_str(), valStr.data()); } } bool namesWithSpaces(const HighsInt num_name, const std::vector<std::string>& names, const bool report) { bool names_with_spaces = false; for (HighsInt ix = 0; ix < num_name; ix++) { HighsInt space_pos = names[ix].find(" "); if (space_pos >= 0) { if (report) printf( "Name |%s| contains a space character in position %" HIGHSINT_FORMAT "\n", names[ix].c_str(), space_pos); names_with_spaces = true; } } return names_with_spaces; } HighsInt maxNameLength(const HighsInt num_name, const std::vector<std::string>& names) { HighsInt max_name_length = 0; for (HighsInt ix = 0; ix < num_name; ix++) max_name_length = std::max((HighsInt)names[ix].length(), max_name_length); return max_name_length; } HighsStatus normaliseNames(const HighsLogOptions& log_options, const std::string name_type, const HighsInt num_name, std::vector<std::string>& names, HighsInt& max_name_length) { // Record the desired maximum name length HighsInt desired_max_name_length = max_name_length; // First look for empty names HighsInt num_empty_name = 0; std::string name_prefix = name_type.substr(0, 1); bool names_with_spaces = false; for (HighsInt ix = 0; ix < num_name; ix++) { if ((HighsInt)names[ix].length() == 0) num_empty_name++; } // If there are no empty names - in which case they will all be // replaced - find the maximum name length if (!num_empty_name) max_name_length = maxNameLength(num_name, names); bool construct_names = num_empty_name || max_name_length > desired_max_name_length; if (construct_names) { // Construct names, either because they are empty names, or // because the existing names are too long highsLogUser(log_options, HighsLogType::kWarning, "There are empty or excessively-long %s names: using " "constructed names with prefix %s\n", name_type.c_str(), name_prefix.c_str()); for (HighsInt ix = 0; ix < num_name; ix++) names[ix] = name_prefix + std::to_string(ix); } else { // Using original names, so look to see whether there are names with spaces names_with_spaces = namesWithSpaces(num_name, names); } // Find the final maximum name length max_name_length = maxNameLength(num_name, names); // Can't have names with spaces and more than 8 characters if (max_name_length > 8 && names_with_spaces) return HighsStatus::kError; if (construct_names) return HighsStatus::kWarning; return HighsStatus::kOk; } HighsBasisStatus checkedVarHighsNonbasicStatus( const HighsBasisStatus ideal_status, const double lower, const double upper) { HighsBasisStatus checked_status; if (ideal_status == HighsBasisStatus::kLower || ideal_status == HighsBasisStatus::kZero) { // Looking to give status LOWER or ZERO if (highs_isInfinity(-lower)) { // Lower bound is infinite if (highs_isInfinity(upper)) { // Upper bound is infinite checked_status = HighsBasisStatus::kZero; } else { // Upper bound is finite checked_status = HighsBasisStatus::kUpper; } } else { checked_status = HighsBasisStatus::kLower; } } else { // Looking to give status UPPER if (highs_isInfinity(upper)) { // Upper bound is infinite if (highs_isInfinity(-lower)) { // Lower bound is infinite checked_status = HighsBasisStatus::kZero; } else { // Upper bound is finite checked_status = HighsBasisStatus::kLower; } } else { checked_status = HighsBasisStatus::kUpper; } } return checked_status; } // Return a string representation of SolutionStatus std::string utilSolutionStatusToString(const HighsInt solution_status) { switch (solution_status) { case kSolutionStatusNone: return "None"; break; case kSolutionStatusInfeasible: return "Infeasible"; break; case kSolutionStatusFeasible: return "Feasible"; break; default: assert(1 == 0); return "Unrecognised solution status"; } } // Return a string representation of HighsBasisStatus std::string utilBasisStatusToString(const HighsBasisStatus basis_status) { switch (basis_status) { case HighsBasisStatus::kLower: return "At lower/fixed bound"; break; case HighsBasisStatus::kBasic: return "Basic"; break; case HighsBasisStatus::kUpper: return "At upper bound"; break; case HighsBasisStatus::kZero: return "Free at zero"; break; case HighsBasisStatus::kNonbasic: return "Nonbasic"; break; default: assert(1 == 0); return "Unrecognised solution status"; } } // Return a string representation of basis validity std::string utilBasisValidityToString(const HighsInt basis_validity) { if (basis_validity) { return "Valid"; } else { return "Not valid"; } } // Return a string representation of HighsModelStatus. std::string utilModelStatusToString(const HighsModelStatus model_status) { switch (model_status) { case HighsModelStatus::kNotset: return "Not Set"; break; case HighsModelStatus::kLoadError: return "Load error"; break; case HighsModelStatus::kModelError: return "Model error"; break; case HighsModelStatus::kPresolveError: return "Presolve error"; break; case HighsModelStatus::kSolveError: return "Solve error"; break; case HighsModelStatus::kPostsolveError: return "Postsolve error"; break; case HighsModelStatus::kModelEmpty: return "Model empty"; break; case HighsModelStatus::kOptimal: return "Optimal"; break; case HighsModelStatus::kInfeasible: return "Infeasible"; break; case HighsModelStatus::kUnboundedOrInfeasible: return "Primal infeasible or unbounded"; break; case HighsModelStatus::kUnbounded: return "Unbounded"; break; case HighsModelStatus::kObjectiveBound: return "Reached objective bound"; break; case HighsModelStatus::kObjectiveTarget: return "Reached objective target"; break; case HighsModelStatus::kTimeLimit: return "Reached time limit"; break; case HighsModelStatus::kIterationLimit: return "Reached iteration limit"; break; case HighsModelStatus::kUnknown: return "Unknown"; break; default: assert(1 == 0); return "Unrecognised HiGHS model status"; } } void zeroHighsIterationCounts(HighsIterationCounts& iteration_counts) { iteration_counts.simplex = 0; iteration_counts.ipm = 0; iteration_counts.crossover = 0; iteration_counts.qp = 0; } // Deduce the HighsStatus value corresponding to a HighsModelStatus value. HighsStatus highsStatusFromHighsModelStatus(HighsModelStatus model_status) { switch (model_status) { case HighsModelStatus::kNotset: return HighsStatus::kError; case HighsModelStatus::kLoadError: return HighsStatus::kError; case HighsModelStatus::kModelError: return HighsStatus::kError; case HighsModelStatus::kPresolveError: return HighsStatus::kError; case HighsModelStatus::kSolveError: return HighsStatus::kError; case HighsModelStatus::kPostsolveError: return HighsStatus::kError; case HighsModelStatus::kModelEmpty: return HighsStatus::kOk; case HighsModelStatus::kOptimal: return HighsStatus::kOk; case HighsModelStatus::kInfeasible: return HighsStatus::kOk; case HighsModelStatus::kUnboundedOrInfeasible: return HighsStatus::kOk; case HighsModelStatus::kUnbounded: return HighsStatus::kOk; case HighsModelStatus::kObjectiveBound: return HighsStatus::kOk; case HighsModelStatus::kObjectiveTarget: return HighsStatus::kOk; case HighsModelStatus::kTimeLimit: return HighsStatus::kWarning; case HighsModelStatus::kIterationLimit: return HighsStatus::kWarning; case HighsModelStatus::kUnknown: return HighsStatus::kWarning; default: return HighsStatus::kError; } }
26,344
8,439
#pragma once #include <so_5_extra/disp/asio_one_thread/pub.hpp> void make_coop_a( so_5::environment_t & env, so_5::extra::disp::asio_one_thread::dispatcher_handle_t disp );
178
79
/* This file is a part of liblsdj, a C library for managing everything that has to do with LSDJ, software for writing music (chiptune) with your gameboy. For more information, see: * https://github.com/stijnfrishert/liblsdj * http://www.littlesounddj.com -------------------------------------------------------------------------------- MIT License Copyright (c) 2018 - 2020 Stijn Frishert Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef LSDJ_WAVETABLE_IMPORTER_HPP #define LSDJ_WAVETABLE_IMPORTER_HPP #include <ghc/filesystem.hpp> #include <string> #include <vector> #include <lsdj/error.h> #include <lsdj/song.h> namespace lsdj { class WavetableImporter { public: bool import(const std::string& projectName, const std::string& wavetableName); public: std::string outputName; uint8_t wavetableIndex = 0; bool zero = false; bool force = false; bool verbose = false; private: bool importToSav(const ghc::filesystem::path& path, const std::string& wavetableName); bool importToLsdsng(const ghc::filesystem::path& path, const std::string& wavetableName); std::pair<bool, unsigned int> importToSong(lsdj_song_t* song, const std::string& wavetableName); }; } #endif
2,314
758
#include "OptimisticTask.h" /// In the optimistic task, you get reward epsilon in the normal /// state, reward 1 in the good state. OptimisticTask::OptimisticTask(real epsilon_, real delta_) : Environment<int, int>(3, 2), epsilon(epsilon_), delta(delta_) { Reset(); } void OptimisticTask::Reset() { state = 0; reward = 0; } bool OptimisticTask::Act(const int& action) { // get next state switch (state) { case 0: if (action == 0) { state = 0; } else { state = 1; } break; case 1: if (urandom() < delta) { if (action == 0) { state = 0; } else { state = 2; } } break; case 2: if (action == 1) { state = 2; } else { state = 1; } break; } // get next reward switch (state) { case 0: case 2: reward = epsilon; break; case 1: reward = 0; break; } return true; } DiscreteMDP* OptimisticTask::getMDP() const { DiscreteMDP* mdp = new DiscreteMDP(n_states, n_actions); // get next state mdp->setTransitionProbability(0, 0, 0, 1); mdp->setTransitionProbability(0, 1, 1, 1); mdp->setTransitionProbability(2, 0, 1, 1); mdp->setTransitionProbability(2, 1, 2, 1); mdp->setTransitionProbability(1, 0, 0, delta); mdp->setTransitionProbability(1, 0, 1, 1 - delta); mdp->setTransitionProbability(1, 1, 2, delta); mdp->setTransitionProbability(1, 1, 1, 1 - delta); mdp->addFixedReward(0, 0, epsilon); mdp->addFixedReward(0, 1, epsilon); mdp->addFixedReward(1, 0, 0.0); mdp->addFixedReward(1, 1, 0.0); mdp->addFixedReward(2, 0, epsilon); mdp->addFixedReward(2, 1, epsilon); return mdp; }
1,728
722
/* * Copyright (c) 2011-2020, The Linux Foundation. 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 Linux Foundation 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 "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <log/log.h> #include <cutils/properties.h> #include <algorithm> #include <vector> #include "gr_allocator.h" #include "gr_utils.h" #include "gralloc_priv.h" #include "qd_utils.h" #ifndef ION_FLAG_CP_PIXEL #define ION_FLAG_CP_PIXEL 0 #endif #ifndef ION_FLAG_ALLOW_NON_CONTIG #define ION_FLAG_ALLOW_NON_CONTIG 0 #endif #ifndef ION_FLAG_CP_CAMERA_PREVIEW #define ION_FLAG_CP_CAMERA_PREVIEW 0 #endif #ifndef ION_SECURE #define ION_SECURE ION_FLAG_SECURE #endif #ifndef ION_FLAG_CP_CDSP #define ION_FLAG_CP_CDSP 0 #endif #ifdef SLAVE_SIDE_CP #define CP_HEAP_ID ION_CP_MM_HEAP_ID #define SD_HEAP_ID CP_HEAP_ID #define ION_CP_FLAGS (ION_SECURE | ION_FLAG_ALLOW_NON_CONTIG) #define ION_SD_FLAGS ION_SECURE #define ION_SC_FLAGS ION_SECURE #define ION_SC_PREVIEW_FLAGS ION_SECURE #else // MASTER_SIDE_CP #ifdef HYPERVISOR #define CP_HEAP_ID ION_SECURE_DISPLAY_HEAP_ID #else #define CP_HEAP_ID ION_SECURE_HEAP_ID #endif #define SD_HEAP_ID ION_SECURE_DISPLAY_HEAP_ID #define ION_CP_FLAGS (ION_SECURE | ION_FLAG_CP_PIXEL) #define ION_SD_FLAGS (ION_SECURE | ION_FLAG_CP_SEC_DISPLAY) #define ION_SC_FLAGS (ION_SECURE | ION_FLAG_CP_CAMERA) #define ION_SC_PREVIEW_FLAGS (ION_SECURE | ION_FLAG_CP_CAMERA_PREVIEW) #endif using std::shared_ptr; using std::vector; namespace gralloc { static BufferInfo GetBufferInfo(const BufferDescriptor &descriptor) { return BufferInfo(descriptor.GetWidth(), descriptor.GetHeight(), descriptor.GetFormat(), descriptor.GetUsage()); } Allocator::Allocator() : ion_allocator_(nullptr) {} bool Allocator::Init() { ion_allocator_ = new IonAlloc(); if (!ion_allocator_->Init()) { return false; } return true; } Allocator::~Allocator() { if (ion_allocator_) { delete ion_allocator_; } } void Allocator::SetProperties(gralloc::GrallocProperties props) { use_system_heap_for_sensors_ = props.use_system_heap_for_sensors; } int Allocator::AllocateMem(AllocData *alloc_data, uint64_t usage, int format) { int ret; alloc_data->uncached = UseUncached(format, usage); // After this point we should have the right heap set, there is no fallback GetIonHeapInfo(usage, &alloc_data->heap_id, &alloc_data->alloc_type, &alloc_data->flags); ret = ion_allocator_->AllocBuffer(alloc_data); if (ret >= 0) { alloc_data->alloc_type |= private_handle_t::PRIV_FLAGS_USES_ION; } else { ALOGE("%s: Failed to allocate buffer - heap: 0x%x flags: 0x%x", __FUNCTION__, alloc_data->heap_id, alloc_data->flags); } return ret; } int Allocator::MapBuffer(void **base, unsigned int size, unsigned int offset, int fd) { if (ion_allocator_) { return ion_allocator_->MapBuffer(base, size, offset, fd); } return -EINVAL; } int Allocator::ImportBuffer(int fd) { if (ion_allocator_) { return ion_allocator_->ImportBuffer(fd); } return -EINVAL; } int Allocator::FreeBuffer(void *base, unsigned int size, unsigned int offset, int fd, int handle) { if (ion_allocator_) { return ion_allocator_->FreeBuffer(base, size, offset, fd, handle); } return -EINVAL; } int Allocator::CleanBuffer(void *base, unsigned int size, unsigned int offset, int handle, int op, int fd) { if (ion_allocator_) { return ion_allocator_->CleanBuffer(base, size, offset, handle, op, fd); } return -EINVAL; } bool Allocator::CheckForBufferSharing(uint32_t num_descriptors, const vector<shared_ptr<BufferDescriptor>> &descriptors, ssize_t *max_index) { unsigned int cur_heap_id = 0, prev_heap_id = 0; unsigned int cur_alloc_type = 0, prev_alloc_type = 0; unsigned int cur_ion_flags = 0, prev_ion_flags = 0; bool cur_uncached = false, prev_uncached = false; unsigned int alignedw, alignedh; unsigned int max_size = 0; *max_index = -1; for (uint32_t i = 0; i < num_descriptors; i++) { // Check Cached vs non-cached and all the ION flags cur_uncached = UseUncached(descriptors[i]->GetFormat(), descriptors[i]->GetUsage()); GetIonHeapInfo(descriptors[i]->GetUsage(), &cur_heap_id, &cur_alloc_type, &cur_ion_flags); if (i > 0 && (cur_heap_id != prev_heap_id || cur_alloc_type != prev_alloc_type || cur_ion_flags != prev_ion_flags)) { return false; } // For same format type, find the descriptor with bigger size GetAlignedWidthAndHeight(GetBufferInfo(*descriptors[i]), &alignedw, &alignedh); unsigned int size = GetSize(GetBufferInfo(*descriptors[i]), alignedw, alignedh); if (max_size < size) { *max_index = INT(i); max_size = size; } prev_heap_id = cur_heap_id; prev_uncached = cur_uncached; prev_ion_flags = cur_ion_flags; prev_alloc_type = cur_alloc_type; } return true; } void Allocator::GetIonHeapInfo(uint64_t usage, unsigned int *ion_heap_id, unsigned int *alloc_type, unsigned int *ion_flags) { unsigned int heap_id = 0; unsigned int type = 0; uint32_t flags = 0; if (usage & GRALLOC_USAGE_PROTECTED) { if (usage & GRALLOC_USAGE_PRIVATE_SECURE_DISPLAY) { heap_id = ION_HEAP(SD_HEAP_ID); /* * There is currently no flag in ION for Secure Display * VM. Please add it to the define once available. */ flags |= UINT(ION_SD_FLAGS); } else if (usage & BufferUsage::CAMERA_OUTPUT) { heap_id = ION_HEAP(SD_HEAP_ID); if (usage & GRALLOC_USAGE_PRIVATE_CDSP) { flags |= UINT(ION_SECURE | ION_FLAG_CP_CDSP); } if (usage & BufferUsage::COMPOSER_OVERLAY) { flags |= UINT(ION_SC_PREVIEW_FLAGS); } else { flags |= UINT(ION_SC_FLAGS); } } else if (usage & GRALLOC_USAGE_PRIVATE_CDSP) { heap_id = ION_HEAP(ION_SECURE_CARVEOUT_HEAP_ID); flags |= UINT(ION_SECURE | ION_FLAG_CP_CDSP); } else { heap_id = ION_HEAP(CP_HEAP_ID); flags |= UINT(ION_CP_FLAGS); } } if (usage & BufferUsage::SENSOR_DIRECT_DATA) { if (use_system_heap_for_sensors_) { ALOGI("gralloc::sns_direct_data with system_heap"); heap_id |= ION_HEAP(ION_SYSTEM_HEAP_ID); } else { ALOGI("gralloc::sns_direct_data with adsp_heap"); heap_id |= ION_HEAP(ION_ADSP_HEAP_ID); } } if (flags & UINT(ION_SECURE)) { type |= private_handle_t::PRIV_FLAGS_SECURE_BUFFER; } // if no ion heap flags are set, default to system heap if (!heap_id) { heap_id = ION_HEAP(ION_SYSTEM_HEAP_ID); } *alloc_type = type; *ion_flags = flags; *ion_heap_id = heap_id; return; } } // namespace gralloc
8,184
3,167
#include <cstdio> #include <vector> #include <limits> #include <algorithm> using namespace std; int g[501][501]; int stoer_wagner(int N) { vector<int> v(N); for (int i = 0; i < N; i++) { v[i] = i; } int cut = numeric_limits<int>::max(); for (int m = N; m > 1; m--) { //vector<int> ws(m, 0); int ws[501]; fill(ws, ws + m, 0); int s, t = 0; int w; for (int k = 0; k < m; k++) { s = t; t = distance(ws, max_element(ws, ws + m)); w = ws[t]; ws[t] = -1; for (int i = 0; i < m; i++) { if (ws[i] >= 0) { ws[i] += g[v[t]][v[i]]; } } } for (int i = 0; i < m; i++) { g[v[i]][v[s]] += g[v[i]][v[t]]; g[v[s]][v[i]] += g[v[t]][v[i]]; } v.erase(v.begin() + t); cut = min(cut, w); } return cut; } int main() { int N, M; while (scanf("%d %d", &N, &M) != EOF) { for (int i = 0; i < N; i++) { fill(g[i], g[i] + N, 0); } for (int i = 0; i < M; i++) { int u, v, w; scanf("%d %d %d", &u, &v, &w); g[u][v] += w; g[v][u] += w; } printf("%d\n", stoer_wagner(N)); } return 0; }
1,150
571
// Copyright (c) 2012 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 <string.h> #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/extensions/extension_function_test_utils.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/ui/browser.h" #include "chrome/test/base/ui_test_utils.h" #include "device/bluetooth/bluetooth_adapter.h" #include "device/bluetooth/bluetooth_uuid.h" #include "device/bluetooth/test/mock_bluetooth_adapter.h" #include "device/bluetooth/test/mock_bluetooth_device.h" #include "device/bluetooth/test/mock_bluetooth_discovery_session.h" #include "extensions/browser/api/bluetooth/bluetooth_api.h" #include "extensions/browser/api/bluetooth/bluetooth_event_router.h" #include "extensions/common/test_util.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" #include "testing/gmock/include/gmock/gmock.h" using device::BluetoothAdapter; using device::BluetoothDevice; using device::BluetoothDiscoverySession; using device::BluetoothUUID; using device::MockBluetoothAdapter; using device::MockBluetoothDevice; using device::MockBluetoothDiscoverySession; using extensions::Extension; using extensions::ResultCatcher; namespace utils = extension_function_test_utils; namespace api = extensions::core_api; namespace { static const char* kAdapterAddress = "A1:A2:A3:A4:A5:A6"; static const char* kName = "whatsinaname"; class BluetoothApiTest : public ExtensionApiTest { public: BluetoothApiTest() {} virtual void SetUpOnMainThread() OVERRIDE { ExtensionApiTest::SetUpOnMainThread(); empty_extension_ = extensions::test_util::CreateEmptyExtension(); SetUpMockAdapter(); } virtual void TearDownOnMainThread() OVERRIDE { EXPECT_CALL(*mock_adapter_, RemoveObserver(testing::_)); } void SetUpMockAdapter() { // The browser will clean this up when it is torn down mock_adapter_ = new testing::StrictMock<MockBluetoothAdapter>(); event_router()->SetAdapterForTest(mock_adapter_); device1_.reset(new testing::NiceMock<MockBluetoothDevice>( mock_adapter_, 0, "d1", "11:12:13:14:15:16", true /* paired */, true /* connected */)); device2_.reset(new testing::NiceMock<MockBluetoothDevice>( mock_adapter_, 0, "d2", "21:22:23:24:25:26", false /* paired */, false /* connected */)); device3_.reset(new testing::NiceMock<MockBluetoothDevice>( mock_adapter_, 0, "d3", "31:32:33:34:35:36", false /* paired */, false /* connected */)); } void DiscoverySessionCallback( const BluetoothAdapter::DiscoverySessionCallback& callback, const BluetoothAdapter::ErrorCallback& error_callback) { if (mock_session_.get()) { callback.Run( scoped_ptr<BluetoothDiscoverySession>(mock_session_.release())); return; } error_callback.Run(); } template <class T> T* setupFunction(T* function) { function->set_extension(empty_extension_.get()); function->set_has_callback(true); return function; } protected: testing::StrictMock<MockBluetoothAdapter>* mock_adapter_; scoped_ptr<testing::NiceMock<MockBluetoothDiscoverySession> > mock_session_; scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device1_; scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device2_; scoped_ptr<testing::NiceMock<MockBluetoothDevice> > device3_; extensions::BluetoothEventRouter* event_router() { return bluetooth_api()->event_router(); } extensions::BluetoothAPI* bluetooth_api() { return extensions::BluetoothAPI::Get(browser()->profile()); } private: scoped_refptr<Extension> empty_extension_; }; static void StopDiscoverySessionCallback(const base::Closure& callback, const base::Closure& error_callback) { callback.Run(); } } // namespace IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetAdapterState) { EXPECT_CALL(*mock_adapter_, GetAddress()) .WillOnce(testing::Return(kAdapterAddress)); EXPECT_CALL(*mock_adapter_, GetName()) .WillOnce(testing::Return(kName)); EXPECT_CALL(*mock_adapter_, IsPresent()) .WillOnce(testing::Return(false)); EXPECT_CALL(*mock_adapter_, IsPowered()) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_adapter_, IsDiscovering()) .WillOnce(testing::Return(false)); scoped_refptr<api::BluetoothGetAdapterStateFunction> get_adapter_state; get_adapter_state = setupFunction(new api::BluetoothGetAdapterStateFunction); scoped_ptr<base::Value> result(utils::RunFunctionAndReturnSingleResult( get_adapter_state.get(), "[]", browser())); ASSERT_TRUE(result.get() != NULL); api::bluetooth::AdapterState state; ASSERT_TRUE(api::bluetooth::AdapterState::Populate(*result, &state)); EXPECT_FALSE(state.available); EXPECT_TRUE(state.powered); EXPECT_FALSE(state.discovering); EXPECT_EQ(kName, state.name); EXPECT_EQ(kAdapterAddress, state.address); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DeviceEvents) { ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth/device_events"))); ExtensionTestMessageListener events_received("ready", true); event_router()->DeviceAdded(mock_adapter_, device1_.get()); event_router()->DeviceAdded(mock_adapter_, device2_.get()); EXPECT_CALL(*device2_.get(), GetDeviceName()) .WillRepeatedly(testing::Return("the real d2")); EXPECT_CALL(*device2_.get(), GetName()) .WillRepeatedly(testing::Return(base::UTF8ToUTF16("the real d2"))); event_router()->DeviceChanged(mock_adapter_, device2_.get()); event_router()->DeviceAdded(mock_adapter_, device3_.get()); event_router()->DeviceRemoved(mock_adapter_, device1_.get()); EXPECT_TRUE(events_received.WaitUntilSatisfied()); events_received.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, Discovery) { // Try with a failure to start. This will return an error as we haven't // initialied a session object. EXPECT_CALL(*mock_adapter_, StartDiscoverySession(testing::_, testing::_)) .WillOnce( testing::Invoke(this, &BluetoothApiTest::DiscoverySessionCallback)); // StartDiscovery failure will not reference the adapter. scoped_refptr<api::BluetoothStartDiscoveryFunction> start_function; start_function = setupFunction(new api::BluetoothStartDiscoveryFunction); std::string error( utils::RunFunctionAndReturnError(start_function.get(), "[]", browser())); ASSERT_FALSE(error.empty()); // Reset the adapter and initiate a discovery session. The ownership of the // mock session will be passed to the event router. ASSERT_FALSE(mock_session_.get()); SetUpMockAdapter(); // Create a mock session to be returned as a result. Get a handle to it as // its ownership will be passed and |mock_session_| will be reset. mock_session_.reset(new testing::NiceMock<MockBluetoothDiscoverySession>()); MockBluetoothDiscoverySession* session = mock_session_.get(); EXPECT_CALL(*mock_adapter_, StartDiscoverySession(testing::_, testing::_)) .WillOnce( testing::Invoke(this, &BluetoothApiTest::DiscoverySessionCallback)); start_function = setupFunction(new api::BluetoothStartDiscoveryFunction); (void) utils::RunFunctionAndReturnError(start_function.get(), "[]", browser()); // End the discovery session. The StopDiscovery function should succeed. testing::Mock::VerifyAndClearExpectations(mock_adapter_); EXPECT_CALL(*session, IsActive()).WillOnce(testing::Return(true)); EXPECT_CALL(*session, Stop(testing::_, testing::_)) .WillOnce(testing::Invoke(StopDiscoverySessionCallback)); // StopDiscovery success will remove the session object, unreferencing the // adapter. scoped_refptr<api::BluetoothStopDiscoveryFunction> stop_function; stop_function = setupFunction(new api::BluetoothStopDiscoveryFunction); (void) utils::RunFunctionAndReturnSingleResult( stop_function.get(), "[]", browser()); // Reset the adapter. Simulate failure for stop discovery. The event router // still owns the session. Make it appear inactive. SetUpMockAdapter(); EXPECT_CALL(*session, IsActive()).WillOnce(testing::Return(false)); stop_function = setupFunction(new api::BluetoothStopDiscoveryFunction); error = utils::RunFunctionAndReturnError(stop_function.get(), "[]", browser()); ASSERT_FALSE(error.empty()); SetUpMockAdapter(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DiscoveryCallback) { mock_session_.reset(new testing::NiceMock<MockBluetoothDiscoverySession>()); MockBluetoothDiscoverySession* session = mock_session_.get(); EXPECT_CALL(*mock_adapter_, StartDiscoverySession(testing::_, testing::_)) .WillOnce( testing::Invoke(this, &BluetoothApiTest::DiscoverySessionCallback)); EXPECT_CALL(*session, IsActive()).WillOnce(testing::Return(true)); EXPECT_CALL(*session, Stop(testing::_, testing::_)) .WillOnce(testing::Invoke(StopDiscoverySessionCallback)); ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); ExtensionTestMessageListener discovery_started("ready", true); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth/discovery_callback"))); EXPECT_TRUE(discovery_started.WaitUntilSatisfied()); event_router()->DeviceAdded(mock_adapter_, device1_.get()); discovery_started.Reply("go"); ExtensionTestMessageListener discovery_stopped("ready", true); EXPECT_CALL(*mock_adapter_, RemoveObserver(testing::_)); EXPECT_TRUE(discovery_stopped.WaitUntilSatisfied()); SetUpMockAdapter(); event_router()->DeviceAdded(mock_adapter_, device2_.get()); discovery_stopped.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DiscoveryInProgress) { EXPECT_CALL(*mock_adapter_, GetAddress()) .WillOnce(testing::Return(kAdapterAddress)); EXPECT_CALL(*mock_adapter_, GetName()) .WillOnce(testing::Return(kName)); EXPECT_CALL(*mock_adapter_, IsPresent()) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_adapter_, IsPowered()) .WillOnce(testing::Return(true)); // Fake that the adapter is discovering EXPECT_CALL(*mock_adapter_, IsDiscovering()) .WillOnce(testing::Return(true)); event_router()->AdapterDiscoveringChanged(mock_adapter_, true); // Cache a device before the extension starts discovering event_router()->DeviceAdded(mock_adapter_, device1_.get()); ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); mock_session_.reset(new testing::NiceMock<MockBluetoothDiscoverySession>()); MockBluetoothDiscoverySession* session = mock_session_.get(); EXPECT_CALL(*mock_adapter_, StartDiscoverySession(testing::_, testing::_)) .WillOnce( testing::Invoke(this, &BluetoothApiTest::DiscoverySessionCallback)); EXPECT_CALL(*session, IsActive()).WillOnce(testing::Return(true)); EXPECT_CALL(*session, Stop(testing::_, testing::_)) .WillOnce(testing::Invoke(StopDiscoverySessionCallback)); ExtensionTestMessageListener discovery_started("ready", true); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bluetooth/discovery_in_progress"))); EXPECT_TRUE(discovery_started.WaitUntilSatisfied()); // Only this should be received. No additional notification should be sent for // devices discovered before the discovery session started. event_router()->DeviceAdded(mock_adapter_, device2_.get()); discovery_started.Reply("go"); ExtensionTestMessageListener discovery_stopped("ready", true); EXPECT_CALL(*mock_adapter_, RemoveObserver(testing::_)); EXPECT_TRUE(discovery_stopped.WaitUntilSatisfied()); SetUpMockAdapter(); // This should never be received. event_router()->DeviceAdded(mock_adapter_, device2_.get()); discovery_stopped.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, OnAdapterStateChanged) { ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); // Load and wait for setup ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE( LoadExtension( test_data_dir_.AppendASCII("bluetooth/on_adapter_state_changed"))); EXPECT_TRUE(listener.WaitUntilSatisfied()); EXPECT_CALL(*mock_adapter_, GetAddress()) .WillOnce(testing::Return(kAdapterAddress)); EXPECT_CALL(*mock_adapter_, GetName()) .WillOnce(testing::Return(kName)); EXPECT_CALL(*mock_adapter_, IsPresent()) .WillOnce(testing::Return(false)); EXPECT_CALL(*mock_adapter_, IsPowered()) .WillOnce(testing::Return(false)); EXPECT_CALL(*mock_adapter_, IsDiscovering()) .WillOnce(testing::Return(false)); event_router()->AdapterPoweredChanged(mock_adapter_, false); EXPECT_CALL(*mock_adapter_, GetAddress()) .WillOnce(testing::Return(kAdapterAddress)); EXPECT_CALL(*mock_adapter_, GetName()) .WillOnce(testing::Return(kName)); EXPECT_CALL(*mock_adapter_, IsPresent()) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_adapter_, IsPowered()) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_adapter_, IsDiscovering()) .WillOnce(testing::Return(true)); event_router()->AdapterPresentChanged(mock_adapter_, true); EXPECT_CALL(*mock_adapter_, GetAddress()) .WillOnce(testing::Return(kAdapterAddress)); EXPECT_CALL(*mock_adapter_, GetName()) .WillOnce(testing::Return(kName)); EXPECT_CALL(*mock_adapter_, IsPresent()) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_adapter_, IsPowered()) .WillOnce(testing::Return(true)); EXPECT_CALL(*mock_adapter_, IsDiscovering()) .WillOnce(testing::Return(true)); event_router()->AdapterDiscoveringChanged(mock_adapter_, true); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevices) { ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); BluetoothAdapter::ConstDeviceList devices; devices.push_back(device1_.get()); devices.push_back(device2_.get()); EXPECT_CALL(*mock_adapter_, GetDevices()) .Times(1) .WillRepeatedly(testing::Return(devices)); // Load and wait for setup ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("bluetooth/get_devices"))); EXPECT_TRUE(listener.WaitUntilSatisfied()); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevice) { ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); EXPECT_CALL(*mock_adapter_, GetDevice(device1_->GetAddress())) .WillOnce(testing::Return(device1_.get())); EXPECT_CALL(*mock_adapter_, GetDevice(device2_->GetAddress())) .Times(1) .WillRepeatedly(testing::Return(static_cast<BluetoothDevice*>(NULL))); // Load and wait for setup ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("bluetooth/get_device"))); EXPECT_TRUE(listener.WaitUntilSatisfied()); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(BluetoothApiTest, DeviceInfo) { ResultCatcher catcher; catcher.RestrictToBrowserContext(browser()->profile()); // Set up the first device object to reflect a real-world device. BluetoothAdapter::ConstDeviceList devices; EXPECT_CALL(*device1_.get(), GetAddress()) .WillRepeatedly(testing::Return("A4:17:31:00:00:00")); EXPECT_CALL(*device1_.get(), GetDeviceName()) .WillRepeatedly(testing::Return("Chromebook Pixel")); EXPECT_CALL(*device1_.get(), GetName()) .WillRepeatedly(testing::Return(base::UTF8ToUTF16("Chromebook Pixel"))); EXPECT_CALL(*device1_.get(), GetBluetoothClass()) .WillRepeatedly(testing::Return(0x080104)); EXPECT_CALL(*device1_.get(), GetDeviceType()) .WillRepeatedly(testing::Return(BluetoothDevice::DEVICE_COMPUTER)); EXPECT_CALL(*device1_.get(), GetVendorIDSource()) .WillRepeatedly(testing::Return(BluetoothDevice::VENDOR_ID_BLUETOOTH)); EXPECT_CALL(*device1_.get(), GetVendorID()) .WillRepeatedly(testing::Return(0x00E0)); EXPECT_CALL(*device1_.get(), GetProductID()) .WillRepeatedly(testing::Return(0x240A)); EXPECT_CALL(*device1_.get(), GetDeviceID()) .WillRepeatedly(testing::Return(0x0400)); EXPECT_CALL(*device1_, GetRSSI()).WillRepeatedly(testing::Return(-42)); EXPECT_CALL(*device1_, GetCurrentHostTransmitPower()) .WillRepeatedly(testing::Return(-16)); EXPECT_CALL(*device1_, GetMaximumHostTransmitPower()) .WillRepeatedly(testing::Return(10)); BluetoothDevice::UUIDList uuids; uuids.push_back(BluetoothUUID("1105")); uuids.push_back(BluetoothUUID("1106")); EXPECT_CALL(*device1_.get(), GetUUIDs()) .WillOnce(testing::Return(uuids)); devices.push_back(device1_.get()); // Leave the second largely empty so we can check a device without // available information. devices.push_back(device2_.get()); EXPECT_CALL(*mock_adapter_, GetDevices()) .Times(1) .WillRepeatedly(testing::Return(devices)); // Load and wait for setup ExtensionTestMessageListener listener("ready", true); ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("bluetooth/device_info"))); EXPECT_TRUE(listener.WaitUntilSatisfied()); listener.Reply("go"); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); }
17,912
5,967
#include <iostream> #include <vector> #include <string> #include <fstream> #include <algorithm> #include <sstream> using namespace std; struct configpeer{ int peerId; string hostname; int listport; bool havefile; } confp; struct configcommon{ int noprfnbrs; int unchokint; int optunchokint; string filename; long filesize; int piecesize; } conf; vector<string> split (string s, string delimiter) { size_t pos_start = 0, pos_end, delim_len = delimiter.length(); string token; vector<string> res; while ((pos_end = s.find (delimiter, pos_start)) != string::npos) { token = s.substr (pos_start, pos_end - pos_start); pos_start = pos_end + delim_len; res.push_back (token); } res.push_back (s.substr (pos_start)); return res; } int main() { //Parsing Peer Info Config file std::ifstream pFile ("samplePeerInfo.cfg"); if(pFile.is_open()) { string delimiter=" "; size_t pos = 0; while(pFile.good()){ string line; getline(pFile,line); vector<string> v = split(line, delimiter); confp.peerId=stoi(v[0]); confp.hostname=v[1]; confp.listport=stoi(v[2]); int hfile=stoi(v[3]); (hfile==1) ? confp.havefile=true : confp.havefile=false; } } else { std::cerr << "Couldn't open config file for reading.\n"; } //Parsing Common Config file std::ifstream cFile ("sampleCommon.cfg"); if (cFile.is_open()) { string delimiter=" "; size_t pos = 0; string token1,token2; while(cFile.good()){ string line; getline(cFile,line); pos=line.find(delimiter); token1=line.substr(0,pos); token2=line.substr(pos+1,line.length()); if(token1.compare("NumberOfPreferredNeighbors")==0){ conf.noprfnbrs=stoi(token2); } else if(token1.compare("UnchokingInterval")==0) { conf.unchokint=stoi(token2); } else if(token1.compare("OptimisticUnchokingInterval")==0) { conf.optunchokint=stoi(token2); } else if(token1.compare("FileName")==0) { conf.filename=token2; } else if(token1.compare("FileSize")==0) { conf.filesize=stoi(token2); } else{ conf.piecesize=stoi(token2); } } } else { std::cerr << "Couldn't open config file for reading.\n"; } }
2,799
893
#include <algorithm> #include <iostream> #include <iomanip> #include <vector> #include <cmath> using namespace std; // Disjoint set implementation class disjoint_set { private: int *rank, *parent; unsigned int n; public: // default constructor disjoint_set() = default; // Constructor to create and initialize sets of n items disjoint_set(unsigned int n) { rank = new int[n]; parent = new int[n]; this->n = n; makeSet(); } // Creates n single item sets void makeSet() { for (int i = 0; i < n; i++) { parent[i] = i; } } // Finds set of given item x int find(int x) { // Finds the representative of the set that x is an element of if (parent[x] != x) { // if x is not the parent of itself Then x is not the representative of his set, parent[x] = find(parent[x]); // so we recursively call Find on its parent and move I's node directly under the representative of this set } return parent[x]; } // Do union of two sets represented by x and y. void Union(int x, int y) { // Find current sets of x and y int xSet = find(x); int ySet = find(y); // If they are already in same set if (xSet == ySet) return; // Put smaller ranked item under bigger ranked item if ranks are different if (rank[xSet] < rank[ySet]) { parent[xSet] = ySet; } else if (rank[xSet] > rank[ySet]) { parent[ySet] = xSet; } else { // If ranks are same, then increment rank. parent[ySet] = xSet; rank[xSet]++; } } }; // Undirected weighted edge implementation class edge{ public: int u, v; double weight; // default constructor edge() = default; // Constructor edge(int u, int v, double weight) { this->u = u; this->v = v; this->weight = weight; } }; // Sorting function by weight bool sorting_by_weight(edge a, edge b) { return a.weight < b.weight; } // Kruskal's algorithm implementation pair<vector<edge>, double> kruskal(vector<edge> &edges) { double total_cost = 0; // for all u ∈ V : MakeSet(v) disjoint_set ds(edges.size()); // X ← empty set vector<edge> X(0); // sort the edges E by weight sort(edges.begin(), edges.end(), sorting_by_weight); // for all {u, v} ∈ E in non-decreasing weight order: for(edge e: edges) { int u = e.u; int v = e.v; // if Find(u) ̸= Find(v): if (ds.find(u) != ds.find(v)) { // add {u, v} to X X.push_back(e); // Union(u, v) ds.Union(u, v); total_cost += e.weight; } } return make_pair(X, total_cost); } // Distance between two points function double distance_between_two_points(int x1, int y1, int x2, int y2) { return sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2)); } // Minimum distance (problem solution) double minimum_distance(vector<int> x, vector<int> y) { // Constructing the edges list unsigned int v = x.size(); vector<edge> edges(v); for (int i = 0; i < v; i++) { for (int j = i; j < v; j++) { if (j != i) { double weight = distance_between_two_points(x[i], y[i], x[j], y[j]); edge e(i, j, weight); edges.push_back(e); } } } // Running Kruskal's algorithm in our graph pair<vector<edge>, double> result = kruskal(edges); return result.second; } int main() { size_t n; cin >> n; vector<int> x(n), y(n); for (size_t i = 0; i < n; i++) { cin >> x[i] >> y[i]; } cout << fixed << setprecision(10) << minimum_distance(x, y) << "\n"; }
3,601
1,275
// COPYRIGHT_BEGIN // // The MIT License (MIT) // // Copyright (c) 2020-2021 Wizzer Works // // 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. // // COPYRIGHT_END #include <QDebug> #include "DwpMediaRefContextMenu.h" DwpMediaRefContextMenu::DwpMediaRefContextMenu(QObject *parent) : DwpContextMenu(parent), addPackageAction(nullptr), addMediaRefSourceAction(nullptr), addMediaRefTargetActionAction(nullptr) { // Do nothing extra. } DwpMediaRefContextMenu::~DwpMediaRefContextMenu() { if (addPackageAction != nullptr) delete addPackageAction; if (addMediaRefSourceAction != nullptr) delete addMediaRefSourceAction; if (addMediaRefTargetActionAction != nullptr) delete addMediaRefTargetActionAction; } void DwpMediaRefContextMenu::init(QtDwpAttribute *attr) { // Call super class method. DwpContextMenu::init(attr); // Add menu actions. if (mUseJava) { // Support for Java and Android Digital Workprints. addPackageAction = new QAction(tr("Add DWP Package Item"), this); //addPackageAction->setShortcuts(QKeySequence::New); addPackageAction->setStatusTip(tr("Create a new Package item")); connect(addPackageAction, &QAction::triggered, this, &DwpMediaRefContextMenu::addPackage); mMenu->addAction(addPackageAction); //mMenu->addAction("Add DWP Package Item"); } addMediaRefSourceAction = new QAction(tr("Add DWP MediaRefSource Item"), this); //addMediaRefSourceAction->setShortcuts(QKeySequence::New); addMediaRefSourceAction->setStatusTip(tr("Create a new MediaRefSource item")); connect(addMediaRefSourceAction, &QAction::triggered, this, &DwpMediaRefContextMenu::addPackage); mMenu->addAction(addMediaRefSourceAction); //mMenu->addAction("Add DWP MediaRefSource Item"); addMediaRefTargetActionAction = new QAction(tr("Add DWP MediaRefTarget Item"), this); //addMediaRefTargetActionAction->setShortcuts(QKeySequence::New); addMediaRefTargetActionAction->setStatusTip(tr("Create a new Package item")); connect(addMediaRefTargetActionAction, &QAction::triggered, this, &DwpMediaRefContextMenu::addPackage); mMenu->addAction(addMediaRefTargetActionAction); //mMenu->addAction("Add DWP MediaRefTarget Item"); } void DwpMediaRefContextMenu::addPackage() { qDebug() << "DwpMediaRefContextMenu: Adding DWP Package item"; emit DwpContextMenu::insertAttribute(QtDwpAttribute::DWP_ATTRIBUTE_PACKAGE, mAttr); } void DwpMediaRefContextMenu::addMediaRefSource() { qDebug() << "DwpMediaRefContextMenu: Adding DWP MediaRefSource item"; emit DwpContextMenu::insertAttribute(QtDwpAttribute::DWP_ATTRIBUTE_MEDIAREFSOURCE, mAttr); } void DwpMediaRefContextMenu::addMediaRefTarget() { qDebug() << "DwpMediaRefContextMenu: Adding DWP MediaRefTarget item"; emit DwpContextMenu::insertAttribute(QtDwpAttribute::DWP_ATTRIBUTE_MEDIAREFTARGET, mAttr); }
3,948
1,246
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #ifndef NT2_TOOLBOX_EXPONENTIAL_FUNCTION_SIMD_COMMON_IMPL_EXPO_EXPO_BASE_HPP_INCLUDED #define NT2_TOOLBOX_EXPONENTIAL_FUNCTION_SIMD_COMMON_IMPL_EXPO_EXPO_BASE_HPP_INCLUDED #include <nt2/include/functions/select.hpp> namespace nt2 { namespace details { namespace internal { template < class A0, class Tag, class Speed_Tag > struct exponential < A0, Tag, tag::simd_type, Speed_Tag> { typedef exp_reduction<A0,Tag> reduc_t; typedef exp_finalization<A0,Tag,Speed_Tag> finalize_t; // compute exp(ax) static inline A0 expa(const A0& a0) { A0 hi, lo, x; A0 k = reduc_t::reduce(a0, hi, lo, x); A0 c = reduc_t::approx(x); A0 ge = reduc_t::isgemaxlog(a0); A0 le = reduc_t::isleminlog(a0); return sel(ge, Inf<A0>(), sel(le, Zero<A0>(), finalize_t::finalize(a0, x, c, k, hi, lo) ) ); } }; } } } #endif // ///////////////////////////////////////////////////////////////////////////// // End of expo_base.hpp // /////////////////////////////////////////////////////////////////////////////
1,619
603
#pragma once #ifndef _SHARPEN_ASYNCREADWRITELOCK_HPP #define _SHARPEN_ASYNCREADWRITELOCK_HPP #include <list> #include "AwaitableFuture.hpp" namespace sharpen { enum class ReadWriteLockState { Free, SharedReading, UniquedWriting }; class AsyncReadWriteLock:public sharpen::Noncopyable,public sharpen::Nonmovable { private: using MyFuture = sharpen::AwaitableFuture<void>; using MyFuturePtr = MyFuture*; using List = std::list<MyFuturePtr>; sharpen::ReadWriteLockState state_; List readWaiters_; List writeWaiters_; sharpen::SpinLock lock_; sharpen::Uint32 readers_; void WriteUnlock() noexcept; void ReadUnlock() noexcept; public: AsyncReadWriteLock(); void LockReadAsync(); void LockWriteAsync(); void Unlock() noexcept; ~AsyncReadWriteLock() noexcept = default; }; } #endif
968
310
// Generated from /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home/jre/lib/rt.jar #pragma once #include <java/io/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <java/util/fwd-POI.hpp> #include <sun/util/spi/fwd-POI.hpp> #include <java/lang/Object.hpp> struct default_init_tag; class java::util::Properties_XmlSupport : public virtual ::java::lang::Object { public: typedef ::java::lang::Object super; private: static ::sun::util::spi::XmlPropertiesProvider* PROVIDER_; /*void ctor(); (private) */ public: /* package */ static void load(Properties* props, ::java::io::InputStream* in); /*static ::sun::util::spi::XmlPropertiesProvider* loadProvider(); (private) */ /*static ::sun::util::spi::XmlPropertiesProvider* loadProviderAsService(::java::lang::ClassLoader* cl); (private) */ /*static ::sun::util::spi::XmlPropertiesProvider* loadProviderFromProperty(::java::lang::ClassLoader* cl); (private) */ static void save(Properties* props, ::java::io::OutputStream* os, ::java::lang::String* comment, ::java::lang::String* encoding); // Generated public: Properties_XmlSupport(); protected: Properties_XmlSupport(const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: static ::sun::util::spi::XmlPropertiesProvider*& PROVIDER(); virtual ::java::lang::Class* getClass0(); };
1,396
458
/** * The MIT License (MIT) * * Copyright (c) 2016 by Daniel Eichhorn * Copyright (c) 2016 by Fabrice Weinberg * * 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 the correct display library // For a connection via I2C using Wire include #include <Wire.h> // Only needed for Arduino 1.6.5 and earlier #include "SSD1306.h" // alias for `#include "SSD1306Wire.h"` // or #include "SH1106.h" alis for `#include "SH1106Wire.h"` // For a connection via I2C using brzo_i2c (must be installed) include // #include <brzo_i2c.h> // Only needed for Arduino 1.6.5 and earlier // #include "SSD1306Brzo.h" // #include "SH1106Brzo.h" // For a connection via SPI include // #include <SPI.h> // Only needed for Arduino 1.6.5 and earlier // #include "SSD1306Spi.h" // #include "SH1106SPi.h" // Include the UI lib #include "OLEDDisplayUi.h" // Include custom images #include "images.h" // Use the corresponding display class: // Initialize the OLED display using SPI // D5 -> CLK // D7 -> MOSI (DOUT) // D0 -> RES // D2 -> DC // D8 -> CS // SSD1306Spi display(D0, D2, D8); // or // SH1106Spi display(D0, D2); // Initialize the OLED display using brzo_i2c // D3 -> SDA // D5 -> SCL // SSD1306Brzo display(0x3c, D3, D5); // or // SH1106Brzo display(0x3c, D3, D5); // Initialize the OLED display using Wire library ///SSD1306 display(0x3c, 5, 4); // SH1106 display(0x3c, D3, D5); extern SSD1306 display; OLEDDisplayUi ui ( &display ); void msOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) { display->setTextAlignment(TEXT_ALIGN_RIGHT); display->setFont(ArialMT_Plain_10); display->drawString(128, 0, String(millis())); } void drawFrame1(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) { // draw an xbm image. // Please note that everything that should be transitioned // needs to be drawn relative to x and y display->drawXbm(x + 34, y + 14, WiFi_Logo_width, WiFi_Logo_height, WiFi_Logo_bits); } void drawFrame2(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) { // Demonstrates the 3 included default sizes. The fonts come from SSD1306Fonts.h file // Besides the default fonts there will be a program to convert TrueType fonts into this format display->setTextAlignment(TEXT_ALIGN_LEFT); display->setFont(ArialMT_Plain_10); display->drawString(0 + x, 10 + y, "Arial 10"); display->setFont(ArialMT_Plain_16); display->drawString(0 + x, 20 + y, "Arial 16"); display->setFont(ArialMT_Plain_24); display->drawString(0 + x, 34 + y, "Arial 24"); } void drawFrame3(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) { // Text alignment demo display->setFont(ArialMT_Plain_10); // The coordinates define the left starting point of the text display->setTextAlignment(TEXT_ALIGN_LEFT); display->drawString(0 + x, 11 + y, "Left aligned (0,10)"); // The coordinates define the center of the text display->setTextAlignment(TEXT_ALIGN_CENTER); display->drawString(64 + x, 22 + y, "Center aligned (64,22)"); // The coordinates define the right end of the text display->setTextAlignment(TEXT_ALIGN_RIGHT); display->drawString(128 + x, 33 + y, "Right aligned (128,33)"); } void drawFrame4(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) { // Demo for drawStringMaxWidth: // with the third parameter you can define the width after which words will be wrapped. // Currently only spaces and "-" are allowed for wrapping display->setTextAlignment(TEXT_ALIGN_LEFT); display->setFont(ArialMT_Plain_10); display->drawStringMaxWidth(0 + x, 10 + y, 128, "Lorem ipsum\n dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore."); } void drawFrame5(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) { } // This array keeps function pointers to all frames // frames are the single views that slide in FrameCallback frames[] = { drawFrame1, drawFrame2, drawFrame3, drawFrame4, drawFrame5 }; // how many frames are there? int frameCount = 5; // Overlays are statically drawn on top of a frame eg. a clock OverlayCallback overlays[] = { msOverlay }; int overlaysCount = 1; void ui_setup() { //Serial.begin(115200); //Serial.println(); //Serial.println(); // The ESP is capable of rendering 60fps in 80Mhz mode // but that won't give you much time for anything else // run it in 160Mhz mode or just set it to 30 fps ui.setTargetFPS(60); // Customize the active and inactive symbol ui.setActiveSymbol(activeSymbol); ui.setInactiveSymbol(inactiveSymbol); // You can change this to // TOP, LEFT, BOTTOM, RIGHT ui.setIndicatorPosition(BOTTOM); // Defines where the first frame is located in the bar. ui.setIndicatorDirection(LEFT_RIGHT); // You can change the transition that is used // SLIDE_LEFT, SLIDE_RIGHT, SLIDE_UP, SLIDE_DOWN ui.setFrameAnimation(SLIDE_LEFT); // Add frames ui.setFrames(frames, frameCount); // Add overlays ui.setOverlays(overlays, overlaysCount); // Initialising the UI will init the display too. ui.init(); display.flipScreenVertically(); } void ui_loop() { int remainingTimeBudget = ui.update(); if (remainingTimeBudget > 0) { // You can do some work here // Don't do stuff if you are below your // time budget. delay(remainingTimeBudget); } }
6,424
2,333
#include <iostream> #include <vector> int main() { // create a vector containing int std::vector<int> v = {1, 2, 3, 4}; v.push_back(6); v.push_back(7); for (int n:v) { std::cout << n << '\n'; } return 0; }
261
111
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> pii; map<string, pii> mk; int sol = 0; int main() { string a; cin >> a; for(int i = 0 ; i < a.size() ; i++) for(int j = i ; j < a.size() ; j++){ string c = a.substr(i, j - i + 1); if(mk.find(c) == mk.end()){ mk[c] = (pii(i, j)); } else{ pii a = mk[c]; // if(a.second <= i) sol = max(sol, j - i + 1); } } cout << sol; return 0; }
595
230
/* * File: ASTCreateIndex.cpp * Copyright (C) 2009 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS) */ #include "tr/xqp/serial/deser.h" #include "tr/xqp/visitor/ASTVisitor.h" #include "ASTCreateIndex.h" ASTCreateIndex::~ASTCreateIndex() { delete name; delete on_path; delete by_path; delete type; delete tree_type; } void ASTCreateIndex::accept(ASTVisitor &v) { v.addToPath(this); v.visit(*this); v.removeFromPath(this); } ASTNode *ASTCreateIndex::dup() { return new ASTCreateIndex(cd, name->dup(), on_path->dup(), by_path->dup(), type->dup(), new std::string(*tree_type) ); } ASTNode *ASTCreateIndex::createNode(scheme_list &sl) { ASTNodeCommonData cd; ASTNode *name = NULL, *on_path = NULL, *by_path = NULL, *type = NULL; std::string *tree_type; U_ASSERT(sl[1].type == SCM_LIST && sl[2].type == SCM_LIST && sl[3].type == SCM_LIST && sl[4].type == SCM_LIST && sl[5].type == SCM_LIST && sl[6].type == SCM_STRING); cd = dsGetASTCommonFromSList(*sl[1].internal.list); name = dsGetASTFromSchemeList(*sl[2].internal.list); on_path = dsGetASTFromSchemeList(*sl[3].internal.list); by_path = dsGetASTFromSchemeList(*sl[4].internal.list); type = dsGetASTFromSchemeList(*sl[5].internal.list); tree_type = new std::string(sl[6].internal.str); return new ASTCreateIndex(cd, name, on_path, by_path, type, tree_type); } void ASTCreateIndex::modifyChild(const ASTNode *oldc, ASTNode *newc) { if (name == oldc) { name = newc; return; } if (on_path == oldc) { on_path = newc; return; } if (by_path == oldc) { by_path = newc; return; } if (type == oldc) { type = newc; return; } }
1,803
685
#include "prpch.h" #include "parrot/core/Input.h" #include "parrot/core/Application.h" #include <GLFW/glfw3.h> namespace parrot { bool Input::isKeyPressed(KeyCode key_code) { auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow()); auto state = glfwGetKey(window, (int)key_code); return state == GLFW_PRESS || state == GLFW_REPEAT; } bool Input::isMouseButtonPressed(MouseButton button) { auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow()); auto state = glfwGetMouseButton(window, (int)button); return state == GLFW_PRESS; } std::pair<float, float> Input::getMousePosition() { auto window = static_cast<GLFWwindow*>(Application::get().getWindow().getNativeWindow()); double xpos, ypos; glfwGetCursorPos(window, &xpos, &ypos); return { (float)xpos, (float)ypos }; } }
951
316
// // VADM - class for loading the executable in Amiga Hunk format // // Copyright(C) 2016 Constantin Wiemer // #include "loader.h" // global logger extern log4cxx::LoggerPtr g_logger; // global pointer to memory extern uint8_t *g_mem; void AmiHunkLoader::load(char *fname, uint32_t loc) { Poco::FileInputStream exe(fname); Poco::BinaryReader::BinaryReader reader(exe, Poco::BinaryReader::BIG_ENDIAN_BYTE_ORDER); uint32_t btype; // block type uint32_t hnum = 0; // hunk number uint32_t hloc = loc; // hunk location relative to the base address g_mem std::vector <uint32_t> hlocs; // mapping of hunk numbers to locations while (true) { reader >> btype; if (reader.eof()) break; switch (btype) { case HUNK_HEADER: LOG4CXX_INFO(g_logger, "hunk #" << hnum << ", block type = HUNK_HEADER"); uint32_t lword; reader >> lword; LOG4CXX_DEBUG(g_logger, "long words reserved for resident libraries: " << lword); reader >> lword; LOG4CXX_DEBUG(g_logger, "number of hunks: " << lword); uint32_t fhunk; reader >> fhunk; LOG4CXX_DEBUG(g_logger, "number of first hunk: " << fhunk); uint32_t lhunk; reader >> lhunk; LOG4CXX_DEBUG(g_logger, "number of last hunk: " << lhunk); for (int i = fhunk; i <= lhunk; i++) { reader >> lword; LOG4CXX_DEBUG(g_logger, "size (in bytes) of hunk #" << i << " = " << lword * 4 << ", location = " << Poco::format("0x%08x", hloc)); hlocs.push_back(hloc); hloc += lword * 4; } break; case HUNK_CODE: LOG4CXX_INFO(g_logger, "hunk #" << hnum << ", block type = HUNK_CODE"); uint32_t nwords; reader >> nwords; LOG4CXX_DEBUG(g_logger, "size (in bytes) of code block: " << nwords * 4); reader.readRaw((char *) g_mem + hlocs[hnum], nwords * 4); LOG4CXX_TRACE(g_logger, "hex dump of block:\n" << hexdump(g_mem + hlocs[hnum], nwords * 4)); break; case HUNK_DATA: LOG4CXX_INFO(g_logger, "hunk #" << hnum << ", block type = HUNK_DATA"); reader >> nwords; LOG4CXX_DEBUG(g_logger, "size (in bytes) of data block: " << nwords * 4); // Both the AmigaDOS manual and the Amiga Guru book state that after the length word only the data itself and nothing else follows, // but it seems in executables the data is always followed by a null word... reader.readRaw((char *) g_mem + hlocs[hnum], (nwords + 1) * 4); LOG4CXX_TRACE(g_logger, "hex dump of block:\n" << hexdump(g_mem + hlocs[hnum], nwords * 4)); break; case HUNK_BSS: LOG4CXX_INFO(g_logger, "hunk #" << hnum << ", block type = HUNK_BSS"); reader >> nwords; LOG4CXX_DEBUG(g_logger, "size (in bytes) of BSS block: " << nwords * 4); break; case HUNK_RELOC32: LOG4CXX_INFO(g_logger, "hunk #" << hnum << ", block type = HUNK_RELOC32"); uint32_t noffsets; while (true) { reader >> noffsets; if (noffsets == 0) break; uint32_t refhnum; reader >> refhnum; if (hnum > lhunk) { LOG4CXX_ERROR(g_logger, "reloc referring to hunk #" << refhnum << " found while executable contains only " << lhunk + 1 << " hunks"); throw std::runtime_error ("bad executable"); } uint32_t offset; for (int i = 0; i < noffsets; i++) { reader >> offset; LOG4CXX_TRACE(g_logger, "applying reloc referring to hunk #" << refhnum << ", offset = " << offset); m68k_write_32(hlocs[hnum] + offset, m68k_read_32(hlocs[hnum] + offset) + hlocs[refhnum]); } } break; case HUNK_SYMBOL: LOG4CXX_INFO(g_logger, "hunk #" << hnum << ", block type = HUNK_SYMBOL"); LOG4CXX_ERROR(g_logger, "block type is not implemented"); throw std::runtime_error ("block type not implemented"); break; case HUNK_END: LOG4CXX_INFO(g_logger, "hunk #" << hnum << ", block type = HUNK_END"); ++hnum; break; default: LOG4CXX_ERROR(g_logger, "unknown block type: " << btype); } } }
5,024
1,573
#pragma once #include <string> #include <vector> #include <unordered_map> class Variant { public: enum Type : uint8_t { Unknown, Pointer, //void* Bool, //bool Int, //int64_t Float, //double String, //std::string PointerArray, //std::vector<void*> BoolArray, //std::vector<bool> ByteArray, //std::vector<uint8_t> IntArray, //std::vector<int64_t> FloatArray, //std::vector<double> StringArray, //std::vector<std::string> VariantArray, //std::vector<Variant> Dictionary, //std::unordered_map<std::string, Variant> Max }; Variant(const Variant& other) { other.CopyData(*this); } Variant& operator=(const Variant& other) { //Free original data, if any if (OwnsData()) FreeHeapData(); other.CopyData(*this); return *this; } Variant(Variant&& other) { //Move data and adquire ownership of it ptr = other.ptr; type = other.type; ownership = other.ownership; other.ownership = false; } Variant& operator=(Variant&& other) { //Free original data, if any if (OwnsData()) FreeHeapData(); //Move data and adquire ownership of it ptr = other.ptr; type = other.type; ownership = other.ownership; other.ownership = false; return *this; } Variant() { *(int64_t*)&ptr = 0; type = Int; ownership = false; } Variant(void* pData) { ptr = pData; type = Pointer; ownership = false; } Variant(bool pData) { *(bool*)&ptr = pData; type = Bool; ownership = false; } Variant(int32_t pData) { *(int64_t*)&ptr = pData; type = Int; ownership = false; } Variant(int64_t pData) { *(int64_t*)&ptr = pData; type = Int; ownership = false; } Variant(float pData) { *(double*)&ptr = pData; type = Float; ownership = false; } Variant(double pData) { *(double*)&ptr = pData; type = Float; ownership = false; } Variant(const char* pData) { ptr = new std::string(pData); type = String; ownership = true; } Variant(std::string pData) { ptr = new std::string(pData); type = String; ownership = true; } Variant(std::vector<void*> pData) { ptr = new std::vector<void*>(pData); type = PointerArray; ownership = true; } Variant(std::vector<bool> pData) { ptr = new std::vector<bool>(pData); type = BoolArray; ownership = true; } Variant(std::vector<uint8_t> pData) { ptr = new std::vector<uint8_t>(pData); type = ByteArray; ownership = true; } Variant(std::vector<int64_t> pData) { ptr = new std::vector<int64_t>(pData); type = IntArray; ownership = true; } Variant(std::vector<double> pData) { ptr = new std::vector<double>(pData); type = FloatArray; ownership = true; } Variant(std::vector<std::string> pData) { ptr = new std::vector<std::string>(pData); type = StringArray; ownership = true; } Variant(std::vector<Variant> pData) { ptr = new std::vector<Variant>(pData); type = VariantArray; ownership = true; } Variant(std::unordered_map<std::string, Variant> pData) { ptr = new std::unordered_map<std::string, Variant>(pData); type = Dictionary; ownership = true; } Variant(std::unordered_map<std::string, Variant>* pData) { *(std::unordered_map<std::string, Variant>**)&ptr = pData; type = Dictionary; ownership = false; } ~Variant() { if (OwnsData()) FreeHeapData(); } inline void* GetData() const { return ptr; } inline Variant::Type GetType() const { return type; } inline bool OwnsData() const { return ownership; } //Copy Conversion operators //Should be safe no matter what operator void*() const { if (type == Pointer || type == Int) { return (void*)(uintptr_t)ptr; } return nullptr; } operator bool() const { if (type == Bool) return (bool)ptr; return false; } operator int64_t() const { if (type == Float) //Must be casted first for correct conversion //NOTE: Rounds the double first, else the decimal part would get truncated/discarded (Example: 7.9 -> 7 instead of 8) return (int64_t)std::round(*(double*)&ptr); if (type == Int) return (int64_t)ptr; return 0; } operator double() const { if (type == Int) //Must be casted first for correct conversion return *(double*)(int64_t*)&ptr; if (type == Float) return *(double*)&ptr; return 0.0; } operator std::string() const { if (type == String) return *(std::string*)ptr; if (type == Bool) { if (*(bool*)ptr) return "true"; return "false"; } if (type == Int) return std::to_string(*(int64_t*)ptr); if (type == Float) return std::to_string(*(double*)ptr); return ""; } operator std::vector<void*>() const { if (type == PointerArray) { return *(std::vector<void*>*)ptr; } if (type == VariantArray) { const auto& thisVector = *(std::vector<Variant>*)ptr; std::vector<void*> converted; converted.resize(thisVector.size()); for (uint32_t i = 0; i < thisVector.size(); ++i) { converted[i] = thisVector[i].ptr; } return converted; } return std::vector<void*>(); } operator std::vector<bool>() const { if (type == BoolArray) { return *(std::vector<bool>*)ptr; } if (type == VariantArray) { const auto& thisVector = *(std::vector<Variant>*)ptr; std::vector<bool> converted; converted.resize(thisVector.size()); for (uint32_t i = 0; i < thisVector.size(); ++i) { converted[i] = bool(thisVector[i]); } return converted; } return std::vector<bool>(); } operator std::vector<uint8_t>() const { if (type == ByteArray) { return *(std::vector<uint8_t>*)ptr; } if (type == VariantArray) { const auto& thisVector = *(std::vector<Variant>*)ptr; std::vector<uint8_t> converted; converted.resize(thisVector.size()); for (uint32_t i = 0; i < thisVector.size(); ++i) { converted[i] = (uint8_t)int64_t(thisVector[i]); } return converted; } return std::vector<uint8_t>(); } operator std::vector<int64_t>() const { if (type == IntArray) { return *(std::vector<int64_t>*)ptr; } if (type == VariantArray) { const auto& thisVector = *(std::vector<Variant>*)ptr; std::vector<int64_t> converted; converted.resize(thisVector.size()); for (uint32_t i = 0; i < thisVector.size(); ++i) { converted[i] = int64_t(thisVector[i]); } return converted; } return std::vector<int64_t>(); } operator std::vector<double>() const { if (type == FloatArray) { return *(std::vector<double>*)ptr; } if (type == VariantArray) { const auto& thisVector = *(std::vector<Variant>*)ptr; std::vector<double> converted; converted.resize(thisVector.size()); for (uint32_t i = 0; i < thisVector.size(); ++i) { converted[i] = double(thisVector[i]); } return converted; } return std::vector<double>(); } operator std::vector<std::string>() const { if (type == StringArray) { return *(std::vector<std::string>*)ptr; } if (type == VariantArray) { const auto& thisVector = *(std::vector<Variant>*)ptr; std::vector<std::string> converted; converted.resize(thisVector.size()); for (uint32_t i = 0; i < thisVector.size(); ++i) { converted[i] = std::string(thisVector[i]); } return converted; } return std::vector<std::string>(); } operator std::vector<Variant>() const { if (type == VariantArray) return *(std::vector<Variant>*)ptr; return std::vector<Variant>(); } operator std::unordered_map<std::string, Variant>() const { if (type == Dictionary) return *(std::unordered_map<std::string, Variant>*)ptr; return std::unordered_map<std::string, Variant>(); } private: void* ptr; //This value is also used to store primitive types as if it was an union struct { Type type : 7; bool ownership : 1; }; inline void CopyData(Variant& toVariant) const { switch (type) { case Pointer: { toVariant.ptr = ptr; toVariant.type = type; toVariant.ownership = false; break; } case Bool: { toVariant.ptr = ptr; toVariant.type = type; toVariant.ownership = false; break; } case Int: { toVariant.ptr = ptr; toVariant.type = type; toVariant.ownership = false; break; } case Float: { toVariant.ptr = ptr; toVariant.type = type; toVariant.ownership = false; break; } case String: { toVariant.ptr = new std::string(*(std::string*)ptr); toVariant.type = type; toVariant.ownership = true; break; } case PointerArray: { toVariant.ptr = new std::vector<void*>(*(std::vector<void*>*)ptr); toVariant.type = type; toVariant.ownership = true; break; } case BoolArray: { toVariant.ptr = new std::vector<bool>(*(std::vector<bool>*)ptr); toVariant.type = type; toVariant.ownership = true; break; } case ByteArray: { toVariant.ptr = new std::vector<uint8_t>(*(std::vector<uint8_t>*)ptr); toVariant.type = type; toVariant.ownership = true; break; } case IntArray: { toVariant.ptr = new std::vector<int64_t>(*(std::vector<int64_t>*)ptr); toVariant.type = type; toVariant.ownership = true; break; } case FloatArray: { toVariant.ptr = new std::vector<double>(*(std::vector<double>*)ptr); toVariant.type = type; toVariant.ownership = true; break; } case StringArray: { toVariant.ptr = new std::vector<std::string>(*(std::vector<std::string>*)ptr); toVariant.type = type; toVariant.ownership = true; break; } case VariantArray: { toVariant.ptr = new std::vector<Variant>(*(std::vector<Variant>*)ptr); toVariant.type = type; toVariant.ownership = true; break; } case Dictionary: { toVariant.ptr = new std::unordered_map<std::string, Variant>(*(std::unordered_map<std::string, Variant>*)ptr); toVariant.type = type; toVariant.ownership = true; break; } default: break; } } inline void FreeHeapData() { switch (type) //We only care about heap allocated types { case String: { delete (std::string*)ptr; break; } case PointerArray: { delete (std::vector<void*>*)ptr; break; } case BoolArray: { delete (std::vector<bool>*)ptr; break; } case ByteArray: { delete (std::vector<uint8_t>*)ptr; break; } case IntArray: { delete (std::vector<int64_t>*)ptr; break; } case FloatArray: { delete (std::vector<double>*)ptr; break; } case StringArray: { delete (std::vector<std::string>*)ptr; break; } case VariantArray: { delete (std::vector<Variant>*)ptr; break; } case Dictionary: { delete (std::unordered_map<std::string, Variant>*)ptr; break; } default: break; } } };
10,574
4,572
#include <math.h> #include <float.h> /* defines DBL_EPSILON */ #include <assert.h> #include "gtest/gtest.h" namespace { TEST(Examples, Allocation) { int * x = new int; double * p = new double[10]; delete x; delete[] p; } }
266
102
#include "extdll.h" #include "util.h" #include "cbase.h" #include "CInfoIntermission.h" LINK_ENTITY_TO_CLASS( info_intermission, CInfoIntermission ); void CInfoIntermission::Spawn( void ) { SetAbsOrigin( GetAbsOrigin() ); SetSolidType( SOLID_NOT ); GetEffects() = EF_NODRAW; SetViewAngle( g_vecZero ); SetNextThink( 2 );// let targets spawn! } void CInfoIntermission::Think( void ) { // find my target CBaseEntity* pTarget = UTIL_FindEntityByTargetname( nullptr, GetTarget() ); if( pTarget ) { Vector vecViewAngle = UTIL_VecToAngles( ( pTarget->GetAbsOrigin() - GetAbsOrigin() ).Normalize() ); vecViewAngle.x = -vecViewAngle.x; SetViewAngle( vecViewAngle ); } }
684
274
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "IOSWindow.h" #include "IOSAppDelegate.h" #include "IOSView.h" FIOSWindow::~FIOSWindow() { // NOTE: The Window is invalid here! // Use NativeWindow_Destroy() instead. } TSharedRef<FIOSWindow> FIOSWindow::Make() { return MakeShareable( new FIOSWindow() ); } FIOSWindow::FIOSWindow() { } void FIOSWindow::Initialize( class FIOSApplication* const Application, const TSharedRef< FGenericWindowDefinition >& InDefinition, const TSharedPtr< FIOSWindow >& InParent, const bool bShowImmediately ) { OwningApplication = Application; Definition = InDefinition; Window = [[UIApplication sharedApplication] keyWindow]; #if !PLATFORM_TVOS if(InParent.Get() != NULL) { dispatch_async(dispatch_get_main_queue(),^ { #ifdef __IPHONE_8_0 if ([UIAlertController class]) { UIAlertController* AlertController = [UIAlertController alertControllerWithTitle:@"" message:@"Error: Only one UIWindow may be created on iOS." preferredStyle:UIAlertControllerStyleAlert]; UIAlertAction* okAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction* action) { [AlertController dismissViewControllerAnimated : YES completion : nil]; } ]; [AlertController addAction : okAction]; [[IOSAppDelegate GetDelegate].IOSController presentViewController : AlertController animated : YES completion : nil]; } else #endif { #if __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_9_0 UIAlertView* AlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Error: Only one UIWindow may be created on iOS." delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok", nil) otherButtonTitles:nil]; [AlertView show]; [AlertView release]; #endif } } ); } #endif } FPlatformRect FIOSWindow::GetScreenRect() { // get the main view's frame IOSAppDelegate* AppDelegate = (IOSAppDelegate*)[[UIApplication sharedApplication] delegate]; UIView* View = AppDelegate.IOSView; CGRect Frame = [View frame]; CGFloat Scale = View.contentScaleFactor; FPlatformRect ScreenRect; ScreenRect.Top = Frame.origin.y * Scale; ScreenRect.Bottom = (Frame.origin.y + Frame.size.height) * Scale; ScreenRect.Left = Frame.origin.x * Scale; ScreenRect.Right = (Frame.origin.x + Frame.size.width) * Scale; return ScreenRect; } bool FIOSWindow::GetFullScreenInfo( int32& X, int32& Y, int32& Width, int32& Height ) const { FPlatformRect ScreenRect = GetScreenRect(); X = ScreenRect.Left; Y = ScreenRect.Top; Width = ScreenRect.Right - ScreenRect.Left; Height = ScreenRect.Bottom - ScreenRect.Top; return true; }
2,797
1,038
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #include "Delete.hpp" #include "Select.hpp" #include "../CompMapEntity.hpp" #include "../MapDocument.hpp" #include "../MapEntRepres.hpp" #include "../MapPrimitive.hpp" using namespace MapEditor; CommandDeleteT::CommandDeleteT(MapDocumentT& MapDoc, MapElementT* DeleteElem) : m_MapDoc(MapDoc), m_Entities(), m_EntityParents(), m_EntityIndices(), m_DeletePrims(), m_DeletePrimsParents(), m_CommandSelect(NULL) { ArrayT<MapElementT*> DeleteElems; DeleteElems.PushBack(DeleteElem); Init(DeleteElems); } CommandDeleteT::CommandDeleteT(MapDocumentT& MapDoc, const ArrayT<MapElementT*>& DeleteElems) : m_MapDoc(MapDoc), m_Entities(), m_EntityParents(), m_EntityIndices(), m_DeletePrims(), m_DeletePrimsParents(), m_CommandSelect(NULL) { Init(DeleteElems); } void CommandDeleteT::Init(const ArrayT<MapElementT*>& DeleteElems) { // Split the list of elements into a list of primitives and a list of entities. // The lists are checked for duplicates (and kept free of them). for (unsigned long ElemNr = 0; ElemNr < DeleteElems.Size(); ElemNr++) { MapElementT* Elem = DeleteElems[ElemNr]; if (Elem->GetType() == &MapEntRepresT::TypeInfo) { // Double-check that this is really a MapEntRepresT. wxASSERT(Elem->GetParent()->GetRepres() == Elem); IntrusivePtrT<cf::GameSys::EntityT> Entity = Elem->GetParent()->GetEntity(); // The root entity (the world) cannot be deleted. // (The if-tests below are three versions of the logically same check.) if (Elem->GetParent()->IsWorld()) continue; if (Entity == Entity->GetRoot()) continue; if (Entity->GetParent() == NULL) continue; m_Entities.PushBack(Entity); m_EntityParents.PushBack(Entity->GetParent()); m_EntityIndices.PushBack(-1); } else { // Double-check that this is really *not* a MapEntRepresT. wxASSERT(Elem->GetParent()->GetRepres() != Elem); MapPrimitiveT* Prim = dynamic_cast<MapPrimitiveT*>(Elem); wxASSERT(Prim); if (m_DeletePrims.Find(Prim) == -1) { m_DeletePrims.PushBack(Prim); m_DeletePrimsParents.PushBack(Prim->GetParent()); } } } // Remove entities from m_Entities that are already in the tree of another entity. // This also removes any duplicates from m_Entities. for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++) { for (unsigned long TreeNr = 0; TreeNr < m_Entities.Size(); TreeNr++) { if (EntNr != TreeNr && m_Entities[TreeNr]->Has(m_Entities[EntNr])) { m_Entities.RemoveAt(EntNr); m_EntityParents.RemoveAt(EntNr); m_EntityIndices.RemoveAt(EntNr); EntNr--; break; } } } // Remove primitives from m_DeletePrims whose entire entity is deleted anyways. for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++) { for (unsigned long TreeNr = 0; TreeNr < m_Entities.Size(); TreeNr++) { if (m_Entities[TreeNr]->Has(m_DeletePrims[PrimNr]->GetParent()->GetEntity())) { m_DeletePrims.RemoveAt(PrimNr); m_DeletePrimsParents.RemoveAt(PrimNr); PrimNr--; break; } } } // Build the combined list of all deleted elements in order to unselect them. ArrayT<MapElementT*> Unselect; for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++) Unselect.PushBack(m_DeletePrims[PrimNr]); for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++) { IntrusivePtrT<CompMapEntityT> MapEnt = GetMapEnt(m_Entities[EntNr]); Unselect.PushBack(MapEnt->GetAllMapElements()); } m_CommandSelect = CommandSelectT::Remove(&m_MapDoc, Unselect); } CommandDeleteT::~CommandDeleteT() { delete m_CommandSelect; if (m_Done) { // for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++) // delete m_Entities[EntNr]; for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++) delete m_DeletePrims[PrimNr]; } } bool CommandDeleteT::Do() { wxASSERT(!m_Done); if (m_Done) return false; if (m_Entities.Size() == 0 && m_DeletePrims.Size() == 0) { // If there is nothing to delete, e.g. because only the world representation // was selected (and dropped in Init()), bail out early. return false; } // Deselect any affected elements that are selected. m_CommandSelect->Do(); for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++) { m_MapDoc.Remove(m_DeletePrims[PrimNr]); } for (unsigned long EntNr = 0; EntNr < m_Entities.Size(); EntNr++) { IntrusivePtrT<cf::GameSys::EntityT> Entity = m_Entities[EntNr]; wxASSERT(m_EntityParents[EntNr]->GetChildren().Find(Entity) >= 0); // The proper index number can only be determined here, because removing a child // may change the index numbers of its siblings. m_EntityIndices[EntNr] = m_EntityParents[EntNr]->GetChildren().Find(Entity); m_MapDoc.Remove(Entity); } // Update all observers. m_MapDoc.UpdateAllObservers_Deleted(m_DeletePrims); m_MapDoc.UpdateAllObservers_Deleted(m_Entities); m_Done = true; return true; } void CommandDeleteT::Undo() { wxASSERT(m_Done); if (!m_Done) return; for (unsigned long RevNr = 0; RevNr < m_Entities.Size(); RevNr++) { const unsigned long EntNr = m_Entities.Size() - RevNr - 1; // This call to AddChild() should never see a reason to modify the name of the m_Entities[EntNr] // to make it unique among its siblings -- it used to be there and was unique, after all. m_MapDoc.Insert(m_Entities[EntNr], m_EntityParents[EntNr], m_EntityIndices[EntNr]); } for (unsigned long PrimNr = 0; PrimNr < m_DeletePrims.Size(); PrimNr++) m_MapDoc.Insert(m_DeletePrims[PrimNr], m_DeletePrimsParents[PrimNr]); // Update all observers. m_MapDoc.UpdateAllObservers_Created(m_Entities); m_MapDoc.UpdateAllObservers_Created(m_DeletePrims); // Select the previously selected elements again. m_CommandSelect->Undo(); m_Done = false; } wxString CommandDeleteT::GetName() const { const unsigned long Sum = m_Entities.Size() + m_DeletePrims.Size(); if (m_Entities.Size() == 0) { return (Sum == 1) ? "Delete 1 primitive" : wxString::Format("Delete %lu primitives", Sum); } if (m_DeletePrims.Size() == 0) { return (Sum == 1) ? "Delete 1 entity" : wxString::Format("Delete %lu entities", Sum); } return (Sum == 1) ? "Delete 1 element" : wxString::Format("Delete %lu elements", Sum); }
7,253
2,420
#include "opt/dedicate_to_window.hpp" #if defined(DEBUG) #include <iostream> #endif #include <windows.h> #include "bind/emu/edi_change_mode.hpp" #include "bind/mode/change_mode.hpp" #include "err_logger.hpp" #include "g_params.hpp" #include "io/mouse.hpp" #include "key/key_absorber.hpp" #include "key/keycode_def.hpp" #include "opt/vcmdline.hpp" namespace { HWND target_hwnd = NULL ; HWND past_hwnd = NULL ; } namespace vind { Dedicate2Window::Dedicate2Window() : OptionCreator("dedicate_to_window") {} void Dedicate2Window::do_enable() const { } void Dedicate2Window::do_disable() const { } void Dedicate2Window::enable_targeting() { if(gparams::get_b("dedicate_to_window")) { target_hwnd = GetForegroundWindow() ; past_hwnd = NULL ; VCmdLine::print(GeneralMessage("-- TARGET ON --")) ; } } void Dedicate2Window::disable_targeting() { if(gparams::get_b("dedicate_to_window")) { target_hwnd = NULL ; past_hwnd = NULL ; VCmdLine::print(GeneralMessage("-- TARGET OFF --")) ; } } void Dedicate2Window::do_process() const { if(!target_hwnd) return ; auto foreground_hwnd = GetForegroundWindow() ; //is selected window changed? if(past_hwnd == foreground_hwnd) { return ; } if(target_hwnd == foreground_hwnd) { //other -> target ToEdiNormal::sprocess(true) ; } else if(past_hwnd == target_hwnd) { //target -> other ToInsert::sprocess(true) ; } past_hwnd = foreground_hwnd ; } }
1,674
580
/* $Id: RTSignTool.cpp $ */ /** @file * IPRT - Signing Tool. */ /* * Copyright (C) 2006-2015 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /******************************************************************************* * Header Files * *******************************************************************************/ #include <iprt/assert.h> #include <iprt/buildconfig.h> #include <iprt/err.h> #include <iprt/getopt.h> #include <iprt/file.h> #include <iprt/initterm.h> #include <iprt/ldr.h> #include <iprt/message.h> #include <iprt/mem.h> #include <iprt/path.h> #include <iprt/stream.h> #include <iprt/string.h> #include <iprt/crypto/x509.h> #include <iprt/crypto/pkcs7.h> #include <iprt/crypto/store.h> #ifdef VBOX # include <VBox/sup.h> /* Certificates */ #endif /******************************************************************************* * Structures and Typedefs * *******************************************************************************/ /** Help detail levels. */ typedef enum RTSIGNTOOLHELP { RTSIGNTOOLHELP_USAGE, RTSIGNTOOLHELP_FULL } RTSIGNTOOLHELP; /******************************************************************************* * Internal Functions * *******************************************************************************/ static RTEXITCODE HandleHelp(int cArgs, char **papszArgs); static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel); static RTEXITCODE HandleVersion(int cArgs, char **papszArgs); /* * The 'extract-exe-signer-cert' command. */ static RTEXITCODE HelpExtractExeSignerCert(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel) { RTStrmPrintf(pStrm, "extract-exe-signer-cert [--ber|--cer|--der] [--exe|-e] <exe> [--output|-o] <outfile.cer>\n"); return RTEXITCODE_SUCCESS; } static RTEXITCODE HandleExtractExeSignerCert(int cArgs, char **papszArgs) { /* * Parse arguments. */ static const RTGETOPTDEF s_aOptions[] = { { "--ber", 'b', RTGETOPT_REQ_NOTHING }, { "--cer", 'c', RTGETOPT_REQ_NOTHING }, { "--der", 'd', RTGETOPT_REQ_NOTHING }, { "--exe", 'e', RTGETOPT_REQ_STRING }, { "--output", 'o', RTGETOPT_REQ_STRING }, }; const char *pszExe = NULL; const char *pszOut = NULL; RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER; uint32_t fCursorFlags = RTASN1CURSOR_FLAGS_DER; RTGETOPTSTATE GetState; int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST); AssertRCReturn(rc, RTEXITCODE_FAILURE); RTGETOPTUNION ValueUnion; int ch; while ((ch = RTGetOpt(&GetState, &ValueUnion))) { switch (ch) { case 'e': pszExe = ValueUnion.psz; break; case 'o': pszOut = ValueUnion.psz; break; case 'b': fCursorFlags = 0; break; case 'c': fCursorFlags = RTASN1CURSOR_FLAGS_CER; break; case 'd': fCursorFlags = RTASN1CURSOR_FLAGS_DER; break; case 'V': return HandleVersion(cArgs, papszArgs); case 'h': return HelpExtractExeSignerCert(g_pStdOut, RTSIGNTOOLHELP_FULL); case VINF_GETOPT_NOT_OPTION: if (!pszExe) pszExe = ValueUnion.psz; else if (!pszOut) pszOut = ValueUnion.psz; else return RTMsgErrorExit(RTEXITCODE_FAILURE, "Too many file arguments: %s", ValueUnion.psz); break; default: return RTGetOptPrintError(ch, &ValueUnion); } } if (!pszExe) return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given."); if (!pszOut) return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file given."); if (RTPathExists(pszOut)) return RTMsgErrorExit(RTEXITCODE_FAILURE, "The output file '%s' exists.", pszOut); /* * Do it. */ /* Open the executable image and query the PKCS7 info. */ RTLDRMOD hLdrMod; rc = RTLdrOpen(pszExe, RTLDR_O_FOR_VALIDATION, enmLdrArch, &hLdrMod); if (RT_FAILURE(rc)) return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszExe, rc); RTEXITCODE rcExit = RTEXITCODE_FAILURE; #ifdef DEBUG size_t cbBuf = 64; #else size_t cbBuf = _512K; #endif void *pvBuf = RTMemAlloc(cbBuf); size_t cbRet = 0; rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbRet); if (rc == VERR_BUFFER_OVERFLOW && cbRet < _4M && cbRet > 0) { RTMemFree(pvBuf); cbBuf = cbRet; pvBuf = RTMemAlloc(cbBuf); rc = RTLdrQueryPropEx(hLdrMod, RTLDRPROP_PKCS7_SIGNED_DATA, NULL /*pvBits*/, pvBuf, cbBuf, &cbRet); } if (RT_SUCCESS(rc)) { static RTERRINFOSTATIC s_StaticErrInfo; RTErrInfoInitStatic(&s_StaticErrInfo); /* * Decode the output. */ RTASN1CURSORPRIMARY PrimaryCursor; RTAsn1CursorInitPrimary(&PrimaryCursor, pvBuf, (uint32_t)cbRet, &s_StaticErrInfo.Core, &g_RTAsn1DefaultAllocator, fCursorFlags, "exe"); RTCRPKCS7CONTENTINFO Pkcs7Ci; rc = RTCrPkcs7ContentInfo_DecodeAsn1(&PrimaryCursor.Cursor, 0, &Pkcs7Ci, "pkcs7"); if (RT_SUCCESS(rc)) { if (RTCrPkcs7ContentInfo_IsSignedData(&Pkcs7Ci)) { PCRTCRPKCS7SIGNEDDATA pSd = Pkcs7Ci.u.pSignedData; if (pSd->SignerInfos.cItems == 1) { PCRTCRPKCS7ISSUERANDSERIALNUMBER pISN = &pSd->SignerInfos.paItems[0].IssuerAndSerialNumber; PCRTCRX509CERTIFICATE pCert; pCert = RTCrPkcs7SetOfCerts_FindX509ByIssuerAndSerialNumber(&pSd->Certificates, &pISN->Name, &pISN->SerialNumber); if (pCert) { /* * Write it out. */ RTFILE hFile; rc = RTFileOpen(&hFile, pszOut, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE); if (RT_SUCCESS(rc)) { uint32_t cbCert = pCert->SeqCore.Asn1Core.cbHdr + pCert->SeqCore.Asn1Core.cb; rc = RTFileWrite(hFile, pCert->SeqCore.Asn1Core.uData.pu8 - pCert->SeqCore.Asn1Core.cbHdr, cbCert, NULL); if (RT_SUCCESS(rc)) { rc = RTFileClose(hFile); if (RT_SUCCESS(rc)) { hFile = NIL_RTFILE; rcExit = RTEXITCODE_SUCCESS; RTMsgInfo("Successfully wrote %u bytes to '%s'", cbCert, pszOut); } else RTMsgError("RTFileClose failed: %Rrc", rc); } else RTMsgError("RTFileWrite failed: %Rrc", rc); RTFileClose(hFile); } else RTMsgError("Error opening '%s': %Rrc", pszOut, rc); } else RTMsgError("Certificate not found."); } else RTMsgError("SignerInfo count: %u", pSd->SignerInfos.cItems); } else RTMsgError("No PKCS7 content: ContentType=%s", Pkcs7Ci.ContentType.szObjId); RTAsn1VtDelete(&Pkcs7Ci.SeqCore.Asn1Core); } else RTMsgError("RTPkcs7ContentInfoDecodeAsn1 failed: %Rrc - %s", rc, s_StaticErrInfo.szMsg); } else RTMsgError("RTLDRPROP_PKCS7_SIGNED_DATA failed on '%s': %Rrc", pszExe, rc); RTMemFree(pvBuf); rc = RTLdrClose(hLdrMod); if (RT_FAILURE(rc)) rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc); return rcExit; } #ifndef IPRT_IN_BUILD_TOOL /* * The 'verify-exe' command. */ static RTEXITCODE HelpVerifyExe(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel) { RTStrmPrintf(pStrm, "verify-exe [--verbose|--quiet] [--kernel] [--root <root-cert.der>] [--additional <supp-cert.der>]\n" " [--type <win|osx>] <exe1> [exe2 [..]]\n"); return RTEXITCODE_SUCCESS; } typedef struct VERIFYEXESTATE { RTCRSTORE hRootStore; RTCRSTORE hKernelRootStore; RTCRSTORE hAdditionalStore; bool fKernel; int cVerbose; enum { kSignType_Windows, kSignType_OSX } enmSignType; uint64_t uTimestamp; RTLDRARCH enmLdrArch; } VERIFYEXESTATE; #ifdef VBOX /** Certificate store load set. * Declared outside HandleVerifyExe because of braindead gcc visibility crap. */ struct STSTORESET { RTCRSTORE hStore; PCSUPTAENTRY paTAs; unsigned cTAs; }; #endif /** * @callback_method_impl{FNRTCRPKCS7VERIFYCERTCALLBACK, * Standard code signing. Use this for Microsoft SPC.} */ static DECLCALLBACK(int) VerifyExecCertVerifyCallback(PCRTCRX509CERTIFICATE pCert, RTCRX509CERTPATHS hCertPaths, uint32_t fFlags, void *pvUser, PRTERRINFO pErrInfo) { VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser; uint32_t cPaths = hCertPaths != NIL_RTCRX509CERTPATHS ? RTCrX509CertPathsGetPathCount(hCertPaths) : 0; /* * Dump all the paths. */ if (pState->cVerbose > 0) { for (uint32_t iPath = 0; iPath < cPaths; iPath++) { RTPrintf("---\n"); RTCrX509CertPathsDumpOne(hCertPaths, iPath, pState->cVerbose, RTStrmDumpPrintfV, g_pStdOut); *pErrInfo->pszMsg = '\0'; } RTPrintf("---\n"); } /* * Test signing certificates normally doesn't have all the necessary * features required below. So, treat them as special cases. */ if ( hCertPaths == NIL_RTCRX509CERTPATHS && RTCrX509Name_Compare(&pCert->TbsCertificate.Issuer, &pCert->TbsCertificate.Subject) == 0) { RTMsgInfo("Test signed.\n"); return VINF_SUCCESS; } if (hCertPaths == NIL_RTCRX509CERTPATHS) RTMsgInfo("Signed by trusted certificate.\n"); /* * Standard code signing capabilites required. */ int rc = RTCrPkcs7VerifyCertCallbackCodeSigning(pCert, hCertPaths, fFlags, NULL, pErrInfo); if ( RT_SUCCESS(rc) && (fFlags & RTCRPKCS7VCC_F_SIGNED_DATA)) { /* * If kernel signing, a valid certificate path must be anchored by the * microsoft kernel signing root certificate. The only alternative is * test signing. */ if (pState->fKernel && hCertPaths != NIL_RTCRX509CERTPATHS) { uint32_t cFound = 0; uint32_t cValid = 0; for (uint32_t iPath = 0; iPath < cPaths; iPath++) { bool fTrusted; PCRTCRX509NAME pSubject; PCRTCRX509SUBJECTPUBLICKEYINFO pPublicKeyInfo; int rcVerify; rc = RTCrX509CertPathsQueryPathInfo(hCertPaths, iPath, &fTrusted, NULL /*pcNodes*/, &pSubject, &pPublicKeyInfo, NULL, NULL /*pCertCtx*/, &rcVerify); AssertRCBreak(rc); if (RT_SUCCESS(rcVerify)) { Assert(fTrusted); cValid++; /* Search the kernel signing root store for a matching anchor. */ RTCRSTORECERTSEARCH Search; rc = RTCrStoreCertFindBySubjectOrAltSubjectByRfc5280(pState->hKernelRootStore, pSubject, &Search); AssertRCBreak(rc); PCRTCRCERTCTX pCertCtx; while ((pCertCtx = RTCrStoreCertSearchNext(pState->hKernelRootStore, &Search)) != NULL) { PCRTCRX509SUBJECTPUBLICKEYINFO pPubKeyInfo; if (pCertCtx->pCert) pPubKeyInfo = &pCertCtx->pCert->TbsCertificate.SubjectPublicKeyInfo; else if (pCertCtx->pTaInfo) pPubKeyInfo = &pCertCtx->pTaInfo->PubKey; else pPubKeyInfo = NULL; if (RTCrX509SubjectPublicKeyInfo_Compare(pPubKeyInfo, pPublicKeyInfo) == 0) cFound++; RTCrCertCtxRelease(pCertCtx); } int rc2 = RTCrStoreCertSearchDestroy(pState->hKernelRootStore, &Search); AssertRC(rc2); } } if (RT_SUCCESS(rc) && cFound == 0) rc = RTErrInfoSetF(pErrInfo, VERR_GENERAL_FAILURE, "Not valid kernel code signature."); if (RT_SUCCESS(rc) && cValid != 2) RTMsgWarning("%u valid paths, expected 2", cValid); } } return rc; } /** @callback_method_impl{FNRTLDRVALIDATESIGNEDDATA} */ static DECLCALLBACK(int) VerifyExeCallback(RTLDRMOD hLdrMod, RTLDRSIGNATURETYPE enmSignature, void const *pvSignature, size_t cbSignature, PRTERRINFO pErrInfo, void *pvUser) { VERIFYEXESTATE *pState = (VERIFYEXESTATE *)pvUser; switch (enmSignature) { case RTLDRSIGNATURETYPE_PKCS7_SIGNED_DATA: { PCRTCRPKCS7CONTENTINFO pContentInfo = (PCRTCRPKCS7CONTENTINFO)pvSignature; RTTIMESPEC ValidationTime; RTTimeSpecSetSeconds(&ValidationTime, pState->uTimestamp); /* * Dump the signed data if so requested. */ if (pState->cVerbose) RTAsn1Dump(&pContentInfo->SeqCore.Asn1Core, 0, 0, RTStrmDumpPrintfV, g_pStdOut); /* * Do the actual verification. Will have to modify this so it takes * the authenticode policies into account. */ return RTCrPkcs7VerifySignedData(pContentInfo, RTCRPKCS7VERIFY_SD_F_COUNTER_SIGNATURE_SIGNING_TIME_ONLY | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_SIGNING_TIME_IF_PRESENT | RTCRPKCS7VERIFY_SD_F_ALWAYS_USE_MS_TIMESTAMP_IF_PRESENT, pState->hAdditionalStore, pState->hRootStore, &ValidationTime, VerifyExecCertVerifyCallback, pState, pErrInfo); } default: return RTErrInfoSetF(pErrInfo, VERR_NOT_SUPPORTED, "Unsupported signature type: %d", enmSignature); } return VINF_SUCCESS; } /** Worker for HandleVerifyExe. */ static RTEXITCODE HandleVerifyExeWorker(VERIFYEXESTATE *pState, const char *pszFilename, PRTERRINFOSTATIC pStaticErrInfo) { /* * Open the executable image and verify it. */ RTLDRMOD hLdrMod; int rc = RTLdrOpen(pszFilename, RTLDR_O_FOR_VALIDATION, pState->enmLdrArch, &hLdrMod); if (RT_FAILURE(rc)) return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error opening executable image '%s': %Rrc", pszFilename, rc); rc = RTLdrQueryProp(hLdrMod, RTLDRPROP_TIMESTAMP_SECONDS, &pState->uTimestamp, sizeof(pState->uTimestamp)); if (RT_SUCCESS(rc)) { rc = RTLdrVerifySignature(hLdrMod, VerifyExeCallback, pState, RTErrInfoInitStatic(pStaticErrInfo)); if (RT_SUCCESS(rc)) RTMsgInfo("'%s' is valid.\n", pszFilename); else RTMsgError("RTLdrVerifySignature failed on '%s': %Rrc - %s\n", pszFilename, rc, pStaticErrInfo->szMsg); } else RTMsgError("RTLdrQueryProp/RTLDRPROP_TIMESTAMP_SECONDS failed on '%s': %Rrc\n", pszFilename, rc); int rc2 = RTLdrClose(hLdrMod); if (RT_FAILURE(rc2)) return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTLdrClose failed: %Rrc\n", rc2); if (RT_FAILURE(rc)) return rc != VERR_LDRVI_NOT_SIGNED ? RTEXITCODE_FAILURE : RTEXITCODE_SKIPPED; return RTEXITCODE_SUCCESS; } static RTEXITCODE HandleVerifyExe(int cArgs, char **papszArgs) { RTERRINFOSTATIC StaticErrInfo; /* Note! This code does not try to clean up the crypto stores on failure. This is intentional as the code is only expected to be used in a one-command-per-process environment where we do exit() upon returning from this function. */ /* * Parse arguments. */ static const RTGETOPTDEF s_aOptions[] = { { "--kernel", 'k', RTGETOPT_REQ_NOTHING }, { "--root", 'r', RTGETOPT_REQ_STRING }, { "--additional", 'a', RTGETOPT_REQ_STRING }, { "--add", 'a', RTGETOPT_REQ_STRING }, { "--type", 't', RTGETOPT_REQ_STRING }, { "--verbose", 'v', RTGETOPT_REQ_NOTHING }, { "--quiet", 'q', RTGETOPT_REQ_NOTHING }, }; VERIFYEXESTATE State = { NIL_RTCRSTORE, NIL_RTCRSTORE, NIL_RTCRSTORE, false, false, VERIFYEXESTATE::kSignType_Windows, 0, RTLDRARCH_WHATEVER }; int rc = RTCrStoreCreateInMem(&State.hRootStore, 0); if (RT_SUCCESS(rc)) rc = RTCrStoreCreateInMem(&State.hKernelRootStore, 0); if (RT_SUCCESS(rc)) rc = RTCrStoreCreateInMem(&State.hAdditionalStore, 0); if (RT_FAILURE(rc)) return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error creating in-memory certificate store: %Rrc", rc); RTGETOPTSTATE GetState; rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST); AssertRCReturn(rc, RTEXITCODE_FAILURE); RTGETOPTUNION ValueUnion; int ch; while ((ch = RTGetOpt(&GetState, &ValueUnion)) && ch != VINF_GETOPT_NOT_OPTION) { switch (ch) { case 'r': case 'a': rc = RTCrStoreCertAddFromFile(ch == 'r' ? State.hRootStore : State.hAdditionalStore, 0, ValueUnion.psz, RTErrInfoInitStatic(&StaticErrInfo)); if (RT_FAILURE(rc)) return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error loading certificate '%s': %Rrc - %s", ValueUnion.psz, rc, StaticErrInfo.szMsg); break; case 't': if (!strcmp(ValueUnion.psz, "win") || !strcmp(ValueUnion.psz, "windows")) State.enmSignType = VERIFYEXESTATE::kSignType_Windows; else if (!strcmp(ValueUnion.psz, "osx") || !strcmp(ValueUnion.psz, "apple")) State.enmSignType = VERIFYEXESTATE::kSignType_OSX; else return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown signing type: '%s'", ValueUnion.psz); break; case 'k': State.fKernel = true; break; case 'v': State.cVerbose++; break; case 'q': State.cVerbose = 0; break; case 'V': return HandleVersion(cArgs, papszArgs); case 'h': return HelpVerifyExe(g_pStdOut, RTSIGNTOOLHELP_FULL); default: return RTGetOptPrintError(ch, &ValueUnion); } } if (ch != VINF_GETOPT_NOT_OPTION) return RTMsgErrorExit(RTEXITCODE_FAILURE, "No executable given."); /* * Populate the certificate stores according to the signing type. */ #ifdef VBOX unsigned cSets = 0; struct STSTORESET aSets[6]; #endif switch (State.enmSignType) { case VERIFYEXESTATE::kSignType_Windows: #ifdef VBOX aSets[cSets].hStore = State.hRootStore; aSets[cSets].paTAs = g_aSUPTimestampTAs; aSets[cSets].cTAs = g_cSUPTimestampTAs; cSets++; aSets[cSets].hStore = State.hRootStore; aSets[cSets].paTAs = g_aSUPSpcRootTAs; aSets[cSets].cTAs = g_cSUPSpcRootTAs; cSets++; aSets[cSets].hStore = State.hRootStore; aSets[cSets].paTAs = g_aSUPNtKernelRootTAs; aSets[cSets].cTAs = g_cSUPNtKernelRootTAs; cSets++; aSets[cSets].hStore = State.hKernelRootStore; aSets[cSets].paTAs = g_aSUPNtKernelRootTAs; aSets[cSets].cTAs = g_cSUPNtKernelRootTAs; cSets++; #endif break; case VERIFYEXESTATE::kSignType_OSX: return RTMsgErrorExit(RTEXITCODE_FAILURE, "Mac OS X executable signing is not implemented."); } #ifdef VBOX for (unsigned i = 0; i < cSets; i++) for (unsigned j = 0; j < aSets[i].cTAs; j++) { rc = RTCrStoreCertAddEncoded(aSets[i].hStore, RTCRCERTCTX_F_ENC_TAF_DER, aSets[i].paTAs[j].pch, aSets[i].paTAs[j].cb, RTErrInfoInitStatic(&StaticErrInfo)); if (RT_FAILURE(rc)) return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTCrStoreCertAddEncoded failed (%u/%u): %s", i, j, StaticErrInfo.szMsg); } #endif /* * Do it. */ RTEXITCODE rcExit; for (;;) { rcExit = HandleVerifyExeWorker(&State, ValueUnion.psz, &StaticErrInfo); if (rcExit != RTEXITCODE_SUCCESS) break; /* * Next file */ ch = RTGetOpt(&GetState, &ValueUnion); if (ch == 0) break; if (ch != VINF_GETOPT_NOT_OPTION) { rcExit = RTGetOptPrintError(ch, &ValueUnion); break; } } /* * Clean up. */ uint32_t cRefs; cRefs = RTCrStoreRelease(State.hRootStore); Assert(cRefs == 0); cRefs = RTCrStoreRelease(State.hKernelRootStore); Assert(cRefs == 0); cRefs = RTCrStoreRelease(State.hAdditionalStore); Assert(cRefs == 0); return rcExit; } #endif /* !IPRT_IN_BUILD_TOOL */ /* * The 'make-tainfo' command. */ static RTEXITCODE HelpMakeTaInfo(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel) { RTStrmPrintf(pStrm, "make-tainfo [--verbose|--quiet] [--cert <cert.der>] [-o|--output] <tainfo.der>\n"); return RTEXITCODE_SUCCESS; } typedef struct MAKETAINFOSTATE { int cVerbose; const char *pszCert; const char *pszOutput; } MAKETAINFOSTATE; /** @callback_method_impl{FNRTASN1ENCODEWRITER} */ static DECLCALLBACK(int) handleMakeTaInfoWriter(const void *pvBuf, size_t cbToWrite, void *pvUser, PRTERRINFO pErrInfo) { return RTStrmWrite((PRTSTREAM)pvUser, pvBuf, cbToWrite); } static RTEXITCODE HandleMakeTaInfo(int cArgs, char **papszArgs) { /* * Parse arguments. */ static const RTGETOPTDEF s_aOptions[] = { { "--cert", 'c', RTGETOPT_REQ_STRING }, { "--output", 'o', RTGETOPT_REQ_STRING }, { "--verbose", 'v', RTGETOPT_REQ_NOTHING }, { "--quiet", 'q', RTGETOPT_REQ_NOTHING }, }; RTLDRARCH enmLdrArch = RTLDRARCH_WHATEVER; MAKETAINFOSTATE State = { 0, NULL, NULL }; RTGETOPTSTATE GetState; int rc = RTGetOptInit(&GetState, cArgs, papszArgs, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST); AssertRCReturn(rc, RTEXITCODE_FAILURE); RTGETOPTUNION ValueUnion; int ch; while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0) { switch (ch) { case 'c': if (State.pszCert) return RTMsgErrorExit(RTEXITCODE_FAILURE, "The --cert option can only be used once."); State.pszCert = ValueUnion.psz; break; case 'o': case VINF_GETOPT_NOT_OPTION: if (State.pszOutput) return RTMsgErrorExit(RTEXITCODE_FAILURE, "Multiple output files specified."); State.pszOutput = ValueUnion.psz; break; case 'v': State.cVerbose++; break; case 'q': State.cVerbose = 0; break; case 'V': return HandleVersion(cArgs, papszArgs); case 'h': return HelpMakeTaInfo(g_pStdOut, RTSIGNTOOLHELP_FULL); default: return RTGetOptPrintError(ch, &ValueUnion); } } if (!State.pszCert) return RTMsgErrorExit(RTEXITCODE_FAILURE, "No input certificate was specified."); if (!State.pszOutput) return RTMsgErrorExit(RTEXITCODE_FAILURE, "No output file was specified."); /* * Read the certificate. */ RTERRINFOSTATIC StaticErrInfo; RTCRX509CERTIFICATE Certificate; rc = RTCrX509Certificate_ReadFromFile(&Certificate, State.pszCert, 0, &g_RTAsn1DefaultAllocator, RTErrInfoInitStatic(&StaticErrInfo)); if (RT_FAILURE(rc)) return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error reading certificate from %s: %Rrc - %s", State.pszCert, rc, StaticErrInfo.szMsg); /* * Construct the trust anchor information. */ RTCRTAFTRUSTANCHORINFO TrustAnchor; rc = RTCrTafTrustAnchorInfo_Init(&TrustAnchor, &g_RTAsn1DefaultAllocator); if (RT_SUCCESS(rc)) { /* Public key. */ Assert(RTCrX509SubjectPublicKeyInfo_IsPresent(&TrustAnchor.PubKey)); RTCrX509SubjectPublicKeyInfo_Delete(&TrustAnchor.PubKey); rc = RTCrX509SubjectPublicKeyInfo_Clone(&TrustAnchor.PubKey, &Certificate.TbsCertificate.SubjectPublicKeyInfo, &g_RTAsn1DefaultAllocator); if (RT_FAILURE(rc)) RTMsgError("RTCrX509SubjectPublicKeyInfo_Clone failed: %Rrc", rc); RTAsn1Core_ResetImplict(RTCrX509SubjectPublicKeyInfo_GetAsn1Core(&TrustAnchor.PubKey)); /* temporary hack. */ /* Key Identifier. */ PCRTASN1OCTETSTRING pKeyIdentifier = NULL; if (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_SUBJECT_KEY_IDENTIFIER) pKeyIdentifier = Certificate.TbsCertificate.T3.pSubjectKeyIdentifier; else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_AUTHORITY_KEY_IDENTIFIER) && RTCrX509Certificate_IsSelfSigned(&Certificate) && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier) ) pKeyIdentifier = &Certificate.TbsCertificate.T3.pAuthorityKeyIdentifier->KeyIdentifier; else if ( (Certificate.TbsCertificate.T3.fFlags & RTCRX509TBSCERTIFICATE_F_PRESENT_OLD_AUTHORITY_KEY_IDENTIFIER) && RTCrX509Certificate_IsSelfSigned(&Certificate) && RTAsn1OctetString_IsPresent(&Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier) ) pKeyIdentifier = &Certificate.TbsCertificate.T3.pOldAuthorityKeyIdentifier->KeyIdentifier; if (pKeyIdentifier && pKeyIdentifier->Asn1Core.cb > 0) { Assert(RTAsn1OctetString_IsPresent(&TrustAnchor.KeyIdentifier)); RTAsn1OctetString_Delete(&TrustAnchor.KeyIdentifier); rc = RTAsn1OctetString_Clone(&TrustAnchor.KeyIdentifier, pKeyIdentifier, &g_RTAsn1DefaultAllocator); if (RT_FAILURE(rc)) RTMsgError("RTAsn1OctetString_Clone failed: %Rrc", rc); RTAsn1Core_ResetImplict(RTAsn1OctetString_GetAsn1Core(&TrustAnchor.KeyIdentifier)); /* temporary hack. */ } else RTMsgWarning("No key identifier found or has zero length."); /* Subject */ if (RT_SUCCESS(rc)) { Assert(!RTCrTafCertPathControls_IsPresent(&TrustAnchor.CertPath)); rc = RTCrTafCertPathControls_Init(&TrustAnchor.CertPath, &g_RTAsn1DefaultAllocator); if (RT_SUCCESS(rc)) { Assert(RTCrX509Name_IsPresent(&TrustAnchor.CertPath.TaName)); RTCrX509Name_Delete(&TrustAnchor.CertPath.TaName); rc = RTCrX509Name_Clone(&TrustAnchor.CertPath.TaName, &Certificate.TbsCertificate.Subject, &g_RTAsn1DefaultAllocator); if (RT_SUCCESS(rc)) { RTAsn1Core_ResetImplict(RTCrX509Name_GetAsn1Core(&TrustAnchor.CertPath.TaName)); /* temporary hack. */ rc = RTCrX509Name_RecodeAsUtf8(&TrustAnchor.CertPath.TaName, &g_RTAsn1DefaultAllocator); if (RT_FAILURE(rc)) RTMsgError("RTCrX509Name_RecodeAsUtf8 failed: %Rrc", rc); } else RTMsgError("RTCrX509Name_Clone failed: %Rrc", rc); } else RTMsgError("RTCrTafCertPathControls_Init failed: %Rrc", rc); } /* Check that what we've constructed makes some sense. */ if (RT_SUCCESS(rc)) { rc = RTCrTafTrustAnchorInfo_CheckSanity(&TrustAnchor, 0, RTErrInfoInitStatic(&StaticErrInfo), "TAI"); if (RT_FAILURE(rc)) RTMsgError("RTCrTafTrustAnchorInfo_CheckSanity failed: %Rrc - %s", rc, StaticErrInfo.szMsg); } if (RT_SUCCESS(rc)) { /* * Encode it and write it to the output file. */ uint32_t cbEncoded; rc = RTAsn1EncodePrepare(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER, &cbEncoded, RTErrInfoInitStatic(&StaticErrInfo)); if (RT_SUCCESS(rc)) { if (State.cVerbose >= 1) RTAsn1Dump(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), 0, 0, RTStrmDumpPrintfV, g_pStdOut); PRTSTREAM pStrm; rc = RTStrmOpen(State.pszOutput, "wb", &pStrm); if (RT_SUCCESS(rc)) { rc = RTAsn1EncodeWrite(RTCrTafTrustAnchorInfo_GetAsn1Core(&TrustAnchor), RTASN1ENCODE_F_DER, handleMakeTaInfoWriter, pStrm, RTErrInfoInitStatic(&StaticErrInfo)); if (RT_SUCCESS(rc)) { rc = RTStrmClose(pStrm); if (RT_SUCCESS(rc)) RTMsgInfo("Successfully wrote TrustedAnchorInfo to '%s'.", State.pszOutput); else RTMsgError("RTStrmClose failed: %Rrc"); } else { RTMsgError("RTAsn1EncodeWrite failed: %Rrc - %s", rc, StaticErrInfo.szMsg); RTStrmClose(pStrm); } } else RTMsgError("Error opening '%s' for writing: %Rrcs", State.pszOutput, rc); } else RTMsgError("RTAsn1EncodePrepare failed: %Rrc - %s", rc, StaticErrInfo.szMsg); } RTCrTafTrustAnchorInfo_Delete(&TrustAnchor); } else RTMsgError("RTCrTafTrustAnchorInfo_Init failed: %Rrc", rc); RTCrX509Certificate_Delete(&Certificate); return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE; } /* * The 'version' command. */ static RTEXITCODE HelpVersion(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel) { RTStrmPrintf(pStrm, "version\n"); return RTEXITCODE_SUCCESS; } static RTEXITCODE HandleVersion(int cArgs, char **papszArgs) { RTPrintf("%s\n", RTBldCfgVersion()); return RTEXITCODE_SUCCESS; } /** * Command mapping. */ static struct { /** The command. */ const char *pszCmd; /** * Handle the command. * @returns Program exit code. * @param cArgs Number of arguments. * @param papszArgs The argument vector, starting with the command name. */ RTEXITCODE (*pfnHandler)(int cArgs, char **papszArgs); /** * Produce help. * @returns RTEXITCODE_SUCCESS to simplify handling '--help' in the handler. * @param pStrm Where to send help text. * @param enmLevel The level of the help information. */ RTEXITCODE (*pfnHelp)(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel); } /** Mapping commands to handler and helper functions. */ const g_aCommands[] = { { "extract-exe-signer-cert", HandleExtractExeSignerCert, HelpExtractExeSignerCert }, #ifndef IPRT_IN_BUILD_TOOL { "verify-exe", HandleVerifyExe, HelpVerifyExe }, #endif { "make-tainfo", HandleMakeTaInfo, HelpMakeTaInfo }, { "help", HandleHelp, HelpHelp }, { "--help", HandleHelp, NULL }, { "-h", HandleHelp, NULL }, { "version", HandleVersion, HelpVersion }, { "--version", HandleVersion, NULL }, { "-V", HandleVersion, NULL }, }; /* * The 'help' command. */ static RTEXITCODE HelpHelp(PRTSTREAM pStrm, RTSIGNTOOLHELP enmLevel) { RTStrmPrintf(pStrm, "help [cmd-patterns]\n"); return RTEXITCODE_SUCCESS; } static RTEXITCODE HandleHelp(int cArgs, char **papszArgs) { RTSIGNTOOLHELP enmLevel = cArgs <= 1 ? RTSIGNTOOLHELP_USAGE : RTSIGNTOOLHELP_FULL; uint32_t cShowed = 0; for (uint32_t iCmd = 0; iCmd < RT_ELEMENTS(g_aCommands); iCmd++) { if (g_aCommands[iCmd].pfnHelp) { bool fShow; if (cArgs <= 1) fShow = true; else { for (int iArg = 1; iArg < cArgs; iArg++) if (RTStrSimplePatternMultiMatch(papszArgs[iArg], RTSTR_MAX, g_aCommands[iCmd].pszCmd, RTSTR_MAX, NULL)) { fShow = true; break; } } if (fShow) { g_aCommands[iCmd].pfnHelp(g_pStdOut, enmLevel); cShowed++; } } } return cShowed ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE; } int main(int argc, char **argv) { int rc = RTR3InitExe(argc, &argv, 0); if (RT_FAILURE(rc)) return RTMsgInitFailure(rc); /* * Parse global arguments. */ int iArg = 1; /* none presently. */ /* * Command dispatcher. */ if (iArg < argc) { const char *pszCmd = argv[iArg]; uint32_t i = RT_ELEMENTS(g_aCommands); while (i-- > 0) if (!strcmp(g_aCommands[i].pszCmd, pszCmd)) return g_aCommands[i].pfnHandler(argc - iArg, &argv[iArg]); RTMsgError("Unknown command '%s'.", pszCmd); } else RTMsgError("No command given. (try --help)"); return RTEXITCODE_SYNTAX; }
36,450
12,647
/** * @file * @brief Generate fibonacci sequence * * Calculate the the value on Fibonacci's sequence given an * integer as input. * \f[\text{fib}(n) = \text{fib}(n-1) + \text{fib}(n-2)\f] * * @see fibonacci_large.cpp, fibonacci_fast.cpp, string_fibonacci.cpp */ #include <cassert> #include <iostream> /** * Recursively compute sequences * @param n input * @returns n-th element of the Fbinacci's sequence */ uint64_t fibonacci(uint64_t n) { /* If the input is 0 or 1 just return the same This will set the first 2 values of the sequence */ if (n <= 1) { return n; } /* Add the last 2 values of the sequence to get next */ return fibonacci(n - 1) + fibonacci(n - 2); } /** * Function for testing the fibonacci() function with a few * test cases and assert statement. * @returns `void` */ static void test() { uint64_t test_case_1 = fibonacci(0); assert(test_case_1 == 0); std::cout << "Passed Test 1!" << std::endl; uint64_t test_case_2 = fibonacci(1); assert(test_case_2 == 1); std::cout << "Passed Test 2!" << std::endl; uint64_t test_case_3 = fibonacci(2); assert(test_case_3 == 1); std::cout << "Passed Test 3!" << std::endl; uint64_t test_case_4 = fibonacci(3); assert(test_case_4 == 2); std::cout << "Passed Test 4!" << std::endl; uint64_t test_case_5 = fibonacci(4); assert(test_case_5 == 3); std::cout << "Passed Test 5!" << std::endl; uint64_t test_case_6 = fibonacci(15); assert(test_case_6 == 610); std::cout << "Passed Test 6!" << std::endl << std::endl; } /// Main function int main() { test(); int n = 0; std::cin >> n; assert(n >= 0); std::cout << "F(" << n << ")= " << fibonacci(n) << std::endl; }
1,702
688
/****************************************************************************/ /** * @file TinyXML.cpp */ /*---------------------------------------------------------------------------- * * Copyright (c) Visualization Laboratory, Kyoto University. * All rights reserved. * See http://www.viz.media.kyoto-u.ac.jp/kvs/copyright/ for details. * * $Id: TinyXML.cpp 631 2010-10-10 02:15:35Z naohisa.sakamoto $ */ /****************************************************************************/ /* Copyright (c) 2000 Lee Thomason (www.grinninglizard.com) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "TinyXML.h" #include <cctype> #include <kvs/DebugNew> namespace { template <typename T> void Ignore( T ){} } const char* TiXmlBase::errorString[ TIXML_ERROR_STRING_COUNT ] = { "No error.", "Failed to open file.", "Memory allocation failed.", "Error parsing Element.", "Failed to read Element name", "Error reading Element value.", "Error reading Attributes.", "Error: empty tag.", "Error reading end tag.", "Error parsing Unknown.", "Error parsing Comment.", "Error parsing Declaration.", }; const char* TiXmlBase::SkipWhiteSpace( const char* p ) { while ( p && *p && ( isspace( *p ) || *p == '\n' || *p == '\r' ) ) p++; return p; } const char* TiXmlBase::ReadName( const char* p, std::string* name ) { *name = ""; const char* start = p; // Names start with letters or underscores. // After that, they can be letters, underscores, numbers, // hyphens, or colons. (Colons are valid ony for namespaces, // but tinyxml can't tell namespaces from names.) if ( p && ( isalpha( *p ) || *p == '_' ) ) { p++; while( p && *p && ( isalnum( *p ) || *p == '_' || *p == '-' || *p == ':' ) ) { p++; } name->append( start, p - start ); return p; } return 0; } const char* TiXmlBase::ReadText( const char* p, std::string* text, bool trimWhiteSpace, const char* endTag, bool caseInsensitive ) { ::Ignore( caseInsensitive ); *text = ""; if ( !trimWhiteSpace // certain tags always keep whitespace /*|| !condenseWhiteSpace*/ ) // if true, whitespace is always kept { // Keep all the white space. while ( p && *p && strncmp( p, endTag, strlen(endTag) ) != 0 ) { char c = *(p++); (* text) += c; } } else { bool whitespace = false; // Remove leading white space: p = SkipWhiteSpace( p ); while ( p && *p && strncmp( p, endTag, strlen(endTag) ) != 0 ) { if ( *p == '\r' || *p == '\n' ) { whitespace = true; ++p; } else if ( isspace( *p ) ) { whitespace = true; ++p; } else { // If we've found whitespace, add it before the // new character. Any whitespace just becomes a space. if ( whitespace ) { (* text) += ' '; whitespace = false; } char c = *(p++); (* text) += c; } } } return p + strlen( endTag ); } const char* TiXmlDocument::Parse( const char* start ) { // Parse away, at the document level. Since a document // contains nothing but other tags, most of what happens // here is skipping white space. const char* p = start; p = SkipWhiteSpace( p ); if ( !p || !*p ) { error = true; errorDesc = "Document empty."; } while ( p && *p ) { if ( *p != '<' ) { error = true; errorDesc = "The '<' symbol that starts a tag was not found."; break; } else { TiXmlNode* node = IdentifyAndParse( &p ); if ( node ) { LinkEndChild( node ); } } p = SkipWhiteSpace( p ); } return 0; // Return null is fine for a document: once it is read, the parsing is over. } TiXmlNode* TiXmlNode::IdentifyAndParse( const char** where ) { const char* p = *where; TiXmlNode* returnNode = 0; assert( *p == '<' ); TiXmlDocument* doc = GetDocument(); p = SkipWhiteSpace( p+1 ); // What is this thing? // - Elements start with a letter or underscore, but xml is reserved. // - Comments: <!-- // - Everthing else is unknown to tinyxml. // if ( tolower( *(p+0) ) == '?' && tolower( *(p+1) ) == 'x' && tolower( *(p+2) ) == 'm' && tolower( *(p+3) ) == 'l' ) { #ifdef DEBUG_PARSER printf( "XML parsing Declaration\n" ); #endif returnNode = new TiXmlDeclaration(); } else if ( isalpha( *p ) || *p == '_' ) { #ifdef DEBUG_PARSER printf( "XML parsing Element\n" ); #endif returnNode = new TiXmlElement( "" ); } else if ( *(p+0) == '!' && *(p+1) == '-' && *(p+2) == '-' ) { #ifdef DEBUG_PARSER printf( "XML parsing Comment\n" ); #endif returnNode = new TiXmlComment(); } else if ( strncmp(p, "![CDATA[", 8) == 0 ) { TiXmlNode* cdataNode = new TiXmlCData(); if ( !cdataNode ) { if ( doc ) doc->SetError( TIXML_ERROR_OUT_OF_MEMORY ); return 0; } returnNode = cdataNode; } else { #ifdef DEBUG_PARSER printf( "XML parsing Comment\n" ); #endif returnNode = new TiXmlUnknown(); } if ( returnNode ) { // Set the parent, so it can report errors returnNode->parent = this; p = returnNode->Parse( p ); } else { if ( doc ) doc->SetError( TIXML_ERROR_OUT_OF_MEMORY ); p = 0; } *where = p; return returnNode; } const char* TiXmlElement::Parse( const char* p ) { TiXmlDocument* document = GetDocument(); p = SkipWhiteSpace( p ); if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_PARSING_ELEMENT ); return 0; } // Read the name. p = ReadName( p, &value ); if ( !p ) { if ( document ) document->SetError( TIXML_ERROR_FAILED_TO_READ_ELEMENT_NAME ); return 0; } std::string endTag = "</"; endTag += value; endTag += ">"; // Check for and read attributes. Also look for an empty // tag or an end tag. while ( p && *p ) { p = SkipWhiteSpace( p ); if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES ); return 0; } if ( *p == '/' ) { // Empty tag. if ( *(p+1) != '>' ) { if ( document ) document->SetError( TIXML_ERROR_PARSING_EMPTY ); return 0; } return p+2; } else if ( *p == '>' ) { // Done with attributes (if there were any.) // Read the value -- which can include other // elements -- read the end tag, and return. p = ReadValue( p+1 ); // Note this is an Element method, and will set the error if one happens. if ( !p ) return 0; // We should find the end tag now std::string buf( p, endTag.size() ); if ( endTag == buf ) { return p+endTag.size(); } else { if ( document ) document->SetError( TIXML_ERROR_READING_END_TAG ); return 0; } } else { // Try to read an element: TiXmlAttribute attrib; attrib.SetDocument( document ); p = attrib.Parse( p ); if ( p ) { SetAttribute( attrib.Name(), attrib.Value() ); } } } return 0; } const char* TiXmlElement::ReadValue( const char* p ) { TiXmlDocument* document = GetDocument(); // Read in text and elements in any order. p = SkipWhiteSpace( p ); while ( p && *p ) { const char* start = p; while ( *p && *p != '<' ) p++; if ( !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ELEMENT_VALUE ); return 0; } if ( p != start ) { // Take what we have, make a text element. TiXmlText* text = new TiXmlText(); if ( !text ) { if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY ); return 0; } text->Parse( start ); if ( !text->Blank() ) LinkEndChild( text ); else delete text; } else { // We hit a '<' // Have we hit a new element or an end tag? if ( *(p+1) == '/' ) { return p; // end tag } else { // TiXmlElement* element = new TiXmlElement( "" ); // // if ( element ) // { // p = element->Parse( p+1 ); // if ( p ) // LinkEndChild( element ); // } // else // { // if ( document ) document->SetError( ERROR_OUT_OF_MEMORY ); // return 0; // } TiXmlNode* node = IdentifyAndParse( &p ); if ( node ) { LinkEndChild( node ); } else { return 0; } } } } return 0; } const char* TiXmlUnknown::Parse( const char* p ) { const char* end = strchr( p, '>' ); if ( !end ) { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_PARSING_UNKNOWN ); return 0; } else { value = std::string( p, end-p ); // value.resize( end - p ); return end + 1; // return just past the '>' } } const char* TiXmlComment::Parse( const char* p ) { assert( *p == '!' && *(p+1) == '-' && *(p+2) == '-' ); // Find the end, copy the parts between to the value of // this object, and return. const char* start = p+3; const char* end = strstr( p, "-->" ); if ( !end ) { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_PARSING_COMMENT ); return 0; } else { // Assemble the comment, removing the white space. bool whiteSpace = false; const char* q; for( q=start; q<end; q++ ) { if ( isspace( *q ) ) { if ( !whiteSpace ) { value += ' '; whiteSpace = true; } } else { value += *q; whiteSpace = false; } } // value = std::string( start, end-start ); return end + 3; // return just past the '>' } } const char* TiXmlAttribute::Parse( const char* p ) { // Read the name, the '=' and the value. p = ReadName( p, &name ); if ( !p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES ); return 0; } p = SkipWhiteSpace( p ); if ( !p || *p != '=' ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES ); return 0; } p = SkipWhiteSpace( p+1 ); if ( !p || !*p ) { if ( document ) document->SetError( TIXML_ERROR_READING_ATTRIBUTES ); return 0; } const char* end = 0; const char* start = p+1; const char* past = 0; if ( *p == '\'' ) { end = strchr( start, '\'' ); past = end+1; } else if ( *p == '"' ) { end = strchr( start, '"' ); past = end+1; } else { // All attribute values should be in single or double quotes. // But this is such a common error that the parser will try // its best, even without them. start--; for ( end = start; *end; end++ ) { if ( isspace( *end ) || *end == '/' || *end == '>' ) break; } past = end; } value = std::string( start, end-start ); return past; } const char* TiXmlText::Parse( const char* p ) { value = ""; bool ignoreWhite = true; const char* end = "<"; p = ReadText( p, &value, ignoreWhite, end, false ); if ( p ) return p-1; // don't truncate the '<' return 0; #if 0 // Remove leading white space: p = SkipWhiteSpace( p ); while ( *p && *p != '<' ) { if ( *p == '\r' || *p == '\n' ) { whitespace = true; } else if ( isspace( *p ) ) { whitespace = true; } else { // If we've found whitespace, add it before the // new character. Any whitespace just becomes a space. if ( whitespace ) { value += ' '; whitespace = false; } value += *p; } p++; } // Keep white space before the '<' if ( whitespace ) value += ' '; return p; #endif } const char* TiXmlCData::Parse( const char* p ) { value = ""; bool ignoreWhite = false; p += 8; const char* end = "]]>"; p = ReadText( p, &value, ignoreWhite, end, false ); if ( p ) return p; return 0; } const char* TiXmlDeclaration::Parse( const char* p ) { // Find the beginning, find the end, and look for // the stuff in-between. const char* start = p+4; const char* end = strstr( start, "?>" ); // Be nice to the user: if ( !end ) { end = strstr( start, ">" ); end++; } else { end += 2; } if ( !end ) { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_PARSING_DECLARATION ); return 0; } else { const char* p; p = strstr( start, "version" ); if ( p && p < end ) { TiXmlAttribute attrib; attrib.Parse( p ); version = attrib.Value(); } p = strstr( start, "encoding" ); if ( p && p < end ) { TiXmlAttribute attrib; attrib.Parse( p ); encoding = attrib.Value(); } p = strstr( start, "standalone" ); if ( p && p < end ) { TiXmlAttribute attrib; attrib.Parse( p ); standalone = attrib.Value(); } } return end; } bool TiXmlText::Blank() { for ( unsigned i=0; i<value.size(); i++ ) if ( !isspace( value[i] ) ) return false; return true; } TiXmlNode::TiXmlNode( NodeType _type ) { parent = 0; type = _type; firstChild = 0; lastChild = 0; prev = 0; next = 0; } TiXmlNode::~TiXmlNode() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } } void TiXmlNode::Clear() { TiXmlNode* node = firstChild; TiXmlNode* temp = 0; while ( node ) { temp = node; node = node->next; delete temp; } firstChild = 0; lastChild = 0; } TiXmlNode* TiXmlNode::LinkEndChild( TiXmlNode* node ) { node->parent = this; node->prev = lastChild; node->next = 0; if ( lastChild ) lastChild->next = node; else firstChild = node; // it was an empty list. lastChild = node; return node; } TiXmlNode* TiXmlNode::InsertEndChild( const TiXmlNode& addThis ) { TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; return LinkEndChild( node ); } TiXmlNode* TiXmlNode::InsertBeforeChild( TiXmlNode* beforeThis, const TiXmlNode& addThis ) { if ( beforeThis->parent != this ) return 0; TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->next = beforeThis; node->prev = beforeThis->prev; beforeThis->prev->next = node; beforeThis->prev = node; return node; } TiXmlNode* TiXmlNode::InsertAfterChild( TiXmlNode* afterThis, const TiXmlNode& addThis ) { if ( afterThis->parent != this ) return 0; TiXmlNode* node = addThis.Clone(); if ( !node ) return 0; node->parent = this; node->prev = afterThis; node->next = afterThis->next; afterThis->next->prev = node; afterThis->next = node; return node; } TiXmlNode* TiXmlNode::ReplaceChild( TiXmlNode* replaceThis, const TiXmlNode& withThis ) { if ( replaceThis->parent != this ) return 0; TiXmlNode* node = withThis.Clone(); if ( !node ) return 0; node->next = replaceThis->next; node->prev = replaceThis->prev; if ( replaceThis->next ) replaceThis->next->prev = node; else lastChild = node; if ( replaceThis->prev ) replaceThis->prev->next = node; else firstChild = node; delete replaceThis; return node; } bool TiXmlNode::RemoveChild( TiXmlNode* removeThis ) { if ( removeThis->parent != this ) { assert( 0 ); return false; } if ( removeThis->next ) removeThis->next->prev = removeThis->prev; else lastChild = removeThis->prev; if ( removeThis->prev ) removeThis->prev->next = removeThis->next; else firstChild = removeThis->next; delete removeThis; return true; } TiXmlNode* TiXmlNode::FirstChild( const std::string& value ) const { TiXmlNode* node; for ( node = firstChild; node; node = node->next ) { if ( node->Value() == value ) return node; } return 0; } TiXmlNode* TiXmlNode::LastChild( const std::string& value ) const { TiXmlNode* node; for ( node = lastChild; node; node = node->prev ) { if ( node->Value() == value ) return node; } return 0; } TiXmlNode* TiXmlNode::IterateChildren( TiXmlNode* previous ) { if ( !previous ) { return FirstChild(); } else { assert( previous->parent == this ); return previous->NextSibling(); } } TiXmlNode* TiXmlNode::IterateChildren( const std::string& val, TiXmlNode* previous ) { if ( !previous ) { return FirstChild( val ); } else { assert( previous->parent == this ); return previous->NextSibling( val ); } } TiXmlNode* TiXmlNode::NextSibling( const std::string& value ) const { TiXmlNode* node; for ( node = next; node; node = node->next ) { if ( node->Value() == value ) return node; } return 0; } TiXmlNode* TiXmlNode::PreviousSibling( const std::string& value ) const { TiXmlNode* node; for ( node = prev; node; node = node->prev ) { if ( node->Value() == value ) return node; } return 0; } void TiXmlElement::RemoveAttribute( const std::string& name ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { attributeSet.Remove( node ); delete node; } } TiXmlElement* TiXmlNode::FirstChildElement() const { TiXmlNode* node; for ( node = FirstChild(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::FirstChildElement( const std::string& value ) const { TiXmlNode* node; for ( node = FirstChild( value ); node; node = node->NextSibling( value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::NextSiblingElement() const { TiXmlNode* node; for ( node = NextSibling(); node; node = node->NextSibling() ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlElement* TiXmlNode::NextSiblingElement( const std::string& value ) const { TiXmlNode* node; for ( node = NextSibling( value ); node; node = node->NextSibling( value ) ) { if ( node->ToElement() ) return node->ToElement(); } return 0; } TiXmlDocument* TiXmlNode::GetDocument() const { const TiXmlNode* node; for( node = this; node; node = node->parent ) { if ( node->ToDocument() ) return node->ToDocument(); } return 0; } // TiXmlElement::TiXmlElement() // : TiXmlNode( TiXmlNode::ELEMENT ) // { // } TiXmlElement::TiXmlElement( const std::string& _value ) : TiXmlNode( TiXmlNode::ELEMENT ) { firstChild = lastChild = 0; value = _value; } TiXmlElement::~TiXmlElement() { while( attributeSet.First() ) { TiXmlAttribute* node = attributeSet.First(); attributeSet.Remove( node ); delete node; } } const std::string* TiXmlElement::Attribute( const std::string& name ) const { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) return &(node->Value() ); return 0; } const std::string* TiXmlElement::Attribute( const std::string& name, int* i ) const { const std::string* s = Attribute( name ); if ( s ) *i = atoi( s->c_str() ); else *i = 0; return s; } void TiXmlElement::SetAttribute( const std::string& name, int val ) { char buf[64]; sprintf( buf, "%d", val ); std::string v = buf; SetAttribute( name, v ); } void TiXmlElement::SetAttribute( const std::string& name, const std::string& value ) { TiXmlAttribute* node = attributeSet.Find( name ); if ( node ) { node->SetValue( value ); return; } TiXmlAttribute* attrib = new TiXmlAttribute( name, value ); if ( attrib ) { attributeSet.Add( attrib ); } else { TiXmlDocument* document = GetDocument(); if ( document ) document->SetError( TIXML_ERROR_OUT_OF_MEMORY ); } } void TiXmlElement::Print( FILE* fp, int depth ) { int i; for ( i=0; i<depth; i++ ) fprintf( fp, " " ); fprintf( fp, "<%s", value.c_str() ); TiXmlAttribute* attrib; for ( attrib = attributeSet.First(); attrib; attrib = attrib->Next() ) { fprintf( fp, " " ); attrib->Print( fp, 0 ); } // If this node has children, give it a closing tag. Else // make it an empty tag. TiXmlNode* node; if ( firstChild ) { fprintf( fp, ">" ); for ( node = firstChild; node; node=node->NextSibling() ) { if ( !node->ToText() ) fprintf( fp, "\n" ); node->Print( fp, depth+1 ); } fprintf( fp, "\n" ); for ( i=0; i<depth; i++ ) fprintf( fp, " " ); fprintf( fp, "</%s>", value.c_str() ); } else { fprintf( fp, " />" ); } } TiXmlNode* TiXmlElement::Clone() const { TiXmlElement* clone = new TiXmlElement( Value() ); if ( !clone ) return 0; CopyToClone( clone ); // Clone the attributes, then clone the children. TiXmlAttribute* attribute = 0; for( attribute = attributeSet.First(); attribute; attribute = attribute->Next() ) { clone->SetAttribute( attribute->Name(), attribute->Value() ); } TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { clone->LinkEndChild( node->Clone() ); } return clone; } TiXmlDocument::TiXmlDocument() : TiXmlNode( TiXmlNode::DOCUMENT ) { error = false; // factory = new TiXmlFactory(); } TiXmlDocument::TiXmlDocument( const std::string& documentName ) : TiXmlNode( TiXmlNode::DOCUMENT ) { // factory = new TiXmlFactory(); value = documentName; error = false; } // void TiXmlDocument::SetFactory( TiXmlFactory* f ) // { // delete factory; // factory = f; // } bool TiXmlDocument::LoadFile() { return LoadFile( value ); } bool TiXmlDocument::SaveFile() { return SaveFile( value ); } bool TiXmlDocument::LoadFile( FILE* fp ) { // Delete the existing data: Clear(); unsigned size, first; first = ftell( fp ); fseek( fp, 0, SEEK_END ); size = ftell( fp ) - first + 1; fseek( fp, first, SEEK_SET ); char* buf = new char[size]; char* p = buf; while( fgets( p, size, fp ) ) { p = strchr( p, 0 ); } fclose( fp ); Parse( buf ); delete [] buf; if ( !Error() ) return true; return false; } bool TiXmlDocument::LoadFile( const std::string& filename ) { // Delete the existing data: Clear(); // Load the new data: FILE* fp = fopen( filename.c_str(), "r" ); if ( fp ) { return LoadFile(fp); } else { SetError( TIXML_ERROR_OPENING_FILE ); } return false; } bool TiXmlDocument::SaveFile( const std::string& filename ) { FILE* fp = fopen( filename.c_str(), "w" ); if ( fp ) { Print( fp, 0 ); fclose( fp ); return true; } return false; } TiXmlNode* TiXmlDocument::Clone() const { TiXmlDocument* clone = new TiXmlDocument(); if ( !clone ) return 0; CopyToClone( clone ); clone->error = error; clone->errorDesc = errorDesc; TiXmlNode* node = 0; for ( node = firstChild; node; node = node->NextSibling() ) { clone->LinkEndChild( node->Clone() ); } return clone; } void TiXmlDocument::Print( FILE* fp, int ) { TiXmlNode* node; for ( node=FirstChild(); node; node=node->NextSibling() ) { node->Print( fp, 0 ); fprintf( fp, "\n" ); } } TiXmlAttribute* TiXmlAttribute::Next() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( next->value.empty() && next->name.empty() ) return 0; return next; } TiXmlAttribute* TiXmlAttribute::Previous() { // We are using knowledge of the sentinel. The sentinel // have a value or name. if ( prev->value.empty() && prev->name.empty() ) return 0; return prev; } void TiXmlAttribute::Print( FILE* fp, int ) { if ( value.find( '\"' ) != std::string::npos ) fprintf( fp, "%s='%s'", name.c_str(), value.c_str() ); else fprintf( fp, "%s=\"%s\"", name.c_str(), value.c_str() ); } void TiXmlComment::Print( FILE* fp, int depth ) { for ( int i=0; i<depth; i++ ) fprintf( fp, " " ); fprintf( fp, "<!--%s-->", value.c_str() ); } TiXmlNode* TiXmlComment::Clone() const { TiXmlComment* clone = new TiXmlComment(); if ( !clone ) return 0; CopyToClone( clone ); return clone; } void TiXmlText::Print( FILE* fp, int ) { fprintf( fp, "%s", value.c_str() ); } TiXmlNode* TiXmlText::Clone() const { TiXmlText* clone = 0; clone = new TiXmlText(); if ( !clone ) return 0; CopyToClone( clone ); return clone; } TiXmlDeclaration::TiXmlDeclaration( const std::string& _version, const std::string& _encoding, const std::string& _standalone ) : TiXmlNode( TiXmlNode::DECLARATION ) { version = _version; encoding = _encoding; standalone = _standalone; } void TiXmlDeclaration::Print( FILE* fp, int ) { std::string out = "<?xml "; if ( !version.empty() ) { out += "version=\""; out += version; out += "\" "; } if ( !encoding.empty() ) { out += "encoding=\""; out += encoding; out += "\" "; } if ( !standalone.empty() ) { out += "standalone=\""; out += standalone; out += "\" "; } out += "?>"; fprintf( fp, "%s", out.c_str() ); } TiXmlNode* TiXmlDeclaration::Clone() const { TiXmlDeclaration* clone = new TiXmlDeclaration(); if ( !clone ) return 0; CopyToClone( clone ); clone->version = version; clone->encoding = encoding; clone->standalone = standalone; return clone; } void TiXmlUnknown::Print( FILE* fp, int depth ) { for ( int i=0; i<depth; i++ ) fprintf( fp, " " ); fprintf( fp, "<%s>", value.c_str() ); } TiXmlNode* TiXmlUnknown::Clone() const { TiXmlUnknown* clone = new TiXmlUnknown(); if ( !clone ) return 0; CopyToClone( clone ); return clone; } TiXmlAttributeSet::TiXmlAttributeSet() { sentinel.next = &sentinel; sentinel.prev = &sentinel; } TiXmlAttributeSet::~TiXmlAttributeSet() { assert( sentinel.next == &sentinel ); assert( sentinel.prev == &sentinel ); } void TiXmlAttributeSet::Add( TiXmlAttribute* addMe ) { assert( !Find( addMe->Name() ) ); // Shouldn't be multiply adding to the set. addMe->next = &sentinel; addMe->prev = sentinel.prev; sentinel.prev->next = addMe; sentinel.prev = addMe; } void TiXmlAttributeSet::Remove( TiXmlAttribute* removeMe ) { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node == removeMe ) { node->prev->next = node->next; node->next->prev = node->prev; node->next = 0; node->prev = 0; return; } } assert( 0 ); // we tried to remove a non-linked attribute. } TiXmlAttribute* TiXmlAttributeSet::Find( const std::string& name ) const { TiXmlAttribute* node; for( node = sentinel.next; node != &sentinel; node = node->next ) { if ( node->Name() == name ) return node; } return 0; }
31,786
10,230
/* Copyright 2017 Google Inc. * * 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 "support/entry/entry.h" #include "support/log/log.h" #include "vulkan_helpers/vulkan_application.h" #include "vulkan_wrapper/sub_objects.h" #include <algorithm> int main_entry(const entry::entry_data* data) { data->log->LogInfo("Application Startup"); vulkan::VulkanApplication app(data->root_allocator, data->log.get(), data); vulkan::VkDevice& device = app.device(); { // 1. Clear a 2D single layer, single mip level depth/stencil image const VkExtent3D image_extent{32, 32, 1}; const VkImageCreateInfo image_create_info{ /* sType = */ VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, /* pNext = */ nullptr, /* flags = */ 0, /* imageType = */ VK_IMAGE_TYPE_2D, /* format = */ VK_FORMAT_D16_UNORM, /* extent = */ image_extent, /* mipLevels = */ 1, /* arrayLayers = */ 1, /* samples = */ VK_SAMPLE_COUNT_1_BIT, /* tiling = */ VK_IMAGE_TILING_OPTIMAL, /* usage = */ VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_BUFFER_USAGE_TRANSFER_SRC_BIT, /* sharingMode = */ VK_SHARING_MODE_EXCLUSIVE, /* queueFamilyIndexCount = */ 0, /* pQueueFamilyIndices = */ nullptr, /* initialLayout = */ VK_IMAGE_LAYOUT_UNDEFINED, }; vulkan::ImagePointer image_ptr = app.CreateAndBindImage(&image_create_info); // Clear value and range const float depth_clear_float = 0.2; unsigned short depth_clear_unorm = depth_clear_float * 0xffff; VkClearDepthStencilValue clear_depth_stencil{ depth_clear_float, // depth 1, // stencil, not used here as the format does not contain stencil // data. }; VkImageSubresourceRange clear_range{ VK_IMAGE_ASPECT_DEPTH_BIT, // aspectMask 0, // baseMipLevel 1, // levelCount 0, // baseArrayLayer 1, // layerCount }; // Get command buffer and call the vkCmdClearDepthStencilImage command vulkan::VkCommandBuffer cmd_buf = app.GetCommandBuffer(); ::VkCommandBuffer raw_cmd_buf = cmd_buf.get_command_buffer(); VkCommandBufferBeginInfo cmd_buf_begin_info{ VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, nullptr, 0, nullptr}; cmd_buf->vkBeginCommandBuffer(cmd_buf, &cmd_buf_begin_info); VkImageMemoryBarrier image_barrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, // sType nullptr, // pNext 0, // srcAccessMask VK_ACCESS_TRANSFER_WRITE_BIT, // dstAccessMask VK_IMAGE_LAYOUT_UNDEFINED, // oldLayout VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // newLayout VK_QUEUE_FAMILY_IGNORED, // srcQueueFamilyIndex VK_QUEUE_FAMILY_IGNORED, // dstQueueFamilyIndex *image_ptr, // image {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 1, 0, 1}, // subresourceRange }; cmd_buf->vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, nullptr, 0, nullptr, 1, &image_barrier); cmd_buf->vkCmdClearDepthStencilImage( cmd_buf, // commandBuffer *image_ptr, // image VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, // imageLayout &clear_depth_stencil, // pDepthStencil 1, // rangeCount &clear_range // pRagnes ); cmd_buf->vkEndCommandBuffer(cmd_buf); VkSubmitInfo submit_info{VK_STRUCTURE_TYPE_SUBMIT_INFO, nullptr, 0, nullptr, nullptr, 1, &raw_cmd_buf, 0, nullptr}; app.render_queue()->vkQueueSubmit(app.render_queue(), 1, &submit_info, static_cast<VkFence>(VK_NULL_HANDLE)); app.render_queue()->vkQueueWaitIdle(app.render_queue()); // Dump the data in the cleared image containers::vector<uint8_t> dump_data(data->root_allocator); app.DumpImageLayersData( image_ptr.get(), {VK_IMAGE_ASPECT_DEPTH_BIT, 0, 0, 1}, {0, 0, 0}, image_extent, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, &dump_data, {}); // Check the dump data containers::vector<unsigned short> expected_data( vulkan::GetImageExtentSizeInBytes(image_extent, VK_FORMAT_D16_UNORM) / sizeof(unsigned short), depth_clear_unorm, data->root_allocator); LOG_ASSERT(==, data->log, expected_data.size(), dump_data.size() / sizeof(unsigned short)); unsigned short* dump_data_ptr = reinterpret_cast<unsigned short*>(dump_data.data()); std::for_each(expected_data.begin(), expected_data.end(), [&data, &dump_data_ptr](unsigned short d) { LOG_ASSERT(==, data->log, d, *dump_data_ptr++); }); } data->log->LogInfo("Application Shutdown"); return 0; }
5,988
1,941
#include "exercise_10.h" void f() { string s = "a series of whitespace seperated words"; vector<string> substrings = split(s); for (auto substring : substrings) { cout << substring << endl; } } int main() { try { f(); } catch (...) { cout << "MAJOR ERROR\n"; return -1; } return 0; }
367
133
// Arquivo player_mail_box.hpp // Criado em 13/01/2021 as 09:52 por Acrisio // Defini��o da classe PlayerMailBox #pragma once #ifndef _STDA_PLAYER_MAIL_BOX_HPP #define _STDA_PLAYER_MAIL_BOX_HPP #if defined(_WIN32) #include <Windows.h> #elif defined(__linux__) #include "../../Projeto IOCP/UTIL/WinPort.h" #include <pthread.h> #include <unistd.h> #endif #include <map> #include "../TYPE/pangya_game_st.h" #include "../../Projeto IOCP/PANGYA_DB/pangya_db.h" namespace stdA { constexpr uint64_t EXPIRES_CACHE_TIME = 3 * 1000ull; // 3 Segundos constexpr uint32_t NUM_OF_EMAIL_PER_PAGE = 20u; // 20 Emails por p�gina constexpr uint32_t LIMIT_OF_UNREAD_EMAIL = 300u; // 300 Emails n�o lidos que pode enviar para o player class PlayerMailBox { public: PlayerMailBox(); virtual ~PlayerMailBox(); void init(std::map< int32_t, EmailInfoEx >& _emails, uint32_t _uid); void clear(); std::vector< MailBox > getPage(uint32_t _page); std::vector< MailBox > getAllUnreadEmail(); uint32_t getTotalPages(); void addNewEmailArrived(int32_t _id); EmailInfo getEmailInfo(int32_t _id, bool _ler = true); // Deleta todos os itens quem tem no email, eles j� foram tirados do email pelo player void leftItensFromEmail(int32_t _id); // Deleta 1 ou mais emails de uma vez void deleteEmail(int32_t* _a_id, uint32_t _count); protected: // Methods Static static void SQLDBResponse(uint32_t _msg_id, pangya_db& _pangya_db, void* _arg); static bool sort_last_arrived(MailBox& _rhs, MailBox& _lhs); protected: // Unsafe thread sync bool checkLastUpdate(); void checkAndUpdate(); // Unsafe thread sync void copyEmailInfoExToMailBox(EmailInfoEx& _email, MailBox& _mail); void update(); protected: uint32_t m_uid; std::map< int32_t, EmailInfoEx > m_emails; SYSTEMTIME m_last_update; #if defined(_WIN32) CRITICAL_SECTION m_cs; #elif defined(__linux__) pthread_mutex_t m_cs; #endif }; } #endif // !_STDA_PLAYER_MAIL_BOX_HPP
2,008
909
/* * Copyright 2017 The WizTK Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "wiztk/base/string.hpp" #include <unicode/utf.h> #include <unicode/unistr.h> #include <unicode/ustream.h> #include <unicode/stringpiece.h> namespace wiztk { namespace base { String::String(const char *str) { // TODO: temporary workaround, optimize this by ICU later: icu::UnicodeString unicode = icu::UnicodeString::fromUTF8(icu::StringPiece(str)); assign(unicode.getBuffer()); } String::String(const char16_t *str) { assign(reinterpret_cast<const UChar *>(str)); } String::String(const char32_t *str) { // TODO: temporary workaround, optimize this by ICU later. icu::UnicodeString unicode = icu::UnicodeString::fromUTF32(reinterpret_cast<const UChar32 *>(str), static_cast<uint32_t>(std::char_traits<char32_t>::length(str))); assign(unicode.getBuffer()); } std::ostream &operator<<(std::ostream &out, const String &str) { // TODO: This create and copy the string array from String16 to icu::UnicodeString, find a better way for performance. return out << icu::UnicodeString(str.data()); } std::string String::ToUTF8() const { std::string utf8; icu::UnicodeString unicode = data(); unicode.toUTF8String(utf8); return utf8; } } // namespace base } // namespace wiztk
1,855
608
#include "channel.h" #include "library.h" #include "fileinfo.h" #include "connection.h" #include "filetransfer.h" #include "private/cachemanager_p.h" #include "private/interfacemanager_p.h" namespace TeamSpeakSdk { class Channel::Private { public: int getInt(const Channel* channel, ChannelProperty flag) { return api().getChannelVariableAsInt(channel, flag); } uint64 getUInt64(const Channel* channel, ChannelProperty flag) { return api().getChannelVariableAsUInt64(channel, flag); } QString getString(const Channel* channel, ChannelProperty flag) { return api().getChannelVariableAsString(channel, flag); } void setInt(Channel* channel, ChannelProperty flag, int value) { api().setChannelVariableAsInt(channel, flag, value); flushChannelUpdates(channel); } void setUInt64(Channel* channel, ChannelProperty flag, uint64 value) { api().setChannelVariableAsUInt64(channel, flag, value); flushChannelUpdates(channel); } void setString(Channel* channel, ChannelProperty flag, const QString& value) { api().setChannelVariableAsString(channel, flag, value); flushChannelUpdates(channel); } void flushChannelUpdates(Channel* channel) { if (channel->id() == 0) return; } ID id = 0; Connection* connection = nullptr; struct Cache { QString name; QString topic; } cached; }; /*! * \class Channel * * \brief */ Channel::Channel(Connection* connection) : d(new Private) { d->connection = connection; } Channel::Channel(Connection* connection, ID id, bool waitForProperties) : Channel(connection) { setId(id); refreshProperties(waitForProperties); } Channel::~Channel() { delete d; } Channel::Channel(const Channel& other) Q_DECL_NOTHROW : d(new Private) { *d = *other.d; } Channel::Channel(Channel&& other) Q_DECL_NOTHROW { *d = *other.d; } void Channel::swap(Channel&& other) { qSwap(d, other.d); } Channel& Channel::operator=(const Channel& other) Q_DECL_NOTHROW { swap(std::move(Channel(other))); return *this; } Channel& Channel::operator=(Channel&& other) Q_DECL_NOTHROW { swap(std::move(Channel(std::move(other)))); return *this; } bool Channel::operator==(const Channel& o) const Q_DECL_NOTHROW { if ((this) == &o) return true; return connection() == o.connection() && id() == o.id(); } /*! * ID of the channel */ Channel::ID Channel::id() const { return d->id; } void Channel::setId(ID id) { d->id = id; } /*! * Server Connection */ Connection* Channel::connection() const { return d->connection; } void Channel::setConnection(Connection* server) { d->connection = server; } /*! * The parent channel */ Channel* Channel::parent() const { return api().getParentChannelOfChannel(this); } /*! * List of all clients in the channel, if the channel is currently subscribed. */ QList<Client*> Channel::clients() const { return api().getChannelClientList(this); } QList<Channel*> Channel::channels() const { return QList<Channel*>(); } /*! * Name of the channel */ QString Channel::name() const { return d->cached.name; } void Channel::setName(const QString& value) { d->setString(this, ChannelProperty::Name, value); } /*! * Single-line channel topic */ QString Channel::topic() const { return d->cached.topic; } void Channel::setTopic(const QString& value) { d->setString(this, ChannelProperty::Topic, value); } /*! * Optional channel description. Can have multiple lines. * Needs to be request with \sa getChannelDescription(). */ QString Channel::description() const { return d->getString(this, ChannelProperty::Description); } void Channel::setDescription(const QString& value) { d->setString(this, ChannelProperty::Description, value); } /*! * Optional password for password-protected channels. */ void Channel::setPassword(const QString& value) { d->setString(this, ChannelProperty::Password, value); } /*! * Codec used for this channel */ CodecType Channel::codec() const { return CodecType(d->getInt(this, ChannelProperty::Codec)); } void Channel::setCodec(CodecType value) { d->setInt(this, ChannelProperty::Codec, utils::underlay(value)); } /*! * Quality of channel codec of this channel. * Valid values range from 0 to 10, default is 7. * Higher values result in better speech quality but more bandwidth usage */ int Channel::codecQuality() const { return d->getInt(this, ChannelProperty::CodecQuality); } void Channel::setCodecQuality(int value) { d->setInt(this, ChannelProperty::CodecQuality, value); } /*! * Number of maximum clients who can join this channel */ int Channel::maxClients() const { return d->getInt(this, ChannelProperty::Maxclients); } void Channel::setMaxClients(int value) { d->setInt(this, ChannelProperty::Maxclients, value); } /*! * Number of maximum clients who can join this channel and all subchannels */ int Channel::maxFamilyClients() const { return d->getInt(this, ChannelProperty::Maxfamilyclients); } void Channel::setMaxFamilyClients(int value) { d->setInt(this, ChannelProperty::Maxfamilyclients, value); } /*! * \sa order() is the \sa channel() after which this channel is sorted. * <see lang word="null" meaning its going to be the first \sa channel() under \sa parent() */ Channel* Channel::order() const { const auto orderId = d->getUInt64(this, ChannelProperty::Order); return connection()->getChannel(orderId); } void Channel::setOrder(const Channel* value) { d->setUInt64(this, ChannelProperty::Order, value ? value->id() : 0); } /*! * Permanent channels will be restored when the server restarts. */ bool Channel::isPermanent() const { return d->getInt(this, ChannelProperty::FlagPermanent) != 0; } void Channel::setPermanent(bool value) { d->setInt(this, ChannelProperty::FlagPermanent, value ? 1 : 0); } /*! * Semi-permanent channels are not automatically deleted when the last user left * but will not be restored when the server restarts. */ bool Channel::isSemiPermanent() const { return d->getInt(this, ChannelProperty::FlagSemiPermanent) != 0; } void Channel::setSemiPermanent(bool value) { d->setInt(this, ChannelProperty::FlagSemiPermanent, value ? 1 : 0); } /*! * Channel is the default channel. * There can only be one default channel per server. * New users who did not configure a channel to join on login in ts3client_startConnection will automatically join the default channel. */ bool Channel::isDefault() const { return d->getInt(this, ChannelProperty::FlagDefault) != 0; } void Channel::setDefault(bool value) { d->setInt(this, ChannelProperty::FlagDefault, value ? 1 : 0); } /*! * If set, channel is password protected. * The password itself is stored in ChannelPassword */ bool Channel::isPasswordProtected() const { return d->getInt(this, ChannelProperty::FlagPassword) != 0; } /*! * Latency of this channel. * Allows to increase the packet size resulting in less bandwidth usage at the cost of higher latency. * A value of 1 (default) is the best setting for lowest latency and best quality. * If bandwidth or network quality are restricted, increasing the latency factor can help stabilize the connection. * Higher latency values are only possible for low-quality codec and codec quality settings. */ int Channel::codecLatencyFactor() const { return d->getInt(this, ChannelProperty::CodecLatencyFactor); } void Channel::setCodecLatencyFactor(int value) { d->setInt(this, ChannelProperty::CodecLatencyFactor, value); } /*! * If true, this channel is not using encrypted voice data. * If false, voice data is encrypted for this channel. * Note that channel voice data encryption can be globally disabled or enabled for the virtual server. * Changing this flag makes only sense if global voice data encryption is set to be configured per channel. */ bool Channel::codecIsUnencrypted() const { return d->getInt(this, ChannelProperty::CodecIsUnencrypted) != 0; } void Channel::setCodecIsUnencrypted(bool value) { d->setInt(this, ChannelProperty::CodecIsUnencrypted, value ? 1 : 0); } time::seconds Channel::deleteDelay() const { const auto time = d->getInt(this, ChannelProperty::DeleteDelay); return time::seconds(time); } void Channel::setDeleteDelay(const time::seconds& value) { d->setInt(this, ChannelProperty::DeleteDelay, int(value.count())); } time::seconds Channel::channelEmptyTime() const { const auto time = api().getChannelEmptySecs(this); return time::seconds(time); } /*! * Uploads a local file to the server * \a "file" Path of the local file, which is to be uploaded. * \a "overwrite" when false, upload will abort if remote file exists * \a "resume" If we have a previously halted transfer: true = resume, false = restart transfer * \a "channelPassword" Optional channel password. Pass empty string or null if unused. * Returns \c A task that represents the asynchronous upload operation. */ void Channel::sendFile(const FileTransferOption& option) { api().sendFile( this, option.password, option.file.fileName(), option.overwrite, option.resume, option.file.dir().path(), TODO_RETURN_CODE ); } /*! * Download a file from the server. * \a "fileName" Filename of the remote file, which is to be downloaded. * \a "destinationDirectory" Local target directory name where the download file should be saved. * \a "overwrite" when false, download will abort if local file exists * \a "resume" If we have a previously halted transfer: true = resume, false = restart transfer * \a "channelPassword" Optional channel password. Pass empty string or null if unused. * \a "cancellationToken" The token to monitor for cancellation requests. The default value is \sa "CancellationToken.None" * Returns \c A task that represents the asynchronous download operation. */ void Channel::requestFile(const FileTransferOption& option) { api().requestFile( this, option.password, option.file.fileName(), option.overwrite, option.resume, option.file.dir().path(), TODO_RETURN_CODE ); } /*! * Query list of files in a directory. * \a "path" Path inside the channel, defining the subdirectory. Top level path is ?? * \a "channelPassword" Optional channel password. Pass empty string or null if unused. * Returns \c A task that returns the list of files contained in path */ void Channel::getFileList(const QString& path, const QString& channelPassword) { api().requestFileList(this, channelPassword, path, TODO_RETURN_CODE); } /*! * Query information of a specified file. The answer from the server will trigger \sa "Connection.FileInfoReceived" with the requested information. * \a "file" File name we want to request info from, needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory. * \a "channelPassword" Optional channel password. Pass empty string or null if unused. * Returns \c A task that represents the asynchronous operation. */ void Channel::getFileInfo(const QString& file, const QString& channelPassword) { api().requestFileInfo(this, channelPassword, file, TODO_RETURN_CODE); } /*! * Create a directory. * \a path Name of the directory to create. The directory name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory. * \a password Optional channel password. Pass empty string or null if unused. * Returns \c A task that represents the asynchronous operation. */ void Channel::mkdir(const QString& path, const QString& password) { api().requestCreateDirectory(this, password, path, TODO_RETURN_CODE); } /*! * Moves or renames a file. If the source and target channels and paths are the same, the file will simply be renamed. * \a "file" Old name of the file. The file name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory. * \a "channelPassword" Optional channel password. Pass empty string or null if unused. * \a "toFile" New name of the file. The new name needs to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory. * \a "toChannel" Target channel, to which we want to move the file. * \a "toChannelPassword" Optional channel password. Pass empty string or null if unused. * Returns \c A task that represents the asynchronous operation. */ void Channel::moveFile(const QString& file, const QString& toFile, const QString& channelPassword, const Channel* toChannel, const QString& toChannelPassword) { api().requestRenameFile( this, channelPassword, toChannel ? toChannel : this, toChannelPassword, file, toFile, TODO_RETURN_CODE ); } /*! * Delete one or more remote files on the server. * \a "files" List of files we request to be deleted. The file names need to include the full path within the channel, e.g. ?file?for a top-level file or ?dir1/dir2/file?for a file located in a subdirectory. * \a "channelPassword" Optional channel password. Pass empty string or null if unused. * Returns \c A task that represents the asynchronous operation. */ void Channel::deleteFile(const QStringList& files, const QString& channelPassword) { api().requestDeleteFile(this, channelPassword, files, TODO_RETURN_CODE); } /*! * Request updating the channel description * Returns \c A task that represents the asynchronous operation. */ void Channel::getChannelDescription() const { api().requestChannelDescription(this, TODO_RETURN_CODE); } /*! * Removes the channel from the server * \a "force" If true, the channel will be deleted even when it is not empty. * Clients within the deleted channel are transfered to the default channel. * Any contained subchannels are removed as well. * If \c false, the server will refuse to delete a channel that is not empty. * Returns \c A task that represents the asynchronous operation. */ void Channel::remove(bool force) { api().requestChannelDelete(this, force, TODO_RETURN_CODE); } /*! * Send a text message to the channel * \a "message" The text message * Returns \c A task that represents the asynchronous operation. */ void Channel::sendTextMessage(const QString& message) { api().requestSendChannelTextMsg(this, message, TODO_RETURN_CODE); } /*! * Move the channel to a new parent channel * \a "newParent" The parent channel where the moved channel is to be inserted as child. Use null to insert as top-level channel. * \a "newChannelOrder" the \sa "Channel" after which <see langword="this" \sa "Channel" is sorted. <see langword="null" meaning its going to be the first \sa "Channel" under <paramref name="newParent". * Returns \c A task that represents the asynchronous operation. */ void Channel::moveTo(Channel* newParent, Channel* newChannelOrder) { if (utils::has_null(newParent)) return; if (!utils::is_same_server(connection(), newParent, newChannelOrder)) return; api().requestChannelMove(this, newParent, newChannelOrder, TODO_RETURN_CODE); } void Channel::flushUpdates() { d->flushChannelUpdates(this); } void Channel::refreshProperties(bool wait) { } } // namespace TeamSpeakSdk
15,546
4,651
// MIT Licensed (see LICENSE.md). #pragma once namespace Math { namespace Simd { // loading SimMat4 LoadMat4x4(const scalar vals[16]); SimMat4 SetMat4x4(scalar m00, scalar m01, scalar m02, scalar m03, scalar m10, scalar m11, scalar m12, scalar m13, scalar m20, scalar m21, scalar m22, scalar m23, scalar m30, scalar m31, scalar m32, scalar m33); SimMat4 UnAlignedLoadMat4x4(const scalar vals[16]); // storing void StoreMat4x4(scalar vals[16], SimMat4Param mat); void UnAlignedStoreMat4x4(scalar vals[16], SimMat4Param mat); // default matrix sets SimMat4 ZeroOutMat4x4(); SimMat4 IdentityMat4x4(); // basis elements SimVec BasisX(SimMat4Param mat); SimVec BasisY(SimMat4Param mat); SimVec BasisZ(SimMat4Param mat); SimVec BasisW(SimMat4Param mat); SimMat4 SetBasisX(SimMat4Param mat, SimVecParam value); SimMat4 SetBasisY(SimMat4Param mat, SimVecParam value); SimMat4 SetBasisZ(SimMat4Param mat, SimVecParam value); SimMat4 SetBasisW(SimMat4Param mat, SimVecParam value); // basic arithmetic SimMat4 Add(SimMat4Param lhs, SimMat4Param rhs); SimMat4 Subtract(SimMat4Param lhs, SimMat4Param rhs); SimMat4 Multiply(SimMat4Param lhs, SimMat4Param rhs); SimMat4 Scale(SimMat4Param mat, scalar scale); SimMat4 ComponentScale(SimMat4Param lhs, SimMat4Param rhs); SimMat4 ComponentDivide(SimMat4Param lhs, SimMat4Param rhs); // matrix vector arithmetic SimVec TransformPoint(SimMat4Param mat, SimVecParam vec); SimVec TransposeTransformPoint(SimMat4Param mat, SimVecParam vec); SimVec TransformNormal(SimMat4Param mat, SimVecParam vec); SimVec TransposeTransformNormal(SimMat4Param mat, SimVecParam vec); SimVec TransformPointProjected(SimMat4Param mat, SimVecParam vec); // transform building SimMat4 BuildScale(SimVecParam scale); SimMat4 BuildRotation(SimVecParam axis, scalar angle); SimMat4 BuildRotation(SimVecParam quat); SimMat4 BuildTranslation(SimVecParam translation); SimMat4 BuildTransform(SimVecParam translation, SimVecParam axis, scalar angle, SimVecParam scale); SimMat4 BuildTransform(SimVecParam translation, SimVecParam quat, SimVecParam scale); SimMat4 BuildTransform(SimVecParam translation, SimMat4Param rot, SimVecParam scale); // transposes the upper 3x3 of the 4x4 and leaves the remaining elements alone SimMat4 TransposeUpper3x3(SimMat4Param mat); SimMat4 Transpose4x4(SimMat4Param mat); SimMat4 AffineInverse4x4(SimMat4Param transform); SimMat4 AffineInverseWithScale4x4(SimMat4Param transform); // basic logic SimMat4 Equal(SimMat4Param mat1, SimMat4Param mat2); // arithmetic operators SimMat4 operator+(SimMat4Param lhs, SimMat4Param rhs); SimMat4 operator-(SimMat4Param lhs, SimMat4Param rhs); SimMat4 operator*(SimMat4Param lhs, SimMat4Param rhs); // vector with scalar arithmetic operators SimMat4 operator*(SimMat4Param lhs, scalar rhs); SimMat4 operator/(SimMat4Param lhs, scalar rhs); } // namespace Simd } // namespace Math #include "Math/SimMatrix4.inl"
3,165
1,023
#include "serialization_demo.hpp" #include "serialization_examples.hpp" #include "blob.hpp" #include <iostream> #include <stdint.h> #include <stdarg.h> #define WIN32_LEAN_AND_MEAN #include <Windows.h> // Allocator ////////////////////////////////////////////////////////////// void* Allocator::allocate( sizet size, sizet alignment ) { return malloc( size ); } void* Allocator::allocate( sizet size, sizet alignment, cstring file, i32 line ) { return malloc( size ); } void Allocator::deallocate( void* pointer ) { free( pointer ); } // Log //////////////////////////////////////////////////////////////////// static constexpr u32 k_string_buffer_size = 1024 * 1024; static char log_buffer[ k_string_buffer_size ]; static void output_console( char* log_buffer_ ) { printf( "%s", log_buffer_ ); } static void output_visual_studio( char* log_buffer_ ) { OutputDebugStringA( log_buffer_ ); } void hprint( cstring format, ... ) { va_list args; va_start( args, format ); vsnprintf_s( log_buffer, k_string_buffer_size, format, args ); log_buffer[ k_string_buffer_size - 1 ] = '\0'; va_end( args ); output_console( log_buffer ); #if defined(_MSC_VER) output_visual_studio( log_buffer ); #endif // _MSC_VER } // CharArray ////////////////////////////////////////////////////////////// void CharArray::init( Allocator* allocator_, cstring string ) { size = ( u32 )( strlen( string ) + 1 ); capacity = size; allocator = allocator_; data = ( char* )halloca( size, allocator ); strcpy( data, string ); } // File /////////////////////////////////////////////////////////////////// static long file_get_size( FILE* f ) { long fileSizeSigned; fseek( f, 0, SEEK_END ); fileSizeSigned = ftell( f ); fseek( f, 0, SEEK_SET ); return fileSizeSigned; } char* file_read_binary( cstring filename, Allocator* allocator, sizet* size ) { char* out_data = 0; FILE* file = fopen( filename, "rb" ); if ( file ) { // TODO: Use filesize or read result ? sizet filesize = file_get_size( file ); out_data = ( char* )halloca( filesize + 1, allocator ); fread( out_data, filesize, 1, file ); out_data[ filesize ] = 0; if ( size ) *size = filesize; fclose( file ); } return out_data; } char* file_read_text( cstring filename, Allocator* allocator, sizet* size ) { char* text = 0; FILE* file = fopen( filename, "r" ); if ( file ) { sizet filesize = file_get_size( file ); text = ( char* )halloca( filesize + 1, allocator ); // Correct: use elementcount as filesize, bytes_read becomes the actual bytes read // AFTER the end of line conversion for Windows (it uses \r\n). sizet bytes_read = fread( text, 1, filesize, file ); text[ bytes_read ] = 0; if ( size ) *size = filesize; fclose( file ); } return text; } void file_write_binary( cstring filename, void* memory, sizet size ) { FILE* file = fopen( filename, "wb" ); fwrite( memory, size, 1, file ); fclose( file ); } // Vec2s ////////////////////////////////////////////////////////////////// // Forward declaration for template specialization. template<> void BlobSerializer::serialize<vec2s>( vec2s* data ); // Serialization binary template<> void BlobSerializer::serialize<vec2s>( vec2s* data ) { serialize( &data->x ); serialize( &data->y ); } // OtherData ////////////////////////////////////////////////////////////// // Data structure added just to have a pointer to test. // struct OtherData { f32 a; u32 b; }; template<> void BlobSerializer::serialize<OtherData>( OtherData* data ) { serialize( &data->a ); serialize( &data->b ); } // GameDataV0 ///////////////////////////////////////////////////////////// // // First version of the game data. // Used to write older binaries and test versioning. struct GameDataV0 : public Blob { vec2s position; RelativeArray<u32> all_effs; OtherData other; RelativeString name; RelativePointer<OtherData> other_pointer; static constexpr u32 k_version = 0; }; // struct GameDataV0 template<> void BlobSerializer::serialize<GameDataV0>( GameDataV0* data ) { serialize( &data->position ); serialize( &data->all_effs ); serialize( &data->other ); serialize( &data->name ); serialize( &data->other_pointer ); } // // Second version of game data. // struct GameDataV1 : public Blob { vec2s position; RelativeArray<u32> all_effs; OtherData other; RelativeArray<u32> all_cs; // Added in V1 RelativeString name; RelativePointer<OtherData> other_pointer; static constexpr u32 k_version = 1; }; // struct GameDataV1 template<> void BlobSerializer::serialize<GameDataV1>( GameDataV1* data ) { serialize( &data->position ); serialize( &data->all_effs ); serialize( &data->other ); if ( serializer_version > 0 ) { serialize( &data->all_cs ); } serialize( &data->name ); serialize( &data->other_pointer ); } // // struct GameData : public Blob { vec2s position; RelativeArray<u32> all_effs; OtherData other; RelativeArray<u32> all_cs; // Added in V1 Array<u32> all_as; // Added in V2 CharArray new_name; // Added in V2 RelativeString name; RelativePointer<OtherData> other_pointer; static constexpr u32 k_version = 2; }; // struct GameData template<> void BlobSerializer::serialize<GameData>( GameData* data ) { serialize( &data->position ); serialize( &data->all_effs ); serialize( &data->other ); if ( serializer_version > 0 ) { serialize( &data->all_cs ); } else { data->all_cs.set_empty(); } if ( serializer_version > 1 ) { serialize( &data->all_as ); serialize( &data->new_name ); } else { } serialize( &data->name ); serialize( &data->other_pointer ); } static Allocator s_heap_allocator; int main() { hprint( "Serialization demo\n" ); Allocator* allocator = &s_heap_allocator; // 1. Resource Compilation and Inspection ///////////////////////////// compile_cutscene( allocator, "..//data//articles//serializationdemo//cutscene.json", "..//data//bin//cutscene.bin" ); inspect_cutscene( allocator, "..//data//bin//cutscene.bin" ); compile_scene( allocator, "..//data//articles//serializationdemo//new_game.json", "..//data//bin//new_game.bin" ); inspect_scene( allocator, "..//data//bin//new_game.bin" ); // 2. Write GameDataV0 binary BlobSerializer write_blob_v0, read_blob_v0; { // NOTE: this is a non-optimal way of writing the blob, but still doable. // Write V0 and read with GameData (V2) char* memory = (char*)malloc( 1000 ); memset( memory, 0, 1000 ); GameDataV0* writing_data = ( GameDataV0* )memory; writing_data->position = { 100,200 }; writing_data->other.a = 7.0f; writing_data->other.b = 0xffff; u32* effs = ( u32* )( memory + sizeof( GameDataV0 ) ); *effs = 0xffffffff; char* name_memory = ( char* )( effs + 1 ); strcpy( name_memory, "IncredibleName" ); OtherData* other_pointer = ( OtherData* )( name_memory + strlen( name_memory ) + 1 ); other_pointer->a = 16.f; other_pointer->b = 0xaaaaaaaa; // Close to the allocate_and_set method used in blobs. // Calculate the offset for the arrays writing_data->all_effs.set( ( char* )effs, 1 ); writing_data->name.set( name_memory, strlen( name_memory ) ); // Calculate the offset for the pointer writing_data->other_pointer.set( ( char* )other_pointer ); // Write to blob using serialization methods, by passing the writing data. write_blob_v0.write_and_serialize( allocator, 0, 1000, writing_data ); // GameData* game_data = read_blob_v0.read<GameData>( allocator, GameData::k_version, write_blob_v0.blob_memory, write_blob_v0.allocated_offset * 2 ); if ( game_data ) { OtherData* other_data = game_data->other_pointer.get(); hy_assert( game_data->position.x == 100.f ); hy_assert( other_data->a == 16.f ); hy_assert( other_data->b == 0xaaaaaaaa ); hy_assert( strcmp( game_data->name.c_str(), "IncredibleName" ) == 0 ); hy_assert( game_data->all_effs[ 0 ] == 0xffffffff ); hprint( "V0 Read Done %s!\n", game_data->name.c_str() ); } } // Write GameDataV1 binary BlobSerializer write_blob_v1, read_blob_v1; { // Use write blob to already fill the data. // Allocate just a blob with 200 bytes GameDataV1* game_data_v1 = write_blob_v1.write_and_prepare<GameDataV1>( allocator, 1, 200 ); game_data_v1->position.x = 700.f; game_data_v1->position.y = 42.f; u32 all_effs[] = { 0xffffffff, 0xffffffff }; write_blob_v1.allocate_and_set( game_data_v1->all_effs, 2, all_effs ); // other game_data_v1->other.a = 8.f; game_data_v1->other.b = 0xbbbbbbbb; // all c u32 all_cs[] = { 0xcccccccc, 0xcccccccc, 0xcccccccc }; write_blob_v1.allocate_and_set( game_data_v1->all_cs, 3, all_cs ); // name cstring name_string = "GameDataV1Awesomeness"; write_blob_v1.allocate_and_set( game_data_v1->name, "%s", name_string ); // other pointer write_blob_v1.allocate_and_set( game_data_v1->other_pointer, nullptr ); OtherData* other_data_pointed = game_data_v1->other_pointer.get(); other_data_pointed->a = 32.f; other_data_pointed->b = 0xdddddddd; // Read V1 blob, again with the v2 serializer. GameData* game_data = read_blob_v1.read<GameData>( allocator, GameData::k_version, write_blob_v1.blob_memory, write_blob_v1.allocated_offset * 2 ); if ( game_data ) { OtherData* other_data = game_data->other_pointer.get(); hy_assert( game_data->position.x == 700.f ); hy_assert( game_data->other.a == 8.f ); hy_assert( game_data->other.b == 0xbbbbbbbb ); hy_assert( other_data->a == 32.f ); hy_assert( other_data->b == 0xdddddddd ); hy_assert( strcmp( game_data->name.c_str(), "GameDataV1Awesomeness" ) == 0 ); hy_assert( game_data->all_effs[ 1 ] == 0xffffffff ); hy_assert( game_data->other_pointer->a == 32.f ); hprint( "V1 Read Done %s!\n", game_data->name.c_str() ); } } // Write GameDataV2 binary BlobSerializer write_blob_v2, read_blob_v2, read_blob_v2_serialized; { GameData* game_data = write_blob_v2.write_and_prepare<GameData>( allocator, GameData::k_version, 300 ); game_data->position.x = 700.f; game_data->position.y = 42.f; u32 all_effs[] = { 0xffffffff, 0xffffffff }; write_blob_v2.allocate_and_set( game_data->all_effs, 2, all_effs ); // other game_data->other.a = 8.f; game_data->other.b = 0xbbbbbbbb; // all c u32 all_cs[] = { 0xcccccccc, 0xcccccccc, 0xcccccccc }; write_blob_v2.allocate_and_set( game_data->all_cs, 3, all_cs ); // all as u32 all_as[] = { 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa, 0xaaaaaaaa }; write_blob_v2.allocate_and_set( game_data->all_as, 4, all_as ); // new name cstring new_name_string = "GameDataV2Plus"; write_blob_v2.allocate_and_set( game_data->new_name, new_name_string ); // name cstring name_string = "GameDataV2Awesomeness"; write_blob_v2.allocate_and_set( game_data->name, "%s", name_string ); // other pointer write_blob_v2.allocate_and_set( game_data->other_pointer, nullptr ); OtherData* other_data_pointed = game_data->other_pointer.get(); other_data_pointed->a = 32.f; other_data_pointed->b = 0xdddddddd; // Read V2 blob. This is MEMORY MAPPED. GameData* mmap_game_data = read_blob_v2.read<GameData>( allocator, GameData::k_version, write_blob_v2.blob_memory, write_blob_v2.allocated_offset * 2 ); // Force serialization of game data and test fields. GameData* serialized_game_data = read_blob_v2_serialized.read<GameData>( allocator, GameData::k_version, write_blob_v2.blob_memory, write_blob_v2.allocated_offset * 2, true ); if ( mmap_game_data && serialized_game_data ) { OtherData* mmap_other_data = mmap_game_data->other_pointer.get(); OtherData* serialized_other_data = serialized_game_data->other_pointer.get(); hy_assert( mmap_game_data->position.x == serialized_game_data->position.x ); hy_assert( mmap_game_data->position.x == 700.f ); hy_assert( mmap_other_data->a == serialized_other_data->a ); hy_assert( mmap_other_data->a == 32.f ); hy_assert( mmap_other_data->b == serialized_other_data->b ); hy_assert( mmap_other_data->b == 0xdddddddd ); hy_assert( strcmp( mmap_game_data->name.c_str(), serialized_game_data->name.c_str() ) == 0 ); hy_assert( mmap_game_data->all_effs[ 1 ] == serialized_game_data->all_effs[ 1 ] ); hy_assert( mmap_game_data->all_effs[ 1 ] == 0xffffffff ); hy_assert( mmap_game_data->other_pointer->a == serialized_game_data->other_pointer->a ); hy_assert( mmap_game_data->all_as.get()[3] == serialized_game_data->all_as[ 3 ] ); hy_assert( serialized_game_data->all_as[ 3 ] == 0xaaaaaaaa ); hy_assert( serialized_game_data->all_as[ 0 ] == 0xaaaaaaaa ); hy_assert( mmap_game_data->all_as.get()[ 3 ] == 0xaaaaaaaa ); hy_assert( mmap_game_data->all_as.get()[ 0 ] == 0xaaaaaaaa ); cstring aa0 = mmap_game_data->new_name.get(); hy_assert( strcmp( mmap_game_data->new_name.get(), "GameDataV2Plus" ) == 0 ); cstring aa1 = serialized_game_data->new_name.c_str(); hy_assert( strcmp( serialized_game_data->new_name.c_str(), "GameDataV2Plus" ) == 0 ); hprint( "V2 Read Done %s!\n", mmap_game_data->name.c_str() ); } } hprint( "Test finished SUCCESSFULLY!\n" ); }
14,601
5,062
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "CommonCommonPch.h" #include "Common/Tick.h" namespace Js { uint64 Tick::s_luFreq; uint64 Tick::s_luBegin; #if DBG uint64 Tick::s_DEBUG_luStart = 0; uint64 Tick::s_DEBUG_luSkip = 0; #endif ///---------------------------------------------------------------------------- ///---------------------------------------------------------------------------- /// /// struct Tick /// ///---------------------------------------------------------------------------- ///---------------------------------------------------------------------------- ///---------------------------------------------------------------------------- /// /// Tick::Tick /// /// Tick() initializes a new Tick instance to an "empty" time. This instance /// must be assigned to another Tick instance or Now() to have value. /// ///---------------------------------------------------------------------------- Tick::Tick() { m_luTick = 0; } ///---------------------------------------------------------------------------- /// /// Tick::Tick /// /// Tick() initializes a new Tick instance to a specific time, in native /// time units. /// ///---------------------------------------------------------------------------- Tick::Tick( uint64 luTick) // Tick, in internal units { m_luTick = luTick; } ///---------------------------------------------------------------------------- /// /// Tick::FromMicroseconds /// /// FromMicroseconds() returns a Tick instance from a given time in /// microseconds. /// ///---------------------------------------------------------------------------- Tick Tick::FromMicroseconds( uint64 luTime) // Time, in microseconds { // // Ensure we can convert losslessly. // #if DBG const uint64 luMaxTick = _UI64_MAX / s_luFreq; AssertMsg(luTime <= luMaxTick, "Ensure time can be converted losslessly"); #endif // DBG // // Create the Tick // uint64 luTick = luTime * s_luFreq / ((uint64) 1000000); return Tick(luTick); } ///---------------------------------------------------------------------------- /// /// Tick::FromQPC /// /// FromQPC() returns a Tick instance from a given QPC time. /// ///---------------------------------------------------------------------------- Tick Tick::FromQPC( uint64 luTime) // Time, in QPC units { return Tick(luTime - s_luBegin); } ///---------------------------------------------------------------------------- /// /// Tick::ToQPC /// /// ToQPC() returns the QPC time for this time instance /// ///---------------------------------------------------------------------------- uint64 Tick::ToQPC() { return (m_luTick + s_luBegin); } ///---------------------------------------------------------------------------- /// /// Tick::operator + /// /// operator +() /// ///---------------------------------------------------------------------------- Tick Tick::operator +( TickDelta tdChange // RHS TickDelta ) const { return Tick(m_luTick + tdChange.m_lnDelta); } ///---------------------------------------------------------------------------- /// /// Tick::operator - /// /// operator -() /// ///---------------------------------------------------------------------------- Tick Tick::operator -( TickDelta tdChange // RHS TickDelta ) const { return Tick(m_luTick - tdChange.m_lnDelta); } ///---------------------------------------------------------------------------- /// /// Tick::operator - /// /// operator -() /// ///---------------------------------------------------------------------------- TickDelta Tick::operator -( Tick timeOther // RHS Tick ) const { return TickDelta(m_luTick - timeOther.m_luTick); } ///---------------------------------------------------------------------------- /// /// Tick::operator == /// /// operator ==() /// ///---------------------------------------------------------------------------- bool Tick::operator ==( Tick timeOther // RHS Tick ) const { return m_luTick == timeOther.m_luTick; } ///---------------------------------------------------------------------------- /// /// Tick::operator != /// /// operator !=() /// ///---------------------------------------------------------------------------- bool Tick::operator !=( Tick timeOther // RHS Tick ) const { return m_luTick != timeOther.m_luTick; } ///---------------------------------------------------------------------------- /// /// Tick::operator < /// /// operator <() /// ///---------------------------------------------------------------------------- bool Tick::operator <( Tick timeOther // RHS Tick ) const { return m_luTick < timeOther.m_luTick; } ///---------------------------------------------------------------------------- /// /// Tick::operator <= /// /// operator <=() /// ///---------------------------------------------------------------------------- bool Tick::operator <=( Tick timeOther // RHS Tick ) const { return m_luTick <= timeOther.m_luTick; } ///---------------------------------------------------------------------------- /// /// Tick::operator > /// /// operator >() /// ///---------------------------------------------------------------------------- bool Tick::operator >( Tick timeOther // RHS Tick ) const { return m_luTick > timeOther.m_luTick; } ///---------------------------------------------------------------------------- /// /// Tick::operator >= /// /// operator >=() /// ///---------------------------------------------------------------------------- bool Tick::operator >=( Tick timeOther // RHS Tick ) const { return m_luTick >= timeOther.m_luTick; } ///---------------------------------------------------------------------------- ///---------------------------------------------------------------------------- /// /// struct TickDelta /// ///---------------------------------------------------------------------------- ///---------------------------------------------------------------------------- ///---------------------------------------------------------------------------- /// /// TickDelta::TickDelta /// /// TickDelta() initializes a new TickDelta instance to "zero" delta. /// ///---------------------------------------------------------------------------- TickDelta::TickDelta() { m_lnDelta = 0; } ///---------------------------------------------------------------------------- /// /// TickDelta::TickDelta /// /// TickDelta() initializes a new TickDelta instance to a specific time delta, /// in native time units. /// ///---------------------------------------------------------------------------- TickDelta::TickDelta( int64 lnDelta) { m_lnDelta = lnDelta; } ///---------------------------------------------------------------------------- /// /// TickDelta::ToMicroseconds /// /// ToMicroseconds() returns the time delta, in microseconds. The time is /// rounded to the nearest available whole units. /// ///---------------------------------------------------------------------------- int64 TickDelta::ToMicroseconds() const { if (*this == Infinite()) { return _I64_MAX; } // // Ensure we can convert losslessly. // const int64 lnMinTimeDelta = _I64_MIN / ((int64) 1000000); const int64 lnMaxTimeDelta = _I64_MAX / ((int64) 1000000); AssertMsg((m_lnDelta <= lnMaxTimeDelta) && (m_lnDelta >= lnMinTimeDelta), "Ensure delta can be converted to microseconds losslessly"); // // Compute the microseconds. // int64 lnFreq = (int64) Tick::s_luFreq; int64 lnTickDelta = (m_lnDelta * ((int64) 1000000)) / lnFreq; return lnTickDelta; } ///---------------------------------------------------------------------------- /// /// TickDelta::FromMicroseconds /// /// FromMicroseconds() returns a TickDelta instance from a given delta in /// microseconds. /// ///---------------------------------------------------------------------------- TickDelta TickDelta::FromMicroseconds( int64 lnTimeDelta) // Time delta, in 1/1000^2 sec { AssertMsg(lnTimeDelta != _I64_MAX, "Use Infinite() to create an infinite TickDelta"); // // Ensure that we can convert losslessly. // int64 lnFreq = (int64) Tick::s_luFreq; #if DBG const int64 lnMinTimeDelta = _I64_MIN / lnFreq; const int64 lnMaxTimeDelta = _I64_MAX / lnFreq; AssertMsg((lnTimeDelta <= lnMaxTimeDelta) && (lnTimeDelta >= lnMinTimeDelta), "Ensure delta can be converted to native format losslessly"); #endif // DBG // // Create the TickDelta // int64 lnTickDelta = (lnTimeDelta * lnFreq) / ((int64) 1000000); TickDelta td(lnTickDelta); AssertMsg(td != Infinite(), "Can not create infinite TickDelta"); return td; } ///---------------------------------------------------------------------------- /// /// TickDelta::FromMicroseconds /// /// FromMicroseconds() returns a TickDelta instance from a given delta in /// microseconds. /// ///---------------------------------------------------------------------------- TickDelta TickDelta::FromMicroseconds( int nTimeDelta) // Tick delta, in 1/1000^2 sec { AssertMsg(nTimeDelta != _I32_MAX, "Use Infinite() to create an infinite TickDelta"); return FromMicroseconds((int64) nTimeDelta); } ///---------------------------------------------------------------------------- /// /// TickDelta::FromMilliseconds /// /// FromMilliseconds() returns a TickDelta instance from a given delta in /// milliseconds. /// ///---------------------------------------------------------------------------- TickDelta TickDelta::FromMilliseconds( int nTimeDelta) // Tick delta, in 1/1000^1 sec { AssertMsg(nTimeDelta != _I32_MAX, "Use Infinite() to create an infinite TickDelta"); return FromMicroseconds(((int64) nTimeDelta) * ((int64) 1000)); } ///---------------------------------------------------------------------------- /// /// TickDelta::Infinite /// /// Infinite() returns a time-delta infinitely far away. /// ///---------------------------------------------------------------------------- TickDelta TickDelta::Infinite() { return TickDelta(_I64_MAX); } ///---------------------------------------------------------------------------- /// /// TickDelta::IsForward /// /// IsForward() returns whether adding this TickDelta to a given Tick will /// not move the time backwards. /// ///---------------------------------------------------------------------------- bool TickDelta::IsForward() const { return m_lnDelta >= 0; } ///---------------------------------------------------------------------------- /// /// TickDelta::IsBackward /// /// IsBackward() returns whether adding this TickDelta to a given Tick will /// not move the time forwards. /// ///---------------------------------------------------------------------------- bool TickDelta::IsBackward() const { return m_lnDelta <= 0; } ///---------------------------------------------------------------------------- /// /// TickDelta::Abs /// /// Abs() returns the absolute value of the TickDelta. /// ///---------------------------------------------------------------------------- TickDelta TickDelta::Abs(TickDelta tdOther) { return TickDelta(tdOther.m_lnDelta < 0 ? -tdOther.m_lnDelta : tdOther.m_lnDelta); } ///---------------------------------------------------------------------------- /// /// TickDelta::operator % /// /// operator %() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator %( TickDelta tdOther // RHS TickDelta ) const { return TickDelta(m_lnDelta % tdOther.m_lnDelta); } ///---------------------------------------------------------------------------- /// /// TickDelta::operator \ /// /// operator \() - Divides one TickDelta by another, in TickDelta units /// ///---------------------------------------------------------------------------- int64 TickDelta::operator /( TickDelta tdOther // RHS TickDelta ) const { return m_lnDelta / tdOther.m_lnDelta; } ///---------------------------------------------------------------------------- /// /// TickDelta::operator + /// /// operator +() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator +( TickDelta tdOther // RHS TickDelta ) const { AssertMsg((*this != Infinite()) && (tdOther != Infinite()), "Can not combine infinite TickDeltas"); return TickDelta(m_lnDelta + tdOther.m_lnDelta); } ///---------------------------------------------------------------------------- /// /// TickDelta::operator - /// /// operator -() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator -( TickDelta tdOther // RHS TickDelta ) const { AssertMsg((*this != Infinite()) && (tdOther != Infinite()), "Can not combine infinite TickDeltas"); return TickDelta(m_lnDelta - tdOther.m_lnDelta); } ///---------------------------------------------------------------------------- /// /// TickDelta::operator * /// /// operator *() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator *( int nScale // RHS scale ) const { AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas"); return TickDelta(m_lnDelta * nScale); } ///---------------------------------------------------------------------------- /// /// TickDelta::operator * /// /// operator *() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator *( float flScale // RHS scale ) const { AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas"); return TickDelta((int64) (((double) m_lnDelta) * ((double) flScale))); } ///---------------------------------------------------------------------------- /// /// TickDelta::operator / /// /// operator /() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator /( int nScale // RHS scale ) const { AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas"); AssertMsg(nScale != 0, "Can not scale by 0"); return TickDelta(m_lnDelta / nScale); } ///---------------------------------------------------------------------------- /// /// TickDelta::operator / /// /// operator /() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator /( float flScale // RHS scale ) const { AssertMsg(*this != Infinite(), "Can not combine infinite TickDeltas"); AssertMsg(flScale != 0, "Can not scale by 0"); return TickDelta((int64) (((double) m_lnDelta) / ((double) flScale))); } ///---------------------------------------------------------------------------- /// /// TickDelta::operator += /// /// operator +=() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator +=( TickDelta tdOther) // RHS TickDelta { AssertMsg((*this != Infinite()) && (tdOther != Infinite()), "Can not combine infinite TickDeltas"); m_lnDelta = m_lnDelta + tdOther.m_lnDelta; return *this; } ///---------------------------------------------------------------------------- /// /// TickDelta::operator -= /// /// operator -=() /// ///---------------------------------------------------------------------------- TickDelta TickDelta::operator -=( TickDelta tdOther) // RHS TickDelta { AssertMsg((*this != Infinite()) && (tdOther != Infinite()), "Can not combine infinite TickDeltas"); m_lnDelta = m_lnDelta - tdOther.m_lnDelta; return *this; } ///---------------------------------------------------------------------------- /// /// TickDelta::operator == /// /// operator ==() /// ///---------------------------------------------------------------------------- bool TickDelta::operator ==( TickDelta tdOther // RHS TickDelta ) const { return m_lnDelta == tdOther.m_lnDelta; } ///---------------------------------------------------------------------------- /// /// TickDelta::operator != /// /// operator !=() /// ///---------------------------------------------------------------------------- bool TickDelta::operator !=( TickDelta tdOther // RHS TickDelta ) const { return m_lnDelta != tdOther.m_lnDelta; } ///---------------------------------------------------------------------------- /// /// TickDelta::operator < /// /// operator <() /// ///---------------------------------------------------------------------------- bool TickDelta::operator <( TickDelta tdOther // RHS TickDelta ) const { return m_lnDelta < tdOther.m_lnDelta; } ///---------------------------------------------------------------------------- /// /// TickDelta::operator <= /// /// operator <=() /// ///---------------------------------------------------------------------------- bool TickDelta::operator <=( TickDelta tdOther // RHS TickDelta ) const { return m_lnDelta <= tdOther.m_lnDelta; } ///---------------------------------------------------------------------------- /// /// TickDelta::operator > /// /// operator >() /// ///---------------------------------------------------------------------------- bool TickDelta::operator >( TickDelta tdOther // RHS TickDelta ) const { return m_lnDelta > tdOther.m_lnDelta; } ///---------------------------------------------------------------------------- /// /// TickDelta::operator >= /// /// operator >=() /// ///---------------------------------------------------------------------------- bool TickDelta::operator >=( TickDelta tdOther // RHS TickDelta ) const { return m_lnDelta >= tdOther.m_lnDelta; } void Tick::InitType() { /* CheckWin32( */ QueryPerformanceFrequency((LARGE_INTEGER *) &s_luFreq); /* CheckWin32( */ QueryPerformanceCounter((LARGE_INTEGER *) &s_luBegin); #if DBG s_luBegin += s_DEBUG_luStart; #endif // // Ensure that we have a sufficient amount of time so that we can handle useful time operations. // uint64 nSec = _UI64_MAX / s_luFreq; if (nSec < 5 * 60) { #if FIXTHIS PromptInvalid("QueryPerformanceFrequency() will not provide at least 5 minutes"); return Results::GenericFailure; #endif } } Tick Tick::Now() { // Determine our current time uint64 luCurrent = s_luBegin; /* Verify( */ QueryPerformanceCounter((LARGE_INTEGER *) &luCurrent); #if DBG luCurrent += s_DEBUG_luStart + s_DEBUG_luSkip; #endif // Create a Tick instance, using our delta since we started tracking time. uint64 luDelta = luCurrent - s_luBegin; return Tick(luDelta); } uint64 Tick::ToMicroseconds() const { // // Convert time in microseconds (1 / 1000^2). Because of the finite precision and wrap-around, // this math depends on where the Tick is. // const uint64 luOneSecUs = (uint64) 1000000; const uint64 luSafeTick = _UI64_MAX / luOneSecUs; if (m_luTick < luSafeTick) { // // Small enough to convert directly into microseconds. // uint64 luTick = (m_luTick * luOneSecUs) / s_luFreq; return luTick; } else { // // Number is too large, so we need to do this is stages. // 1. Compute the number of seconds // 2. Convert the remainder // 3. Add the two parts together // uint64 luSec = m_luTick / s_luFreq; uint64 luRemain = m_luTick - luSec * s_luFreq; uint64 luTick = (luRemain * luOneSecUs) / s_luFreq; luTick += luSec * luOneSecUs; return luTick; } } int TickDelta::ToMilliseconds() const { if (*this == Infinite()) { return _I32_MAX; } int64 nTickUs = ToMicroseconds(); int64 lnRound = 500; if (nTickUs < 0) { lnRound = -500; } int64 lnDelta = (nTickUs + lnRound) / ((int64) 1000); AssertMsg((lnDelta <= INT_MAX) && (lnDelta >= INT_MIN), "Ensure no overflow"); return (int) lnDelta; } }
23,938
6,113
// MIT License // // Copyright (c) 2020, The Regents of the University of California, // through Lawrence Berkeley National Laboratory (subject to receipt of any // required approvals from the U.S. Dept. of Energy). All rights reserved. // // 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 "test_macros.hpp" TIMEMORY_TEST_DEFAULT_MAIN #include "timemory/timemory.hpp" //--------------------------------------------------------------------------------------// namespace details { // Get the current tests name inline std::string get_test_name() { return std::string(::testing::UnitTest::GetInstance()->current_test_suite()->name()) + "." + ::testing::UnitTest::GetInstance()->current_test_info()->name(); } // this function consumes approximately "n" milliseconds of real time inline void do_sleep(long n) { std::this_thread::sleep_for(std::chrono::milliseconds(n)); } // this function consumes an unknown number of cpu resources inline long fibonacci(long n) { return (n < 2) ? n : (fibonacci(n - 1) + fibonacci(n - 2)); } // this function consumes approximately "t" milliseconds of cpu time void consume(long n) { // a mutex held by one lock mutex_t mutex; // acquire lock lock_t hold_lk(mutex); // associate but defer lock_t try_lk(mutex, std::defer_lock); // get current time auto now = std::chrono::steady_clock::now(); // try until time point while(std::chrono::steady_clock::now() < (now + std::chrono::milliseconds(n))) try_lk.try_lock(); } // get a random entry from vector template <typename Tp> void random_fill(std::vector<Tp>& v, Tp scale, Tp offset = 1.0) { std::mt19937 rng; rng.seed(std::random_device()()); std::generate(v.begin(), v.end(), [&]() { return (scale * std::generate_canonical<Tp, 10>(rng)) + offset; }); } // get a random entry from vector template <typename Tp> size_t random_entry(const std::vector<Tp>& v) { std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<std::mt19937::result_type> dist(0, v.size() - 1); return v.at(dist(rng)); } } // namespace details //--------------------------------------------------------------------------------------// class api_tests : public ::testing::Test { protected: TIMEMORY_TEST_DEFAULT_SUITE_BODY }; namespace os = ::tim::os; namespace project = ::tim::project; namespace category = ::tim::category; namespace tpls = ::tim::tpls; namespace trait = ::tim::trait; using namespace tim::component; using tim_bundle_t = tim::component_bundle<project::timemory, wall_clock, cpu_clock>; using cali_bundle_t = tim::component_bundle<tpls::caliper, caliper_marker, wall_clock>; using time_bundle_t = tim::component_tuple<wall_clock, cpu_clock, num_minor_page_faults, read_bytes, written_bytes>; using os_bundle_t = tim::component_bundle<os::agnostic, wall_clock, cpu_clock>; //--------------------------------------------------------------------------------------// TEST_F(api_tests, enum_vs_macro) { namespace component = tim::component; auto macro_sz = std::tuple_size<tim::type_list<TIMEMORY_COMPONENT_TYPES>>::value; auto enum_sz = TIMEMORY_NATIVE_COMPONENTS_END - TIMEMORY_NATIVE_COMPONENT_INTERNAL_SIZE; EXPECT_EQ(macro_sz, enum_sz); } //--------------------------------------------------------------------------------------// TEST_F(api_tests, placeholder) { using nothing_placeholder = placeholder<nothing>; auto in_complete = tim::is_one_of<nothing_placeholder, tim::complete_types_t>::value; auto in_avail = tim::is_one_of<nothing_placeholder, tim::available_types_t>::value; EXPECT_FALSE(in_complete) << "complete_types_t: " << tim::demangle<tim::complete_types_t>() << std::endl; EXPECT_FALSE(in_avail) << "available_types_t: " << tim::demangle<tim::available_types_t>() << std::endl; } //--------------------------------------------------------------------------------------// TEST_F(api_tests, timemory) { using test_t = project::timemory; auto incoming = trait::runtime_enabled<test_t>::get(); trait::runtime_enabled<test_t>::set(false); tim_bundle_t _obj(details::get_test_name()); _obj.start(); details::consume(1000); _obj.stop(); EXPECT_NEAR(_obj.get<wall_clock>()->get(), 0.0, 1.0e-6); EXPECT_NEAR(_obj.get<cpu_clock>()->get(), 0.0, 1.0e-6); trait::runtime_enabled<test_t>::set(incoming); } //--------------------------------------------------------------------------------------// TEST_F(api_tests, tpls) { using test_t = tpls::caliper; auto incoming = trait::runtime_enabled<test_t>::get(); trait::runtime_enabled<test_t>::set(false); EXPECT_FALSE(trait::runtime_enabled<test_t>::get()); EXPECT_FALSE(trait::runtime_enabled<caliper_marker>::get()); cali_bundle_t _obj(details::get_test_name()); _obj.start(); details::consume(1000); _obj.stop(); std::cout << "tpls::caliper available == " << std::boolalpha << "[compile-time " << tim::trait::is_available<test_t>::value << "] [run-time " << trait::runtime_enabled<test_t>::get() << "]\n"; if(tim::trait::is_available<test_t>::value) { EXPECT_NEAR(_obj.get<wall_clock>()->get(), 0.0, 1.0e-6) << "obj: " << _obj; } else { EXPECT_EQ(_obj.get<wall_clock>(), nullptr) << "obj: " << _obj; } trait::runtime_enabled<test_t>::set(incoming); } //--------------------------------------------------------------------------------------// TEST_F(api_tests, category) { // a type in a non-timing category that should still be enabled #if defined(TIMEMORY_UNIX) using check_type = num_minor_page_faults; #elif defined(TIMEMORY_WINDOWS) using check_type = read_bytes; #endif using test_t = category::timing; auto incoming = trait::runtime_enabled<test_t>::get(); trait::runtime_enabled<test_t>::set(false); using wc_api_t = trait::component_apis_t<wall_clock>; using wc_true_t = tim::mpl::get_true_types_t<trait::runtime_configurable, wc_api_t>; using wc_false_t = tim::mpl::get_false_types_t<trait::runtime_configurable, wc_api_t>; using apitypes_t = typename trait::runtime_enabled<wall_clock>::api_type_list; puts(""); PRINT_HERE("component-apis : %s", tim::demangle<wc_api_t>().c_str()); PRINT_HERE("true-types : %s", tim::demangle<wc_false_t>().c_str()); PRINT_HERE("false-types : %s", tim::demangle<wc_true_t>().c_str()); PRINT_HERE("type-traits : %s", tim::demangle<apitypes_t>().c_str()); puts(""); EXPECT_FALSE(trait::runtime_enabled<wall_clock>::get()); EXPECT_FALSE(trait::runtime_enabled<cpu_clock>::get()); EXPECT_TRUE(trait::runtime_enabled<check_type>::get()); time_bundle_t _obj(details::get_test_name()); _obj.start(); details::consume(500); for(size_t i = 0; i < 10; ++i) { std::vector<double> _data(10000, 0.0); details::random_fill(_data, 10.0, 1.0); { std::ofstream ofs{ TIMEMORY_JOIN("", ".", details::get_test_name(), "_data", i, ".txt") }; for(auto& itr : _data) ofs << std::fixed << std::setprecision(6) << itr << " "; } auto _data_cpy = _data; _data.clear(); _data.resize(10000, 0.0); { std::ifstream ifs{ TIMEMORY_JOIN("", ".", details::get_test_name(), "_data", i, ".txt") }; for(auto& itr : _data) ifs >> itr; } for(size_t j = 0; j < _data.size(); ++j) EXPECT_NEAR(_data.at(j), _data_cpy.at(j), 1.0e-3); auto val = details::random_entry(_data); EXPECT_GE(val, 1.0); EXPECT_LE(val, 11.0); } _obj.stop(); ASSERT_TRUE(_obj.get<wall_clock>() != nullptr); ASSERT_TRUE(_obj.get<cpu_clock>() != nullptr); ASSERT_TRUE(_obj.get<check_type>() != nullptr); EXPECT_NEAR(_obj.get<wall_clock>()->get(), 0.0, 1.0e-6); EXPECT_NEAR(_obj.get<cpu_clock>()->get(), 0.0, 1.0e-6); #if defined(TIMEMORY_UNIX) EXPECT_GT(_obj.get<check_type>()->get(), 0); #elif defined(TIMEMORY_WINDOWS) EXPECT_GT(std::get<0>(_obj.get<check_type>()->get()), 0); EXPECT_GT(std::get<1>(_obj.get<check_type>()->get()), 0); EXPECT_NEAR(std::get<0>(_obj.get<read_bytes>()->get()), std::get<0>(_obj.get<written_bytes>()->get()), 1.0e-3); #endif trait::runtime_enabled<test_t>::set(incoming); } //--------------------------------------------------------------------------------------// TEST_F(api_tests, os) { trait::apply<trait::runtime_enabled>::set<os::supports_unix, os::supports_windows, cpu_clock>(false); os_bundle_t _obj(details::get_test_name()); _obj.start(); details::consume(1000); _obj.stop(); EXPECT_NEAR(_obj.get<wall_clock>()->get(), 1.0, 0.1); EXPECT_NEAR(_obj.get<cpu_clock>()->get(), 0.0, 1.0e-6); trait::apply<trait::runtime_enabled>::set<os::supports_unix, os::supports_windows, cpu_clock>(true); } //--------------------------------------------------------------------------------------//
10,440
3,595
/* * Copyright (c) 2008, Willow Garage, Inc. * 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 Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <QtGlobal> #include <QTimer> #include "rviz/ogre_helpers/qt_ogre_render_window.h" #include "rviz/ogre_helpers/initialization.h" #include "rviz/image/ros_image_texture.h" #include "ros/ros.h" #include <ros/package.h> #include <OgreRoot.h> #include <OgreRenderWindow.h> #include <OgreSceneManager.h> #include <OgreViewport.h> #include <OgreRectangle2D.h> #include <OgreMaterial.h> #include <OgreMaterialManager.h> #include <OgreTextureUnitState.h> #include <OgreSharedPtr.h> #include <OgreTechnique.h> #include <OgreSceneNode.h> #include "image_view.h" using namespace rviz; ImageView::ImageView( QWidget* parent ) : QtOgreRenderWindow( parent ) , texture_it_(nh_) { setAutoRender(false); scene_manager_ = ogre_root_->createSceneManager( Ogre::ST_GENERIC, "TestSceneManager" ); } ImageView::~ImageView() { delete texture_; } void ImageView::showEvent( QShowEvent* event ) { QtOgreRenderWindow::showEvent( event ); V_string paths; paths.push_back(ros::package::getPath(ROS_PACKAGE_NAME) + "/ogre_media/textures"); initializeResources(paths); setCamera( scene_manager_->createCamera( "Camera" )); std::string resolved_image = nh_.resolveName("image"); if( resolved_image == "/image" ) { ROS_WARN("image topic has not been remapped"); } std::stringstream title; title << "rviz Image Viewer [" << resolved_image << "]"; setWindowTitle( QString::fromStdString( title.str() )); texture_ = new ROSImageTexture(); try { texture_->clear(); texture_sub_.reset(new image_transport::SubscriberFilter()); texture_sub_->subscribe(texture_it_, "image", 1, image_transport::TransportHints("raw")); texture_sub_->registerCallback(boost::bind(&ImageView::textureCallback, this, _1)); } catch (ros::Exception& e) { ROS_ERROR("%s", (std::string("Error subscribing: ") + e.what()).c_str()); } Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create( "Material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME ); material->setCullingMode(Ogre::CULL_NONE); material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(true); material->getTechnique(0)->setLightingEnabled(false); Ogre::TextureUnitState* tu = material->getTechnique(0)->getPass(0)->createTextureUnitState(); tu->setTextureName(texture_->getTexture()->getName()); tu->setTextureFiltering( Ogre::TFO_NONE ); Ogre::Rectangle2D* rect = new Ogre::Rectangle2D(true); rect->setCorners(-1.0f, 1.0f, 1.0f, -1.0f); rect->setMaterial(material->getName()); rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_OVERLAY - 1); Ogre::AxisAlignedBox aabb; aabb.setInfinite(); rect->setBoundingBox(aabb); Ogre::SceneNode* node = scene_manager_->getRootSceneNode()->createChildSceneNode(); node->attachObject(rect); node->setVisible(true); QTimer* timer = new QTimer( this ); connect( timer, SIGNAL( timeout() ), this, SLOT( onTimer() )); timer->start( 33 ); } void ImageView::onTimer() { ros::spinOnce(); static bool first = true; try { if( texture_->update() ) { if( first ) { first = false; resize( texture_->getWidth(), texture_->getHeight() ); } } ogre_root_->renderOneFrame(); } catch( UnsupportedImageEncoding& e ) { ROS_ERROR("%s", e.what()); } if( !nh_.ok() ) { close(); } } void ImageView::textureCallback(const sensor_msgs::Image::ConstPtr& msg) { if (texture_) { texture_->addMessage(msg); } }
5,146
1,823
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/gpdb/model/DescribeSlowLogRecordsRequest.h> using AlibabaCloud::Gpdb::Model::DescribeSlowLogRecordsRequest; DescribeSlowLogRecordsRequest::DescribeSlowLogRecordsRequest() : RpcServiceRequest("gpdb", "2016-05-03", "DescribeSlowLogRecords") { setMethod(HttpRequest::Method::Post); } DescribeSlowLogRecordsRequest::~DescribeSlowLogRecordsRequest() {} std::string DescribeSlowLogRecordsRequest::getStartTime()const { return startTime_; } void DescribeSlowLogRecordsRequest::setStartTime(const std::string& startTime) { startTime_ = startTime; setParameter("StartTime", startTime); } int DescribeSlowLogRecordsRequest::getPageNumber()const { return pageNumber_; } void DescribeSlowLogRecordsRequest::setPageNumber(int pageNumber) { pageNumber_ = pageNumber; setParameter("PageNumber", std::to_string(pageNumber)); } std::string DescribeSlowLogRecordsRequest::getAccessKeyId()const { return accessKeyId_; } void DescribeSlowLogRecordsRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } int DescribeSlowLogRecordsRequest::getPageSize()const { return pageSize_; } void DescribeSlowLogRecordsRequest::setPageSize(int pageSize) { pageSize_ = pageSize; setParameter("PageSize", std::to_string(pageSize)); } std::string DescribeSlowLogRecordsRequest::getDBInstanceId()const { return dBInstanceId_; } void DescribeSlowLogRecordsRequest::setDBInstanceId(const std::string& dBInstanceId) { dBInstanceId_ = dBInstanceId; setParameter("DBInstanceId", dBInstanceId); } long DescribeSlowLogRecordsRequest::getSQLId()const { return sQLId_; } void DescribeSlowLogRecordsRequest::setSQLId(long sQLId) { sQLId_ = sQLId; setParameter("SQLId", std::to_string(sQLId)); } std::string DescribeSlowLogRecordsRequest::getEndTime()const { return endTime_; } void DescribeSlowLogRecordsRequest::setEndTime(const std::string& endTime) { endTime_ = endTime; setParameter("EndTime", endTime); } std::string DescribeSlowLogRecordsRequest::getDBName()const { return dBName_; } void DescribeSlowLogRecordsRequest::setDBName(const std::string& dBName) { dBName_ = dBName; setParameter("DBName", dBName); }
2,932
1,011
/* * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include "b2DistanceJoint.h" #include "../b2Body.h" #include "../b2World.h" // C = norm(p2 - p1) - L // u = (p2 - p1) / norm(p2 - p1) // Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) // J = [-u -cross(r1, u) u cross(r2, u)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) : b2Joint(def) { m_localAnchor1 = b2MulT(m_body1->m_R, def->anchorPoint1 - m_body1->m_position); m_localAnchor2 = b2MulT(m_body2->m_R, def->anchorPoint2 - m_body2->m_position); b2Vec2 d = def->anchorPoint2 - def->anchorPoint1; m_length = d.Length(); m_impulse = 0.0f; } void b2DistanceJoint::InitVelocityConstraints() { // Compute the effective mass matrix. b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1); b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2); m_u = m_body2->m_position + r2 - m_body1->m_position - r1; // Handle singularity. float32 length = m_u.Length(); if (length > b2_linearSlop) { m_u *= 1.0f / length; } else { m_u.Set(0.0f, 0.0f); } float32 cr1u = b2Cross(r1, m_u); float32 cr2u = b2Cross(r2, m_u); m_mass = m_body1->m_invMass + m_body1->m_invI * cr1u * cr1u + m_body2->m_invMass + m_body2->m_invI * cr2u * cr2u; b2Assert(m_mass > FLT_EPSILON); m_mass = 1.0f / m_mass; if (b2World::s_enableWarmStarting) { b2Vec2 P = m_impulse * m_u; m_body1->m_linearVelocity -= m_body1->m_invMass * P; m_body1->m_angularVelocity -= m_body1->m_invI * b2Cross(r1, P); m_body2->m_linearVelocity += m_body2->m_invMass * P; m_body2->m_angularVelocity += m_body2->m_invI * b2Cross(r2, P); } else { m_impulse = 0.0f; } } void b2DistanceJoint::SolveVelocityConstraints(const b2TimeStep& step) { NOT_USED(step); b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1); b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2); // Cdot = dot(u, v + cross(w, r)) b2Vec2 v1 = m_body1->m_linearVelocity + b2Cross(m_body1->m_angularVelocity, r1); b2Vec2 v2 = m_body2->m_linearVelocity + b2Cross(m_body2->m_angularVelocity, r2); float32 Cdot = b2Dot(m_u, v2 - v1); float32 impulse = -m_mass * Cdot; m_impulse += impulse; b2Vec2 P = impulse * m_u; m_body1->m_linearVelocity -= m_body1->m_invMass * P; m_body1->m_angularVelocity -= m_body1->m_invI * b2Cross(r1, P); m_body2->m_linearVelocity += m_body2->m_invMass * P; m_body2->m_angularVelocity += m_body2->m_invI * b2Cross(r2, P); } bool b2DistanceJoint::SolvePositionConstraints() { b2Vec2 r1 = b2Mul(m_body1->m_R, m_localAnchor1); b2Vec2 r2 = b2Mul(m_body2->m_R, m_localAnchor2); b2Vec2 d = m_body2->m_position + r2 - m_body1->m_position - r1; float32 length = d.Normalize(); float32 C = length - m_length; C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); float32 impulse = -m_mass * C; m_u = d; b2Vec2 P = impulse * m_u; m_body1->m_position -= m_body1->m_invMass * P; m_body1->m_rotation -= m_body1->m_invI * b2Cross(r1, P); m_body2->m_position += m_body2->m_invMass * P; m_body2->m_rotation += m_body2->m_invI * b2Cross(r2, P); m_body1->m_R.Set(m_body1->m_rotation); m_body2->m_R.Set(m_body2->m_rotation); return b2Abs(C) < b2_linearSlop; } b2Vec2 b2DistanceJoint::GetAnchor1() const { return m_body1->m_position + b2Mul(m_body1->m_R, m_localAnchor1); } b2Vec2 b2DistanceJoint::GetAnchor2() const { return m_body2->m_position + b2Mul(m_body2->m_R, m_localAnchor2); } b2Vec2 b2DistanceJoint::GetReactionForce(float32 invTimeStep) const { b2Vec2 F = (m_impulse * invTimeStep) * m_u; return F; } float32 b2DistanceJoint::GetReactionTorque(float32 invTimeStep) const { NOT_USED(invTimeStep); return 0.0f; }
4,544
2,082
#include "routing-algos/alg/nth-element.h" #include <algorithm> #include <vector> #include "absl/strings/substitute.h" #include "absl/types/span.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace routing_algos { namespace { std::vector<int64_t> RoutingAlgosNth(const std::vector<int64_t>& arg, int n) { std::vector<int64_t> result = arg; routing_algos::NthElement(result.begin(), result.begin() + n, result.end()); return result; } std::vector<int64_t> StdNth(const std::vector<int64_t>& arg, int n) { std::vector<int64_t> result = arg; std::nth_element(result.begin(), result.begin() + n, result.end()); return result; } class NthElementExhaustiveTest : public testing::TestWithParam<std::vector<int64_t>> {}; TEST_P(NthElementExhaustiveTest, MatchesStd) { for (int i = 0; i < GetParam().size(); i++) { SCOPED_TRACE(absl::Substitute("i = $0", i)); auto result_routing_algos = RoutingAlgosNth(GetParam(), i); auto result_std = StdNth(GetParam(), i); EXPECT_THAT(result_routing_algos[i], testing::Eq(result_std[i])); EXPECT_THAT(absl::MakeSpan(result_routing_algos).subspan(0, i), testing::Each(testing::Le(result_routing_algos[i]))); } } struct SampledTest { std::vector<int64_t> data; std::vector<int> ns; }; class NthElementSampledTest : public testing::TestWithParam<SampledTest> {}; TEST_P(NthElementSampledTest, MatchesStd) { for (int i : GetParam().ns) { auto result_routing_algos = RoutingAlgosNth(GetParam().data, i); auto result_std = StdNth(GetParam().data, i); EXPECT_THAT(result_routing_algos[i], testing::Eq(result_std[i])); EXPECT_THAT(absl::MakeSpan(result_routing_algos).subspan(0, i), testing::Each(testing::Le(result_routing_algos[i]))); } } std::vector<int64_t> RandomData(int n) { std::vector<int64_t> data(n, 0); for (int i = 0; i < n; i++) { data[i] = rand() % 55; } return data; } std::vector<int64_t> RepeatN(int n, int64_t v) { return std::vector<int64_t>(n, v); } INSTANTIATE_TEST_SUITE_P(Sampled, NthElementExhaustiveTest, testing::Values(RandomData(1), RandomData(10), RandomData(111), RandomData(301), RepeatN(257, 0), RepeatN(30, 4981))); INSTANTIATE_TEST_SUITE_P(Sampled, NthElementSampledTest, testing::Values( SampledTest{ RandomData(5000), {0, 1, 555, 1123, 4999}, }, SampledTest{ RandomData(51003), {0, 1, 555, 3, 49945}, }, SampledTest{ RepeatN(5000, 4), {0, 1, 555, 1123, 4999}, })); } // namespace } // namespace routing_algos
3,009
1,110
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/comprehendmedical/model/UnmappedAttribute.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ComprehendMedical { namespace Model { UnmappedAttribute::UnmappedAttribute() : m_type(EntityType::NOT_SET), m_typeHasBeenSet(false), m_attributeHasBeenSet(false) { } UnmappedAttribute::UnmappedAttribute(JsonView jsonValue) : m_type(EntityType::NOT_SET), m_typeHasBeenSet(false), m_attributeHasBeenSet(false) { *this = jsonValue; } UnmappedAttribute& UnmappedAttribute::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Type")) { m_type = EntityTypeMapper::GetEntityTypeForName(jsonValue.GetString("Type")); m_typeHasBeenSet = true; } if(jsonValue.ValueExists("Attribute")) { m_attribute = jsonValue.GetObject("Attribute"); m_attributeHasBeenSet = true; } return *this; } JsonValue UnmappedAttribute::Jsonize() const { JsonValue payload; if(m_typeHasBeenSet) { payload.WithString("Type", EntityTypeMapper::GetNameForEntityType(m_type)); } if(m_attributeHasBeenSet) { payload.WithObject("Attribute", m_attribute.Jsonize()); } return payload; } } // namespace Model } // namespace ComprehendMedical } // namespace Aws
1,454
518
/* * Copyright 1993-2019 NVIDIA Corporation. All rights reserved. * * NOTICE TO LICENSEE: * * This source code and/or documentation ("Licensed Deliverables") are * subject to NVIDIA intellectual property rights under U.S. and * international Copyright laws. * * These Licensed Deliverables contained herein is PROPRIETARY and * CONFIDENTIAL to NVIDIA and is being provided under the terms and * conditions of a form of NVIDIA software license agreement by and * between NVIDIA and Licensee ("License Agreement") or electronically * accepted by Licensee. Notwithstanding any terms or conditions to * the contrary in the License Agreement, reproduction or disclosure * of the Licensed Deliverables to any third party without the express * written consent of NVIDIA is prohibited. * * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE * LICENSE AGREEMENT, NVIDIA MAKES NO REPRESENTATION ABOUT THE * SUITABILITY OF THESE LICENSED DELIVERABLES FOR ANY PURPOSE. IT IS * PROVIDED "AS IS" WITHOUT EXPRESS OR IMPLIED WARRANTY OF ANY KIND. * NVIDIA DISCLAIMS ALL WARRANTIES WITH REGARD TO THESE LICENSED * DELIVERABLES, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY, * NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. * NOTWITHSTANDING ANY TERMS OR CONDITIONS TO THE CONTRARY IN THE * LICENSE AGREEMENT, IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY * SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, OR ANY * DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE * OF THESE LICENSED DELIVERABLES. * * U.S. Government End Users. These Licensed Deliverables are a * "commercial item" as that term is defined at 48 C.F.R. 2.101 (OCT * 1995), consisting of "commercial computer software" and "commercial * computer software documentation" as such terms are used in 48 * C.F.R. 12.212 (SEPT 1995) and is provided to the U.S. Government * only as a commercial end item. Consistent with 48 C.F.R.12.212 and * 48 C.F.R. 227.7202-1 through 227.7202-4 (JUNE 1995), all * U.S. Government End Users acquire the Licensed Deliverables with * only those rights set forth herein. * * Any use of the Licensed Deliverables in individual and commercial * software must include, in the user documentation and internal * comments to the code, the above Disclaimer and U.S. Government End * Users Notice. */ #include <cassert> #include <cstring> #include <cuda_runtime_api.h> #include <cudnn.h> #include <cublas_v2.h> #include <iostream> #include <stdexcept> #include <array> #include "NvInfer.h" #include "FullyConnected.h" #define CHECK(status) { if (status != 0) throw std::runtime_error(__FILE__ + __LINE__ + std::string{"CUDA Error: "} + std::to_string(status)); } namespace { constexpr const char* FC_PLUGIN_VERSION{"1"}; constexpr const char* FC_PLUGIN_NAME{"FCPlugin"}; // Helpers to move data to/from the GPU. nvinfer1::Weights copyToDevice(const void* hostData, int count) { void* deviceData; CHECK(cudaMalloc(&deviceData, count * sizeof(float))); CHECK(cudaMemcpy(deviceData, hostData, count * sizeof(float), cudaMemcpyHostToDevice)); return nvinfer1::Weights{nvinfer1::DataType::kFLOAT, deviceData, count}; } nvinfer1::Weights makeDeviceCopy(nvinfer1::Weights deviceWeights) { void* deviceData; CHECK(cudaMalloc(&deviceData, deviceWeights.count * sizeof(float))); CHECK(cudaMemcpy(deviceData, deviceWeights.values, deviceWeights.count * sizeof(float), cudaMemcpyDeviceToDevice)); return nvinfer1::Weights{nvinfer1::DataType::kFLOAT, deviceData, deviceWeights.count}; } int copyFromDevice(char* hostBuffer, nvinfer1::Weights deviceWeights) { *reinterpret_cast<int*>(hostBuffer) = deviceWeights.count; CHECK(cudaMemcpy(hostBuffer + sizeof(int), deviceWeights.values, deviceWeights.count * sizeof(float), cudaMemcpyDeviceToHost)); return sizeof(int) + deviceWeights.count * sizeof(float); } } nvinfer1::PluginFieldCollection FCPluginCreator::mFC{}; std::vector<nvinfer1::PluginField> FCPluginCreator::mPluginAttributes; REGISTER_TENSORRT_PLUGIN(FCPluginCreator); // In this simple case we're going to infer the number of output channels from the bias weights. // The knowledge that the kernel weights are weights[0] and the bias weights are weights[1] was // divined from the caffe innards FCPlugin::FCPlugin(const nvinfer1::Weights* weights, int nbWeights) { assert(nbWeights == 2); mKernelWeights = copyToDevice(weights[0].values, weights[0].count); mBiasWeights = copyToDevice(weights[1].values, weights[1].count); } // Copy from existing device weights FCPlugin::FCPlugin(const nvinfer1::Weights& deviceKernel, const nvinfer1::Weights& deviceBias) { mKernelWeights = makeDeviceCopy(deviceKernel); mBiasWeights = makeDeviceCopy(deviceBias); } // Create the plugin at runtime from a byte stream. FCPlugin::FCPlugin(const void* data, size_t length) { const char* d = reinterpret_cast<const char*>(data); const char* check = d; // Deserialize kernel. const int kernelCount = reinterpret_cast<const int*>(d)[0]; mKernelWeights = copyToDevice(d + sizeof(int), kernelCount); d += sizeof(int) + mKernelWeights.count * sizeof(float); // Deserialize bias. const int biasCount = reinterpret_cast<const int*>(d)[0]; mBiasWeights = copyToDevice(d + sizeof(int), biasCount); d += sizeof(int) + mBiasWeights.count * sizeof(float); // Check that the sizes are what we expected. assert(d == check + length); } // Free buffers. FCPlugin::~FCPlugin() { cudaFree(const_cast<void*>(mKernelWeights.values)); mKernelWeights.values = nullptr; cudaFree(const_cast<void*>(mBiasWeights.values)); mBiasWeights.values = nullptr; } int FCPlugin::getNbOutputs() const { return 1; } nvinfer1::Dims FCPlugin::getOutputDimensions(int index, const nvinfer1::Dims* inputs, int nbInputDims) { assert(index == 0 && nbInputDims == 1 && inputs[0].nbDims == 3); return nvinfer1::DimsCHW{static_cast<int>(mBiasWeights.count), 1, 1}; } int FCPlugin::initialize() { CHECK(cudnnCreate(&mCudnn)); CHECK(cublasCreate(&mCublas)); // Create cudnn tensor descriptors for bias addition. CHECK(cudnnCreateTensorDescriptor(&mSrcDescriptor)); CHECK(cudnnCreateTensorDescriptor(&mDstDescriptor)); return 0; } void FCPlugin::terminate() { CHECK(cudnnDestroyTensorDescriptor(mSrcDescriptor)); CHECK(cudnnDestroyTensorDescriptor(mDstDescriptor)); CHECK(cublasDestroy(mCublas)); CHECK(cudnnDestroy(mCudnn)); } // This plugin requires no workspace memory during build time. size_t FCPlugin::getWorkspaceSize(int maxBatchSize) const { return 0; } int FCPlugin::enqueue(int batchSize, const void* const* inputs, void** outputs, void* workspace, cudaStream_t stream) { int nbOutputChannels = mBiasWeights.count; int nbInputChannels = mKernelWeights.count / nbOutputChannels; constexpr float kONE = 1.0f, kZERO = 0.0f; // Do matrix multiplication. cublasSetStream(mCublas, stream); cudnnSetStream(mCudnn, stream); CHECK(cublasSgemm(mCublas, CUBLAS_OP_T, CUBLAS_OP_N, nbOutputChannels, batchSize, nbInputChannels, &kONE, reinterpret_cast<const float*>(mKernelWeights.values), nbInputChannels, reinterpret_cast<const float*>(inputs[0]), nbInputChannels, &kZERO, reinterpret_cast<float*>(outputs[0]), nbOutputChannels)); // Add bias. CHECK(cudnnSetTensor4dDescriptor(mSrcDescriptor, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, 1, nbOutputChannels, 1, 1)); CHECK(cudnnSetTensor4dDescriptor(mDstDescriptor, CUDNN_TENSOR_NCHW, CUDNN_DATA_FLOAT, batchSize, nbOutputChannels, 1, 1)); CHECK(cudnnAddTensor(mCudnn, &kONE, mSrcDescriptor, mBiasWeights.values, &kONE, mDstDescriptor, outputs[0])); return 0; } size_t FCPlugin::getSerializationSize() const { return sizeof(int) * 2 + mKernelWeights.count * sizeof(float) + mBiasWeights.count * sizeof(float); } void FCPlugin::serialize(void* buffer) const { char* d = reinterpret_cast<char*>(buffer); const char* check = d; d += copyFromDevice(d, mKernelWeights); d += copyFromDevice(d, mBiasWeights); assert(d == check + getSerializationSize()); } // For this sample, we'll only support float32 with NCHW. bool FCPlugin::supportsFormat(nvinfer1::DataType type, nvinfer1::PluginFormat format) const { return (type == nvinfer1::DataType::kFLOAT && format == nvinfer1::PluginFormat::kNCHW); } const char* FCPlugin::getPluginType() const { return FC_PLUGIN_NAME; } const char* FCPlugin::getPluginVersion() const { return FC_PLUGIN_VERSION; } void FCPlugin::destroy() { delete this; } IPluginV2Ext* FCPlugin::clone() const { IPluginV2Ext* plugin = new FCPlugin(mKernelWeights, mBiasWeights); plugin->setPluginNamespace(mPluginNamespace.c_str()); return plugin; } void FCPlugin::setPluginNamespace(const char* pluginNamespace) { mPluginNamespace = pluginNamespace; } const char* FCPlugin::getPluginNamespace() const { return mPluginNamespace.c_str(); } DataType FCPlugin::getOutputDataType(int index, const nvinfer1::DataType* inputTypes, int nbInputs) const { return DataType::kFLOAT; } bool FCPlugin::isOutputBroadcastAcrossBatch(int outputIndex, const bool* inputIsBroadcasted, int nbInputs) const { return false; } bool FCPlugin::canBroadcastInputAcrossBatch(int inputIndex) const { return false; } void FCPlugin::configurePlugin(const Dims* inputDims, int nbInputs, const Dims* outputDims, int nbOutputs, const DataType* inputTypes, const DataType* outputTypes, const bool* inputIsBroadcast, const bool* outputIsBroadcast, PluginFormat floatFormat, int maxBatchSize) { assert(nbInputs == 1 && inputDims[0].d[1] == 1 && inputDims[0].d[2] == 1); assert(nbOutputs == 1 && outputDims[0].d[1] == 1 && outputDims[0].d[2] == 1); assert(mKernelWeights.count == inputDims[0].d[0] * inputDims[0].d[1] * inputDims[0].d[2] * mBiasWeights.count); } void FCPlugin::attachToContext(cudnnContext* cudnnContext, cublasContext* cublasContext, IGpuAllocator* gpuAllocator) { } void FCPlugin::detachFromContext() {} // // Plugin Creator // FCPluginCreator::FCPluginCreator() { mFC.nbFields = mPluginAttributes.size(); mFC.fields = mPluginAttributes.data(); } void FCPluginCreator::setPluginNamespace(const char* libNamespace) { mNamespace = libNamespace; } const char* FCPluginCreator::getPluginNamespace() const { return mNamespace.c_str(); } const char* FCPluginCreator::getPluginName() const { return FC_PLUGIN_NAME; } const char* FCPluginCreator::getPluginVersion() const { return FC_PLUGIN_VERSION; } const PluginFieldCollection* FCPluginCreator::getFieldNames() { return &mFC; } IPluginV2Ext* FCPluginCreator::createPlugin(const char* name, const PluginFieldCollection* fc) { std::array<Weights, 2> weights{}; for (int i = 0; i < fc->nbFields; ++i) { std::string fieldName(fc->fields[i].name); if (fieldName.compare("kernel") == 0) { weights[0].values = fc->fields[i].data; weights[0].count = fc->fields[i].length; weights[0].type = nvinfer1::DataType::kFLOAT; } if (fieldName.compare("bias") == 0) { weights[1].values = fc->fields[i].data; weights[1].count = fc->fields[i].length; weights[1].type = nvinfer1::DataType::kFLOAT; } } return new FCPlugin(static_cast<void*>(weights.data()), weights.size()); } IPluginV2Ext* FCPluginCreator::deserializePlugin(const char* name, const void* serialData, size_t serialLength) { auto* plugin = new FCPlugin(serialData, serialLength); plugin->setPluginNamespace(mNamespace.c_str()); return plugin; }
11,800
4,209
#include <iostream> using namespace std; int main(void) { int k, n, time = 210, ans, t; char z; bool check = false; cin >> k >> n; for (int i = 0; i < n; i++) { cin >> t >> z; if (time - t <= 0 && !check) { ans = k; check = true; } else { time -= t; if (z == 'T') k = (k + 1) > 8 ? 1 : (k + 1); } } cout << ans; }
352
193
#include <iostream> #include "code/utilities/web/chrome/version/chrome_version_getter.hpp" int main(){ auto version = Chrome_Version_Getter::Get_Version(); std::cout << version << std::endl; }
202
66
// Copyright (c) 2011 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 "ui/gfx/surface/accelerated_surface_wayland.h" #include <wayland-egl.h> #include "third_party/angle/include/EGL/egl.h" #include "third_party/angle/include/EGL/eglext.h" #include "ui/gfx/gl/gl_bindings.h" #include "ui/gfx/gl/gl_surface_egl.h" #include "ui/wayland/wayland_display.h" AcceleratedSurface::AcceleratedSurface(const gfx::Size& size) : size_(size), image_(NULL), pixmap_(NULL), texture_(0) { EGLDisplay edpy = gfx::GLSurfaceEGL::GetHardwareDisplay(); pixmap_ = wl_egl_pixmap_create(size_.width(), size_.height(), 0); image_ = eglCreateImageKHR( edpy, EGL_NO_CONTEXT, EGL_NATIVE_PIXMAP_KHR, (void*) pixmap_, NULL); glGenTextures(1, &texture_); GLint current_texture = 0; glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture); glBindTexture(GL_TEXTURE_2D, texture_); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image_); glBindTexture(GL_TEXTURE_2D, current_texture); } AcceleratedSurface::~AcceleratedSurface() { glDeleteTextures(1, &texture_); eglDestroyImageKHR(gfx::GLSurfaceEGL::GetHardwareDisplay(), image_); wl_egl_pixmap_destroy(pixmap_); }
1,642
675
// Copyright 2017 The Fuchsia 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 "garnet/bin/ktrace_provider/reader.h" #include <lib/zircon-internal/ktrace.h> namespace ktrace_provider { Reader::Reader(const char* buffer, size_t buffer_size) : current_(buffer), marker_(buffer), end_(buffer + buffer_size) {} const ktrace_header_t* Reader::ReadNextRecord() { if (AvailableBytes() < sizeof(ktrace_header_t)) { ReadMoreData(); } if (AvailableBytes() < sizeof(ktrace_header_t)) { FX_VLOGS(10) << "No more records"; return nullptr; } auto record = reinterpret_cast<const ktrace_header_t*>(current_); if (AvailableBytes() < KTRACE_LEN(record->tag)) { ReadMoreData(); } if (AvailableBytes() < KTRACE_LEN(record->tag)) { FX_VLOGS(10) << "No more records, incomplete last record"; return nullptr; } record = reinterpret_cast<const ktrace_header_t*>(current_); current_ += KTRACE_LEN(record->tag); number_bytes_read_ += KTRACE_LEN(record->tag); number_records_read_ += 1; FX_VLOGS(10) << "Importing ktrace event 0x" << std::hex << KTRACE_EVENT(record->tag) << ", size " << std::dec << KTRACE_LEN(record->tag); return record; } } // namespace ktrace_provider
1,329
485
#include <config.h> #include <mwoibn/loaders/robot.h> #include <mwoibn/robot_class/robot_ros_nrt.h> #include <mwoibn/robot_class/robot_xbot_nrt.h> #include <mwoibn/visualization_tools/rviz_track_point.h> #include <mwoibn/point_handling/robot_points_handler.h> // std::vector<mwoibn::Vector3> // contactPoints(mwoibn::robot_class::Robot& robot, // mwoibn::point_handling::PositionsHandler& wheels) //{ // mwoibn::Vector3 ground, wheel, x, point; // std::vector<mwoibn::Vector3> points; // ground << 0, 0, 1; // flat ground // double R = 0.010, r = 0.068; // for (int i = 0; i < wheels.size(); i++) // { // points.push_back(point); // } // // std::cout << std::endl; // return points; //} class Flow { public: Flow(mwoibn::robot_class::Robot& robot, mwoibn::point_handling::PositionsHandler& wheels) : _robot(robot), _wheels(wheels), _contacts("ROOT", _robot) { _ground << 0, 0, 1; for (auto link : _robot.getLinks("wheels")) { _contacts.addPoint(link); _current.push_back(mwoibn::Vector3::Zero()); _spherical.push_back(mwoibn::Vector3::Zero()); _modelDiff.push_back(mwoibn::Vector3::Zero()); _equationDiff.push_back(mwoibn::Vector3::Zero()); _flowDiff.push_back(mwoibn::Vector3::Zero()); } _contacts.computeChain(); _contactPoints(); // init estimation _estimated = _current; _fromPosDiff = _current; _contacts.setFullStatesWorld( _current, robot.state.position.get()); } virtual ~Flow() { } void update() { std::vector<mwoibn::Vector3> _previous = _current; _contactPoints(); // update contact position _contacts.setFullStatesWorld( _current, _robot.state.position.get()); // update handler double test = ((_current[0] - _previous[0]).norm() + (_current[1] - _previous[1]).norm() + (_current[2] - _previous[2]).norm() + (_current[3] - _previous[3]).norm()); for (int i = 0; i < _wheels.size(); i++) _fromPosDiff[i] += (_current[i] - _previous[i]); _flowDerivatives(); // update flow derivative _flowEstimates(); // estimate current contact _sphericalPoints(); // compute spherical estimation _modelDerivatives(); // compute contact point derivative _equationDerivatives(); // compute from my equation nr++; if (test > mwoibn::EPS) { std::cout << "nr\t" << nr << "\n"; std::cout << "from position" << "\t"; for (int i = 0; i < _wheels.size(); i++) std::cout << (_current[i][0] - _previous[i][0]) / _robot.rate() / nr << "\t" << (_current[i][1] - _previous[i][1]) / _robot.rate() / nr << "\t" << (_current[i][2] - _previous[i][2]) / _robot.rate() / nr << "\t"; std::cout << std::endl; std::cout << "estimated" << "\t"; for (int i = 0; i < _wheels.size(); i++) std::cout << _estimated[i][0] << "\t" << _estimated[i][1] << "\t" << _estimated[i][2] << "\t"; std::cout << std::endl; std::cout << "point\t" << "\t"; for (int i = 0; i < _wheels.size(); i++) std::cout << _equationDiff[i][0] << "\t" << _equationDiff[i][1] << "\t" << _equationDiff[i][2] << "\t"; std::cout << std::endl; std::cout << "from positions" << "\t"; for (int i = 0; i < _wheels.size(); i++) std::cout << _current[i][0] << "\t" << _current[i][1] << "\t" << _current[i][2] << "\t"; std::cout << std::endl; std::cout << "models\t" << "\t"; for (int i = 0; i < _wheels.size(); i++) std::cout << _modelDiff[i][0] << "\t" << _modelDiff[i][1] << "\t" << _modelDiff[i][2] << "\t"; std::cout << std::endl; nr = 0; } } mwoibn::Vector3& getContact(int i) { return _current[i]; } mwoibn::Vector3& getEstimate(int i) { return _estimated[i]; } mwoibn::Vector3& getSpherical(int i) { return _spherical[i]; } mwoibn::Vector3& getModelDiff(int i) { return _modelDiff[i]; } mwoibn::Vector3& getEquationDiff(int i) { return _equationDiff[i]; } protected: double R = 0.010, r = 0.068; int nr = 0; mwoibn::robot_class::Robot& _robot; mwoibn::point_handling::PositionsHandler& _wheels; // wheels centers mwoibn::point_handling::PositionsHandler _contacts; // contact points std::vector<mwoibn::Vector3> _current, _estimated, _modelDiff, _equationDiff, _fromPosDiff, _flowDiff, _spherical; mwoibn::Vector3 _ground, _wheel_axis, _x; mwoibn::Matrix3 _skew(mwoibn::Vector3 vec) { mwoibn::Matrix3 skew; skew << 0, -vec[2], vec[1], vec[2], 0, -vec[0], -vec[1], vec[0], 0; // std::cout << skew << std::endl; return skew; } void _sphericalPoints() { for (int i = 0; i < _wheels.size(); i++) _sphericalPoint(i); } void _sphericalPoint(int i) { _spherical[i] = _robot.contacts().contact(i).getPosition().head(3); } void _contactPoints() { for (int i = 0; i < _wheels.size(); i++) _contactPoint(i); } void _modelDerivatives() { for (int i = 0; i < _wheels.size(); i++) _modelDerivative(i); } void _modelDerivative(int i) { mwoibn::Matrix jacobian = _contacts.point(i).getPositionJacobian(); _modelDiff[i] = jacobian * _robot.state.velocity.get(); // * //_robot.rate(); } void _contactPoint(int i) { _wheel_axis = _wheels.point(i).getRotationWorld().col(2); // z axis _x = _wheel_axis * _ground.transpose() * _wheel_axis; _x.normalize(); std::cout << "norm: " << _x.norm() << std::endl; _current[i] = _x * R - _ground * (r + R); _current[i] += _wheels.getPointStateWorld(i); } void _equationDerivatives() { for (int i = 0; i < _wheels.size(); i++) _equationDerivative(i); } void _equationDerivative(int i) { _wheel_axis = _wheels.point(i).getRotationWorld().col(2); // z axis mwoibn::Matrix jacobian = _wheels.point(i).getOrientationJacobian(); mwoibn::Matrix jacobian_pos = _wheels.point(i).getPositionJacobian(); mwoibn::Matrix3 temp = -_skew(_current[i] - _wheels.getPointStateWorld(i)); // temp = temp * R; // temp += _skew(_ground) * r; _equationDiff[i] = jacobian * _robot.state.velocity.get(); _equationDiff[i] = temp * _equationDiff[i]; _equationDiff[i] += jacobian_pos * _robot.state.velocity.get(); //_equationDiff[i] = _equationDiff[i] * _robot.rate(); } void _flowEstimates() { for (int i = 0; i < _wheels.size(); i++) _flowEstimate(i); } void _flowEstimate(int i) { _estimated[i] += _flowDiff[i] * _robot.rate(); } void _flowDerivatives() { for (int i = 0; i < _wheels.size(); i++) _flowDerivative(i); } void _flowDerivative(int i) { _wheel_axis = _wheels.point(i).getRotationWorld().col(2); // z axis mwoibn::Matrix jacobian = _wheels.point(i).getOrientationJacobian(); mwoibn::Matrix jacobian_pos = _wheels.point(i).getPositionJacobian(); mwoibn::Matrix3 temp = -_skew(_wheel_axis * _ground.transpose() * _wheel_axis); temp -= _wheel_axis * _ground.transpose() * _skew(_wheel_axis); // if (i == 0) // { // mwoibn::Matrix3 temp1 = // -_skew(_wheel_axis * _ground.transpose() * _wheel_axis); // mwoibn::Vector3 vec1 = // temp1 * jacobian * // _robot.state.velocity.get(); // std::cout << "1\t" << vec1[0] << "\t" << vec1[1] << "\t" << vec1[2] // << "\n"; // temp1 = -_wheel_axis * _ground.transpose() * _skew(_wheel_axis); // vec1 = temp1 * jacobian * // _robot.state.velocity.get(); // std::cout << "2\t" << vec1[0] << "\t" << vec1[1] << "\t" << vec1[2] // << "\n"; // } _flowDiff[i] = jacobian * _robot.state.velocity.get(); _flowDiff[i] = temp * _flowDiff[i]; _flowDiff[i] = _flowDiff[i] * R; _flowDiff[i] += jacobian_pos * _robot.state.velocity.get(); } }; int main(int argc, char** argv) { static const mwoibn::visualization_tools::Utils::TYPE tracker_type = mwoibn::visualization_tools::Utils::TYPE::POINT; ros::init(argc, argv, "contacts_test"); // initalize node needed for the service ros::NodeHandle n; ros::Publisher pub; std::string path = std::string(DRIVING_FRAMEWORK_WORKSPACE); mwoibn::loaders::Robot loader; mwoibn::robot_class::Robot& robot = loader.init( path + "DrivingFramework/locomotion_framework/configs/mwoibn_v2.yaml", "simulated"); mwoibn::point_handling::PositionsHandler wheels_ph("ROOT", robot, robot.getLinks("wheels")); mwoibn::visualization_tools::RvizTrackPoint track_current("rviz/current"); mwoibn::visualization_tools::RvizTrackPoint track_new("rviz/new"); mwoibn::visualization_tools::RvizTrackPoint track_estimated("rviz/estimated"); Flow flow(robot, wheels_ph); double edge = 0.001; for (int i = 0; i < robot.contacts().size(); i++) { // RED: current equation track_current.initMarker(tracker_type, "world", edge, edge, edge); // GREEN: new equation track_new.initMarker(tracker_type, "world", edge, edge, edge); // BLUE: estimated new track_estimated.initMarker(tracker_type, "world", edge, edge, edge); } for (int i = 0; i < robot.contacts().size(); i++) { track_current.setColor(i, 1, 0, 0); track_new.setColor(i, 0, 1, 0); track_estimated.setColor(i, 1, 1, 0); } std::cout.precision(10); std::cout << std::fixed; // std::cout // << "1_new[x]\t1_new[y]\t1_new[z]\t1_simp[x]\t1_simp[y]\t1_simp[z]\t"; // std::cout // << "1_mdt[x]\t1_mdt[y]\t1_mdt[z]\t1_edt[x]\t1_edt[y]\t1_edt[z]\t"; // std::cout // << "2_new[x]\t2_new[y]\t2_new[z]\t2_simp[x]\t2_simp[y]\t2_simp[z]\t"; // std::cout // << "2_mdt[x]\t2_mdt[y]\t2_mdt[z]\t2_edt[x]\t2_edt[y]\t2_edt[z]\t"; // std::cout // << "3_new[x]\t3_new[y]\t3_new[z]\t3_simp[x]\t3_simp[y]\t3_simp[z]\t"; // std::cout // << "3_mdt[x]\t3_mdt[y]\t3_mdt[z]\t3_edt[x]\t3_edt[y]\t3_edt[z]\t"; // std::cout // << "4_new[x]\t4_new[y]\t4_new[z]\t4_simp[x]\t4_simp[y]\t4_simp[z]\t"; // std::cout // << "4_mdt[x]\t4_mdt[y]\t4_mdt[z]\t4_edt[x]\t4_edt[y]\t4_edt[z]\n"; int i = 0; while (ros::ok()) { // std::vector<mwoibn::Vector3> new_contacts = contactPoints(robot, // wheels_ph); for (int i = 0; i < wheels_ph.size(); i++) { track_current.updateMarker(i, flow.getSpherical(i)); track_new.updateMarker(i, flow.getContact(i)); track_estimated.updateMarker(i, flow.getEstimate(i)); // std::cout << flow.getContact(i)[0] << "\t" << // flow.getContact(i)[1] // << "\t" << flow.getContact(i)[2] << "\t"; // std::cout << flow.getEstimate(i)[0] << "\t" << // flow.getEstimate(i)[1] // << "\t" << flow.getEstimate(i)[2] << "\t"; // std::cout << flow.getModelDiff(i)[0] << "\t" << // flow.getModelDiff(i)[1] // << "\t" << flow.getModelDiff(i)[2] << "\t"; // std::cout << flow.getEquationDiff(i)[0] << "\t" << // flow.getEquationDiff(i)[1] // << "\t" << flow.getEquationDiff(i)[2] << "\t"; } std::cout << std::endl; flow.update(); track_estimated.publish(); track_current.publish(); track_new.publish(); robot.update(); } }
13,537
4,766
#include "IntroState.hpp" #include "MainState.hpp" template<> IntroState* Ogre::Singleton<IntroState>::msSingleton = 0; IntroState::IntroState(): _physicsMgr(NULL), _mapMgr(NULL), _overlayMgr(NULL), _cameraMgr(NULL), _shootMgr(NULL), _collisionMgr(NULL), _characterMgr(NULL) {} void IntroState::enter () { if (_root == NULL) { _root = Ogre::Root::getSingletonPtr(); } if (_sceneMgr == NULL) { _sceneMgr = _root->getSceneManager("SceneManager"); } if (_camera == NULL) { _camera = _sceneMgr->createCamera("MainCamera"); } CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().hide(); _viewport = _root->getAutoCreatedWindow()->addViewport(_camera); _viewport->setBackgroundColour(Ogre::ColourValue(0.3, 0.8, 0.8)); // Creating and placing camera _camera->setPosition( Ogre::Vector3(0, 0, 10) ); _camera->lookAt( Ogre::Vector3(0, 0, 8) ); _camera->setNearClipDistance(0.001); _camera->setFarClipDistance(1000); _camera->setFOVy(Ogre::Degree(38)); double width = _viewport->getActualWidth(); double height = _viewport->getActualHeight(); _camera->setAspectRatio(width / height); _sceneMgr->setAmbientLight( Ogre::ColourValue(1, 1, 1) ); _sceneMgr->setShadowTechnique(Ogre::SHADOWTYPE_STENCIL_ADDITIVE); _sceneMgr->setShadowTextureCount(30); _sceneMgr->setShadowTextureSize(512); initializeManagers(); createGUI(); loadBackgroundImage(); _exitGame = false; } void IntroState::initializeManagers() { if (_physicsMgr == NULL) { _physicsMgr = new MyPhysicsManager( _sceneMgr ); } if (_mapMgr == NULL) { _mapMgr = new MapManager( _sceneMgr, MyPhysicsManager::getSingletonPtr()->getPhysicWorld() ); } if (_overlayMgr == NULL) { _overlayMgr = new MyOverlayManager(); } if (_cameraMgr == NULL) { _cameraMgr = new CameraManager( _sceneMgr ); } if (_shootMgr == NULL) { _shootMgr = new ShootManager( _sceneMgr ); } if (_collisionMgr == NULL) { _collisionMgr = new MyCollisionManager( _sceneMgr ); } if (_characterMgr == NULL) { _characterMgr = new CharacterManager( _sceneMgr ); } } void IntroState::exit() { _sceneMgr->clearScene(); _root->getAutoCreatedWindow()->removeAllViewports(); } void IntroState::pause () { CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().show(); Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->hide(); _intro->hide(); } void IntroState::resume () { CEGUI::System::getSingleton().getDefaultGUIContext().getMouseCursor().hide(); Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->show(); _intro->show(); } bool IntroState::frameStarted (const Ogre::FrameEvent& evt) { MapManager::getSingletonPtr()->update( evt.timeSinceLastFrame ); return true; } bool IntroState::frameEnded (const Ogre::FrameEvent& evt) { if (_exitGame) return false; return true; } void IntroState::keyPressed (const OIS::KeyEvent &e) { } void IntroState::keyReleased (const OIS::KeyEvent &e ) { if (e.key == OIS::KC_ESCAPE) { _exitGame = true; } else if (e.key == OIS::KC_SPACE) { pushState(MainState::getSingletonPtr()); } } void IntroState::mouseMoved (const OIS::MouseEvent &e) { CEGUI::System::getSingleton().getDefaultGUIContext().injectMousePosition(e.state.X.abs, e.state.Y.abs); } void IntroState::mousePressed (const OIS::MouseEvent &e, OIS::MouseButtonID id) { } void IntroState::mouseReleased (const OIS::MouseEvent &e, OIS::MouseButtonID id) { } IntroState* IntroState::getSingletonPtr () { return msSingleton; } IntroState& IntroState::getSingleton () { assert(msSingleton); return *msSingleton; } void IntroState::createGUI() { if(_intro == NULL) { _intro = CEGUI::WindowManager::getSingleton().loadLayoutFromFile("splash.layout"); CEGUI::System::getSingleton().getDefaultGUIContext().getRootWindow()->addChild(_intro); } else { _intro->show(); } Ogre::OverlayManager::getSingletonPtr()->getByName("SplashOverlay")->show(); } void IntroState::loadBackgroundImage() { // Randmonly select background std::string _all_backgrounds[3] {"oil.jpg", "cubism.jpg", "glass.jpg"}; unsigned seed = std::time(0); std::srand(seed); std::random_shuffle(&_all_backgrounds[0], &_all_backgrounds[sizeof(_all_backgrounds)/sizeof(*_all_backgrounds)]); Ogre::TexturePtr m_backgroundTexture = Ogre::TextureManager::getSingleton().createManual("BackgroundTexture",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, Ogre::TEX_TYPE_2D,640, 480, 0, Ogre::PF_BYTE_BGR,Ogre::TU_DYNAMIC_WRITE_ONLY_DISCARDABLE); Ogre::Image m_backgroundImage; m_backgroundImage.load(_all_backgrounds[0], Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); m_backgroundTexture->loadImage(m_backgroundImage); Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create("BackgroundMaterial", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); material->getTechnique(0)->getPass(0)->createTextureUnitState("BackgroundTexture"); material->getTechnique(0)->getPass(0)->setLightingEnabled(false); _rect = new Ogre::Rectangle2D(true); _rect->setCorners(-1.0, 1.0, 1.0, -1.0); _rect->setMaterial("BackgroundMaterial"); _rect->setRenderQueueGroup(Ogre::RENDER_QUEUE_BACKGROUND); _rect->setBoundingBox(Ogre::AxisAlignedBox(-100000.0*Ogre::Vector3::UNIT_SCALE, 100000.0*Ogre::Vector3::UNIT_SCALE)); _backgroundNode = _sceneMgr->getRootSceneNode()->createChildSceneNode("BackgroundMenu"); _backgroundNode->attachObject(_rect); MapManager::getSingletonPtr()->fadeIn(); }
5,840
2,206
#include "../../headers.h" /* * Something to remember here is that: * all these functions - take iterators as I/P's. * But iterators are more like pointers and they v * can be incremented or decremented */ int main() { string s = "accenllt"; string::iterator it = adjacent_find(s.begin()+2,s.end()); cout << "The result is: " << it - s.begin() << endl; return 0; }
391
133
#include "VBoxLayout.h" #include <QVBoxLayout> #include <QPoint> VBoxLayout::VBoxLayout() : VBoxLayout(nullptr) { } VBoxLayout::VBoxLayout(QWidget* parent) : QWidget(parent) { QVBoxLayout* layout = new QVBoxLayout(this); layout->setAlignment(Qt::AlignTop); layout->setSpacing(0); } void VBoxLayout::add(QWidget* widget) { widget->setParent(this); layout()->addWidget(widget); } void VBoxLayout::drop(QWidget* widget, QPoint pos) { QVBoxLayout* m_layout = static_cast<QVBoxLayout*>(layout()); pos.setX(width() / 2); if (QWidget* child = childAt(pos)) { if (child == widget) return; int idx = m_layout->indexOf(child); int const x = pos.x() - child->pos().x(); int const h = child->height() / 2; if (x > h) ++idx; m_layout->insertWidget(idx, widget); } else { m_layout->addWidget(widget); } widget->setParent(this); } void VBoxLayout::resizeEvent(QResizeEvent* event) { QWidget::resizeEvent(event); }
935
377
// VroemVroem - World #include "world.hpp" #include "noise.hpp" #include "objects/terrain.hpp" #include "objects/driver.hpp" #include "utils.hpp" #include "config.hpp" #include "timer.hpp" #include <map> #include <cmath> World::World(uint64_t seed, int width, int height) : seed(seed), width(width), height(height) { random = std::make_unique<Random>(seed); terrainMap = std::make_unique<uint8_t[]>(height * width); objectMap = std::make_unique<uint8_t[]>(height * width); FastNoiseLite heightNoise; heightNoise.SetNoiseType(FastNoiseLite::NoiseType_OpenSimplex2); heightNoise.SetSeed(seed); FastNoiseLite objectsNoise; objectsNoise.SetNoiseType(FastNoiseLite::NoiseType_OpenSimplex2); objectsNoise.SetSeed(seed + 1); // Generate terrain and natures for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { float h = heightNoise.GetNoise((float)x, (float)y); float o = objectsNoise.GetNoise((float)x, (float)y); if (h >= 0.9) { terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::SNOW1), static_cast<int>(Objects::Terrain::Type::SNOW2)); } else if (h >= 0.8) { if (o >= 0.2 && random->random(1, 6) == 1) { natures.push_back(std::make_unique<Objects::Nature>(natures.size(), Objects::Nature::Type::GOLD, x + 0.5, y + 0.5)); objectMap[y * width + x] = 1; } else if (o < 0.2 && random->random(1, 6) == 1) { natures.push_back(std::make_unique<Objects::Nature>(natures.size(), Objects::Nature::Type::STONE, x + 0.5, y + 0.5)); objectMap[y * width + x] = 1; } terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::STONE1), static_cast<int>(Objects::Terrain::Type::STONE2)); } else if (h >= 0.7) { terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::DIRT1), static_cast<int>(Objects::Terrain::Type::DIRT2)); } else if (h >= 0.1) { if (h >= 0.4 && o >= 0.3 && random->random(1, random->random(1, 2)) == 1) { if (random->random(1, 4) <= 3) { natures.push_back(std::make_unique<Objects::Nature>( natures.size(), static_cast<Objects::Nature::Type>(random->random(static_cast<int>(Objects::Nature::Type::BEECH), static_cast<int>(Objects::Nature::Type::FIR_SMALL))), x + 0.5, y + 0.5 )); } else { natures.push_back(std::make_unique<Objects::Nature>( natures.size(), static_cast<Objects::Nature::Type>(random->random(static_cast<int>(Objects::Nature::Type::TRUNK), static_cast<int>(Objects::Nature::Type::TRUNK_SMALL))), x + 0.5, y + 0.5 )); } objectMap[y * width + x] = 1; } else if (o < 0.4 && random->random(1, 15) == 1) { natures.push_back(std::make_unique<Objects::Nature>( natures.size(), static_cast<Objects::Nature::Type>(random->random(static_cast<int>(Objects::Nature::Type::BUSHES), static_cast<int>(Objects::Nature::Type::BERRIES))), x + 0.5, y + 0.5 )); objectMap[y * width + x] = 1; } terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::GRASS1), static_cast<int>(Objects::Terrain::Type::GRASS2)); } else if (h >= -0.1) { terrainMap[y * width + x] = random->random(static_cast<int>(Objects::Terrain::Type::SAND1), static_cast<int>(Objects::Terrain::Type::SAND2)); } else if (h >= -0.6) { terrainMap[y * width + x] = static_cast<int>(Objects::Terrain::Type::WATER); } else { terrainMap[y * width + x] = static_cast<int>(Objects::Terrain::Type::WATER_DEEP); } } } // Generate cities for (int i = 0; i < sqrt(height * width) / 3; i++) { int x; int y; do { x = random->random(0, width - 1); y = random->random(0, height - 1); } while (terrainMap[y * width + x] <= 2); cities.push_back(std::make_unique<Objects::City>(cities.size(), Objects::City::randomName(random.get()), x + 0.5, y + 0.5, 0)); } // Generate houses for (auto &city : cities) { int target_population = random->random(50, random->random(100, random->random(200, random->random(300, 1000)))); int spread = ceil(target_population / random->random(20, random->random(20, 30))); for (int j = 0; j < ceil(target_population / 4); j++) { int x; int y; int attempt = 0; do { x = (int)city->getX() + random->random(-spread, spread); y = (int)city->getY() + random->random(-spread, spread); attempt++; } while (!( attempt == spread || ( x >= 0 && y >= 0 && x < width && y < height && terrainMap[y * width + x] >= static_cast<int>(Objects::Terrain::Type::SAND1) && objectMap[y * width + x] == 0 ) )); if (attempt == spread) { continue; } int population = random->random(2, 6); houses.push_back(std::make_unique<Objects::House>( houses.size(), static_cast<Objects::House::Type>(random->random(static_cast<int>(Objects::House::Type::HOUSE), static_cast<int>(Objects::House::Type::SHOP))), x + 0.5, y + 0.5, population )); objectMap[y * width + x] = 1; city->setPopulation(city->getPopulation() + population); } } // Generate roads std::map<int, int> cityCount; for (size_t i = 0; i < cities.size() / 8; i++) { Objects::City *city = cities.at(random->random(0, cities.size() - 1)).get(); int lanes = random->random(1, random->random(1, 3)); for (size_t j = 0; j < cities.size() / 8; j++) { Objects::City *otherCity; size_t attempt = 0; do { otherCity = cities.at(random->random(0, cities.size() - 1)).get(); attempt++; } while (!( attempt == cities.size() * 2 || ( sqrt( (city->getX() - otherCity->getX()) * (city->getX() - otherCity->getX()) + (city->getY() - otherCity->getY()) * (city->getY() - otherCity->getY()) ) < 75 && cityCount[otherCity->getId()] < 2 ) )); if (attempt == cities.size() * 2) { break; } roads.push_back(std::make_unique<Objects::Road>( roads.size(), city->getX(), city->getY(), otherCity->getX(), otherCity->getY(), lanes, random->random(60, 120) )); cityCount[city->getId()]++; cityCount[otherCity->getId()]++; city = otherCity; } } // Create start vehicles for (size_t i = 0; i < cities.size(); i++) { addVehicle(); } // Start vehicle timer vehicleTimer = SDL_AddTimer(Config::vehicleTimeout, Timer::callback, reinterpret_cast<void *>(vehicleTimerEventCode)); } uint64_t World::getSeed() const { return seed; } int World::getWidth() const { return width; } int World::getHeight() const { return height; } std::vector<const Objects::Nature *> World::getNatures() const { std::vector<const Objects::Nature *> naturePointers; for (auto const &nature : natures) { naturePointers.push_back(nature.get()); } return naturePointers; } std::vector<const Objects::House *> World::getHouses() const { std::vector<const Objects::House *> housePointers; for (auto const &house : houses) { housePointers.push_back(house.get()); } return housePointers; } std::vector<const Objects::City *> World::getCities() const { std::vector<const Objects::City *> cityPointers; for (auto const &city : cities) { cityPointers.push_back(city.get()); } return cityPointers; } std::vector<const Objects::Road *> World::getRoads() const { std::vector<const Objects::Road *> roadPointers; for (auto const &road : roads) { roadPointers.push_back(road.get()); } return roadPointers; } std::vector<const Objects::Vehicle *> World::getVehicles() const { std::vector<const Objects::Vehicle *> vehiclePointers; for (auto const &vehicle : vehicles) { vehiclePointers.push_back(vehicle.get()); } return vehiclePointers; } std::vector<const Objects::Explosion *> World::getExplosions() const { std::vector<const Objects::Explosion *> explosionPointers; for (auto const &explosion : explosions) { explosionPointers.push_back(explosion.get()); } return explosionPointers; } bool World::handleEvent(const SDL_Event *event) { // Pass event to explosions for (auto const &explosion : explosions) { if (explosion->handleEvent(event)) { return true; } } // Create vehicle on timer if (event->type == SDL_USEREVENT && event->user.code == vehicleTimerEventCode) { for (size_t i = 0; i < cities.size() / 4; i++) { addVehicle(); } return true; } return false; } void World::update(float delta) { // Update vehicles for (auto &vehicle : vehicles) { vehicle->update(delta); } // Check collision for (auto &vehicle : vehicles) { if (vehicle->getDriver() && !vehicle->getDriver()->isArrived()) { for (auto &otherVehicle : vehicles) { if (vehicle->getId() != otherVehicle->getId()) { if (otherVehicle->getDriver() && !otherVehicle->getDriver()->isArrived()) { if ( sqrt( (vehicle->getX() - otherVehicle->getX()) * (vehicle->getX() - otherVehicle->getX()) + (vehicle->getY() - otherVehicle->getY()) * (vehicle->getY() - otherVehicle->getY()) ) < 1 ) { vehicle->crash(); otherVehicle->crash(); explosions.push_back(std::make_unique<Objects::Explosion>( explosions.size(), static_cast<Objects::Explosion::Type>(random->random(static_cast<int>(Objects::Explosion::Type::FIRE), static_cast<int>(Objects::Explosion::Type::SMOKE))), vehicle->getX(), vehicle->getY() )); } } } } } } } void World::draw(std::shared_ptr<Canvas> canvas, const Camera *camera) const { std::unique_ptr<Rect> canvasRect = canvas->getRect(); // Draw terrain tiles for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int tileSize = Camera::zoomLevels[camera->getZoom()]; Rect tileRect = { (int)(x * tileSize - (camera->getX() * tileSize - canvasRect->width / 2)), (int)(y * tileSize - (camera->getY() * tileSize - canvasRect->height / 2)), tileSize, tileSize }; if (canvasRect->collides(&tileRect)) { Objects::Terrain::getImage(static_cast<Objects::Terrain::Type>(terrainMap[y * width + x]))->draw(&tileRect); } } } // Draw natures for (auto const &nature : natures) { nature->draw(canvas, camera); } // Draw houses for (auto const &house : houses) { house->draw(canvas, camera); } // Draw roads for (auto const &road : roads) { road->draw(canvas, camera); } // Draw not arrived vehicles for (auto const &vehicle : vehicles) { const Objects::Driver *driver = vehicle->getDriver(); if (driver && !driver->isArrived()) { vehicle->draw(canvas, camera); } } // Draw explosions for (auto const &explosion : explosions) { explosion->draw(canvas, camera); } // Draw cities for (auto const &city : cities) { city->draw(canvas, camera); } } void World::addVehicle() { Objects::City *city = cities.at(random->random(0, cities.size() - 1)).get(); float x = 0; float y = 0; float destinationX = 0; float destinationY = 0; int lanes; for (const auto &road : roads) { if (random->random(1, 2) == 1 && road->getX() == city->getX() && road->getY() == city->getY()) { x = road->getX() + 0.5; y = road->getY() + 0.5; destinationX = road->getEndX() + 0.5; destinationY = road->getEndY() + 0.5; lanes = road->getLanes(); break; } if (random->random(1, 2) == 1 && road->getEndX() == city->getX() && road->getEndY() == city->getY()) { x = road->getEndX() + 0.5; y = road->getEndY() + 0.5; destinationX = road->getX() + 0.5; destinationY = road->getY() + 0.5; lanes = road->getLanes(); break; } } if (destinationX == 0) { return; } if (abs(x - destinationX) > abs(y - destinationY)) { y -= lanes - random->random(0, lanes); destinationY -= lanes - random->random(0, lanes); } else { x -= lanes - random->random(0, lanes); destinationX -= lanes - random->random(0, lanes); } float angle = atan2(y - destinationY, x - destinationX); std::unique_ptr<Objects::Vehicle> vehicle = std::make_unique<Objects::Vehicle>( vehicles.size(), static_cast<Objects::Vehicle::Type>(random->random(static_cast<int>(Objects::Vehicle::Type::STANDARD), static_cast<int>(Objects::Vehicle::Type::MOTOR_CYCLE))), x, y, static_cast<Objects::Vehicle::Color>(random->random(static_cast<int>(Objects::Vehicle::Color::BLACK), static_cast<int>(Objects::Vehicle::Color::YELLOW))), angle ); vehicle->setDriver(std::move(std::make_unique<Objects::Driver>(vehicle.get(), destinationX, destinationY))); vehicles.push_back(std::move(vehicle)); }
15,267
4,867
// // util/Math.hpp // pTK // // Created by Robin Gustafsson on 2021-12-11. // #ifndef PTK_UTIL_MATH_HPP #define PTK_UTIL_MATH_HPP // C++ Headers #include <cmath> #include <string> namespace pTK { /** This file is purely for the need of math functions. Since in Linux apparently some math functions, like ceilf are defined in the global namespace and not in std. */ namespace Math { static inline float ceilf(float arg) { // This is apparently needed in Linux. // Since, ceilf is in the global namespace?! // Can't use std::ceilf. using namespace std; // This will call whatever is defined outside this function. return ::ceilf(arg); } } } #endif // PTK_UTIL_MATH_HPP
813
267
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_Streams_SharedMemoryStream_inl_ #define _Stroika_Foundation_Streams_SharedMemoryStream_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include <mutex> #include "../Execution/WaitableEvent.h" namespace Stroika::Foundation::Streams { /* ******************************************************************************** ******************* SharedMemoryStream<ELEMENT_TYPE>::Rep_ ********************* ******************************************************************************** */ template <typename ELEMENT_TYPE> class SharedMemoryStream<ELEMENT_TYPE>::Rep_ : public InputOutputStream<ELEMENT_TYPE>::_IRep { public: using ElementType = ELEMENT_TYPE; private: bool fIsOpenForRead_{true}; public: Rep_ () : fData_{} , fReadCursor_{fData_.begin ()} , fWriteCursor_{fData_.begin ()} { } Rep_ (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) : Rep_{} { Write (start, end); } Rep_ (const Rep_&) = delete; ~Rep_ () = default; nonvirtual Rep_& operator= (const Rep_&) = delete; virtual bool IsSeekable () const override { return true; } virtual void CloseWrite () override { Require (IsOpenWrite ()); { [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; fClosedForWrites_ = true; } fMoreDataWaiter_.Set (); } virtual bool IsOpenWrite () const override { return not fClosedForWrites_; } virtual void CloseRead () override { Require (IsOpenRead ()); fIsOpenForRead_ = false; } virtual bool IsOpenRead () const override { return fIsOpenForRead_; } virtual size_t Read (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override { RequireNotNull (intoStart); RequireNotNull (intoEnd); Require (intoStart < intoEnd); Require (IsOpenRead ()); size_t nRequested = intoEnd - intoStart; tryAgain: fMoreDataWaiter_.Wait (); [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; // hold lock for everything EXCEPT wait Assert ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ())); size_t nAvail = fData_.end () - fReadCursor_; if (nAvail == 0 and not fClosedForWrites_) { fMoreDataWaiter_.Reset (); // ?? @todo consider - is this a race? If we reset at same time(apx) as someone else sets goto tryAgain; // cannot wait while we hold lock } size_t nCopied = min (nAvail, nRequested); { #if qSilenceAnnoyingCompilerWarnings && _MSC_VER Memory::Private::VC_BWA_std_copy (fReadCursor_, fReadCursor_ + nCopied, intoStart); #else copy (fReadCursor_, fReadCursor_ + nCopied, intoStart); #endif fReadCursor_ = fReadCursor_ + nCopied; } return nCopied; // this can be zero on EOF } virtual optional<size_t> ReadNonBlocking (ELEMENT_TYPE* intoStart, ELEMENT_TYPE* intoEnd) override { Require ((intoStart == nullptr and intoEnd == nullptr) or (intoEnd - intoStart) >= 1); Require (IsOpenRead ()); [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; size_t nDefinitelyAvail = fData_.end () - fReadCursor_; if (nDefinitelyAvail > 0) { return this->_ReadNonBlocking_ReferenceImplementation_ForNonblockingUpstream (intoStart, intoEnd, nDefinitelyAvail); } else if (fClosedForWrites_) { return this->_ReadNonBlocking_ReferenceImplementation_ForNonblockingUpstream (intoStart, intoEnd, 0); } else { return {}; // if nothing available, but not closed for write, no idea if more to come } } virtual void Write (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) override { Require (start != nullptr or start == end); Require (end != nullptr or start == end); Require (IsOpenWrite ()); if (start != end) { [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; size_t roomLeft = fData_.end () - fWriteCursor_; size_t roomRequired = end - start; fMoreDataWaiter_.Set (); // just means MAY be more data - readers check if (roomLeft < roomRequired) { size_t curReadOffset = fReadCursor_ - fData_.begin (); size_t curWriteOffset = fWriteCursor_ - fData_.begin (); const size_t kChunkSize_ = 128; // WAG: @todo tune number... Containers::ReserveSpeedTweekAddN (fData_, roomRequired - roomLeft, kChunkSize_); fData_.resize (curWriteOffset + roomRequired); fReadCursor_ = fData_.begin () + curReadOffset; fWriteCursor_ = fData_.begin () + curWriteOffset; Assert (fWriteCursor_ < fData_.end ()); } #if qSilenceAnnoyingCompilerWarnings && _MSC_VER Memory::Private::VC_BWA_std_copy (start, start + roomRequired, fWriteCursor_); #else copy (start, start + roomRequired, fWriteCursor_); #endif fWriteCursor_ += roomRequired; Assert (fReadCursor_ < fData_.end ()); // < because we wrote at least one byte and that didnt move read cursor Assert (fWriteCursor_ <= fData_.end ()); } } virtual void Flush () override { // nothing todo - write 'writes thru' } virtual SeekOffsetType GetReadOffset () const override { Require (IsOpenRead ()); [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; return fReadCursor_ - fData_.begin (); } virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override { Require (IsOpenRead ()); [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; fMoreDataWaiter_.Set (); // just means MAY be more data - readers check switch (whence) { case Whence::eFromStart: { if (offset < 0) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } SeekOffsetType uOffset = static_cast<SeekOffsetType> (offset); if (uOffset > fData_.size ()) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } fReadCursor_ = fData_.begin () + static_cast<size_t> (uOffset); } break; case Whence::eFromCurrent: { Streams::SeekOffsetType curOffset = fReadCursor_ - fData_.begin (); Streams::SignedSeekOffsetType newOffset = curOffset + offset; if (newOffset < 0) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset); if (uNewOffset > fData_.size ()) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset); } break; case Whence::eFromEnd: { Streams::SignedSeekOffsetType newOffset = fData_.size () + offset; if (newOffset < 0) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } SeekOffsetType uNewOffset = static_cast<SeekOffsetType> (newOffset); if (uNewOffset > fData_.size ()) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } fReadCursor_ = fData_.begin () + static_cast<size_t> (uNewOffset); } break; } Ensure ((fData_.begin () <= fReadCursor_) and (fReadCursor_ <= fData_.end ())); return fReadCursor_ - fData_.begin (); } virtual SeekOffsetType GetWriteOffset () const override { Require (IsOpenWrite ()); [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; return fWriteCursor_ - fData_.begin (); } virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override { Require (IsOpenWrite ()); [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; fMoreDataWaiter_.Set (); // just means MAY be more data - readers check switch (whence) { case Whence::eFromStart: { if (offset < 0) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } if (static_cast<SeekOffsetType> (offset) > fData_.size ()) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } fWriteCursor_ = fData_.begin () + static_cast<size_t> (offset); } break; case Whence::eFromCurrent: { Streams::SeekOffsetType curOffset = fWriteCursor_ - fData_.begin (); Streams::SignedSeekOffsetType newOffset = curOffset + offset; if (newOffset < 0) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } if (static_cast<size_t> (newOffset) > fData_.size ()) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset); } break; case Whence::eFromEnd: { Streams::SignedSeekOffsetType newOffset = fData_.size () + offset; if (newOffset < 0) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } if (static_cast<size_t> (newOffset) > fData_.size ()) [[UNLIKELY_ATTR]] { Execution::Throw (range_error{"seek"}); } fWriteCursor_ = fData_.begin () + static_cast<size_t> (newOffset); } break; } Ensure ((fData_.begin () <= fWriteCursor_) and (fWriteCursor_ <= fData_.end ())); return fWriteCursor_ - fData_.begin (); } vector<ElementType> AsVector () const { [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; return fData_; } string AsString () const { [[maybe_unused]] auto&& critSec = lock_guard{fMutex_}; return string (reinterpret_cast<const char*> (Containers::Start (fData_)), reinterpret_cast<const char*> (Containers::End (fData_))); } private: mutable recursive_mutex fMutex_; Execution::WaitableEvent fMoreDataWaiter_{Execution::WaitableEvent::eManualReset}; // not a race cuz always set/reset when holding fMutex; no need to pre-set cuz auto set when someone adds data (Write) vector<ElementType> fData_; typename vector<ElementType>::iterator fReadCursor_; typename vector<ElementType>::iterator fWriteCursor_; bool fClosedForWrites_{false}; }; /* ******************************************************************************** ********************** SharedMemoryStream<ELEMENT_TYPE> ************************ ******************************************************************************** */ DISABLE_COMPILER_GCC_WARNING_START ("GCC diagnostic ignored \"-Wattributes\"") template <typename ELEMENT_TYPE> inline auto SharedMemoryStream<ELEMENT_TYPE>::New ([[maybe_unused]] Execution::InternallySynchronized internallySynchronized) -> Ptr { // always return internally synchronized rep return make_shared<Rep_> (); } DISABLE_COMPILER_GCC_WARNING_END ("GCC diagnostic ignored \"-Wattributes\"") template <typename ELEMENT_TYPE> inline auto SharedMemoryStream<ELEMENT_TYPE>::New (const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) -> Ptr { return make_shared<Rep_> (start, end); } template <typename ELEMENT_TYPE> inline auto SharedMemoryStream<ELEMENT_TYPE>::New (Execution::InternallySynchronized internallySynchronized, const ELEMENT_TYPE* start, const ELEMENT_TYPE* end) -> Ptr { return New (start, end); } template <typename ELEMENT_TYPE> template <typename TEST_TYPE, enable_if_t<is_same_v<TEST_TYPE, byte>>*> inline auto SharedMemoryStream<ELEMENT_TYPE>::New (const Memory::BLOB& blob) -> Ptr { return New (blob.begin (), blob.end ()); } template <typename ELEMENT_TYPE> template <typename TEST_TYPE, enable_if_t<is_same_v<TEST_TYPE, byte>>*> inline auto SharedMemoryStream<ELEMENT_TYPE>::New (Execution::InternallySynchronized internallySynchronized, const Memory::BLOB& blob) -> Ptr { return New (blob.begin (), blob.end ()); } /* ******************************************************************************** ****************** SharedMemoryStream<ELEMENT_TYPE>::Ptr *********************** ******************************************************************************** */ template <typename ELEMENT_TYPE> inline SharedMemoryStream<ELEMENT_TYPE>::Ptr::Ptr (const shared_ptr<Rep_>& from) : inherited{from} { } template <typename ELEMENT_TYPE> inline auto SharedMemoryStream<ELEMENT_TYPE>::Ptr::GetRepConstRef_ () const -> const Rep_& { // reinterpret_cast faster than dynamic_cast - check equivalent Assert (dynamic_cast<const Rep_*> (&inherited::_GetRepConstRef ()) == reinterpret_cast<const Rep_*> (&inherited::_GetRepConstRef ())); return *reinterpret_cast<const Rep_*> (&inherited::_GetRepConstRef ()); } template <typename ELEMENT_TYPE> inline auto SharedMemoryStream<ELEMENT_TYPE>::Ptr::GetRepRWRef_ () const -> Rep_& { // reinterpret_cast faster than dynamic_cast - check equivalent Assert (dynamic_cast<Rep_*> (&inherited::_GetRepRWRef ()) == reinterpret_cast<Rep_*> (&inherited::_GetRepRWRef ())); return *reinterpret_cast<Rep_*> (&inherited::_GetRepRWRef ()); } template <> template <> inline vector<byte> SharedMemoryStream<byte>::Ptr::As () const { return GetRepConstRef_ ().AsVector (); } template <> template <> inline vector<Characters::Character> SharedMemoryStream<Characters::Character>::Ptr::As () const { return GetRepConstRef_ ().AsVector (); } } #endif /*_Stroika_Foundation_Streams_SharedMemoryStream_inl_*/
15,876
4,407
// // ExpansionHunter // Copyright (c) 2020 Illumina, Inc. // // Author: Konrad Scheffler <kscheffler@illumina.com> // // 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. // // These utility functions were copied from source code of Strelka Small Variant Caller. #pragma once #include <boost/math/special_functions/log1p.hpp> // returns log(1+x), switches to log1p function when abs(x) is small static double log1p_switch(const double x) { // TODO Justify this switch point. Related discussion: // http://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf static const double smallx_thresh(0.01); if (std::abs(x) < smallx_thresh) { return boost::math::log1p(x); } else { return std::log(1 + x); } } // Returns the equivalent of log(exp(x1)+exp(x2)) static double getLogSum(double x1, double x2) { if (x1 < x2) std::swap(x1, x2); return x1 + log1p_switch(std::exp(x2 - x1)); }
1,468
495
#include <cassert> #include <cstdint> #include <algorithm> #include <string> std::string MakeUpperCase(std::string str) { std::transform(str.begin(), str.end(), str.begin(), ::toupper); return str; } int main() { assert(MakeUpperCase("hello") == "HELLO"); return 0; }
275
106
/* * 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. */ // Unit-test the server context #include "net/instaweb/rewriter/public/server_context.h" #include <cstddef> // for size_t #include "base/logging.h" #include "net/instaweb/http/public/async_fetch.h" #include "net/instaweb/http/public/counting_url_async_fetcher.h" #include "net/instaweb/http/public/http_cache.h" #include "net/instaweb/http/public/http_cache_failure.h" #include "net/instaweb/http/public/http_value.h" #include "net/instaweb/http/public/mock_url_fetcher.h" #include "net/instaweb/rewriter/input_info.pb.h" #include "net/instaweb/rewriter/public/beacon_critical_images_finder.h" #include "net/instaweb/rewriter/public/critical_finder_support_util.h" #include "net/instaweb/rewriter/public/critical_images_finder.h" #include "net/instaweb/rewriter/public/critical_selector_finder.h" #include "net/instaweb/rewriter/public/css_outline_filter.h" #include "net/instaweb/rewriter/public/domain_lawyer.h" #include "net/instaweb/rewriter/public/file_load_policy.h" #include "net/instaweb/rewriter/public/mock_resource_callback.h" #include "net/instaweb/rewriter/public/output_resource.h" #include "net/instaweb/rewriter/public/output_resource_kind.h" #include "net/instaweb/rewriter/public/resource.h" #include "net/instaweb/rewriter/public/resource_namer.h" #include "net/instaweb/rewriter/public/rewrite_driver.h" #include "net/instaweb/rewriter/public/rewrite_filter.h" #include "net/instaweb/rewriter/public/rewrite_options.h" #include "net/instaweb/rewriter/public/rewrite_query.h" #include "net/instaweb/rewriter/public/rewrite_test_base.h" #include "net/instaweb/rewriter/public/test_rewrite_driver_factory.h" #include "net/instaweb/rewriter/rendered_image.pb.h" #include "net/instaweb/util/public/mock_property_page.h" #include "net/instaweb/util/public/property_cache.h" #include "pagespeed/kernel/base/basictypes.h" #include "pagespeed/kernel/base/gtest.h" #include "pagespeed/kernel/base/mock_message_handler.h" #include "pagespeed/kernel/base/mock_timer.h" #include "pagespeed/kernel/base/ref_counted_ptr.h" #include "pagespeed/kernel/base/scoped_ptr.h" #include "pagespeed/kernel/base/statistics.h" #include "pagespeed/kernel/base/string.h" #include "pagespeed/kernel/base/string_hash.h" #include "pagespeed/kernel/base/string_util.h" #include "pagespeed/kernel/base/timer.h" #include "pagespeed/kernel/cache/lru_cache.h" #include "pagespeed/kernel/html/html_element.h" #include "pagespeed/kernel/html/html_parse_test_base.h" #include "pagespeed/kernel/http/content_type.h" #include "pagespeed/kernel/http/google_url.h" #include "pagespeed/kernel/http/http_names.h" #include "pagespeed/kernel/http/request_headers.h" #include "pagespeed/kernel/http/response_headers.h" #include "pagespeed/kernel/http/user_agent_matcher.h" #include "pagespeed/kernel/http/user_agent_matcher_test_base.h" #include "pagespeed/kernel/util/url_escaper.h" namespace { const char kResourceUrl[] = "http://example.com/image.png"; const char kResourceUrlBase[] = "http://example.com"; const char kResourceUrlPath[] = "/image.png"; const char kOptionsHash[] = "1234"; const char kUrlPrefix[] = "http://www.example.com/"; } // namespace namespace net_instaweb { class VerifyContentsCallback : public Resource::AsyncCallback { public: VerifyContentsCallback(const ResourcePtr& resource, const GoogleString& contents) : Resource::AsyncCallback(resource), contents_(contents), called_(false) {} VerifyContentsCallback(const OutputResourcePtr& resource, const GoogleString& contents) : Resource::AsyncCallback(ResourcePtr(resource)), contents_(contents), called_(false) {} void Done(bool lock_failure, bool resource_ok) override { EXPECT_FALSE(lock_failure); EXPECT_STREQ(contents_, resource()->ExtractUncompressedContents()); called_ = true; } void AssertCalled() { EXPECT_TRUE(called_); } GoogleString contents_; bool called_; }; class ServerContextTest : public RewriteTestBase { protected: // Fetches data (which is expected to exist) for given resource, // but making sure to go through the path that checks for its // non-existence and potentially doing locking, too. // Note: resource must have hash set. bool FetchExtantOutputResourceHelper(const OutputResourcePtr& resource, StringAsyncFetch* async_fetch) { async_fetch->set_response_headers(resource->response_headers()); RewriteFilter* null_filter = nullptr; // We want to test the cache only. EXPECT_TRUE(rewrite_driver()->FetchOutputResource(resource, null_filter, async_fetch)); rewrite_driver()->WaitForCompletion(); EXPECT_TRUE(async_fetch->done()); return async_fetch->success(); } // Helper for testing of FetchOutputResource. Assumes that output_resource // is to be handled by the filter with 2-letter code filter_id, and // verifies result to match expect_success and expect_content. void TestFetchOutputResource(const OutputResourcePtr& output_resource, const char* filter_id, bool expect_success, StringPiece expect_content) { ASSERT_TRUE(output_resource.get()); RewriteFilter* filter = rewrite_driver()->FindFilter(filter_id); ASSERT_TRUE(filter != nullptr); StringAsyncFetch fetch_result(CreateRequestContext()); EXPECT_TRUE(rewrite_driver()->FetchOutputResource(output_resource, filter, &fetch_result)); rewrite_driver()->WaitForCompletion(); EXPECT_TRUE(fetch_result.done()); EXPECT_EQ(expect_success, fetch_result.success()); EXPECT_EQ(expect_content, fetch_result.buffer()); } GoogleString GetOutputResource(const OutputResourcePtr& resource) { StringAsyncFetch fetch(RequestContext::NewTestRequestContext( server_context()->thread_system())); EXPECT_TRUE(FetchExtantOutputResourceHelper(resource, &fetch)); return fetch.buffer(); } // Returns whether there was an existing copy of data for the resource. // If not, makes sure the resource is wrapped. bool TryFetchExtantOutputResource(const OutputResourcePtr& resource) { StringAsyncFetch dummy_fetch(CreateRequestContext()); return FetchExtantOutputResourceHelper(resource, &dummy_fetch); } // Asserts that the given url starts with an appropriate prefix; // then cuts off that prefix. virtual void RemoveUrlPrefix(const GoogleString& prefix, GoogleString* url) { EXPECT_TRUE(StringPiece(*url).starts_with(prefix)); url->erase(0, prefix.length()); } OutputResourcePtr CreateOutputResourceForFetch(const StringPiece& url) { RewriteFilter* dummy; rewrite_driver()->SetBaseUrlForFetch(url); GoogleUrl gurl(url); return rewrite_driver()->DecodeOutputResource(gurl, &dummy); } ResourcePtr CreateInputResourceAndReadIfCached(const StringPiece& url) { rewrite_driver()->SetBaseUrlForFetch(url); GoogleUrl resource_url(url); bool unused; ResourcePtr resource(rewrite_driver()->CreateInputResource( resource_url, RewriteDriver::InputRole::kUnknown, &unused)); if ((resource.get() != nullptr) && !ReadIfCached(resource)) { resource.clear(); } return resource; } // Tests for the lifecycle and various flows of a named output resource. void TestNamed() { const char* filter_prefix = RewriteOptions::kCssFilterId; const char* name = "I.name"; // valid name for CSS filter. const char* contents = "contents"; GoogleString failure_reason; OutputResourcePtr output(rewrite_driver()->CreateOutputResourceWithPath( kUrlPrefix, filter_prefix, name, kRewrittenResource, &failure_reason)); ASSERT_TRUE(output.get() != nullptr); EXPECT_EQ("", failure_reason); // Check name_key against url_prefix/fp.name GoogleString name_key = output->name_key(); RemoveUrlPrefix(kUrlPrefix, &name_key); EXPECT_EQ(output->full_name().EncodeIdName(), name_key); // Make sure the resource hasn't already been created. We do need to give it // a hash for fetching to do anything. output->SetHash("42"); EXPECT_FALSE(TryFetchExtantOutputResource(output)); EXPECT_FALSE(output->IsWritten()); { // Check that a non-blocking attempt to create another resource // with the same name returns quickly. We don't need a hash in this // case since we're just trying to create the resource, not fetch it. OutputResourcePtr output1(rewrite_driver()->CreateOutputResourceWithPath( kUrlPrefix, filter_prefix, name, kRewrittenResource, &failure_reason)); ASSERT_TRUE(output1.get() != nullptr); EXPECT_EQ("", failure_reason); EXPECT_FALSE(output1->IsWritten()); } { // Here we attempt to create the object with the hash and fetch it. // The fetch fails as there is no active filter to resolve it. ResourceNamer namer; namer.CopyFrom(output->full_name()); namer.set_hash("0"); namer.set_ext("txt"); GoogleString name = StrCat(kUrlPrefix, namer.Encode()); OutputResourcePtr output1(CreateOutputResourceForFetch(name)); ASSERT_TRUE(output1.get() != nullptr); // blocking but stealing EXPECT_FALSE(TryFetchExtantOutputResource(output1)); } // Write some data ASSERT_TRUE(output->has_hash()); EXPECT_EQ(kRewrittenResource, output->kind()); EXPECT_TRUE(rewrite_driver()->Write( ResourceVector(), contents, &kContentTypeText, "utf-8", output.get())); EXPECT_TRUE(output->IsWritten()); // Check that hash and ext are correct. EXPECT_EQ("0", output->hash()); EXPECT_EQ("txt", output->extension()); EXPECT_STREQ("utf-8", output->charset()); // With the URL (which contains the hash), we can retrieve it // from the http_cache. OutputResourcePtr output4(CreateOutputResourceForFetch(output->url())); EXPECT_EQ(output->url(), output4->url()); EXPECT_EQ(contents, GetOutputResource(output4)); } bool ResourceIsCached() { ResourcePtr resource(CreateResource(kResourceUrlBase, kResourceUrlPath)); return ReadIfCached(resource); } void StartRead() { ResourcePtr resource(CreateResource(kResourceUrlBase, kResourceUrlPath)); InitiateResourceRead(resource); } GoogleString MakeEvilUrl(const StringPiece& host, const StringPiece& name) { GoogleString escaped_abs; UrlEscaper::EncodeToUrlSegment(name, &escaped_abs); // Do not use Encode, which will make the URL non-evil. // TODO(matterbury): Rewrite this for a non-standard UrlNamer? return StrCat("http://", host, "/dir/123/", escaped_abs, ".pagespeed.jm.0.js"); } // Accessor for ServerContext field; also cleans up // deferred_release_rewrite_drivers_. void EnableRewriteDriverCleanupMode(bool s) { server_context()->trying_to_cleanup_rewrite_drivers_ = s; server_context()->deferred_release_rewrite_drivers_.clear(); } // Creates a response with given ttl and extra cache control under given URL. void SetCustomCachingResponse(const StringPiece& url, int ttl_ms, const StringPiece& extra_cache_control) { ResponseHeaders response_headers; DefaultResponseHeaders(kContentTypeCss, ttl_ms, &response_headers); response_headers.SetDateAndCaching(http_cache()->timer()->NowMs(), ttl_ms * Timer::kSecondMs, extra_cache_control); response_headers.ComputeCaching(); SetFetchResponse(AbsolutifyUrl(url), response_headers, "payload"); } // Creates a resource with given ttl and extra cache control under given URL. ResourcePtr CreateCustomCachingResource( const StringPiece& url, int ttl_ms, const StringPiece& extra_cache_control) { SetCustomCachingResponse(url, ttl_ms, extra_cache_control); GoogleUrl gurl(AbsolutifyUrl(url)); rewrite_driver()->SetBaseUrlForFetch(kTestDomain); bool unused; ResourcePtr resource(rewrite_driver()->CreateInputResource( gurl, RewriteDriver::InputRole::kUnknown, &unused)); VerifyContentsCallback callback(resource, "payload"); resource->LoadAsync(Resource::kLoadEvenIfNotCacheable, rewrite_driver()->request_context(), &callback); callback.AssertCalled(); return resource; } void RefererTest(const RequestHeaders* headers, bool is_background_fetch) { GoogleString url = "test.jpg"; rewrite_driver()->SetBaseUrlForFetch(kTestDomain); SetCustomCachingResponse(url, 100, "foo"); GoogleUrl gurl(AbsolutifyUrl(url)); bool unused; ResourcePtr resource(rewrite_driver()->CreateInputResource( gurl, RewriteDriver::InputRole::kImg, &unused)); if (!is_background_fetch) { rewrite_driver()->SetRequestHeaders(*headers); } resource->set_is_background_fetch(is_background_fetch); VerifyContentsCallback callback(resource, "payload"); resource->LoadAsync(Resource::kLoadEvenIfNotCacheable, rewrite_driver()->request_context(), &callback); callback.AssertCalled(); } void DefaultHeaders(ResponseHeaders* headers) { SetDefaultLongCacheHeaders(&kContentTypeCss, headers); } const RewriteDriver* decoding_driver() { return server_context()->decoding_driver_; } RewriteOptions* GetCustomOptions(const StringPiece& url, RequestHeaders* request_headers, RewriteOptions* domain_options) { // The default url_namer does not yield any name-derived options, and we // have not specified any URL params or request-headers, so there will be // no custom options, and no errors. GoogleUrl gurl(url); RewriteOptions* copy_options = domain_options != nullptr ? domain_options->Clone() : nullptr; RewriteQuery rewrite_query; RequestContextPtr null_request_context; EXPECT_TRUE(server_context()->GetQueryOptions(null_request_context, nullptr, &gurl, request_headers, nullptr, &rewrite_query)); RewriteOptions* options = server_context()->GetCustomOptions( request_headers, copy_options, rewrite_query.ReleaseOptions()); return options; } void CheckExtendCache(RewriteOptions* options, bool x) { EXPECT_EQ(x, options->Enabled(RewriteOptions::kExtendCacheCss)); EXPECT_EQ(x, options->Enabled(RewriteOptions::kExtendCacheImages)); EXPECT_EQ(x, options->Enabled(RewriteOptions::kExtendCacheScripts)); } }; TEST_F(ServerContextTest, CustomOptionsWithNoUrlNamerOptions) { // The default url_namer does not yield any name-derived options, and we // have not specified any URL params or request-headers, so there will be // no custom options, and no errors. RequestHeaders request_headers; std::unique_ptr<RewriteOptions> options( GetCustomOptions("http://example.com/", &request_headers, nullptr)); ASSERT_TRUE(options.get() == nullptr); // Now put a query-param in, just turning on PageSpeed. The core filters // should be enabled. options.reset(GetCustomOptions("http://example.com/?PageSpeed=on", &request_headers, nullptr)); ASSERT_TRUE(options.get() != nullptr); EXPECT_TRUE(options->enabled()); CheckExtendCache(options.get(), true); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kDeferJavascript)); // Now explicitly enable a filter, which should disable others. options.reset( GetCustomOptions("http://example.com/?PageSpeedFilters=extend_cache", &request_headers, nullptr)); ASSERT_TRUE(options.get() != nullptr); CheckExtendCache(options.get(), true); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kDeferJavascript)); // Now put a request-header in, turning off pagespeed. request-headers get // priority over query-params. request_headers.Add("PageSpeed", "off"); options.reset(GetCustomOptions("http://example.com/?PageSpeed=on", &request_headers, nullptr)); ASSERT_TRUE(options.get() != nullptr); EXPECT_FALSE(options->enabled()); // Now explicitly enable a bogus filter, which should will cause the // options to be uncomputable. GoogleUrl gurl("http://example.com/?PageSpeedFilters=bogus_filter"); RewriteQuery rewrite_query; RequestContextPtr null_request_context; EXPECT_FALSE(server_context()->GetQueryOptions( null_request_context, options.get(), &gurl, &request_headers, nullptr, &rewrite_query)); // The default url_namer does not yield any name-derived options, and we // have not specified any URL params or request-headers, and kXRequestedWith // header is set with bogus value, so there will be no custom options, and no // errors. request_headers.Add(HttpAttributes::kXRequestedWith, "bogus"); options.reset( GetCustomOptions("http://example.com/", &request_headers, nullptr)); ASSERT_TRUE(options.get() == nullptr); // The default url_namer does not yield any name-derived options, and we // have not specified any URL params or request-headers, but kXRequestedWith // header is set to 'XmlHttpRequest', so there will be custom options with // all js inserting filters disabled. request_headers.RemoveAll(HttpAttributes::kXRequestedWith); request_headers.Add(HttpAttributes::kXRequestedWith, HttpAttributes::kXmlHttpRequest); options.reset( GetCustomOptions("http://example.com/", &request_headers, nullptr)); // Disable DelayImages for XmlHttpRequests. ASSERT_TRUE(options.get() != nullptr); EXPECT_TRUE(options->enabled()); EXPECT_FALSE(options->Enabled(RewriteOptions::kDelayImages)); // As kDelayImages filter is present in the disabled list, so it will not get // enabled even if it is enabled via EnableFilter(). options->EnableFilter(RewriteOptions::kDelayImages); EXPECT_FALSE(options->Enabled(RewriteOptions::kDelayImages)); options->EnableFilter(RewriteOptions::kCachePartialHtmlDeprecated); EXPECT_FALSE(options->Enabled(RewriteOptions::kCachePartialHtmlDeprecated)); options->EnableFilter(RewriteOptions::kDeferIframe); EXPECT_FALSE(options->Enabled(RewriteOptions::kDeferIframe)); options->EnableFilter(RewriteOptions::kDeferJavascript); EXPECT_FALSE(options->Enabled(RewriteOptions::kDeferJavascript)); options->EnableFilter(RewriteOptions::kFlushSubresources); EXPECT_FALSE(options->Enabled(RewriteOptions::kFlushSubresources)); options->EnableFilter(RewriteOptions::kLazyloadImages); EXPECT_FALSE(options->Enabled(RewriteOptions::kLazyloadImages)); options->EnableFilter(RewriteOptions::kLocalStorageCache); EXPECT_FALSE(options->Enabled(RewriteOptions::kLocalStorageCache)); options->EnableFilter(RewriteOptions::kPrioritizeCriticalCss); EXPECT_FALSE(options->Enabled(RewriteOptions::kPrioritizeCriticalCss)); } TEST_F(ServerContextTest, CustomOptionsWithUrlNamerOptions) { // Inject a url-namer that will establish a domain configuration. RewriteOptions namer_options(factory()->thread_system()); namer_options.EnableFilter(RewriteOptions::kCombineJavascript); namer_options.EnableFilter(RewriteOptions::kDelayImages); RequestHeaders request_headers; std::unique_ptr<RewriteOptions> options(GetCustomOptions( "http://example.com/", &request_headers, &namer_options)); // Even with no query-params or request-headers, we get the custom // options as domain options provided as argument. ASSERT_TRUE(options.get() != nullptr); EXPECT_TRUE(options->enabled()); CheckExtendCache(options.get(), false); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineJavascript)); EXPECT_TRUE(options->Enabled(RewriteOptions::kDelayImages)); // Now combine with query params, which turns core-filters on. options.reset(GetCustomOptions("http://example.com/?PageSpeed=on", &request_headers, &namer_options)); ASSERT_TRUE(options.get() != nullptr); EXPECT_TRUE(options->enabled()); CheckExtendCache(options.get(), true); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineJavascript)); // Explicitly enable a filter in query-params, which will turn off // the core filters that have not been explicitly enabled. Note // that explicit filter-setting in query-params overrides completely // the options provided as a parameter. options.reset( GetCustomOptions("http://example.com/?PageSpeedFilters=combine_css", &request_headers, &namer_options)); ASSERT_TRUE(options.get() != nullptr); EXPECT_TRUE(options->enabled()); CheckExtendCache(options.get(), false); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineJavascript)); // Now explicitly enable a bogus filter, which should will cause the // options to be uncomputable. GoogleUrl gurl("http://example.com/?PageSpeedFilters=bogus_filter"); RewriteQuery rewrite_query; RequestContextPtr null_request_context; EXPECT_FALSE(server_context()->GetQueryOptions( null_request_context, options.get(), &gurl, &request_headers, nullptr, &rewrite_query)); request_headers.Add(HttpAttributes::kXRequestedWith, "bogus"); options.reset(GetCustomOptions("http://example.com/", &request_headers, &namer_options)); // Don't disable DelayImages for Non-XmlHttpRequests. ASSERT_TRUE(options.get() != nullptr); EXPECT_TRUE(options->enabled()); CheckExtendCache(options.get(), false); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineJavascript)); EXPECT_TRUE(options->Enabled(RewriteOptions::kDelayImages)); request_headers.RemoveAll(HttpAttributes::kXRequestedWith); request_headers.Add(HttpAttributes::kXRequestedWith, HttpAttributes::kXmlHttpRequest); options.reset(GetCustomOptions("http://example.com/", &request_headers, &namer_options)); // Disable DelayImages for XmlHttpRequests. ASSERT_TRUE(options.get() != nullptr); EXPECT_TRUE(options->enabled()); CheckExtendCache(options.get(), false); EXPECT_FALSE(options->Enabled(RewriteOptions::kCombineCss)); EXPECT_TRUE(options->Enabled(RewriteOptions::kCombineJavascript)); EXPECT_FALSE(options->Enabled(RewriteOptions::kDelayImages)); } TEST_F(ServerContextTest, QueryOptionsWithInvalidUrl) { RequestHeaders request_headers; GoogleUrl gurl("bogus"); ASSERT_FALSE(gurl.IsWebValid()); RewriteQuery rewrite_query; RequestContextPtr null_request_context; EXPECT_FALSE(server_context()->GetQueryOptions( null_request_context, options(), &gurl, &request_headers, nullptr, &rewrite_query)); } TEST_F(ServerContextTest, TestNamed) { TestNamed(); } TEST_F(ServerContextTest, TestOutputInputUrl) { options()->EnableFilter(RewriteOptions::kRewriteJavascriptExternal); rewrite_driver()->AddFilters(); GoogleString url = Encode("http://example.com/dir/123/", RewriteOptions::kJavascriptMinId, "0", "orig", "js"); SetResponseWithDefaultHeaders("http://example.com/dir/123/orig", kContentTypeJavascript, "foo() /*comment */;", 100); OutputResourcePtr output_resource(CreateOutputResourceForFetch(url)); TestFetchOutputResource(output_resource, RewriteOptions::kJavascriptMinId, true, "foo();"); } // Test to make sure we do not let a crafted output resource URL to get us to // fetch and host things from a non-lawyer permitted external host; which could // lead to XSS vulnerabilities or a firewall bypass. TEST_F(ServerContextTest, TestOutputInputUrlEvil) { options()->EnableFilter(RewriteOptions::kRewriteJavascriptExternal); rewrite_driver()->AddFilters(); GoogleString url = MakeEvilUrl("example.com", "http://www.evil.com"); SetResponseWithDefaultHeaders("http://www.evil.com/", kContentTypeJavascript, "foo() /*comment */;", 100); OutputResourcePtr output_resource(CreateOutputResourceForFetch(url)); TestFetchOutputResource(output_resource, RewriteOptions::kJavascriptMinId, false, ""); } TEST_F(ServerContextTest, TestOutputInputUrlBusy) { EXPECT_TRUE(options()->WriteableDomainLawyer()->AddOriginDomainMapping( "www.busy.com", "example.com", "", message_handler())); options()->EnableFilter(RewriteOptions::kRewriteJavascriptExternal); rewrite_driver()->AddFilters(); GoogleString url = MakeEvilUrl("example.com", "http://www.busy.com"); SetResponseWithDefaultHeaders("http://www.busy.com/", kContentTypeJavascript, "foo() /*comment */;", 100); OutputResourcePtr output_resource(CreateOutputResourceForFetch(url)); TestFetchOutputResource(output_resource, RewriteOptions::kJavascriptMinId, false, ""); } // Check that we can origin-map a domain referenced from an HTML file // to 'localhost', but rewrite-map it to 'cdn.com'. This was not working // earlier because RewriteDriver::CreateInputResource was mapping to the // rewrite domain, preventing us from finding the origin-mapping when // fetching the URL. TEST_F(ServerContextTest, TestMapRewriteAndOrigin) { ASSERT_TRUE(options()->WriteableDomainLawyer()->AddOriginDomainMapping( "localhost", kTestDomain, "", message_handler())); EXPECT_TRUE(options()->WriteableDomainLawyer()->AddRewriteDomainMapping( "cdn.com", kTestDomain, message_handler())); ResourcePtr input( CreateResource(StrCat(kTestDomain, "index.html"), "style.css")); ASSERT_TRUE(input.get() != nullptr); EXPECT_EQ(StrCat(kTestDomain, "style.css"), input->url()); // The absolute input URL is in test.com, but we will only be // able to serve it from localhost, per the origin mapping above. static const char kStyleContent[] = "style content"; const int kOriginTtlSec = 300; SetResponseWithDefaultHeaders("http://localhost/style.css", kContentTypeCss, kStyleContent, kOriginTtlSec); EXPECT_TRUE(ReadIfCached(input)); // When we rewrite the resource as an ouptut, it will show up in the // CDN per the rewrite mapping. GoogleString failure_reason; OutputResourcePtr output(rewrite_driver()->CreateOutputResourceFromResource( RewriteOptions::kCacheExtenderId, rewrite_driver()->default_encoder(), nullptr, input, kRewrittenResource, &failure_reason)); ASSERT_TRUE(output.get() != nullptr); EXPECT_EQ("", failure_reason); // We need to 'Write' an output resource before we can determine its // URL. rewrite_driver()->Write(ResourceVector(), StringPiece(kStyleContent), &kContentTypeCss, StringPiece(), output.get()); EXPECT_EQ(Encode("http://cdn.com/", "ce", "0", "style.css", "css"), output->url()); } class MockRewriteFilter : public RewriteFilter { public: explicit MockRewriteFilter(RewriteDriver* driver) : RewriteFilter(driver) {} ~MockRewriteFilter() override {} const char* id() const override { return "mk"; } const char* Name() const override { return "mock_filter"; } void StartDocumentImpl() override {} void StartElementImpl(HtmlElement* element) override {} void EndElementImpl(HtmlElement* element) override {} private: DISALLOW_COPY_AND_ASSIGN(MockRewriteFilter); }; class CreateMockRewriterCallback : public TestRewriteDriverFactory::CreateRewriterCallback { public: CreateMockRewriterCallback() {} ~CreateMockRewriterCallback() override {} RewriteFilter* Done(RewriteDriver* driver) override { return new MockRewriteFilter(driver); } private: DISALLOW_COPY_AND_ASSIGN(CreateMockRewriterCallback); }; class MockPlatformConfigCallback : public TestRewriteDriverFactory::PlatformSpecificConfigurationCallback { public: explicit MockPlatformConfigCallback(RewriteDriver** result_ptr) : result_ptr_(result_ptr) {} void Done(RewriteDriver* driver) override { *result_ptr_ = driver; } private: RewriteDriver** result_ptr_; DISALLOW_COPY_AND_ASSIGN(MockPlatformConfigCallback); }; // Tests that platform-specific configuration hook runs for various // factory methods. TEST_F(ServerContextTest, TestPlatformSpecificConfiguration) { RewriteDriver* rec_normal_driver = nullptr; RewriteDriver* rec_custom_driver = nullptr; MockPlatformConfigCallback normal_callback(&rec_normal_driver); MockPlatformConfigCallback custom_callback(&rec_custom_driver); factory()->AddPlatformSpecificConfigurationCallback(&normal_callback); RewriteDriver* normal_driver = server_context()->NewRewriteDriver( RequestContext::NewTestRequestContext(server_context()->thread_system())); EXPECT_EQ(normal_driver, rec_normal_driver); factory()->ClearPlatformSpecificConfigurationCallback(); normal_driver->Cleanup(); factory()->AddPlatformSpecificConfigurationCallback(&custom_callback); RewriteDriver* custom_driver = server_context()->NewCustomRewriteDriver( new RewriteOptions(factory()->thread_system()), RequestContext::NewTestRequestContext(server_context()->thread_system())); EXPECT_EQ(custom_driver, rec_custom_driver); custom_driver->Cleanup(); } // Tests that platform-specific rewriters are used for decoding fetches. TEST_F(ServerContextTest, TestPlatformSpecificRewritersDecoding) { GoogleString url = Encode("http://example.com/dir/123/", "mk", "0", "orig", "js"); GoogleUrl gurl(url); RewriteFilter* dummy; // Without the mock rewriter enabled, this URL should not be decoded. OutputResourcePtr bad_output( decoding_driver()->DecodeOutputResource(gurl, &dummy)); ASSERT_TRUE(bad_output.get() == nullptr); // With the mock rewriter enabled, this URL should be decoded. CreateMockRewriterCallback callback; factory()->AddCreateRewriterCallback(&callback); factory()->set_add_platform_specific_decoding_passes(true); factory()->RebuildDecodingDriverForTests(server_context()); // TODO(sligocki): Do we still want to expose decoding_driver() for // platform-specific rewriters? Or should we just use IsPagespeedResource() // in these tests? OutputResourcePtr good_output( decoding_driver()->DecodeOutputResource(gurl, &dummy)); ASSERT_TRUE(good_output.get() != nullptr); EXPECT_EQ(url, good_output->url()); } // Tests that platform-specific rewriters are used for decoding fetches even // if they are only added in AddPlatformSpecificRewritePasses, not // AddPlatformSpecificDecodingPasses. Required for backwards compatibility. TEST_F(ServerContextTest, TestPlatformSpecificRewritersImplicitDecoding) { GoogleString url = Encode("http://example.com/dir/123/", "mk", "0", "orig", "js"); GoogleUrl gurl(url); RewriteFilter* dummy; // The URL should be decoded even if AddPlatformSpecificDecodingPasses is // suppressed. CreateMockRewriterCallback callback; factory()->AddCreateRewriterCallback(&callback); factory()->set_add_platform_specific_decoding_passes(false); factory()->RebuildDecodingDriverForTests(server_context()); OutputResourcePtr good_output( decoding_driver()->DecodeOutputResource(gurl, &dummy)); ASSERT_TRUE(good_output.get() != nullptr); EXPECT_EQ(url, good_output->url()); } // DecodeOutputResource should drop query TEST_F(ServerContextTest, TestOutputResourceFetchQuery) { GoogleString url = Encode("http://example.com/dir/123/", "jm", "0", "orig", "js"); RewriteFilter* dummy; GoogleUrl gurl(StrCat(url, "?query")); OutputResourcePtr output_resource( rewrite_driver()->DecodeOutputResource(gurl, &dummy)); ASSERT_TRUE(output_resource.get() != nullptr); EXPECT_EQ(url, output_resource->url()); } // Input resources and corresponding output resources should keep queries TEST_F(ServerContextTest, TestInputResourceQuery) { const char kUrl[] = "test?param"; ResourcePtr resource(CreateResource(kResourceUrlBase, kUrl)); ASSERT_TRUE(resource.get() != nullptr); EXPECT_EQ(StrCat(GoogleString(kResourceUrlBase), "/", kUrl), resource->url()); GoogleString failure_reason; OutputResourcePtr output(rewrite_driver()->CreateOutputResourceFromResource( "sf", rewrite_driver()->default_encoder(), nullptr, resource, kRewrittenResource, &failure_reason)); ASSERT_TRUE(output.get() != nullptr); EXPECT_EQ("", failure_reason); GoogleString included_name; EXPECT_TRUE(UrlEscaper::DecodeFromUrlSegment(output->name(), &included_name)); EXPECT_EQ(GoogleString(kUrl), included_name); } TEST_F(ServerContextTest, TestRemember404) { // Make sure our resources remember that a page 404'd, for limited time. http_cache()->set_failure_caching_ttl_sec(kFetchStatusUncacheableError, 10000); http_cache()->set_failure_caching_ttl_sec(kFetchStatus4xxError, 100); ResponseHeaders not_found; SetDefaultLongCacheHeaders(&kContentTypeHtml, &not_found); not_found.SetStatusAndReason(HttpStatus::kNotFound); SetFetchResponse("http://example.com/404", not_found, ""); ResourcePtr resource( CreateInputResourceAndReadIfCached("http://example.com/404")); EXPECT_EQ(nullptr, resource.get()); HTTPValue value_out; ResponseHeaders headers_out; EXPECT_EQ( HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatus4xxError), HttpBlockingFind("http://example.com/404", http_cache(), &value_out, &headers_out)); AdvanceTimeMs(150 * Timer::kSecondMs); EXPECT_EQ(kNotFoundResult, HttpBlockingFind("http://example.com/404", http_cache(), &value_out, &headers_out)); } TEST_F(ServerContextTest, TestRememberDropped) { // Fake resource being dropped by adding the appropriate header to the // resource proper. ResponseHeaders not_found; SetDefaultLongCacheHeaders(&kContentTypeHtml, &not_found); not_found.SetStatusAndReason(HttpStatus::kNotFound); not_found.Add(HttpAttributes::kXPsaLoadShed, "1"); SetFetchResponse("http://example.com/404", not_found, ""); ResourcePtr resource( CreateInputResourceAndReadIfCached("http://example.com/404")); EXPECT_EQ(nullptr, resource.get()); HTTPValue value_out; ResponseHeaders headers_out; EXPECT_EQ( HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusDropped), HttpBlockingFind("http://example.com/404", http_cache(), &value_out, &headers_out)); AdvanceTimeMs(11 * Timer::kSecondMs); EXPECT_EQ(kNotFoundResult, HttpBlockingFind("http://example.com/404", http_cache(), &value_out, &headers_out)); } TEST_F(ServerContextTest, TestNonCacheable) { const char kContents[] = "ok"; // Make sure that when we get non-cacheable resources // we mark the fetch as not cacheable in the cache. ResponseHeaders no_cache; SetDefaultLongCacheHeaders(&kContentTypeHtml, &no_cache); no_cache.Replace(HttpAttributes::kCacheControl, "no-cache"); no_cache.ComputeCaching(); SetFetchResponse("http://example.com/", no_cache, kContents); ResourcePtr resource(CreateResource("http://example.com/", "/")); ASSERT_TRUE(resource.get() != nullptr); VerifyContentsCallback callback(resource, kContents); resource->LoadAsync(Resource::kReportFailureIfNotCacheable, rewrite_driver()->request_context(), &callback); callback.AssertCalled(); HTTPValue value_out; ResponseHeaders headers_out; EXPECT_EQ(HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusUncacheable200), HttpBlockingFind("http://example.com/", http_cache(), &value_out, &headers_out)); } TEST_F(ServerContextTest, TestNonCacheableReadResultPolicy) { // Make sure we report the success/failure for non-cacheable resources // depending on the policy. (TestNonCacheable also covers the value). ResponseHeaders no_cache; SetDefaultLongCacheHeaders(&kContentTypeHtml, &no_cache); no_cache.Replace(HttpAttributes::kCacheControl, "no-cache"); no_cache.ComputeCaching(); SetFetchResponse("http://example.com/", no_cache, "stuff"); ResourcePtr resource1(CreateResource("http://example.com/", "/")); ASSERT_TRUE(resource1.get() != nullptr); MockResourceCallback callback1(resource1, factory()->thread_system()); resource1->LoadAsync(Resource::kReportFailureIfNotCacheable, rewrite_driver()->request_context(), &callback1); EXPECT_TRUE(callback1.done()); EXPECT_FALSE(callback1.success()); ResourcePtr resource2(CreateResource("http://example.com/", "/")); ASSERT_TRUE(resource2.get() != nullptr); MockResourceCallback callback2(resource2, factory()->thread_system()); resource2->LoadAsync(Resource::kLoadEvenIfNotCacheable, rewrite_driver()->request_context(), &callback2); EXPECT_TRUE(callback2.done()); EXPECT_TRUE(callback2.success()); } TEST_F(ServerContextTest, TestRememberEmpty) { // Make sure our resources remember that a page is empty, for limited time. http_cache()->set_failure_caching_ttl_sec(kFetchStatusEmpty, 100); ResponseHeaders headers; SetDefaultLongCacheHeaders(&kContentTypeHtml, &headers); headers.SetStatusAndReason(HttpStatus::kOK); static const char kUrl[] = "http://example.com/empty.html"; SetFetchResponse(kUrl, headers, ""); ResourcePtr resource(CreateInputResourceAndReadIfCached(kUrl)); EXPECT_EQ(nullptr, resource.get()); HTTPValue value_out; ResponseHeaders headers_out; EXPECT_EQ(HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusEmpty), HttpBlockingFind(kUrl, http_cache(), &value_out, &headers_out)); AdvanceTimeMs(150 * Timer::kSecondMs); EXPECT_EQ(kNotFoundResult, HttpBlockingFind(kUrl, http_cache(), &value_out, &headers_out)); } TEST_F(ServerContextTest, TestNotRememberEmptyRedirect) { // Parallel to TestRememberEmpty for empty 301 redirect. http_cache()->set_failure_caching_ttl_sec(kFetchStatusEmpty, 100); ResponseHeaders headers; SetDefaultLongCacheHeaders(&kContentTypeHtml, &headers); headers.SetStatusAndReason(HttpStatus::kMovedPermanently); headers.Add(HttpAttributes::kLocation, "http://example.com/destination.html"); static const char kUrl[] = "http://example.com/redirect.html"; SetFetchResponse(kUrl, headers, ""); ResourcePtr resource(CreateInputResourceAndReadIfCached(kUrl)); EXPECT_EQ(nullptr, resource.get()); HTTPValue value_out; ResponseHeaders headers_out; // Currently we are remembering 301 as not cacheable, but in the future if // that changes the important thing here is that we don't remember non-200 // as empty (and thus fail to use them. EXPECT_NE(HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusEmpty), HttpBlockingFind(kUrl, http_cache(), &value_out, &headers_out)); AdvanceTimeMs(150 * Timer::kSecondMs); EXPECT_NE(HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusEmpty), HttpBlockingFind(kUrl, http_cache(), &value_out, &headers_out)); } TEST_F(ServerContextTest, TestVaryOption) { // Make sure that when we get non-cacheable resources // we mark the fetch as not-cacheable in the cache. options()->set_respect_vary(true); ResponseHeaders no_cache; const char kContents[] = "ok"; SetDefaultLongCacheHeaders(&kContentTypeHtml, &no_cache); no_cache.Add(HttpAttributes::kVary, HttpAttributes::kAcceptEncoding); no_cache.Add(HttpAttributes::kVary, HttpAttributes::kUserAgent); no_cache.ComputeCaching(); SetFetchResponse("http://example.com/", no_cache, kContents); ResourcePtr resource(CreateResource("http://example.com/", "/")); ASSERT_TRUE(resource.get() != nullptr); VerifyContentsCallback callback(resource, kContents); resource->LoadAsync(Resource::kReportFailureIfNotCacheable, rewrite_driver()->request_context(), &callback); callback.AssertCalled(); EXPECT_FALSE(resource->IsValidAndCacheable()); HTTPValue valueOut; ResponseHeaders headersOut; EXPECT_EQ(HTTPCache::FindResult(HTTPCache::kRecentFailure, kFetchStatusUncacheable200), HttpBlockingFind("http://example.com/", http_cache(), &valueOut, &headersOut)); } TEST_F(ServerContextTest, TestOutlined) { // Outliner resources should not produce extra cache traffic // due to rname/ entries we can't use anyway. EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(0, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); GoogleString failure_reason; OutputResourcePtr output_resource( rewrite_driver()->CreateOutputResourceWithPath( kUrlPrefix, CssOutlineFilter::kFilterId, "_", kOutlinedResource, &failure_reason)); ASSERT_TRUE(output_resource.get() != nullptr); EXPECT_EQ("", failure_reason); EXPECT_EQ(nullptr, output_resource->cached_result()); EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(0, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); rewrite_driver()->Write(ResourceVector(), "foo", &kContentTypeCss, StringPiece(), output_resource.get()); EXPECT_EQ(nullptr, output_resource->cached_result()); EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(1, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); // Now try fetching again. It should not get a cached_result either. output_resource.reset(rewrite_driver()->CreateOutputResourceWithPath( kUrlPrefix, CssOutlineFilter::kFilterId, "_", kOutlinedResource, &failure_reason)); ASSERT_TRUE(output_resource.get() != nullptr); EXPECT_EQ("", failure_reason); EXPECT_EQ(nullptr, output_resource->cached_result()); EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(1, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); } TEST_F(ServerContextTest, TestOnTheFly) { // Test to make sure that an on-fly insert does not insert the data, // just the rname/ // For derived resources we can and should use the rewrite // summary/metadata cache EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(0, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); GoogleString failure_reason; OutputResourcePtr output_resource( rewrite_driver()->CreateOutputResourceWithPath( kUrlPrefix, RewriteOptions::kCssFilterId, "_", kOnTheFlyResource, &failure_reason)); ASSERT_TRUE(output_resource.get() != nullptr); EXPECT_EQ("", failure_reason); EXPECT_EQ(nullptr, output_resource->cached_result()); EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(0, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); rewrite_driver()->Write(ResourceVector(), "foo", &kContentTypeCss, StringPiece(), output_resource.get()); EXPECT_TRUE(output_resource->cached_result() != nullptr); EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(0, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); } TEST_F(ServerContextTest, TestNotGenerated) { // For derived resources we can and should use the rewrite // summary/metadata cache EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(0, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); GoogleString failure_reason; OutputResourcePtr output_resource( rewrite_driver()->CreateOutputResourceWithPath( kUrlPrefix, RewriteOptions::kCssFilterId, "_", kRewrittenResource, &failure_reason)); ASSERT_TRUE(output_resource.get() != nullptr); EXPECT_EQ("", failure_reason); EXPECT_EQ(nullptr, output_resource->cached_result()); EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(0, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); rewrite_driver()->Write(ResourceVector(), "foo", &kContentTypeCss, StringPiece(), output_resource.get()); EXPECT_TRUE(output_resource->cached_result() != nullptr); EXPECT_EQ(0, lru_cache()->num_hits()); EXPECT_EQ(0, lru_cache()->num_misses()); EXPECT_EQ(1, lru_cache()->num_inserts()); EXPECT_EQ(0, lru_cache()->num_identical_reinserts()); } TEST_F(ServerContextTest, TestHandleBeaconNoLoadParam) { EXPECT_FALSE(server_context()->HandleBeacon( "", UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext())); } TEST_F(ServerContextTest, TestHandleBeaconInvalidLoadParam) { EXPECT_FALSE(server_context()->HandleBeacon( "ets=asd", UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext())); } TEST_F(ServerContextTest, TestHandleBeaconNoUrl) { EXPECT_FALSE(server_context()->HandleBeacon( "ets=load:34", UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext())); } TEST_F(ServerContextTest, TestHandleBeaconInvalidUrl) { EXPECT_FALSE(server_context()->HandleBeacon( "url=%2f%2finvalidurl&ets=load:34", UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext())); } TEST_F(ServerContextTest, TestHandleBeaconMissingValue) { EXPECT_FALSE(server_context()->HandleBeacon( "url=http%3A%2F%2Flocalhost%3A8080%2Findex.html&ets=load:", UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext())); } TEST_F(ServerContextTest, TestHandleBeacon) { EXPECT_TRUE(server_context()->HandleBeacon( "url=http%3A%2F%2Flocalhost%3A8080%2Findex.html&ets=load:34", UserAgentMatcherTestBase::kChromeUserAgent, CreateRequestContext())); } class BeaconTest : public ServerContextTest { protected: BeaconTest() : property_cache_(nullptr) {} ~BeaconTest() override {} void SetUp() override { ServerContextTest::SetUp(); property_cache_ = server_context()->page_property_cache(); property_cache_->set_enabled(true); const PropertyCache::Cohort* beacon_cohort = SetupCohort(property_cache_, RewriteDriver::kBeaconCohort); server_context()->set_beacon_cohort(beacon_cohort); server_context()->set_critical_images_finder(new BeaconCriticalImagesFinder( beacon_cohort, factory()->nonce_generator(), statistics())); server_context()->set_critical_selector_finder( new BeaconCriticalSelectorFinder( beacon_cohort, factory()->nonce_generator(), statistics())); ResetDriver(); candidates_.insert("#foo"); candidates_.insert(".bar"); candidates_.insert("img"); } void ResetDriver() { rewrite_driver()->Clear(); SetDriverRequestHeaders(); } MockPropertyPage* MockPageForUA(StringPiece user_agent) { UserAgentMatcher::DeviceType device_type = server_context()->user_agent_matcher()->GetDeviceTypeForUA(user_agent); MockPropertyPage* page = NewMockPage(kUrlPrefix, kOptionsHash, device_type); property_cache_->Read(page); return page; } void InsertCssBeacon(StringPiece user_agent) { // Simulate effects on pcache of CSS beacon insertion. rewrite_driver()->set_property_page(MockPageForUA(user_agent)); factory()->mock_timer()->AdvanceMs( options()->beacon_reinstrument_time_sec() * Timer::kSecondMs); last_beacon_metadata_ = server_context()->critical_selector_finder()->PrepareForBeaconInsertion( candidates_, rewrite_driver()); ASSERT_EQ(kBeaconWithNonce, last_beacon_metadata_.status); ASSERT_FALSE(last_beacon_metadata_.nonce.empty()); rewrite_driver()->property_page()->WriteCohort( server_context()->beacon_cohort()); } void InsertImageBeacon(StringPiece user_agent) { // Simulate effects on pcache of image beacon insertion. rewrite_driver()->set_property_page(MockPageForUA(user_agent)); // Some of the critical image tests send enough beacons with the same set of // images that we can go into low frequency beaconing mode, so advance time // by the low frequency rebeacon interval. factory()->mock_timer()->AdvanceMs( options()->beacon_reinstrument_time_sec() * Timer::kSecondMs * kLowFreqBeaconMult); last_beacon_metadata_ = server_context()->critical_images_finder()->PrepareForBeaconInsertion( rewrite_driver()); ASSERT_EQ(kBeaconWithNonce, last_beacon_metadata_.status); ASSERT_FALSE(last_beacon_metadata_.nonce.empty()); rewrite_driver()->property_page()->WriteCohort( server_context()->beacon_cohort()); } // Send a beacon through ServerContext::HandleBeacon and verify that the // property cache entries for critical images, critical selectors and rendered // dimensions of images were updated correctly. void TestBeacon(const StringSet* critical_image_hashes, const StringSet* critical_css_selectors, const GoogleString* rendered_images_json_map, StringPiece user_agent) { ASSERT_EQ(kBeaconWithNonce, last_beacon_metadata_.status) << "Remember to insert a beacon!"; // Setup the beacon_url and pass to HandleBeacon. GoogleString beacon_url = StrCat( "url=http%3A%2F%2Fwww.example.com" "&oh=", kOptionsHash, "&n=", last_beacon_metadata_.nonce); if (critical_image_hashes != nullptr) { StrAppend(&beacon_url, "&ci="); AppendJoinCollection(&beacon_url, *critical_image_hashes, ","); } if (critical_css_selectors != nullptr) { StrAppend(&beacon_url, "&cs="); AppendJoinCollection(&beacon_url, *critical_css_selectors, ","); } if (rendered_images_json_map != nullptr) { StrAppend(&beacon_url, "&rd=", *rendered_images_json_map); } EXPECT_TRUE(server_context()->HandleBeacon(beacon_url, user_agent, CreateRequestContext())); // Read the property cache value for critical images, and verify that it has // the expected value. ResetDriver(); std::unique_ptr<MockPropertyPage> page(MockPageForUA(user_agent)); rewrite_driver()->set_property_page(page.release()); if (critical_image_hashes != nullptr) { critical_html_images_ = server_context()->critical_images_finder()->GetHtmlCriticalImages( rewrite_driver()); } if (critical_css_selectors != nullptr) { critical_css_selectors_ = server_context()->critical_selector_finder()->GetCriticalSelectors( rewrite_driver()); } if (rendered_images_json_map != nullptr) { rendered_images_.reset( server_context() ->critical_images_finder() ->ExtractRenderedImageDimensionsFromCache(rewrite_driver())); } } PropertyCache* property_cache_; // These fields hold data deserialized from the pcache after TestBeacon. StringSet critical_html_images_; StringSet critical_css_selectors_; // This field holds the data deserialized from pcache after a BeaconTest call. std::unique_ptr<RenderedImages> rendered_images_; // This field holds candidate critical css selectors. StringSet candidates_; BeaconMetadata last_beacon_metadata_; }; TEST_F(BeaconTest, BasicPcacheSetup) { const PropertyCache::Cohort* cohort = property_cache_->GetCohort(RewriteDriver::kBeaconCohort); UserAgentMatcher::DeviceType device_type = server_context()->user_agent_matcher()->GetDeviceTypeForUA( UserAgentMatcherTestBase::kChromeUserAgent); std::unique_ptr<MockPropertyPage> page( NewMockPage(kUrlPrefix, kOptionsHash, device_type)); property_cache_->Read(page.get()); PropertyValue* property = page->GetProperty(cohort, "critical_images"); EXPECT_FALSE(property->has_value()); } TEST_F(BeaconTest, HandleBeaconRenderedDimensionsofImages) { GoogleString img1 = "http://www.example.com/img1.png"; GoogleString hash1 = IntegerToString( HashString<CasePreserve, unsigned>(img1.c_str(), img1.size())); options()->EnableFilter(RewriteOptions::kResizeToRenderedImageDimensions); RenderedImages rendered_images; RenderedImages_Image* images = rendered_images.add_image(); images->set_src(hash1); images->set_rendered_width(40); images->set_rendered_height(50); GoogleString json_map_rendered_dimensions = StrCat( "{\"", hash1, "\":{\"rw\":40,", "\"rh\":50,\"ow\":160,\"oh\":200}}"); InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent); TestBeacon(nullptr, nullptr, &json_map_rendered_dimensions, UserAgentMatcherTestBase::kChromeUserAgent); ASSERT_FALSE(rendered_images_.get() == nullptr); EXPECT_EQ(1, rendered_images_->image_size()); EXPECT_STREQ(hash1, rendered_images_->image(0).src()); EXPECT_EQ(40, rendered_images_->image(0).rendered_width()); EXPECT_EQ(50, rendered_images_->image(0).rendered_height()); } TEST_F(BeaconTest, HandleBeaconCritImages) { GoogleString img1 = "http://www.example.com/img1.png"; GoogleString img2 = "http://www.example.com/img2.png"; GoogleString hash1 = IntegerToString( HashString<CasePreserve, unsigned>(img1.c_str(), img1.size())); GoogleString hash2 = IntegerToString( HashString<CasePreserve, unsigned>(img2.c_str(), img2.size())); StringSet critical_image_hashes; critical_image_hashes.insert(hash1); InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent); TestBeacon(&critical_image_hashes, nullptr, nullptr, UserAgentMatcherTestBase::kChromeUserAgent); EXPECT_STREQ(hash1, JoinCollection(critical_html_images_, ",")); // Beacon both images as critical. Since we require 80% support, img2 won't // show as critical until we've beaconed four times. It doesn't require five // beacon results because we weight recent beacon values more heavily and // beacon support decays over time. critical_image_hashes.insert(hash2); for (int i = 0; i < 3; ++i) { InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent); TestBeacon(&critical_image_hashes, nullptr, nullptr, UserAgentMatcherTestBase::kChromeUserAgent); EXPECT_STREQ(hash1, JoinCollection(critical_html_images_, ",")); } GoogleString expected = StrCat(hash1, ",", hash2); InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent); TestBeacon(&critical_image_hashes, nullptr, nullptr, UserAgentMatcherTestBase::kChromeUserAgent); EXPECT_STREQ(expected, JoinCollection(critical_html_images_, ",")); // Test with a different user agent, providing support only for img1. critical_image_hashes.clear(); critical_image_hashes.insert(hash1); InsertImageBeacon(UserAgentMatcherTestBase::kIPhoneUserAgent); TestBeacon(&critical_image_hashes, nullptr, nullptr, UserAgentMatcherTestBase::kIPhoneUserAgent); EXPECT_STREQ(hash1, JoinCollection(critical_html_images_, ",")); // Beacon once more with the original user agent and with only img1; img2 // loses 80% support again. InsertImageBeacon(UserAgentMatcherTestBase::kChromeUserAgent); TestBeacon(&critical_image_hashes, nullptr, nullptr, UserAgentMatcherTestBase::kChromeUserAgent); EXPECT_STREQ(hash1, JoinCollection(critical_html_images_, ",")); } TEST_F(BeaconTest, HandleBeaconCriticalCss) { InsertCssBeacon(UserAgentMatcherTestBase::kChromeUserAgent); StringSet critical_css_selector; critical_css_selector.insert("%23foo"); critical_css_selector.insert(".bar"); critical_css_selector.insert("%23noncandidate"); TestBeacon(nullptr, &critical_css_selector, nullptr, UserAgentMatcherTestBase::kChromeUserAgent); EXPECT_STREQ("#foo,.bar", JoinCollection(critical_css_selectors_, ",")); // Send another beacon response, and make sure we are storing a history of // responses. InsertCssBeacon(UserAgentMatcherTestBase::kChromeUserAgent); critical_css_selector.clear(); critical_css_selector.insert(".bar"); critical_css_selector.insert("img"); critical_css_selector.insert("%23noncandidate"); TestBeacon(nullptr, &critical_css_selector, nullptr, UserAgentMatcherTestBase::kChromeUserAgent); EXPECT_STREQ("#foo,.bar,img", JoinCollection(critical_css_selectors_, ",")); } TEST_F(BeaconTest, EmptyCriticalCss) { InsertCssBeacon(UserAgentMatcherTestBase::kChromeUserAgent); StringSet empty_critical_selectors; TestBeacon(nullptr, &empty_critical_selectors, nullptr, UserAgentMatcherTestBase::kChromeUserAgent); EXPECT_TRUE(critical_css_selectors_.empty()); } class ResourceFreshenTest : public ServerContextTest { protected: void SetUp() override { ServerContextTest::SetUp(); HTTPCache::InitStats(statistics()); expirations_ = statistics()->GetVariable(HTTPCache::kCacheExpirations); CHECK(expirations_ != nullptr); SetDefaultLongCacheHeaders(&kContentTypePng, &response_headers_); response_headers_.SetStatusAndReason(HttpStatus::kOK); response_headers_.RemoveAll(HttpAttributes::kCacheControl); response_headers_.RemoveAll(HttpAttributes::kExpires); } Variable* expirations_; ResponseHeaders response_headers_; }; // Many resources expire in 5 minutes, because that is our default for // when caching headers are not present. This test ensures that iff // we ask for the resource when there's just a minute left, we proactively // fetch it rather than allowing it to expire. TEST_F(ResourceFreshenTest, TestFreshenImminentlyExpiringResources) { SetupWaitFetcher(); FetcherUpdateDateHeaders(); // Make sure we don't try to insert non-cacheable resources // into the cache wastefully, but still fetch them well. int max_age_sec = RewriteOptions::kDefaultImplicitCacheTtlMs / Timer::kSecondMs; response_headers_.Add(HttpAttributes::kCacheControl, absl::StrFormat("max-age=%d", max_age_sec)); SetFetchResponse(kResourceUrl, response_headers_, "foo"); // The test here is not that the ReadIfCached will succeed, because // it's a fake url fetcher. StartRead(); CallFetcherCallbacks(); EXPECT_TRUE(ResourceIsCached()); // Now let the time expire with no intervening fetches to freshen the cache. // This is because we do not proactively initiate refreshes for all resources; // only the ones that are actually asked for on a regular basis. So a // completely inactive site will not see its resources freshened. AdvanceTimeMs((max_age_sec + 1) * Timer::kSecondMs); expirations_->Clear(); StartRead(); EXPECT_EQ(1, expirations_->Get()); expirations_->Clear(); CallFetcherCallbacks(); EXPECT_TRUE(ResourceIsCached()); // But if we have just a little bit of traffic then when we get a request // for a soon-to-expire resource it will auto-freshen. AdvanceTimeMs((1 + (max_age_sec * 4) / 5) * Timer::kSecondMs); EXPECT_TRUE(ResourceIsCached()); CallFetcherCallbacks(); // freshens cache. AdvanceTimeMs((max_age_sec / 5) * Timer::kSecondMs); EXPECT_TRUE(ResourceIsCached()); // Yay, no cache misses after 301 seconds EXPECT_EQ(0, expirations_->Get()); } // Tests that freshining will not be performed when we have caching // forced. Nothing will ever be evicted due to time, so there is no // need to freshen. TEST_F(ResourceFreshenTest, NoFreshenOfForcedCachedResources) { http_cache()->set_force_caching(true); FetcherUpdateDateHeaders(); response_headers_.Add(HttpAttributes::kCacheControl, "max-age=0"); SetFetchResponse(kResourceUrl, response_headers_, "foo"); // We should get just 1 fetch. If we were aggressively freshening // we would get 2. EXPECT_TRUE(ResourceIsCached()); EXPECT_EQ(1, counting_url_async_fetcher()->fetch_count()); // There should be no extra fetches required because our cache is // still active. We shouldn't have needed an extra fetch to freshen, // either, because the cache expiration time is irrelevant -- we are // forcing caching so we consider the resource to always be fresh. // So even after an hour we should have no expirations. AdvanceTimeMs(1 * Timer::kHourMs); EXPECT_TRUE(ResourceIsCached()); EXPECT_EQ(1, counting_url_async_fetcher()->fetch_count()); // Nothing expires with force-caching on. EXPECT_EQ(0, expirations_->Get()); } // Tests that freshining will not occur for short-lived resources, // which could impact the performance of the server. TEST_F(ResourceFreshenTest, NoFreshenOfShortLivedResources) { FetcherUpdateDateHeaders(); int max_age_sec = RewriteOptions::kDefaultImplicitCacheTtlMs / Timer::kSecondMs - 1; response_headers_.Add(HttpAttributes::kCacheControl, absl::StrFormat("max-age=%d", max_age_sec)); SetFetchResponse(kResourceUrl, response_headers_, "foo"); EXPECT_TRUE(ResourceIsCached()); EXPECT_EQ(1, counting_url_async_fetcher()->fetch_count()); // There should be no extra fetches required because our cache is // still active. We shouldn't have needed an extra fetch to freshen, // either. AdvanceTimeMs((max_age_sec - 1) * Timer::kSecondMs); EXPECT_TRUE(ResourceIsCached()); EXPECT_EQ(1, counting_url_async_fetcher()->fetch_count()); EXPECT_EQ(0, expirations_->Get()); // Now let the resource expire. We'll need another fetch since we did not // freshen. AdvanceTimeMs(2 * Timer::kSecondMs); EXPECT_TRUE(ResourceIsCached()); EXPECT_EQ(2, counting_url_async_fetcher()->fetch_count()); EXPECT_EQ(1, expirations_->Get()); } class ServerContextShardedTest : public ServerContextTest { protected: void SetUp() override { ServerContextTest::SetUp(); EXPECT_TRUE(options()->WriteableDomainLawyer()->AddShard( "example.com", "shard0.com,shard1.com", message_handler())); } }; TEST_F(ServerContextShardedTest, TestNamed) { GoogleString url = Encode("http://example.com/dir/123/", "jm", "0", "orig", "js"); GoogleString failure_reason; OutputResourcePtr output_resource( rewrite_driver()->CreateOutputResourceWithPath( "http://example.com/dir/", "jm", "orig.js", kRewrittenResource, &failure_reason)); ASSERT_TRUE(output_resource.get()); EXPECT_EQ("", failure_reason); ASSERT_TRUE(rewrite_driver()->Write(ResourceVector(), "alert('hello');", &kContentTypeJavascript, StringPiece(), output_resource.get())); // This always gets mapped to shard0 because we are using the mock // hasher for the content hash. Note that the sharding sensitivity // to the hash value is tested in DomainLawyerTest.Shard, and will // also be covered in a system test. EXPECT_EQ(Encode("http://shard0.com/dir/", "jm", "0", "orig.js", "js"), output_resource->url()); } TEST_F(ServerContextTest, TestMergeNonCachingResponseHeaders) { ResponseHeaders input, output; input.Add("X-Extra-Header", "Extra Value"); // should be copied to output input.Add(HttpAttributes::kCacheControl, "max-age=300"); // should not be server_context()->MergeNonCachingResponseHeaders(input, &output); ConstStringStarVector v; EXPECT_FALSE(output.Lookup(HttpAttributes::kCacheControl, &v)); ASSERT_TRUE(output.Lookup("X-Extra-Header", &v)); ASSERT_EQ(1, v.size()); EXPECT_EQ("Extra Value", *v[0]); } class ServerContextCacheControlTest : public ServerContextTest { protected: void SetUp() override { ServerContextTest::SetUp(); implicit_public_100_ = CreateCustomCachingResource("ipub_100", 100, ""); implicit_public_200_ = CreateCustomCachingResource("ipub_200", 200, ""); explicit_public_200_ = CreateCustomCachingResource("epub_200", 200, ",public"); private_300_ = CreateCustomCachingResource("pri_300", 300, ",private"); private_400_ = CreateCustomCachingResource("pri_400", 400, ",private"); no_cache_150_ = CreateCustomCachingResource("noc_150", 400, ",no-cache"); no_store_200_ = CreateCustomCachingResource("nos_200", 200, ",no-store"); DefaultHeaders(&response_headers_); } GoogleString LongCacheTtl() const { return StrCat("max-age=", Integer64ToString(ServerContext::kGeneratedMaxAgeMs / Timer::kSecondMs)); } bool HasCacheControl(StringPiece value) { return response_headers_.HasValue(HttpAttributes::kCacheControl, value); } ResourcePtr implicit_public_100_; ResourcePtr implicit_public_200_; ResourcePtr explicit_public_200_; ResourcePtr private_300_; ResourcePtr private_400_; ResourcePtr no_cache_150_; ResourcePtr no_store_200_; ResourceVector resources_; ResponseHeaders response_headers_; }; TEST_F(ServerContextCacheControlTest, ImplicitPublic) { // If we feed in just implicitly public resources, we should get // something with ultra-long TTL, regardless of how soon they // expire. resources_.push_back(implicit_public_100_); resources_.push_back(implicit_public_200_); server_context()->ApplyInputCacheControl(resources_, &response_headers_); EXPECT_STREQ(LongCacheTtl(), response_headers_.Lookup1(HttpAttributes::kCacheControl)); } TEST_F(ServerContextCacheControlTest, ExplicitPublic) { // An explicit 'public' gets reflected in the output. resources_.push_back(explicit_public_200_); server_context()->ApplyInputCacheControl(resources_, &response_headers_); EXPECT_TRUE(HasCacheControl("public")); EXPECT_FALSE(HasCacheControl("private")); EXPECT_TRUE(HasCacheControl(LongCacheTtl())); } TEST_F(ServerContextCacheControlTest, Private) { // If an input is private, however, we must mark output appropriately // and not cache-extend. resources_.push_back(implicit_public_100_); resources_.push_back(private_300_); resources_.push_back(private_400_); server_context()->ApplyInputCacheControl(resources_, &response_headers_); EXPECT_FALSE(HasCacheControl("public")); EXPECT_TRUE(HasCacheControl("private")); EXPECT_TRUE(HasCacheControl("max-age=100")); } TEST_F(ServerContextCacheControlTest, NoCache) { // Similarly no-cache should be incorporated --- but then we also need // to have 0 ttl. resources_.push_back(implicit_public_100_); resources_.push_back(private_300_); resources_.push_back(private_400_); resources_.push_back(no_cache_150_); server_context()->ApplyInputCacheControl(resources_, &response_headers_); EXPECT_FALSE(HasCacheControl("public")); EXPECT_TRUE(HasCacheControl("no-cache")); EXPECT_TRUE(HasCacheControl("max-age=0")); } TEST_F(ServerContextCacheControlTest, NoStore) { // Make sure we save no-store as well. resources_.push_back(implicit_public_100_); resources_.push_back(private_300_); resources_.push_back(private_400_); resources_.push_back(no_cache_150_); resources_.push_back(no_store_200_); server_context()->ApplyInputCacheControl(resources_, &response_headers_); EXPECT_FALSE(HasCacheControl("public")); EXPECT_TRUE(HasCacheControl("no-cache")); EXPECT_TRUE(HasCacheControl("no-store")); EXPECT_TRUE(HasCacheControl("max-age=0")); } TEST_F(ServerContextTest, WriteChecksInputVector) { // Make sure ->Write incorporates the cache control info from inputs, // and doesn't cache a private resource improperly. Also make sure // we get the charset right (including quoting). ResourcePtr private_400( CreateCustomCachingResource("pri_400", 400, ",private")); // Should have the 'it's not cacheable!' entry here; see also below. EXPECT_EQ(1, http_cache()->cache_inserts()->Get()); GoogleString failure_reason; OutputResourcePtr output_resource( rewrite_driver()->CreateOutputResourceFromResource( "cf", rewrite_driver()->default_encoder(), nullptr /* no context*/, private_400, kRewrittenResource, &failure_reason)); ASSERT_TRUE(output_resource.get() != nullptr); EXPECT_EQ("", failure_reason); rewrite_driver()->Write(ResourceVector(1, private_400), "boo!", &kContentTypeText, "\"\\koi8-r\"", // covers escaping behavior, too. output_resource.get()); ResponseHeaders* headers = output_resource->response_headers(); EXPECT_FALSE(headers->HasValue(HttpAttributes::kCacheControl, "public")); EXPECT_TRUE(headers->HasValue(HttpAttributes::kCacheControl, "private")); EXPECT_TRUE(headers->HasValue(HttpAttributes::kCacheControl, "max-age=400")); EXPECT_STREQ("text/plain; charset=\"\\koi8-r\"", headers->Lookup1(HttpAttributes::kContentType)); // Make sure nothing extra in the cache at this point. EXPECT_EQ(1, http_cache()->cache_inserts()->Get()); } TEST_F(ServerContextTest, IsPagespeedResource) { GoogleUrl rewritten( Encode("http://shard0.com/dir/", "jm", "0", "orig.js", "js")); EXPECT_TRUE(server_context()->IsPagespeedResource(rewritten)); GoogleUrl normal("http://jqueryui.com/jquery-1.6.2.js"); EXPECT_FALSE(server_context()->IsPagespeedResource(normal)); } TEST_F(ServerContextTest, PartlyFailedFetch) { // Regression test for invalid Resource state when the fetch physically // succeeds but does not get added to cache due to invalid cacheability. // In that case, we would end up with headers claiming successful fetch, // but an HTTPValue without headers set (which would also crash on // access if no data was emitted by fetcher via Write). static const char kCssName[] = "a.css"; GoogleString abs_url = AbsolutifyUrl(kCssName); ResponseHeaders non_cacheable; SetDefaultLongCacheHeaders(&kContentTypeCss, &non_cacheable); non_cacheable.SetDateAndCaching(start_time_ms() /* date */, 0 /* ttl */, "private, no-cache"); non_cacheable.ComputeCaching(); SetFetchResponse(abs_url, non_cacheable, "foo"); // We tell the fetcher to quash the zero-bytes writes, as that behavior // (which Serf has) made the bug more severe, with not only // loaded() and HttpStatusOk() lying, but also contents() crashing. mock_url_fetcher()->set_omit_empty_writes(true); // We tell the fetcher to output the headers and then immediately fail. mock_url_fetcher()->set_fail_after_headers(true); GoogleUrl gurl(abs_url); SetBaseUrlForFetch(abs_url); bool is_authorized; ResourcePtr resource = rewrite_driver()->CreateInputResource( gurl, RewriteDriver::InputRole::kStyle, &is_authorized); ASSERT_TRUE(resource.get() != nullptr); EXPECT_TRUE(is_authorized); MockResourceCallback callback(resource, factory()->thread_system()); resource->LoadAsync(Resource::kReportFailureIfNotCacheable, rewrite_driver()->request_context(), &callback); EXPECT_TRUE(callback.done()); EXPECT_FALSE(callback.success()); EXPECT_FALSE(resource->IsValidAndCacheable()); EXPECT_FALSE(resource->loaded()); EXPECT_FALSE(resource->HttpStatusOk()) << " Unexpectedly got access to resource contents:" << resource->ExtractUncompressedContents(); } TEST_F(ServerContextTest, LoadFromFileReadAsync) { // This reads a resource twice, to make sure that there is no misbehavior // (read: check failures or crashes) when cache invalidation logic tries to // deal with FileInputResource. const char kContents[] = "lots of bits of data"; options()->file_load_policy()->Associate("http://test.com/", "/test/"); GoogleUrl test_url("http://test.com/a.css"); // Init file resources. WriteFile("/test/a.css", kContents); SetBaseUrlForFetch("http://test.com"); bool unused; ResourcePtr resource(rewrite_driver()->CreateInputResource( test_url, RewriteDriver::InputRole::kStyle, &unused)); VerifyContentsCallback callback(resource, kContents); resource->LoadAsync(Resource::kReportFailureIfNotCacheable, rewrite_driver()->request_context(), &callback); callback.AssertCalled(); resource = rewrite_driver()->CreateInputResource( test_url, RewriteDriver::InputRole::kStyle, &unused); VerifyContentsCallback callback2(resource, kContents); resource->LoadAsync(Resource::kReportFailureIfNotCacheable, rewrite_driver()->request_context(), &callback2); callback2.AssertCalled(); } namespace { void CheckMatchesHeaders(const ResponseHeaders& headers, const InputInfo& input) { ASSERT_TRUE(input.has_type()); EXPECT_EQ(InputInfo::CACHED, input.type()); EXPECT_EQ(headers.has_last_modified_time_ms(), input.has_last_modified_time_ms()); EXPECT_EQ(headers.last_modified_time_ms(), input.last_modified_time_ms()); ASSERT_TRUE(input.has_expiration_time_ms()); EXPECT_EQ(headers.CacheExpirationTimeMs(), input.expiration_time_ms()); ASSERT_TRUE(input.has_date_ms()); EXPECT_EQ(headers.date_ms(), input.date_ms()); } } // namespace TEST_F(ServerContextTest, FillInPartitionInputInfo) { // Test for Resource::FillInPartitionInputInfo. const char kUrl[] = "http://example.com/page.html"; const char kContents[] = "bits"; SetBaseUrlForFetch("http://example.com/"); ResponseHeaders headers; SetDefaultLongCacheHeaders(&kContentTypeHtml, &headers); headers.ComputeCaching(); SetFetchResponse(kUrl, headers, kContents); GoogleUrl gurl(kUrl); bool unused; ResourcePtr resource(rewrite_driver()->CreateInputResource( gurl, RewriteDriver::InputRole::kUnknown, &unused)); VerifyContentsCallback callback(resource, kContents); resource->LoadAsync(Resource::kReportFailureIfNotCacheable, rewrite_driver()->request_context(), &callback); callback.AssertCalled(); InputInfo with_hash, without_hash; resource->FillInPartitionInputInfo(Resource::kIncludeInputHash, &with_hash); resource->FillInPartitionInputInfo(Resource::kOmitInputHash, &without_hash); CheckMatchesHeaders(headers, with_hash); CheckMatchesHeaders(headers, without_hash); ASSERT_TRUE(with_hash.has_input_content_hash()); EXPECT_STREQ("zEEebBNnDlISRim4rIP30", with_hash.input_content_hash()); EXPECT_FALSE(without_hash.has_input_content_hash()); resource->response_headers()->RemoveAll(HttpAttributes::kLastModified); resource->response_headers()->ComputeCaching(); EXPECT_FALSE(resource->response_headers()->has_last_modified_time_ms()); InputInfo without_last_modified; resource->FillInPartitionInputInfo(Resource::kOmitInputHash, &without_last_modified); CheckMatchesHeaders(*resource->response_headers(), without_last_modified); } // Test of referer for BackgroundFetch: When the resource fetching request // header misses referer, we set the driver base url as its referer. TEST_F(ServerContextTest, TestRefererBackgroundFetch) { RefererTest(nullptr, true); EXPECT_EQ(rewrite_driver()->base_url().Spec(), mock_url_fetcher()->last_referer()); } // Test of referer for NonBackgroundFetch: When the resource fetching request // header misses referer and the original request referer header misses, no // referer would be added. TEST_F(ServerContextTest, TestRefererNonBackgroundFetch) { RequestHeaders headers; RefererTest(&headers, false); EXPECT_EQ("", mock_url_fetcher()->last_referer()); } // Test of referer for NonBackgroundFetch: When the resource fetching request // header misses referer but the original request header has referer set, we set // this referer as the referer of resource fetching request. TEST_F(ServerContextTest, TestRefererNonBackgroundFetchWithDriverRefer) { RequestHeaders headers; const char kReferer[] = "http://other.com/"; headers.Add(HttpAttributes::kReferer, kReferer); RefererTest(&headers, false); EXPECT_EQ(kReferer, mock_url_fetcher()->last_referer()); } // Regression test for RewriteTestBase::DefaultResponseHeaders, which is based // on ServerContext methods. It used to not set 'Expires' correctly. TEST_F(ServerContextTest, RewriteTestBaseDefaultResponseHeaders) { ResponseHeaders headers; DefaultResponseHeaders(kContentTypeCss, 100 /* ttl_sec */, &headers); int64 expire_time_ms = 0; ASSERT_TRUE( headers.ParseDateHeader(HttpAttributes::kExpires, &expire_time_ms)); EXPECT_EQ(timer()->NowMs() + 100 * Timer::kSecondMs, expire_time_ms); } } // namespace net_instaweb
77,621
24,110
/***************************************************************************************** * * * OpenSpace * * * * Copyright (c) 2014-2021 * * * * 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 <openspace/scene/lightsource.h> #include <openspace/documentation/documentation.h> #include <openspace/documentation/verifier.h> #include <openspace/util/factorymanager.h> #include <openspace/scene/scenegraphnode.h> #include <openspace/util/updatestructures.h> #include <ghoul/logging/logmanager.h> #include <ghoul/misc/dictionary.h> #include <ghoul/misc/templatefactory.h> namespace { constexpr const char* KeyType = "Type"; constexpr const char* KeyIdentifier = "Identifier"; constexpr openspace::properties::Property::PropertyInfo EnabledInfo = { "Enabled", "Enabled", "Whether the light source is enabled or not" }; } // namespace namespace openspace { bool LightSource::isEnabled() const { return _enabled; } documentation::Documentation LightSource::Documentation() { using namespace openspace::documentation; return { "Light Source", "core_light_source", { { KeyType, new StringAnnotationVerifier("Must name a valid LightSource type"), Optional::No, "The type of the light source that is described in this element. " "The available types of light sources depend on the configuration " "of the application and can be written to disk on " "application startup into the FactoryDocumentation." }, { KeyIdentifier, new StringVerifier, Optional::No, "The identifier of the light source." }, { EnabledInfo.identifier, new BoolVerifier, Optional::Yes, EnabledInfo.description } } }; } std::unique_ptr<LightSource> LightSource::createFromDictionary( const ghoul::Dictionary& dictionary) { documentation::testSpecificationAndThrow(Documentation(), dictionary, "LightSource"); const std::string timeFrameType = dictionary.value<std::string>(KeyType); auto factory = FactoryManager::ref().factory<LightSource>(); LightSource* source = factory->create(timeFrameType, dictionary); const std::string identifier = dictionary.value<std::string>(KeyIdentifier); source->setIdentifier(identifier); return std::unique_ptr<LightSource>(source); } LightSource::LightSource() : properties::PropertyOwner({ "LightSource" }) , _enabled(EnabledInfo, true) { addProperty(_enabled); } LightSource::LightSource(const ghoul::Dictionary& dictionary) : properties::PropertyOwner({ "LightSource" }) , _enabled(EnabledInfo, true) { if (dictionary.hasValue<bool>(EnabledInfo.identifier)) { _enabled = dictionary.value<bool>(EnabledInfo.identifier); } addProperty(_enabled); } bool LightSource::initialize() { return true; } } // namespace openspace
5,018
1,217
#include <iostream> using std::cout; int main(void) { for (int i = 0; i < 10;) { cout << i; } int i = 0; for (;;) { cout << i; } } // i jedan i drugi for loop rade infinite loop
222
92
// Copyright (c) 2018-2021 The Cash2 developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "gtest/gtest.h" #include "Logging/ConsoleLogger.h" using namespace Logging; // constructor TEST(ConsoleLogger, 1) { ConsoleLogger logger1; Level level = Level::DEBUGGING; ConsoleLogger logger2(level); ConsoleLogger logger3(Level::FATAL); ConsoleLogger logger4(Level::ERROR); ConsoleLogger logger5(Level::WARNING); ConsoleLogger logger6(Level::INFO); ConsoleLogger logger7(Level::TRACE); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
714
249
/* * Copyright (c) Facebook, 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 <sstream> #include <boost/algorithm/string/trim.hpp> #include <boost/filesystem/fstream.hpp> #include <fmt/format.h> #include <mariana-trench/Assert.h> #include <mariana-trench/JsonValidation.h> #include <mariana-trench/Log.h> #include <mariana-trench/Redex.h> namespace marianatrench { namespace { std::string invalid_argument_message( const Json::Value& value, const std::optional<std::string>& field, const std::string& expected) { auto field_information = field ? fmt::format(" for field `{}`", *field) : ""; return fmt::format( "Error validating `{}`. Expected {}{}.", boost::algorithm::trim_copy(JsonValidation::to_styled_string(value)), expected, field_information); } } // namespace JsonValidationError::JsonValidationError( const Json::Value& value, const std::optional<std::string>& field, const std::string& expected) : std::invalid_argument(invalid_argument_message(value, field, expected)) {} void JsonValidation::validate_object(const Json::Value& value) { if (value.isNull() || !value.isObject()) { throw JsonValidationError( value, /* field */ std::nullopt, /* expected */ "non-null object"); } } const Json::Value& JsonValidation::object( const Json::Value& value, const std::string& field) { validate_object(value); const auto& attribute = value[field]; if (attribute.isNull() || !attribute.isObject()) { throw JsonValidationError(value, field, /* expected */ "non-null object"); } return attribute; } std::string JsonValidation::string(const Json::Value& value) { if (value.isNull() || !value.isString()) { throw JsonValidationError( value, /* field */ std::nullopt, /* expected */ "string"); } return value.asString(); } std::string JsonValidation::string( const Json::Value& value, const std::string& field) { validate_object(value); const auto& string = value[field]; if (string.isNull() || !string.isString()) { throw JsonValidationError(value, field, /* expected */ "string"); } return string.asString(); } int JsonValidation::integer(const Json::Value& value) { if (value.isNull() || !value.isInt()) { throw JsonValidationError( value, /* field */ std::nullopt, /* expected */ "integer"); } return value.asInt(); } int JsonValidation::integer( const Json::Value& value, const std::string& field) { validate_object(value); const auto& integer = value[field]; if (integer.isNull() || !integer.isInt()) { throw JsonValidationError(value, field, /* expected */ "integer"); } return integer.asInt(); } bool JsonValidation::boolean(const Json::Value& value) { if (value.isNull() || !value.isBool()) { throw JsonValidationError( value, /* field */ std::nullopt, /* expected */ "boolean"); } return value.asBool(); } bool JsonValidation::boolean( const Json::Value& value, const std::string& field) { validate_object(value); const auto& boolean = value[field]; if (boolean.isNull() || !boolean.isBool()) { throw JsonValidationError(value, field, /* expected */ "boolean"); } return boolean.asBool(); } const Json::Value& JsonValidation::null_or_array(const Json::Value& value) { if (!value.isNull() && !value.isArray()) { throw JsonValidationError( value, /* field */ std::nullopt, /* expected */ "null or array"); } return value; } const Json::Value& JsonValidation::null_or_array( const Json::Value& value, const std::string& field) { validate_object(value); const auto& null_or_array = value[field]; if (!null_or_array.isNull() && !null_or_array.isArray()) { throw JsonValidationError(value, field, /* expected */ "null or array"); } return null_or_array; } const Json::Value& JsonValidation::nonempty_array( const Json::Value& value, const std::string& field) { validate_object(value); const auto& nonempty_array = value[field]; if (nonempty_array.isNull() || !nonempty_array.isArray() || nonempty_array.empty()) { throw JsonValidationError(value, field, /* expected */ "non-empty array"); } return nonempty_array; } const Json::Value& JsonValidation::object_or_string( const Json::Value& value, const std::string& field) { validate_object(value); const auto& attribute = value[field]; if (attribute.isNull() || (!attribute.isObject() && !attribute.isString())) { throw JsonValidationError(value, field, /* expected */ "object or string"); } return attribute; } DexType* JsonValidation::dex_type(const Json::Value& value) { auto type_name = JsonValidation::string(value); auto* type = redex::get_type(type_name); if (!type) { throw JsonValidationError( value, /* field */ std::nullopt, /* expected */ "existing type name"); } return type; } DexType* JsonValidation::dex_type( const Json::Value& value, const std::string& field) { auto type_name = JsonValidation::string(value, field); auto* type = redex::get_type(type_name); if (!type) { throw JsonValidationError( value, field, /* expected */ "existing type name"); } return type; } DexFieldRef* JsonValidation::dex_field(const Json::Value& value) { auto field_name = JsonValidation::string(value); auto* dex_field = redex::get_field(field_name); if (!dex_field) { throw JsonValidationError( value, /* field */ std::nullopt, /* expected */ "existing field name"); } return dex_field; } DexFieldRef* JsonValidation::dex_field( const Json::Value& value, const std::string& field) { auto field_name = JsonValidation::string(value, field); auto* dex_field = redex::get_field(field_name); if (!dex_field) { throw JsonValidationError( value, field, /* expected */ "existing field name"); } return dex_field; } Json::Value JsonValidation::parse_json(std::string string) { std::istringstream stream(std::move(string)); static const auto reader = Json::CharReaderBuilder(); std::string errors; Json::Value json; if (!Json::parseFromStream(reader, stream, &json, &errors)) { throw std::invalid_argument(fmt::format("Invalid json: {}", errors)); } return json; } Json::Value JsonValidation::parse_json_file( const boost::filesystem::path& path) { boost::filesystem::ifstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { file.open(path, std::ios_base::binary); } catch (const std::ifstream::failure&) { ERROR(1, "Could not open json file: `{}`.", path.string()); throw; } static const auto reader = Json::CharReaderBuilder(); std::string errors; Json::Value json; if (!Json::parseFromStream(reader, file, &json, &errors)) { throw std::invalid_argument( fmt::format("File `{}` is not valid json: {}", path.string(), errors)); } return json; } Json::Value JsonValidation::parse_json_file(const std::string& path) { return parse_json_file(boost::filesystem::path(path)); } namespace { Json::StreamWriterBuilder compact_writer_builder() { Json::StreamWriterBuilder writer; writer["indentation"] = ""; return writer; } Json::StreamWriterBuilder styled_writer_builder() { Json::StreamWriterBuilder writer; writer["indentation"] = " "; return writer; } } // namespace std::unique_ptr<Json::StreamWriter> JsonValidation::compact_writer() { static const auto writer_builder = compact_writer_builder(); return std::unique_ptr<Json::StreamWriter>(writer_builder.newStreamWriter()); } std::unique_ptr<Json::StreamWriter> JsonValidation::styled_writer() { static const auto writer_builder = styled_writer_builder(); return std::unique_ptr<Json::StreamWriter>(writer_builder.newStreamWriter()); } void JsonValidation::write_json_file( const boost::filesystem::path& path, const Json::Value& value) { boost::filesystem::ofstream file; file.exceptions(std::ofstream::failbit | std::ofstream::badbit); file.open(path, std::ios_base::binary); compact_writer()->write(value, &file); file << "\n"; file.close(); } std::string JsonValidation::to_styled_string(const Json::Value& value) { std::ostringstream string; styled_writer()->write(value, &string); return string.str(); } void JsonValidation::update_object( Json::Value& left, const Json::Value& right) { mt_assert(left.isObject()); mt_assert(right.isObject()); for (const auto& key : right.getMemberNames()) { left[key] = right[key]; } } } // namespace marianatrench
8,712
2,740
// Copyright 2020 MongoDB Inc. // // 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 <string> #include <vector> #include <bsoncxx/document/view_or_value.hpp> #include <bsoncxx/stdx/optional.hpp> #include <mongocxx/stdx.hpp> #include <mongocxx/config/prelude.hpp> namespace mongocxx { MONGOCXX_INLINE_NAMESPACE_BEGIN class client_encryption; namespace options { /// /// Class representing options for data key generation for encryption. /// class MONGOCXX_API data_key { public: /// /// Sets a KMS-specific key used to encrypt the new data key. /// /// If the KMS provider is "aws" the masterKey is required and has the following fields: /// /// { /// region: String, /// key: String, // The Amazon Resource Name (ARN) to the AWS customer master key (CMK). /// endpoint: Optional<String> // An alternate host identifier to send KMS requests to. May /// include port number. Defaults to "kms.<region>.amazonaws.com" /// } /// /// If the KMS provider is "azure" the masterKey is required and has the following fields: /// /// { /// keyVaultEndpoint: String, // Host with optional port. Example: "example.vault.azure.net". /// keyName: String, /// keyVersion: Optional<String> // A specific version of the named key, defaults to using /// the key's primary version. /// } /// /// If the KMS provider is "gcp" the masterKey is required and has the following fields: /// /// { /// projectId: String, /// location: String, /// keyRing: String, /// keyName: String, /// keyVersion: Optional<String>, // A specific version of the named key, defaults to using /// the key's primary version. /// endpoint: Optional<String> // Host with optional port. Defaults to /// "cloudkms.googleapis.com". /// } /// /// If the KMS provider is "local" the masterKey is not applicable. /// /// @param master_key /// The document representing the master key. /// /// @return /// A reference to this object. /// /// @see https://docs.mongodb.com/manual/core/security-client-side-encryption-key-management/ /// data_key& master_key(bsoncxx::document::view_or_value master_key); /// /// Gets the master key. /// /// @return /// An optional document containing the master key. /// const stdx::optional<bsoncxx::document::view_or_value>& master_key() const; /// /// Sets an optional list of string alternate names used to reference the key. /// If a key is created with alternate names, then encryption may refer to the /// key by the unique alternate name instead of by _id. /// /// @param key_alt_names /// The alternate names for the key. /// /// @return /// A reference to this object. /// /// @see https://docs.mongodb.com/manual/reference/method/getClientEncryption/ /// data_key& key_alt_names(std::vector<std::string> key_alt_names); /// /// Gets the alternate names for the data key. /// /// @return /// The alternate names for the data key. /// const std::vector<std::string>& key_alt_names() const; private: friend class mongocxx::client_encryption; MONGOCXX_PRIVATE void* convert() const; stdx::optional<bsoncxx::document::view_or_value> _master_key; std::vector<std::string> _key_alt_names; }; } // namespace options MONGOCXX_INLINE_NAMESPACE_END } // namespace mongocxx
4,066
1,221
/***************************************************************************** export.cpp Author: Laurent de Soras, 2016 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/Err.h" #include "mfx/piapi/FactoryTpl.h" #include "mfx/pi/adsr/EnvAdsr.h" #include "mfx/pi/adsr/EnvAdsrDesc.h" #include "mfx/pi/bmp1/BigMuff1.h" #include "mfx/pi/bmp1/BigMuff1Desc.h" #include "mfx/pi/click/Click.h" #include "mfx/pi/click/ClickDesc.h" #include "mfx/pi/colorme/ColorMe.h" #include "mfx/pi/colorme/ColorMeDesc.h" #include "mfx/pi/cpx/Compex.h" #include "mfx/pi/cpx/CompexDesc.h" #include "mfx/pi/dclip/DiodeClipper.h" #include "mfx/pi/dclip/DiodeClipperDesc.h" #include "mfx/pi/dist1/DistoSimple.h" #include "mfx/pi/dist1/DistoSimpleDesc.h" #include "mfx/pi/dist2/Disto2x.h" #include "mfx/pi/dist2/Disto2xDesc.h" #include "mfx/pi/dist3/Dist3.h" #include "mfx/pi/dist3/Dist3Desc.h" #include "mfx/pi/distapf/DistApf.h" #include "mfx/pi/distapf/DistApfDesc.h" #include "mfx/pi/distpwm/DistoPwm.h" #include "mfx/pi/distpwm/DistoPwmDesc.h" #include "mfx/pi/distpwm2/DistoPwm2.h" #include "mfx/pi/distpwm2/DistoPwm2Desc.h" #include "mfx/pi/dly0/Delay.h" #include "mfx/pi/dly0/DelayDesc.h" #include "mfx/pi/dly1/Delay.h" #include "mfx/pi/dly1/DelayDesc.h" #include "mfx/pi/dly2/Delay2.h" #include "mfx/pi/dly2/Delay2Desc.h" #include "mfx/pi/dtone1/DistTone.h" #include "mfx/pi/dtone1/DistToneDesc.h" #include "mfx/pi/dwm/DryWet.h" #include "mfx/pi/dwm/DryWetDesc.h" #include "mfx/pi/envf/EnvFollow.h" #include "mfx/pi/envf/EnvFollowDesc.h" #include "mfx/pi/freqsh/FrequencyShifter.h" #include "mfx/pi/freqsh/FreqShiftDesc.h" #include "mfx/pi/flancho/Flancho.h" #include "mfx/pi/flancho/FlanchoDesc.h" #include "mfx/pi/fsplit/FreqSplit.h" #include "mfx/pi/fsplit/FreqSplitDesc.h" #include "mfx/pi/fv/Freeverb.h" #include "mfx/pi/fv/FreeverbDesc.h" #include "mfx/pi/hcomb/HyperComb.h" #include "mfx/pi/hcomb/HyperCombDesc.h" #include "mfx/pi/iifix/IIFix.h" #include "mfx/pi/iifix/IIFixDesc.h" #include "mfx/pi/lfo1/Lfo.h" #include "mfx/pi/lfo1/LfoDesc.h" #include "mfx/pi/lpfs/Squeezer.h" #include "mfx/pi/lpfs/SqueezerDesc.h" #include "mfx/pi/moog1/MoogLpf.h" #include "mfx/pi/moog1/MoogLpfDesc.h" #include "mfx/pi/nzbl/NoiseBleach.h" #include "mfx/pi/nzbl/NoiseBleachDesc.h" #include "mfx/pi/nzcl/NoiseChlorine.h" #include "mfx/pi/nzcl/NoiseChlorineDesc.h" #include "mfx/pi/osdet/OnsetDetect.h" #include "mfx/pi/osdet/OnsetDetectDesc.h" //#include "mfx/pi/osdet2/OnsetDetect2.h" //#include "mfx/pi/osdet2/OnsetDetect2Desc.h" #include "mfx/pi/peq/PEq.h" #include "mfx/pi/peq/PEqDesc.h" #include "mfx/pi/phase1/Phaser.h" #include "mfx/pi/phase1/PhaserDesc.h" #include "mfx/pi/phase2/Phaser2.h" #include "mfx/pi/phase2/Phaser2Desc.h" #include "mfx/pi/pidet/PitchDetect.h" #include "mfx/pi/pidet/PitchDetectDesc.h" #include "mfx/pi/psh1/PitchShift1.h" #include "mfx/pi/psh1/PitchShift1Desc.h" #include "mfx/pi/ramp/Ramp.h" #include "mfx/pi/ramp/RampDesc.h" #include "mfx/pi/smood/SkoolMood.h" #include "mfx/pi/smood/SkoolMoodDesc.h" #include "mfx/pi/syn0/Synth0.h" #include "mfx/pi/syn0/Synth0Desc.h" #include "mfx/pi/spkem/SpeakerEmu.h" #include "mfx/pi/spkem/SpeakerEmuDesc.h" #include "mfx/pi/testgen/TestGen.h" #include "mfx/pi/testgen/TestGenDesc.h" #include "mfx/pi/tost/ToStereo.h" #include "mfx/pi/tost/ToStereoDesc.h" #include "mfx/pi/trem1/Tremolo.h" #include "mfx/pi/trem1/TremoloDesc.h" #include "mfx/pi/tremh/HarmTrem.h" #include "mfx/pi/tremh/HarmTremDesc.h" #include "mfx/pi/tuner/Tuner.h" #include "mfx/pi/tuner/TunerDesc.h" #include "mfx/pi/wah1/Wah.h" #include "mfx/pi/wah1/WahDesc.h" #include "mfx/pi/wah2/Wah2.h" #include "mfx/pi/wah2/Wah2Desc.h" #include "mfx/pi/export.h" #include <cassert> /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ fstb_EXPORT (int fstb_CDECL enum_factories (std::vector <std::shared_ptr <mfx::piapi::FactoryInterface> > &fact_list)) { int ret_val = fstb::Err_OK; try { static const std::vector <std::shared_ptr <mfx::piapi::FactoryInterface> > l = { mfx::piapi::FactoryTpl <mfx::pi::dwm::DryWetDesc , mfx::pi::dwm::DryWet >::create () , mfx::piapi::FactoryTpl <mfx::pi::tuner::TunerDesc , mfx::pi::tuner::Tuner >::create () , mfx::piapi::FactoryTpl <mfx::pi::dist1::DistoSimpleDesc , mfx::pi::dist1::DistoSimple >::create () , mfx::piapi::FactoryTpl <mfx::pi::freqsh::FreqShiftDesc , mfx::pi::freqsh::FrequencyShifter >::create () , mfx::piapi::FactoryTpl <mfx::pi::trem1::TremoloDesc , mfx::pi::trem1::Tremolo >::create () , mfx::piapi::FactoryTpl <mfx::pi::wah1::WahDesc , mfx::pi::wah1::Wah >::create () , mfx::piapi::FactoryTpl <mfx::pi::dtone1::DistToneDesc , mfx::pi::dtone1::DistTone >::create () , mfx::piapi::FactoryTpl <mfx::pi::iifix::IIFixDesc , mfx::pi::iifix::IIFix >::create () , mfx::piapi::FactoryTpl <mfx::pi::flancho::FlanchoDesc , mfx::pi::flancho::Flancho >::create () , mfx::piapi::FactoryTpl <mfx::pi::dly1::DelayDesc , mfx::pi::dly1::Delay >::create () , mfx::piapi::FactoryTpl <mfx::pi::cpx::CompexDesc , mfx::pi::cpx::Compex >::create () , mfx::piapi::FactoryTpl <mfx::pi::fv::FreeverbDesc , mfx::pi::fv::Freeverb >::create () , mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc < 4> , mfx::pi::peq::PEq < 4> >::create () , mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc < 8> , mfx::pi::peq::PEq < 8> >::create () , mfx::piapi::FactoryTpl <mfx::pi::peq::PEqDesc <16> , mfx::pi::peq::PEq <16> >::create () , mfx::piapi::FactoryTpl <mfx::pi::phase1::PhaserDesc , mfx::pi::phase1::Phaser >::create () , mfx::piapi::FactoryTpl <mfx::pi::lpfs::SqueezerDesc , mfx::pi::lpfs::Squeezer >::create () , mfx::piapi::FactoryTpl <mfx::pi::lfo1::LfoDesc <false> , mfx::pi::lfo1::Lfo <false> >::create () , mfx::piapi::FactoryTpl <mfx::pi::envf::EnvFollowDesc , mfx::pi::envf::EnvFollow >::create () , mfx::piapi::FactoryTpl <mfx::pi::dist2::Disto2xDesc , mfx::pi::dist2::Disto2x >::create () , mfx::piapi::FactoryTpl <mfx::pi::spkem::SpeakerEmuDesc , mfx::pi::spkem::SpeakerEmu >::create () , mfx::piapi::FactoryTpl <mfx::pi::tost::ToStereoDesc , mfx::pi::tost::ToStereo >::create () , mfx::piapi::FactoryTpl <mfx::pi::distpwm::DistoPwmDesc , mfx::pi::distpwm::DistoPwm >::create () , mfx::piapi::FactoryTpl <mfx::pi::tremh::HarmTremDesc , mfx::pi::tremh::HarmTrem >::create () , mfx::piapi::FactoryTpl <mfx::pi::nzbl::NoiseBleachDesc , mfx::pi::nzbl::NoiseBleach >::create () , mfx::piapi::FactoryTpl <mfx::pi::nzcl::NoiseChlorineDesc , mfx::pi::nzcl::NoiseChlorine >::create () , mfx::piapi::FactoryTpl <mfx::pi::click::ClickDesc , mfx::pi::click::Click >::create () , mfx::piapi::FactoryTpl <mfx::pi::wah2::Wah2Desc , mfx::pi::wah2::Wah2 >::create () , mfx::piapi::FactoryTpl <mfx::pi::ramp::RampDesc , mfx::pi::ramp::Ramp >::create () , mfx::piapi::FactoryTpl <mfx::pi::dly2::Delay2Desc , mfx::pi::dly2::Delay2 >::create () , mfx::piapi::FactoryTpl <mfx::pi::colorme::ColorMeDesc , mfx::pi::colorme::ColorMe >::create () , mfx::piapi::FactoryTpl <mfx::pi::phase2::Phaser2Desc , mfx::pi::phase2::Phaser2 >::create () , mfx::piapi::FactoryTpl <mfx::pi::pidet::PitchDetectDesc , mfx::pi::pidet::PitchDetect >::create () , mfx::piapi::FactoryTpl <mfx::pi::osdet::OnsetDetectDesc , mfx::pi::osdet::OnsetDetect >::create () , mfx::piapi::FactoryTpl <mfx::pi::syn0::Synth0Desc , mfx::pi::syn0::Synth0 >::create () , mfx::piapi::FactoryTpl <mfx::pi::hcomb::HyperCombDesc , mfx::pi::hcomb::HyperComb >::create () , mfx::piapi::FactoryTpl <mfx::pi::testgen::TestGenDesc , mfx::pi::testgen::TestGen >::create () , mfx::piapi::FactoryTpl <mfx::pi::psh1::PitchShift1Desc , mfx::pi::psh1::PitchShift1 >::create () , mfx::piapi::FactoryTpl <mfx::pi::distpwm2::DistoPwm2Desc , mfx::pi::distpwm2::DistoPwm2 >::create () // , mfx::piapi::FactoryTpl <mfx::pi::osdet2::OnsetDetect2Desc, mfx::pi::osdet2::OnsetDetect2 >::create () // Does not work well enough , mfx::piapi::FactoryTpl <mfx::pi::distapf::DistApfDesc , mfx::pi::distapf::DistApf >::create () , mfx::piapi::FactoryTpl <mfx::pi::lfo1::LfoDesc <true> , mfx::pi::lfo1::Lfo <true> >::create () , mfx::piapi::FactoryTpl <mfx::pi::adsr::EnvAdsrDesc , mfx::pi::adsr::EnvAdsr >::create () , mfx::piapi::FactoryTpl <mfx::pi::dly0::DelayDesc , mfx::pi::dly0::Delay >::create () , mfx::piapi::FactoryTpl <mfx::pi::fsplit::FreqSplitDesc , mfx::pi::fsplit::FreqSplit >::create () , mfx::piapi::FactoryTpl <mfx::pi::dist3::Dist3Desc , mfx::pi::dist3::Dist3 >::create () , mfx::piapi::FactoryTpl <mfx::pi::moog1::MoogLpfDesc , mfx::pi::moog1::MoogLpf >::create () , mfx::piapi::FactoryTpl <mfx::pi::dclip::DiodeClipperDesc , mfx::pi::dclip::DiodeClipper >::create () , mfx::piapi::FactoryTpl <mfx::pi::smood::SkoolMoodDesc , mfx::pi::smood::SkoolMood >::create () , mfx::piapi::FactoryTpl <mfx::pi::bmp1::BigMuff1Desc , mfx::pi::bmp1::BigMuff1 >::create () }; fact_list = l; } catch (...) { assert (false); ret_val = fstb::Err_EXCEPTION; fact_list.clear (); } return ret_val; } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
10,532
4,873
// +------------------------------------------------------------------------- // | Copyright (C) 2017 Yunify, Inc. // +------------------------------------------------------------------------- // | Licensed under the Apache License, Version 2.0 (the "License"); // | you may not use this work except in compliance with the License. // | You may obtain a copy of the License in the LICENSE file, or 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 <yaml/yaml.h> #include <plog/Log.h> #include "QsConfig.h" #include "StringUtils.h" #include <map> namespace QingStor { static const char *CONFIG_KEY_ACCESS_KEY_ID = "access_key_id"; static const char *CONFIG_KEY_SECRET_ACCESS_KEY = "secret_access_key"; static const char *CONFIG_KEY_HOST = "host"; static const char *CONFIG_KEY_PORT = "port"; static const char *CONFIG_KEY_PROTOCOL = "protocol"; static const char *CONFIG_KEY_CONNECTION_RETRIES = "connection_retries"; static const char *CONFIG_KEY_ADDITIONAL_USER_AGENT = "additional_user_agent"; static const char *CONFIG_KEY_TIMEOUT_PERIOD = "timeOutPeriod"; // Default value static const char *DEFAULT_HOST = "qingstor.com"; static const char *DEFAULT_PROTOCOL = "https"; static const char *DEFAULT_ADDITIONAL_USER_AGENT = ""; static int DEFAULT_RETRIES = 3; static int DEFAULT_PORT = 443; static int DEFAULT_TIMEOUT_PERIOD = 3; QsConfig::QsConfig(const std::string & access_key_id, const std::string & secret_access_key) : additionalUserAgent(DEFAULT_ADDITIONAL_USER_AGENT), accessKeyId(access_key_id),secretAccessKey(secret_access_key), host(DEFAULT_HOST),protocol(DEFAULT_PROTOCOL), port(DEFAULT_PORT),connectionRetries(DEFAULT_RETRIES), timeOutPeriod(DEFAULT_TIMEOUT_PERIOD) { } QsError QsConfig::LoadConfigFile(const std::string &config_file) { FILE *fh = NULL; yaml_parser_t parser; yaml_token_t token; std::map<std::string, std::string> kvs; std::string token_key; std::string token_value; bool reach_key = false; bool reach_value = false; /* Initialize parser */ if (!yaml_parser_initialize(&parser)) { LOG_FATAL << "couldn't initialize yaml parser"; } /* Open configuration file */ if ((fh = fopen(config_file.c_str(), "rb")) == NULL) { yaml_parser_delete(&parser); LOG_FATAL << "couldn't open configure file " << config_file.c_str(); } /* Set input file */ yaml_parser_set_input_file(&parser, fh); do { yaml_parser_scan(&parser, &token); switch (token.type) { case YAML_STREAM_START_TOKEN: case YAML_STREAM_END_TOKEN: case YAML_BLOCK_SEQUENCE_START_TOKEN: case YAML_BLOCK_ENTRY_TOKEN: case YAML_BLOCK_END_TOKEN: case YAML_BLOCK_MAPPING_START_TOKEN: break; case YAML_KEY_TOKEN: { reach_key = true; } break; case YAML_VALUE_TOKEN: { reach_value = true; } break; case YAML_SCALAR_TOKEN: { bool config_invalid = false; if (reach_key) { token_key = std::string((const char *)(token.data.scalar.value)); reach_key = false; break; } else if (reach_value) { token_value = std::string((const char *)(token.data.scalar.value)); reach_value = false; if (token_key.empty() || token_value.empty()) { config_invalid = true; } } else { config_invalid = true; } if (config_invalid) { yaml_token_delete(&token); yaml_parser_delete(&parser); fclose(fh); LOG_FATAL << "YAML configuration is invalid"; return QS_ERR_INVAILD_CONFIG_FILE; } else { kvs.insert(std::pair<std::string, std::string>(token_key, token_value)); token_key.clear(); token_value.clear(); } } break; default: { yaml_token_delete(&token); yaml_parser_delete(&parser); fclose(fh); LOG_FATAL << "YAML configuration is invalid with token type" << token.type; return QS_ERR_INVAILD_CONFIG_FILE; } break; } if (token.type != YAML_STREAM_END_TOKEN) { yaml_token_delete(&token); } } while (token.type != YAML_STREAM_END_TOKEN); yaml_token_delete(&token); yaml_parser_delete(&parser); fclose(fh); /* Go through the interested configurations */ if (kvs[std::string(CONFIG_KEY_ACCESS_KEY_ID)].empty()) { LOG_FATAL << "YAML configuration is invalid with token type" << token.type; return QS_ERR_INVAILD_CONFIG_FILE; } else { accessKeyId = kvs[std::string(CONFIG_KEY_ACCESS_KEY_ID)]; } if (kvs[std::string(CONFIG_KEY_SECRET_ACCESS_KEY)].empty()) { return QS_ERR_INVAILD_CONFIG_FILE; } else { secretAccessKey = kvs[std::string(CONFIG_KEY_SECRET_ACCESS_KEY)]; } if (kvs[std::string(CONFIG_KEY_HOST)].empty()) { host = DEFAULT_HOST; } else { host = kvs[std::string(CONFIG_KEY_HOST)]; } if (kvs[std::string(CONFIG_KEY_PORT)].empty()) { port = DEFAULT_PORT; } else { std::string port_str = kvs[std::string(CONFIG_KEY_PORT)]; int tmp_prot = atoi(port_str.c_str()); if (tmp_prot <= 0 || tmp_prot > 65535) { LOG_WARNING << "Configuration Port" << port_str.c_str() << "is invalid, using default vaule:" << DEFAULT_PORT; tmp_prot = DEFAULT_PORT; } port = tmp_prot; } if (kvs[std::string(CONFIG_KEY_PROTOCOL)].empty()) { protocol = DEFAULT_PROTOCOL; } else { protocol = kvs[std::string(CONFIG_KEY_PROTOCOL)]; } if (kvs[std::string(CONFIG_KEY_CONNECTION_RETRIES)].empty()) { connectionRetries = 3; } else { std::string retries_str = kvs[std::string(CONFIG_KEY_CONNECTION_RETRIES)]; int retries = atoi(retries_str.c_str()); if (retries <= 0 || retries > 16) { LOG_WARNING << "Configuration connection retries" << retries_str.c_str() << " is invalid, using default value:" << DEFAULT_RETRIES; retries = DEFAULT_RETRIES; } connectionRetries = retries; } if (kvs[std::string(CONFIG_KEY_TIMEOUT_PERIOD)].empty()) { timeOutPeriod = 3; } else { std::string timeOutPeriod_str = kvs[std::string(CONFIG_KEY_TIMEOUT_PERIOD)]; int timeOut = atoi(timeOutPeriod_str.c_str()); if (connectionRetries <= 0) { LOG_WARNING << "Configuration connection retries" << timeOutPeriod_str.c_str() << " is invalid, using default value:" << DEFAULT_RETRIES; timeOutPeriod = DEFAULT_TIMEOUT_PERIOD; } timeOutPeriod = timeOut; } if (kvs[std::string(CONFIG_KEY_ADDITIONAL_USER_AGENT)].empty()) { additionalUserAgent = ""; } else { additionalUserAgent = kvs[std::string(CONFIG_KEY_ADDITIONAL_USER_AGENT)]; } return QS_ERR_NO_ERROR; } }
7,894
2,548
#pragma once #include <hitagi/ecs/world.hpp> #include <hitagi/utils/concepts.hpp> #include <memory_resource> #include <typeindex> #include <vector> #include <functional> namespace hitagi::ecs { class Schedule { struct ITask { virtual void Run(World&) = 0; }; template <typename Func> struct Task : public ITask { Task(std::string_view name, Func&& task) : task_name(name), task(std::move(task)) {} Task(const Task&) = delete; Task& operator=(const Task&) = delete; Task(Task&&) noexcept = default; Task& operator=(Task&&) noexcept = default; void Run(World& world) final; std::pmr::string task_name; Func task; }; public: Schedule(World& world) : m_World(world) {} // Do task on the entities that contains components indicated at parameters. template <typename Func> requires utils::unique_parameter_types<Func> Schedule& Register(std::string_view name, Func&& task); void Run() { for (auto&& task : m_Tasks) { task->Run(m_World); } } private: World& m_World; std::pmr::vector<std::shared_ptr<ITask>> m_Tasks; }; template <typename Func> requires utils::unique_parameter_types<Func> Schedule& Schedule::Register(std::string_view name, Func&& task) { std::shared_ptr<ITask> task_info = std::make_shared<Task<Func>>(name, std::forward<Func>(task)); m_Tasks.emplace_back(std::move(task_info)); return *this; } template <typename Func> void Schedule::Task<Func>::Run(World& world) { [&]<std::size_t... I>(std::index_sequence<I...>) { using traits = utils::function_traits<Func>; for (const std::shared_ptr<IArchetype>& archetype : world.GetArchetypes<typename traits::template arg<I>::type...>()) { auto num_entities = archetype->NumEntities(); auto components_array = std::make_tuple(archetype->GetComponentArray<typename traits::template arg<I>::type>()...); for (std::size_t index = 0; index < num_entities; index++) { task(std::get<I>(components_array)[index]...); } }; } (std::make_index_sequence<utils::function_traits<Func>::args_size>{}); } } // namespace hitagi::ecs
2,358
752
// Copyright (c) 2011 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 "ppapi/proxy/plugin_message_filter.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/task/single_thread_task_runner.h" #include "ipc/ipc_channel.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/proxy/resource_message_params.h" #include "ppapi/proxy/resource_reply_thread_registrar.h" #include "ppapi/shared_impl/ppapi_globals.h" #include "ppapi/shared_impl/proxy_lock.h" #include "ppapi/shared_impl/resource.h" #include "ppapi/shared_impl/resource_tracker.h" namespace ppapi { namespace proxy { PluginMessageFilter::PluginMessageFilter( std::set<PP_Instance>* seen_instance_ids, scoped_refptr<ResourceReplyThreadRegistrar> registrar) : seen_instance_ids_(seen_instance_ids), resource_reply_thread_registrar_(registrar), sender_(NULL) { } PluginMessageFilter::~PluginMessageFilter() { } void PluginMessageFilter::OnFilterAdded(IPC::Channel* channel) { sender_ = channel; } void PluginMessageFilter::OnFilterRemoved() { sender_ = NULL; } bool PluginMessageFilter::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PluginMessageFilter, message) IPC_MESSAGE_HANDLER(PpapiMsg_ReserveInstanceId, OnMsgReserveInstanceId) IPC_MESSAGE_HANDLER(PpapiPluginMsg_ResourceReply, OnMsgResourceReply) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } bool PluginMessageFilter::Send(IPC::Message* msg) { if (sender_) return sender_->Send(msg); delete msg; return false; } void PluginMessageFilter::AddResourceMessageFilter( const scoped_refptr<ResourceMessageFilter>& filter) { resource_filters_.push_back(filter); } // static void PluginMessageFilter::DispatchResourceReplyForTest( const ResourceMessageReplyParams& reply_params, const IPC::Message& nested_msg) { DispatchResourceReply(reply_params, nested_msg); } void PluginMessageFilter::OnMsgReserveInstanceId(PP_Instance instance, bool* usable) { // If |seen_instance_ids_| is set to NULL, we are not supposed to see this // message. CHECK(seen_instance_ids_); // See the message definition for how this works. if (seen_instance_ids_->find(instance) != seen_instance_ids_->end()) { // Instance ID already seen, reject it. *usable = false; return; } // This instance ID is new so we can return that it's usable and mark it as // used for future reference. seen_instance_ids_->insert(instance); *usable = true; } void PluginMessageFilter::OnMsgResourceReply( const ResourceMessageReplyParams& reply_params, const IPC::Message& nested_msg) { for (const auto& filter_ptr : resource_filters_) { if (filter_ptr->OnResourceReplyReceived(reply_params, nested_msg)) return; } scoped_refptr<base::SingleThreadTaskRunner> target = resource_reply_thread_registrar_->GetTargetThread(reply_params, nested_msg); target->PostTask(FROM_HERE, base::BindOnce(&DispatchResourceReply, reply_params, nested_msg)); } // static void PluginMessageFilter::DispatchResourceReply( const ResourceMessageReplyParams& reply_params, const IPC::Message& nested_msg) { ProxyAutoLock lock; Resource* resource = PpapiGlobals::Get()->GetResourceTracker()->GetResource( reply_params.pp_resource()); if (!resource) { DVLOG_IF(1, reply_params.sequence() != 0) << "Pepper resource reply message received but the resource doesn't " "exist (probably has been destroyed)."; return; } resource->OnReplyReceived(reply_params, nested_msg); } } // namespace proxy } // namespace ppapi
3,935
1,257
/**************************************************************************\ * Copyright (c) Kongsberg Oil & Gas Technologies AS * 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 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. \**************************************************************************/ /*! \class SoTexture3Transform SoTexture3Transform.h Inventor/nodes/SoTexture3Transform.h \brief The SoTexture3Transform class is used to define 3D texture transformations. \ingroup nodes Textures applied to shapes in the scene can be transformed by "prefixing" in the state with instances of this node type. Translations, rotations and scaling in 3D can all be done. The default settings of this node's fields equals a "null transform", ie no transformation. \COIN_CLASS_EXTENSION <b>FILE FORMAT/DEFAULTS:</b> \code Texture3Transform { translation 0 0 0 rotation 0 0 1 0 scaleFactor 1 1 1 scaleOrientation 0 0 1 0 center 0 0 0 } \endcode \sa SoTexture2Transform \since Coin 2.0 \since TGS Inventor 2.6 */ // ************************************************************************* #include <Inventor/nodes/SoTexture3Transform.h> #include <Inventor/actions/SoGLRenderAction.h> #include <Inventor/actions/SoPickAction.h> #include <Inventor/actions/SoGetMatrixAction.h> #include <Inventor/actions/SoCallbackAction.h> #include <Inventor/elements/SoGLMultiTextureMatrixElement.h> #include <Inventor/elements/SoTextureUnitElement.h> #include <Inventor/elements/SoGLCacheContextElement.h> #include <Inventor/C/glue/gl.h> #include "nodes/SoSubNodeP.h" // ************************************************************************* /*! \var SoSFVec3f SoTexture3Transform::translation Texture coordinate translation. Default value is [0, 0, 0]. */ /*! \var SoSFRotation SoTexture3Transform::rotation Texture coordinate rotation (s is x-axis, t is y-axis and r is z-axis). Defaults to an identity rotation (ie zero rotation). */ /*! \var SoSFVec3f SoTexture3Transform::scaleFactor Texture coordinate scale factors. Default value is [1, 1, 1]. */ /*! \var SoSFRotation SoTexture3Transform::scaleOrientation The orientation the texture is set to before scaling. Defaults to an identity rotation (ie zero rotation). */ /*! \var SoSFVec3f SoTexture3Transform::center Center for scale and rotation. Default value is [0, 0, 0]. */ // ************************************************************************* SO_NODE_SOURCE(SoTexture3Transform); /*! Constructor. */ SoTexture3Transform::SoTexture3Transform(void) { SO_NODE_INTERNAL_CONSTRUCTOR(SoTexture3Transform); SO_NODE_ADD_FIELD(translation, (0.0f, 0.0f, 0.0f)); SO_NODE_ADD_FIELD(rotation, (SbRotation(SbVec3f(0.0f, 0.0f, 1.0f), 0.0f))); SO_NODE_ADD_FIELD(scaleFactor, (1.0f, 1.0f, 1.0f)); SO_NODE_ADD_FIELD(scaleOrientation, (SbRotation(SbVec3f(0.0f, 0.0f, 1.0f), 0.0f))); SO_NODE_ADD_FIELD(center, (0.0f, 0.0f, 0.0f)); } /*! Destructor. */ SoTexture3Transform::~SoTexture3Transform() { } // Documented in superclass. void SoTexture3Transform::initClass(void) { SO_NODE_INTERNAL_INIT_CLASS(SoTexture3Transform, SO_FROM_INVENTOR_1); SO_ENABLE(SoGLRenderAction, SoGLMultiTextureMatrixElement); SO_ENABLE(SoCallbackAction, SoMultiTextureMatrixElement); SO_ENABLE(SoPickAction, SoMultiTextureMatrixElement); } // Documented in superclass. void SoTexture3Transform::GLRender(SoGLRenderAction * action) { SoState * state = action->getState(); int unit = SoTextureUnitElement::get(state); const cc_glglue * glue = cc_glglue_instance(SoGLCacheContextElement::get(state)); int maxunits = cc_glglue_max_texture_units(glue); if (unit < maxunits) { SbMatrix mat; mat.setTransform(this->translation.getValue(), this->rotation.getValue(), this->scaleFactor.getValue(), this->scaleOrientation.getValue(), this->center.getValue()); SoMultiTextureMatrixElement::mult(state, this, unit, mat); } else { // we already warned in SoTextureUnit. I think it's best to just // ignore the texture here so that all textures for non-supported // units will be ignored. pederb, 2003-11-11 } } // Documented in superclass. void SoTexture3Transform::doAction(SoAction *action) { SoState * state = action->getState(); int unit = SoTextureUnitElement::get(state); SbMatrix mat; mat.setTransform(this->translation.getValue(), this->rotation.getValue(), this->scaleFactor.getValue(), this->scaleOrientation.getValue(), this->center.getValue()); SoMultiTextureMatrixElement::mult(action->getState(), this, unit, mat); } // Documented in superclass. void SoTexture3Transform::callback(SoCallbackAction *action) { SoTexture3Transform::doAction(action); } // Documented in superclass. void SoTexture3Transform::getMatrix(SoGetMatrixAction * action) { int unit = SoTextureUnitElement::get(action->getState()); if (unit == 0) { SbMatrix mat; mat.setTransform(this->translation.getValue(), this->rotation.getValue(), this->scaleFactor.getValue(), this->scaleOrientation.getValue(), this->center.getValue()); action->getTextureMatrix().multLeft(mat); action->getTextureInverse().multRight(mat.inverse()); } } // Documented in superclass. void SoTexture3Transform::pick(SoPickAction * action) { SoTexture3Transform::doAction(action); }
7,055
2,306
///////////////////////////////////////////////// // File PulsarSpectrum.cxx // Implementation of PulsarSpectrum class ////////////////////////////////////////////////// #include "Pulsar/PulsarSpectrum.h" #include "Pulsar/PulsarConstants.h" #include "SpectObj/SpectObj.h" #include "flux/SpectrumFactory.h" #include "facilities/commonUtilities.h" #include "facilities/Util.h" #include <cmath> #include <cstdlib> #include <vector> #define DEBUG 0 using namespace cst; //====================================================================== // copied from atErrors.h //---------------------------------------------------------------------- /* Error Code of atFunctions. */ #define NOT_CONVERGED 10 /*equation was not solved*/ //---------------------------------------------------------------------- // copied from atKepler.c (& modified) //---------------------------------------------------------------------- //#include "atFunctions.h" //#include "atError.h" //#include <math.h> /* * solve Kepler equation (KEPLER) g + e sin E = E */ int atKepler( double g, /* input: mean anomaly */ double eccent, /* input: eccentricity */ double *e) /* output: eccentric anomaly */ { static double eps = 1e-7; static int imax = 50; int i; static double error, deltae, d__1; *e = g; if (g == 0.) return 0; for (i=0; i<imax; i++) { deltae = (g - *e + eccent * std::sin(*e)) / (1. - eccent * std::cos(*e)); *e += deltae; error = (d__1 = deltae / *e, std::fabs(d__1)); if (error < eps) return 0; } return NOT_CONVERGED; } ///////////////////////////////////////////////// ISpectrumFactory &PulsarSpectrumFactory() { static SpectrumFactory<PulsarSpectrum> myFactory; return myFactory; } ///////////////////////////////////////////////// /*! * \param params string containing the XML parameters * * This method takes from the XML file the name of the pulsar to be simulated, the model * to be used and the parameters specific for the choosen model. Then extracts from the * TXT DataList file the characteristics of the choosen pulsar (e.g. period, flux, period derivatives * ,ephemerides, flux, etc...) * The names of DataList files are defined in the file <i>PulsarDataList.txt</i><br> * The parameters are:<br> * <ul> * <li> Pulsar name; * <li> Flux, expressed in ph/cm2/s (E>100MeV); * <li> Ephemerides type (P=period and derivatives;F=frequency and derivatives) * <li> Period,pdot,p2dot or f0,f1,f2; * <li> Start of ephemerides validity range (in MJD); * <li> Reference Epoch, t0 (in MJD); * <li> End of ephemerides validity range (in MJD); * </ul> * The parameters taken from XML file are:<br> * <ul> * <li> Pulsar name; * <li> Position (RA,dec) in degrees; * <li> Minimum and maximum energy of extracted photons (in keV); * <li> Model choosen (default = 1, phenomenological); * <li> Random seed; * <li> Model-dependend parameters; * </ul> * Then it calls the PulsarSim class in order to have the TH2D histogram. * For more informations and for a brief tutorial about the use of PulsarSpectrum you can look at: * <br> * <a href="#dejager02">http://www.pi.infn.it/~razzano/Pulsar/PulsarSpTutor/PulsarSpTutor.htm </a> */ PulsarSpectrum::PulsarSpectrum(const std::string& params) : m_solSys(astro::SolarSystem::EARTH), m_params(params) { m_ff=false; // Reset all variables; m_RA = 0.0; m_dec = 0.0; m_l = 0.0; m_b = 0.0; m_flux = 0.0; m_ephemType = ""; m_period = 0.0; m_pdot = 0.0; m_p2dot = 0.0; m_f0 = 0.0; m_f1 = 0.0; m_f2 = 0.0; m_f0NoNoise = 0.0; m_f1NoNoise = 0.0; m_f2NoNoise = 0.0; m_N0 = 0.0; m_t0Init = 0.0; m_t0 = 0.0; m_t0End = 0.0; m_phi0 = 0.0; m_model = 0; m_seed = 0; m_TimingNoiseModel = 0; m_TimingNoiseActivity = 0.; m_TimingNoiseRMS = 0.; m_TimingNoiseMeanRate=0.; m_TimingNoiseTimeNextEvent=0.; m_BinaryFlag = 0; m_Porb = 0; m_Porb_dot = 0.; m_asini = 0; m_xdot = 0.; m_ecc = 0; m_ecc_dot = 0.; m_omega = 0; m_omega_dot = 0.; m_gamma = 0.; m_shapiro_r = 0.; m_shapiro_s = 0.; m_t0PeriastrMJD = 0; m_t0AscNodeMJD = 0; m_PPN =0.; m_FT2_startMET = -1.; m_FT2_stopMET =-1.; m_Sim_startMET = -1.; m_Sim_stopMET =-1.; m_UseFT2 = 0; //Read from XML file m_PSRname = parseParamList(params,0).c_str(); // Pulsar name m_RA = std::atof(parseParamList(params,1).c_str()); // Pulsar Right Ascension m_dec = std::atof(parseParamList(params,2).c_str()); // Pulsar Declination m_enphmin = std::atof(parseParamList(params,3).c_str()); // minimum energy of extracted photons m_enphmax = std::atof(parseParamList(params,4).c_str()); // minimum energy of extracted photons m_model = std::atoi(parseParamList(params,5).c_str()); // choosen model m_seed = std::atoi(parseParamList(params,6).c_str()); //Model Parameters: Random seed //Setting random seed m_PSpectrumRandom = new TRandom; m_PSpectrumRandom->SetSeed(m_seed); if (m_model == 1) //Phenomenological model { m_ppar0 = std::atoi(parseParamList(params,7).c_str()); //Model Parameters: Number of peaks m_ppar1 = std::atof(parseParamList(params,8).c_str()); // model parameters m_ppar2 = std::atof(parseParamList(params,9).c_str()); m_ppar3 = std::atof(parseParamList(params,10).c_str()); m_ppar4 = std::atof(parseParamList(params,11).c_str()); } else if (m_model == 2) //PulsarShape model { m_ppar0 = std::atoi(parseParamList(params,7).c_str()); //Model Parameters: Use normalization? m_PSRShapeName = parseParamList(params,8).c_str(); // model parameters } //look for pulsar data directory, following, in the order $PULSARDATA, $SKYMODEL_DIR/pulsars or $PULSARROOT/data // std::string m_pulsardata_dir; if (::getenv("PULSAR_OUTPUT_LEVEL")) { const char * outlevel = ::getenv("PULSAR_OUTPUT_LEVEL"); m_OutputLevel = atoi(outlevel); if ((m_OutputLevel<0) || (m_OutputLevel>2)) m_OutputLevel=1; } else { m_OutputLevel=1; } if (::getenv("PULSARDATA")) { const char * psrdata = ::getenv("PULSARDATA"); m_pulsardata_dir = std::string(psrdata); } else if (::getenv("SKYMODEL_DIR")) { const char * psrdata = ::getenv("SKYMODEL_DIR"); m_pulsardata_dir = std::string(psrdata)+"/pulsars"; } else { const char * psrdata = ::getenv("PULSARROOT"); m_pulsardata_dir = std::string(psrdata)+"/data"; } if (m_OutputLevel>1) { WriteToLog("PULSARDATA used is: "+std::string(m_pulsardata_dir)); } // Determine start and end time for FT2 or orbit file try { const astro::PointingHistory & history = astro::GPS::instance()->history(); // throw(NoHistoryError); m_FT2_startMET = history.startTime(); m_FT2_stopMET = history.endTime(); m_UseFT2 = 1; } catch (astro::GPS::NoHistoryError & ) { m_FT2_startMET = Spectrum::startTime(); m_FT2_stopMET = astro::GPS::instance()->endTime(); } m_Sim_startMET = Spectrum::startTime(); m_Sim_stopMET = astro::GPS::instance()->endTime(); //Init SolarSystem stuffs useful for barycentric decorrections astro::JulianDate JDStart(StartMissionDateMJD+JDminusMJD); m_earthOrbit = new astro::EarthOrbit(JDStart); astro::SkyDir m_PulsarDir(m_RA,m_dec,astro::SkyDir::EQUATORIAL); m_PulsarVectDir = m_PulsarDir.dir(); m_GalDir = std::make_pair(m_PulsarDir.l(),m_PulsarDir.b()); m_l = m_GalDir.first; m_b = m_GalDir.second; //Load Pulsar General data from PulsarDataList.txt LoadPulsarData(m_pulsardata_dir,0); if (!(::getenv("PULSAR_NO_DB"))) { //Save the output txt file.. int DbFlag = saveDbTxtFile(); if ((DbFlag !=1) && (m_OutputLevel>1)) WriteToLog("WARNING! Problem in saving SimPulsars_spin.txt"); } //Binary Pulsar Data if (m_BinaryFlag ==1) { LoadPulsarData(m_pulsardata_dir,1); //loading orbital data from PulsarBinDataList.txt if (!(::getenv("PULSAR_NO_DB"))) { int BinDbFlag = saveBinDbTxtFile(); if ((BinDbFlag !=1) && (m_OutputLevel>1)) WriteToLog("WARNING! Problem in saving SimPulsars_bin.txt"); } } if (m_TimingNoiseModel != 0) { InitTimingNoise(); } //Instantiate an object of PulsarSim class m_Pulsar = new PulsarSim(m_PSRname, m_seed, m_flux, m_enphmin, m_enphmax, m_period); //Instantiate an object of SpectObj class if (m_model == 1) { m_spectrum = new SpectObj(m_Pulsar->PSRPhenom(double(m_ppar0), m_ppar1,m_ppar2,m_ppar3,m_ppar4),1); m_spectrum->SetAreaDetector(EventSource::totalArea()); } else if (m_model == 2) { m_spectrum = new SpectObj(m_Pulsar->PSRShape(m_PSRShapeName,m_ppar0),1); m_spectrum->SetAreaDetector(EventSource::totalArea()); } else { std::cout << "ERROR! Model choice not implemented " << std::endl; exit(1); } if (m_OutputLevel > 0) { //Redirect output to a subdirectory const char * pulsarOutDir = ::getenv("PULSAROUTFILES"); // override obssim if running in Gleam environment if( pulsarOutDir!=0) m_LogFileName = std::string(pulsarOutDir) + "/" + m_PSRname + "Log.txt"; else m_LogFileName = m_PSRname + "Log.txt"; char temp[200]; sprintf(temp,"** Output Level set to: %d",m_OutputLevel); WriteToLog(std::string(temp)); WritePulsarLog(); } } ///////////////////////////////////////////////// PulsarSpectrum::~PulsarSpectrum() { delete m_Pulsar; delete m_spectrum; delete m_earthOrbit; delete m_PSpectrumRandom; } ///////////////////////////////////////////////// double PulsarSpectrum::flux(double time) const { double flux; flux = m_spectrum->flux(time,m_enphmin); return flux; } ///////////////////////////////////////////////// /*! * \param time time to start the computing of the next photon * * This method find the time when the next photon will come. It takes into account decorrections due to * ephemerides and period derivatives and barycentric decorrections. This method also check for * changes in the ephemerides validity range. * For the ephemerides decorrections the parameters used are: * <ul> * <li> <i>Epoch</i>, espressed in MJD;</li> * <li> <i>Initial Phase Phi0</i>;</li> * <li> <i>First Period derivative</i>;</li> * <li> <i>Second Period derivative</i>;</li> * </ul> * <br> * The barycentric decorrections takes into account conversion TDB->TT, Geometrical and Shapiro delays. * This method also calls the interval method in SpectObj class to determine the next photon in a rest-frame without * ephemerides effects. */ double PulsarSpectrum::interval(double time) { double timeTildeDecorr = time + (StartMissionDateMJD)*SecsOneDay; //Arrival time decorrected //check if time is before FT2 start if (time < m_FT2_startMET) { timeTildeDecorr+=(m_FT2_startMET-time)+510.; } //this should be corrected before applying barycentryc decorr + ephem de-corrections double timeTilde = 0; timeTilde = timeTildeDecorr + getBaryCorr(timeTildeDecorr,0); double timeTildeDemodulated =0.; //binary demodulation if (m_BinaryFlag ==0) { timeTildeDemodulated = timeTilde; } else { if (::getenv("PULSAR_OUT_BIN")) { timeTildeDemodulated = getIterativeDemodulatedTime(timeTilde,1); } else { timeTildeDemodulated = getIterativeDemodulatedTime(timeTilde,0); } // std::cout <<"\n****Test inverso:"<< timeTildeDemodulated-(StartMissionDateMJD)*SecsOneDay << " con correzioni" << getBinaryDemodulationInverse(timeTildeDemodulated)-(StartMissionDateMJD)*SecsOneDay << std::endl; // std::cout << " indietro -->" << getIterativeDemodulatedTime(getBinaryDemodulationInverse(timeTildeDemodulated),0)-(StartMissionDateMJD)*SecsOneDay << std::endl; } //Phase assignment double intPart=0.; //Integer part // double PhaseNoNoise,PhaseWithNoise=0.; //Apply timing noise if (m_TimingNoiseModel !=0) { ApplyTimingNoise(timeTildeDemodulated); } double initTurns = getTurns(timeTildeDemodulated); //Turns made at this time double tStart = modf(initTurns,&intPart)*m_period; // Start time for interval if (tStart < 0.) tStart+=m_period; if (DEBUG) { std::cout << std::setprecision(30) << "\n" << timeTilde -(StartMissionDateMJD)*SecsOneDay << " turns are " << getTurns(timeTilde) << " phase is " << tStart/m_period << " phi0 is " << m_phi0 << std::endl; } CheckEphemeridesValidity(timeTildeDemodulated,initTurns);; if (DEBUG) { if ((int(timeTilde - (StartMissionDateMJD)*SecsOneDay) % 1000) < 1.5) std::cout << "\n\n** " << m_PSRname << " Time is: " << timeTildeDecorr-(StartMissionDateMJD)*SecsOneDay << " s MET in TT | " << timeTilde-(StartMissionDateMJD)*SecsOneDay << "s. MET in SSB in TDB (barycorr.) | " << timeTildeDemodulated-(StartMissionDateMJD)*SecsOneDay << "s. MET in SSB in TDB (barycorr. + demod.)| " << std::endl; } //Log out the barycentric corrections double bl=0; if (::getenv("PULSAR_OUT_BARY")) bl = getBaryCorr(timeTilde,1); //In case of binary add a modulation... if (m_BinaryFlag ==1) { double ModFactor = 0.5; double intOrb; // double Modulation = 1+ModFactor*sin(2*M_PI*modf(initTurns,&intOrb)-DegToRad*m_omega+0.5*M_PI); double OrbPhase = getOrbitalPhase(timeTildeDemodulated); double Modulation = 1+ModFactor*std::sin(2*M_PI*OrbPhase-DegToRad*m_omega+0.5*M_PI); if (DEBUG) std::cout << std::setprecision(12)<<timeTildeDecorr - (StartMissionDateMJD)*SecsOneDay<< " OrbPhase " << OrbPhase << std::endl; //std::cout << std::setprecision(12)<<TrueAn<<" " <<modf(TrueAn,&intOrb)<<" " << Modulation<<std::endl; m_spectrum->SetFluxFactor(Modulation); } //Ephemerides calculations... double inte = m_spectrum->interval(tStart,m_enphmin); //deltaT (in system where Pdot = 0 double inteTurns = inte/m_period; // conversion to # of turns double totTurns = initTurns + inteTurns + m_phi0; //Total turns at the nextTimeTilde //Applying timingnoise double nextTimeTildeDemodulated = retrieveNextTimeTilde(timeTildeDemodulated, totTurns, (ephemCorrTol/m_period)); double nextTimeTilde = 0.; double nextTimeTildeDecorr = 0.; //inverse of binary demodulation and of barycentric corrections if (m_BinaryFlag == 0) { nextTimeTilde = nextTimeTildeDemodulated; nextTimeTildeDecorr = getDecorrectedTime(nextTimeTilde); //Barycentric decorrections } else { nextTimeTilde = getBinaryDemodulationInverse(nextTimeTildeDemodulated); nextTimeTildeDecorr = getDecorrectedTime(nextTimeTilde); //Barycentric decorrections } if (DEBUG) { std::cout << std::setprecision(15) << "\nTimeTildeDecorr at Spacecraft (TT) is: " << timeTildeDecorr - (StartMissionDateMJD)*SecsOneDay << "s." << std::endl; std::cout << "Arrival time after start of the simulation : " << timeTildeDecorr - (StartMissionDateMJD)*SecsOneDay -Spectrum::startTime() << " s." << std::endl; std::cout << std::setprecision(15) <<" TimeTilde at SSB (in TDB) is: " << timeTilde - (StartMissionDateMJD)*SecsOneDay << "sec." << std::endl; std::cout << std::setprecision(15) <<" TimeTildeDemodulated: " << timeTildeDemodulated - (StartMissionDateMJD)*SecsOneDay << "sec.; phase=" << modf(initTurns,&intPart) << std::endl; std::cout << std::setprecision(15) <<" nextTimeTildeDemodulated at SSB (in TDB) is: " << nextTimeTildeDemodulated - (StartMissionDateMJD)*SecsOneDay << " s." << std::endl; std::cout << std::setprecision(15) <<" nextTimeTilde at SSB (in TDB) is: " << nextTimeTilde - (StartMissionDateMJD)*SecsOneDay << " s." << std::endl; std::cout << std::setprecision(15) <<" nextTimeTilde decorrected (TT) is: " << nextTimeTildeDecorr - (StartMissionDateMJD)*SecsOneDay << " s." << std::endl; std::cout << " corrected is " << nextTimeTildeDecorr + getBaryCorr(nextTimeTildeDecorr,0) - (StartMissionDateMJD)*SecsOneDay << std::endl; std::cout << std::setprecision(15) <<" -->Interval is " << nextTimeTildeDecorr - timeTildeDecorr << std::endl; } // double interv = nextTimeTildeDecorr - timeTildeDecorr; double interv = nextTimeTildeDecorr-(time + (StartMissionDateMJD)*SecsOneDay); if (interv <= 0.) interv = m_periodVect[0]/100.; return interv; } ///////////////////////////////////////////// /*! * \param time time where the number of turns is computed * * This method compute the number of turns made by the pulsar according to the ephemerides. * <br> * <blockquote> * f(t) = f<sub>0</sub> + f<sub>1</sub>(t - t<sub>0</sub>) + * f<sub>2</sub>/2(t - t<sub>0</sub>)<sup>2</sup>. * <br>The number of turns is related to the ephemerides as:<br> * dN(t) = N<sub>0</sub> + phi<sub>0</sub> + f<sub>0</sub> + f<sub>1</sub>(t-t<sub>0</sub>) + 1/2f<sub>2</sub>(t-t<sub>0</sub>)<sup>2</sup> * </blockquote> * <br>where * <blockquote> *<ul> * <li> t<sub>0</sub> is an ephemeris epoch.In this simulator epoch must be expressed in MJD;</li> * <li> N<sub>0</sub> is the number of turns at epoch t<sub>0</sub>; * <li> phi<sub>0</sub> is the phase shift at epoch t<sub>0</sub>; * <li>f<sub>0</sub> pulse frequency at time t<sub>0</sub> (usually given in Hz)</li>, * <li>f<sub>1</sub> the 1st time derivative of frequency at time t< sub>0</sub> (Hz s<sup>-1</sup>);</li> * <li>f<sub>2</sub> the 2nd time derivative of frequency at time t<sub>0</sub> (Hz s<sup>-2</sup>).</li> * </ul> * </blockquote> */ double PulsarSpectrum::getTurns( double time ) { double dt = time - m_t0*SecsOneDay; return m_phi0 + m_N0 + m_f0*dt + 0.5*m_f1*dt*dt + ((m_f2*dt*dt*dt)/6.0); } ///////////////////////////////////////////// /*! * \param tTilde Time from where retrieve the nextTime; * \param totalTurns Number of turns completed by the pulsar at nextTime; * \param err Phase tolerance between totalTurns and the number of turns at nextTime * * <br>In this method a recursive way is used to find the <i>nextTime</i>. Starting at <i>tTilde</i>, the method returns * nextTime, the time where the number of turns completed by the pulsar is equal to totalTurns (within the choosen tolerance). */ double PulsarSpectrum::retrieveNextTimeTilde( double tTilde, double totalTurns, double err ) { double tTildeUp,NTup = 0.; double tTildeDown,NTdown = 0; tTildeUp = tTilde; tTildeDown = tTilde; NTdown = totalTurns - getTurns(tTildeDown); NTup = totalTurns - getTurns(tTildeUp); int u = 0; int nIterations = 0; while ((NTdown*NTup)>0) { u++; tTildeUp = tTilde+m_period*pow(2.0,u); NTdown = totalTurns - getTurns(tTildeDown); NTup = totalTurns - getTurns(tTildeUp); } double tTildeMid = (tTildeDown+tTildeUp)/2.0; double NTmid = totalTurns - getTurns(tTildeMid); while(fabs(NTmid) > err ) { nIterations++; if ((fabs(NTmid) < err) || (nIterations > 200)) break; NTmid = totalTurns - getTurns(tTildeMid); NTdown = totalTurns - getTurns(tTildeDown); if ((NTmid*NTdown)>0) { tTildeDown = tTildeMid; tTildeMid = (tTildeDown+tTildeUp)/2.0; } else { tTildeUp = tTildeMid; tTildeMid = (tTildeDown+tTildeUp)/2.0; } } if (DEBUG) { std::cout << "** RetrieveNextTimeTilde " << std::endl; std::cout << std::setprecision(30) << " Stop up is " << tTildeUp << " NT " << NTup << std::endl; std::cout << std::setprecision(30) << " down is " << tTildeDown << " NT " << NTdown << " u= " << u << std::endl; std::cout << std::setprecision(30) << " mid is " << tTildeMid << " NT " << NTmid << " u= " << u << std::endl; std::cout << " nextTimeTilde is " << tTildeMid << std::endl; } return tTildeMid; } ///////////////////////////////////////////// /*! * \param ttInput Photon arrival time at spacecraft in Terrestrial Time (expressed in MJD converted in seconds) * * <br> * This method computes the barycentric corrections for the photon arrival time at spacecraft and returns * the time in Solar System Barycentric Time. The corrections implemented at the moment are: * <ul> * <li> Conversion from TT to TDB; * <li> Geometric Time Delay due to light propagation in Solar System; * <li> Relativistic Shapiro delay; * </ul> */ double PulsarSpectrum::getBaryCorr( double ttInput, int LogCorrFlag) { if (((ttInput-(StartMissionDateMJD)*SecsOneDay)+510)>m_FT2_stopMET) { if (m_OutputLevel>1) { char temp[200]; sprintf(temp,"WARNING!!!Arrival time after FT2 end. No barycentric correction! at t=%.f",ttInput); WriteToLog(std::string(temp)); } return 0.; } //Start Date; astro::JulianDate ttJD(StartMissionDateMJD+JDminusMJD); ttJD = ttJD+(ttInput - (StartMissionDateMJD)*SecsOneDay)/SecsOneDay; if (DEBUG) { std::cout << std::setprecision(30) << "\nBarycentric Corrections for time " << ttJD << " (JD)" << std::endl; } // Conversion TT to TDB, from JDMissionStart (that glbary uses as MJDref) double tdb_min_tt = m_earthOrbit->tdb_minus_tt(ttJD); double timeMET = ttInput - (StartMissionDateMJD)*SecsOneDay; CLHEP::Hep3Vector scPos; //Exception error in case of time not in the range of available position (when using a FT2 file) try { // std::cout<<astro::GPS::time()<<std::endl; //astro::GPS::update(timeMET); // std::cout<<astro::GPS::time()<<std::endl; astro::GPS::instance()->time(timeMET); scPos = astro::GPS::instance()->position(timeMET); } catch (astro::PointingHistory::TimeRangeError & ) { if (DEBUG) { std::cout << "WARNING! FT2 Time Error at " << std::setprecision(30) << timeMET << std::endl; } if ((timeMET+510)>=m_FT2_stopMET) { return 0.; } } //Correction due to geometric time delay of light propagation //GLAST position CLHEP::Hep3Vector GeomVect = (scPos/clight); double GLASTPosGeom = GeomVect.dot(m_PulsarVectDir); double GeomCorr = 0; double EarthPosGeom =0.; try{ //Earth position GeomVect = - m_solSys.getBarycenter(ttJD); EarthPosGeom = GeomVect.dot(m_PulsarVectDir); GeomVect = (scPos/clight) - m_solSys.getBarycenter(ttJD); GeomCorr = GeomVect.dot(m_PulsarVectDir); } catch (astro::SolarSystem::BadDate & ) { std::cout << "WARNING! JD Bad Date " << ttJD <<std::endl; GeomCorr = 0.; } //Correction due to Shapiro delay. CLHEP::Hep3Vector sunV = m_solSys.getSolarVector(ttJD); // Angle of source-sun-observer double costheta = - sunV.dot(m_PulsarVectDir) / ( sunV.mag() * m_PulsarVectDir.mag() ); double m = 4.9271e-6; // m = G * Msun / c^3 double ShapiroCorr = 2.0 * m * log(1+costheta); if (DEBUG) { std::cout << std::setprecision(20) << "** --> TDB-TT = " << tdb_min_tt << std::endl; std::cout << std::setprecision(20) << "** --> Geom. delay = " << GeomCorr << std::endl; std::cout << std::setprecision(20) << "** --> Shapiro delay = " << ShapiroCorr << std::endl; std::cout << std::setprecision(20) << "** ====> Total= " << tdb_min_tt + GeomCorr + ShapiroCorr << " s." <<std::endl; } if ((LogCorrFlag == 1) && (ttInput-StartMissionDateMJD*SecsOneDay > 0.)) { double intPart=0.; double PhaseOut = getTurns(ttInput); PhaseOut = modf(PhaseOut,&intPart); // phase for linear evolution if (PhaseOut < 0) PhaseOut++; std::ofstream BaryCorrLogFile((m_PSRname + "BaryCorr.log").c_str(),std::ios::app); BaryCorrLogFile << std::setprecision(20) << timeMET << "\t" << PhaseOut << "\t" << GLASTPosGeom << "\t"<< EarthPosGeom << "\t" << GeomCorr << "\t" << tdb_min_tt << "\t" << ShapiroCorr << std::endl; BaryCorrLogFile.close(); } return tdb_min_tt + GeomCorr + ShapiroCorr; //seconds } ///////////////////////////////////////////// /*! * \param tInput Photon arrival time do be demodulated * \param LogFlag Flag for writing output * * <br> * This method compute the binary demodulation in an iterative way * using the getBinaryDemodulation method */ double PulsarSpectrum::getIterativeDemodulatedTime(double tInput, int LogFlag) { double timeDemodulated = tInput+getBinaryDemodulation(tInput,0); double TargetTime = tInput; double delay = getBinaryDemodulation(tInput,0); int i=0; while ((fabs(timeDemodulated-delay-TargetTime) > DemodTol) && ( i < 50)) { i++; timeDemodulated = TargetTime+delay; delay = getBinaryDemodulation(timeDemodulated,0); // std::cout << "Step " << i << " t= " << timeDemodulated-(StartMissionDateMJD)*SecsOneDay<<std::endl; } if (LogFlag == 1) { delay = getBinaryDemodulation(timeDemodulated,1); } return timeDemodulated; } ///////////////////////////////////////////// /*! * \param tInput Photon arrival time do be demodulated * <br> * This method returns the true anomaly */ double PulsarSpectrum::getTrueAnomaly(double tInput) { //double BinaryRoemerDelay = 0.; double dt = tInput-m_t0PeriastrMJD*SecsOneDay; double OmegaMean = 2*M_PI/m_Porb; double EccAnConst = OmegaMean*(dt - 0.5*(dt*dt*(m_Porb_dot/m_Porb))); //Calculate Eccenctric Anomaly solving Kepler equation using the atKepler function double EccentricAnomaly = 0.; int status = atKepler(EccAnConst, m_ecc, &EccentricAnomaly); //AtKepler // atKepler not converged if (0 != status) { throw std::runtime_error("atKepler did not converge."); } //Calculate True Anomaly double TrueAnomaly = 2.0 * std::atan(std::sqrt((1.0+m_ecc)/(1.0-m_ecc))*std::tan(EccentricAnomaly*0.5)); TrueAnomaly = TrueAnomaly + 2*M_PI*floor((EccentricAnomaly - TrueAnomaly)/ (2*M_PI)); while ((TrueAnomaly - EccentricAnomaly) > M_PI) TrueAnomaly -= 2*M_PI; while ((EccentricAnomaly - TrueAnomaly) > M_PI) TrueAnomaly += 2*M_PI; return TrueAnomaly; } ///////////////////////////////////////////// /*! * \param tInput Photon arrival time do be demodulated * <br> * This method returns the true anomaly */ double PulsarSpectrum::getOrbitalPhase(double tInput) { //double BinaryRoemerDelay = 0.; double dt = tInput-m_t0PeriastrMJD*SecsOneDay; double dp = dt/m_Porb; // Compute the complete phase. double phase = dp * (1. - dp *m_Porb_dot / 2.0); double intOrb; double OrbPhase = modf(phase,&intOrb); if (OrbPhase<0) OrbPhase+=1; return OrbPhase; } ///////////////////////////////////////////// /*! * \param tInput Photon arrival time do be demodulated * \param LogFlag Flag for writing output * * <br> * This method compute the binary demodulation using the orbital parameters * of the pulsar. The corrections computed are: * *<ul> * <li> Roemer delay * <li> Einstein delay * <li> Shapiro delay *</ul> */ double PulsarSpectrum::getBinaryDemodulation( double tInput, int LogDemodFlag) { double BinaryRoemerDelay = 0.; double dt = tInput-m_t0PeriastrMJD*SecsOneDay; double OmegaMean = 2*M_PI/m_Porb; double EccAnConst = OmegaMean*(dt - 0.5*(dt*dt*(m_Porb_dot/m_Porb))); //Calculate Eccenctric Anomaly solving Kepler equation using the atKepler function double EccentricAnomaly = 0.; int status = atKepler(EccAnConst, m_ecc, &EccentricAnomaly); //AtKepler // atKepler not converged if (0 != status) { throw std::runtime_error("atKepler did not converge."); } //Calculate True Anomaly double TrueAnomaly = 2.0 * std::atan(std::sqrt((1.0+m_ecc)/(1.0-m_ecc))*std::tan(EccentricAnomaly*0.5)); TrueAnomaly = TrueAnomaly + 2*M_PI*floor((EccentricAnomaly - TrueAnomaly)/ (2*M_PI)); while ((TrueAnomaly - EccentricAnomaly) > M_PI) TrueAnomaly -= 2*M_PI; while ((EccentricAnomaly - TrueAnomaly) > M_PI) TrueAnomaly += 2*M_PI; // Calculate longitude of periastron using m_omega_dot double Omega = DegToRad*m_omega + DegToRad*m_omega_dot*(TrueAnomaly/OmegaMean); // compute projected semimajor axis using x_dot double asini = m_asini + m_xdot*dt; //Binary Roemer delay BinaryRoemerDelay = ((std::cos(EccentricAnomaly)-m_ecc)*std::sin(Omega) + std::sin(EccentricAnomaly)*std::cos(Omega)*std::sqrt(1-m_ecc*m_ecc)); //Einstein Delay double BinaryEinsteinDelay = m_gamma*std::sin(EccentricAnomaly); //Shapiro binary delay double BinaryShapiroDelay = -2.0*m_shapiro_r*log(1.-m_ecc*std::cos(EccentricAnomaly)-m_shapiro_s*BinaryRoemerDelay); BinaryRoemerDelay = asini*BinaryRoemerDelay; if (DEBUG) { std::cout << "\n** Binary modulations t=" << std::setprecision(15) << tInput-(StartMissionDateMJD)*SecsOneDay << " dt=" << tInput - m_t0PeriastrMJD*SecsOneDay << std::endl; std::cout << "** Ecc.Anomaly=" << EccentricAnomaly << " deg. True Anomaly=" << TrueAnomaly << " deg." << std::endl; std::cout << "** Omega=" << Omega << " rad. Major Semiaxis " << asini << " light-sec" << std::endl; std::cout << "** --> Binary Roemer Delay=" << BinaryRoemerDelay << " s." << std::endl; std::cout << "** --> Binary Einstein Delay=" << BinaryEinsteinDelay << " s." << std::endl; std::cout << "** --> Binary Shapiro Delay=" << BinaryShapiroDelay << " s." << std::endl; } if ((LogDemodFlag==1) && (tInput-StartMissionDateMJD*SecsOneDay > 0.)) { std::ofstream BinDemodLogFile((m_PSRname + "BinDemod.log").c_str(),std::ios::app); BinDemodLogFile << std::setprecision(15) << tInput-StartMissionDateMJD*SecsOneDay << "\t" << tInput - m_t0PeriastrMJD*SecsOneDay << "\t" << EccentricAnomaly << "\t" << TrueAnomaly << "\t" << Omega << "\t" << m_ecc << "\t" << asini << "\t" << BinaryRoemerDelay << "\t" << BinaryEinsteinDelay << "\t" << BinaryShapiroDelay << "\t" << std::endl; BinDemodLogFile.close(); } return -1.*(BinaryRoemerDelay+BinaryEinsteinDelay+BinaryShapiroDelay); } ///////////////////////////////////////////// /*! * \param CorrectedTime Photon arrival time at SSB (TDB expressed in MJD) * * <br> * This method returns the correspondent decorrected time starting from a photon arrival time * at the Solar System barycenter expressed in Barycentric Dynamical Time. This function uses the bisection method * for inverting barycentric corrections <br> * The corrections implemented at the moment are: * <ul> * <li> Conversion from TT to TDB; * <li> Geometric Time Delay due to light propagation in Solar System; * <li> Relativistic Shapiro delay; * </ul> */ double PulsarSpectrum::getDecorrectedTime(double CorrectedTime) { // double CorrectedTime = 54.2342.; double deltaT = 510.; double tcurr = CorrectedTime-deltaT; double fcurr = tcurr + getBaryCorr(tcurr,0); // fx(tcurr); // double fcurr_ct = CorrectedTime; if (DEBUG) { std::cout << "Get decorrected time from time t=" << CorrectedTime << std::endl; } //double deltaStep = 10.; int s = 0; int SignDirection = 0; //std::cout << "\n\n***\ntstart= " << tcurr << " -->fcurr= " << fcurr // << " -->fcurr_CT= " << fcurr_ct << " inital delta=" << deltaStep << std::endl; if (CorrectedTime <= fcurr) // function increasing { // std::cout << "Case 1: de-crescent function" << std::endl; SignDirection = 1; } else { //std::cout << "Case 2: crescent function" << std::endl; SignDirection = 2; } double deltaStep = pow(10.,(2.-s)); while ( fabs(CorrectedTime-fcurr) > baryCorrTol) { if (SignDirection == 1) { while (fcurr > CorrectedTime) { tcurr = tcurr+deltaStep; fcurr = tcurr + getBaryCorr(tcurr,0); //fx(tcurr); // std::cout << std::setprecision(30) << " tcurr=>" << tcurr << " fcurr " << fcurr // << "df=" << CorrectedTime-fcurr << std::endl; } } else while (fcurr < CorrectedTime) { tcurr = tcurr+deltaStep; fcurr = tcurr + getBaryCorr(tcurr,0); //fx(tcurr); //std::cout << std::setprecision(30) << " tcurr=>" << tcurr << " fcurr " << fcurr // << "df=" << CorrectedTime-fcurr << std::endl; } tcurr = tcurr-deltaStep; fcurr = tcurr + getBaryCorr(tcurr,0); //fx(tcurr); s++; deltaStep = pow(10.,(2.-s)); //std::cout << "\n" << m_PSRname << " Target superated, decreasing to " << deltaStep // << " and starting again1 from " << tcurr << std::endl; //std::cout << std::setprecision(30) << CorrectedTime << //" <--" << fcurr << " df=" << CorrectedTime-fcurr << std::endl; if ((s > 10) || (deltaStep < 1e-7)) { //std::cout << "Skipping ! " << std::endl; break; } } if (DEBUG) { std::cout << std::setprecision(30) << s << " -> " << CorrectedTime << " <--" << fcurr << " df=" << CorrectedTime-fcurr << std::endl; } return tcurr; } ///////////////////////////////////////////// /*! * \param CorrectedTime Photon arrival time Modulatedat SSB (TDB expressed in MJD) * * <br> * This method returns the correspondent inverse-demodulated time of each photons, includingRoemer delay, Einstein delay * and Shapiro delay */ double PulsarSpectrum::getBinaryDemodulationInverse( double CorrectedTime) { double deltaMin = m_asini*(1.+m_ecc);//-m_asini*std::sqrt(1.-m_ecc*m_ecc); double tcurr = CorrectedTime-deltaMin; double fcurr = getIterativeDemodulatedTime(tcurr,0); // double fcurr_ct = CorrectedTime; if (DEBUG) { std::cout << "Get inverse demodulated time for t=" << CorrectedTime << std::endl; } //double deltaStep = 10.; int s = 0; int SignDirection = 0; double StartStep = 1.0*int(log10(fabs(deltaMin/10.))); double deltaStep = pow(10.,(StartStep-s)); //std::cout << "START " << StartStep << " dmin " << deltaMin << std::endl; if (CorrectedTime <= fcurr) // function increasing { // std::cout << "Case 1: de-crescent function" << std::endl; SignDirection = 1; } else { //std::cout << "Case 2: crescent function" << std::endl; SignDirection = 2; } /* std::cout << "\n\n***\n"<<m_PSRname<<"tstart= " << tcurr << " -->fcurr= " << fcurr << " -->fcurr_CT= " << CorrectedTime << " inital delta=" << deltaStep << " sign" << SignDirection << std::endl; */ //double tModMid=0.; int nMaxStepIterations=0; while ( fabs(CorrectedTime-fcurr) > InverseDemodTol) { nMaxStepIterations=0; if (SignDirection == 1) { while ((fcurr > CorrectedTime) && (nMaxStepIterations <1000)) { tcurr = tcurr+deltaStep; fcurr = getIterativeDemodulatedTime(tcurr,0); nMaxStepIterations++; if (fcurr < CorrectedTime) { break; } //std::cout << std::setprecision(30) << nMaxStepIterations <<" tcurr=>" << tcurr << " fcurr " << fcurr // << "df=" << CorrectedTime-fcurr << std::endl; } } else while ((fcurr < CorrectedTime) && (nMaxStepIterations <1000)) { tcurr = tcurr+deltaStep; fcurr = getIterativeDemodulatedTime(tcurr,0); nMaxStepIterations++; //std::cout << std::setprecision(30) << nMaxStepIterations << " tcurr=>" << tcurr << " fcurr " << fcurr //<< "df=" << CorrectedTime-fcurr << std::endl; if (fcurr > CorrectedTime) { break; } } tcurr = tcurr-deltaStep; fcurr = getIterativeDemodulatedTime(tcurr,0); s++; deltaStep = pow(10.,(StartStep-s)); //std::cout << "\n" << m_PSRname << " Target superated, decreasing to " << deltaStep // << " and starting again1 from " << tcurr << std::endl; //std::cout << std::setprecision(30) << CorrectedTime << //" <--" << fcurr << " df=" << CorrectedTime-fcurr << std::endl; if ((s > 8) || (deltaStep < 1e-7)) { //std::cout << "Skipping ! " << std::endl; break; } } // std::cout << std::setprecision(30) << s << " -> " << CorrectedTime // << " <--" << fcurr // << " df=" << CorrectedTime-fcurr << std::endl; return tcurr; } ///////////////////////////////////////////// /*! * \param None * * <br> * This method gets from the ASCII <i>PulsarDatalist.txt</i> file stored in <i>/data</i> directory) * the names of the files that contain the pulsars parameters. The default one is <i>BasicDataList.txt</i>. * This method returns a integer status code (1 is Ok, 0 is failure) */ int PulsarSpectrum::getPulsarFromDataList(std::string sourceFileName) { double startTime = 0.;//Spectrum::startTime(); double endTime = 0.;//astro::GPS::instance()->endTime(); if (m_UseFT2 == 1) { startTime = m_FT2_startMET + (550/86400.); endTime = m_FT2_stopMET - (550/86400.); } else { startTime = m_Sim_startMET + (550/86400.); endTime = m_Sim_stopMET - (550/86400.); } int Status = 0; std::ifstream PulsarDataTXT; if (DEBUG) { std::cout << "\nOpening Pulsar Datalist File : " << sourceFileName << std::endl; } PulsarDataTXT.open(sourceFileName.c_str(), std::ios::in); if (! PulsarDataTXT.is_open()) { throw "Error! Cannot open file "; } else { char aLine[400]; PulsarDataTXT.getline(aLine,400); char tempName[15] = ""; double flux, ephem0, ephem1, ephem2, t0Init, t0, t0End, txbary, phi0, period, pdot, p2dot, f0, f1, f2, phas; char ephemType[15] = ""; int tnmodel, binflag; while (PulsarDataTXT.eof() != 1) { PulsarDataTXT >> tempName >> flux >> ephemType >> ephem0 >> ephem1 >> ephem2 >> t0Init >> t0 >> t0End >> txbary >> tnmodel >> binflag; // std::cout << tempName << flux << ephemType << ephem0 << ephem1 << ephem2 // << t0Init << t0 << t0End << txbary << tnmodel << binflag <<std::endl; if (std::string(tempName) == m_PSRname) { Status = 1; m_flux = flux; m_TimingNoiseModel = tnmodel; m_ephemType = ephemType; m_BinaryFlag = binflag; //Check if txbary or t0 are before start of the simulation double startMJD = StartMissionDateMJD+(startTime/86400.)+(550/86400.); // std::cout << "T0 " << t0 << " start " << startMJD << std::endl; if ((t0 < startMJD) || (txbary < startMJD)) { if (m_OutputLevel>1) { char temp[200]; sprintf(temp,"Warning! Epoch t0 out the simulation range (t0-tStart=%.10f) s.: changing to MJD=%d",(t0-startMJD),startMJD); WriteToLog(std::string(temp)); } t0 = startMJD; txbary = startMJD; } //Check if txbary or t0 are after start of the simulation double endMJD = StartMissionDateMJD+(endTime/86400.)-(550/86400.); // std::cout << "T0 " << t0 << " start " << startMJD << std::endl; if ((t0 > endMJD) || (txbary > endMJD)) { if (m_OutputLevel>1) { char temp[200]; sprintf(temp,"Warning! Epoch t0 out the simulation range (t0-tEnd=%.10f) s.: changing to MJD=%d", (t0-endMJD),endMJD); WriteToLog(std::string(temp)); sprintf(temp,"** Tnd at %d corresp. to MJD %d",endTime,endMJD); WriteToLog(std::string(temp)); } t0 = endMJD; txbary = endMJD; } m_t0InitVect.push_back(t0Init); m_t0Vect.push_back(t0); m_t0EndVect.push_back(t0End); m_txbaryVect.push_back(txbary); //Period-type ephemerides if (std::string(ephemType) == "P") { period = ephem0; pdot = ephem1; p2dot = ephem2; f0 = 1.0/period; f1 = -pdot/(period*period); f2 = 2*pow((pdot/period),2.0)/period - p2dot/(period*period); } else if (std::string(ephemType) == "F") { //Frequency-style ephemrides f0 = ephem0; f1 = ephem1; f2 = ephem2; period = 1.0/f0; } m_periodVect.push_back(period); m_pdotVect.push_back(pdot); m_p2dotVect.push_back(p2dot); m_f0Vect.push_back(f0); m_f1Vect.push_back(f1); m_f2Vect.push_back(f2); double dt = (txbary-t0)*SecsOneDay; phi0 = -1.0*(f0*dt + (f1/2.0)*dt*dt + (f2/6.0)*dt*dt*dt); phi0 = modf(phi0,&phas); if (phi0 < 0. ) phi0++; m_phi0Vect.push_back(phi0); } } } return Status; } ///////////////////////////////////////////// /*! * \param pulsar_data_dir: $PULSARDATA directory; * \param DataType: Type of data to be loaded (0=General data; 1=Orbital Data); * * <br> * This method load pulsar general data (flux, spin parameters, etc..) of * orbital data (kepler parameters, etc..) according to DataType parameter * Datafiles containing parameters must be specified in $PULSARDATA/PulsarDataList.txt * for general data or $PULSARDATA/PulsarBinDataList.txt for orbital data * */ void PulsarSpectrum::LoadPulsarData(std::string pulsar_data_dir, int DataType = 0) { //Scan PulsarDataList.txt for Pulsar general data std::string ListFileName; if (DataType == 0) { ListFileName = facilities::commonUtilities::joinPath(pulsar_data_dir, "PulsarDataList.txt"); if (DEBUG) { std::cout << "Reading General Data" << std::endl; } } else if (DataType == 1) { ListFileName = facilities::commonUtilities::joinPath(pulsar_data_dir, "PulsarBinDataList.txt"); if (DEBUG) { std::cout << "Reading Orbital Data" << std::endl; } } //new block for reading lines //max try { CheckFileExistence(ListFileName); std::ifstream ListFile(ListFileName.c_str()); std::string dataline; std::vector<std::string> datalines; while (std::getline(ListFile, dataline, '\n')) { if (dataline != "" && dataline != " " && dataline.find_first_of('#') != 0) { datalines.push_back(dataline); } } // After lines are parsed, each DataList is processed... int PulsarFound=0; int l=0; while ((l<datalines.size()) && (PulsarFound!=1)) { std::string CompletePathFileName = facilities::commonUtilities::joinPath(pulsar_data_dir,datalines[l]); try { if (DataType == 0) { PulsarFound = getPulsarFromDataList(CompletePathFileName); } else if (DataType == 1) { PulsarFound = getOrbitalDataFromBinDataList(CompletePathFileName); } } catch (char const *error) //DataList does not exists.... { if (m_OutputLevel>1) { WriteToLog("WARNING!"+std::string(error)+std::string(CompletePathFileName) +"... skip to next ASCII Data list file"); } } l++; } if (PulsarFound == 0)//if no Datalist contains pulsars... { std::cout << "ERROR! Unable to find pulsar " << m_PSRname << " in any DataList. Check $PULSARDATA" << std::endl; exit(1); } //if requested, initialize log output for barycentric corrections if (::getenv("PULSAR_OUT_BARY")) { std::ofstream BaryCorrLogFile((m_PSRname + "BaryCorr.log").c_str()); BaryCorrLogFile << "\nPulsar" << m_PSRname << " : Barycentric corrections log generated by PulsarSpectrum" << std::endl; BaryCorrLogFile << "tMET\tTDB-TT\tGeomDelay\tShapiroDelay" << std::endl; BaryCorrLogFile.close(); } //if requested, initialize log output for barycentric corrections if ((m_BinaryFlag ==1) && (::getenv("PULSAR_OUT_BIN"))) { std::ofstream BinDemodLogFile((m_PSRname + "BinDemod.log").c_str()); BinDemodLogFile << "tMET\tdt\tE\tAt\tOmega\tecc\tasini\tdt_Roemer\tdt_einstein\tdt_shapiro" << std::endl; BinDemodLogFile.close(); } } catch (char const *error) //DataList.txt of BinDataList.txt does not exists... { std::cerr << error << ListFileName << std::endl; exit(1); } if (DataType == 0) { //Assign as starting ephemeris the first entry of the vectors... m_t0Init = m_t0InitVect[0]; m_t0 = m_t0Vect[0]; m_t0End = m_t0EndVect[0]; m_period = m_periodVect[0]; m_pdot = m_pdotVect[0]; m_p2dot = m_p2dotVect[0]; m_f0 = m_f0Vect[0]; m_f1 = m_f1Vect[0]; m_f2 = m_f2Vect[0]; m_f0NoNoise = m_f0Vect[0]; m_f1NoNoise = m_f1Vect[0]; m_f2NoNoise = m_f2Vect[0]; m_phi0 = m_phi0Vect[0]; } } ///////////////////////////////////////////// /*! * \param None * * <br> * This method gets the orbital parameters of the binary pulsar from a * <i>BinDataList/i> file among those specified in the<i>/data/PulsarBinDataList</i> * * The orbital parameters are: * * m_Porb Orbital period; * m_asini Projected major semiaxis; * m_eccentr eccentricity; * m_omega longitude of periastron; * m_t0PeriastronMJD epoch of periastron passage; * m_t0AscNodeMJD Epoch of the ascending node; * * The key for finding pulsar is the name of the files that contain the pulsars parameters. * The default one is <i>BasicDataList.txt</i>. * Extra parameters are used to specify a PPN parameterization for General Relativity; * This method returns a integer status code (1 is Ok, 0 is failure) */ int PulsarSpectrum::getOrbitalDataFromBinDataList(std::string sourceBinFileName) { int Status = 0; std::ifstream PulsarBinDataTXT; if (DEBUG) { std::cout << "\nOpening Binary Pulsar BinDatalist File : " << sourceBinFileName << std::endl; } PulsarBinDataTXT.open(sourceBinFileName.c_str(), std::ios::in); if (! PulsarBinDataTXT.is_open()) { throw "Error!Cannot open file"; // std::cout << "Error opening BinDatalist file " << sourceBinFileName // << " (check whether $PULSARDATA is set)" << std::endl; //Status = 0; //exit(1); } char aLine[400]; PulsarBinDataTXT.getline(aLine,400); char tempName[30]; double porb,asini,ecc,omega,t0peri,t0asc,ppn; while (PulsarBinDataTXT.eof() != 1) { PulsarBinDataTXT >> tempName >> porb >> asini >> ecc >> omega >> t0peri >> t0asc >> ppn; if (std::string(tempName) == m_PSRname) { Status = 1; m_Porb = porb; m_asini = asini; m_ecc = ecc; m_omega = omega; m_t0PeriastrMJD = t0peri; m_t0AscNodeMJD = t0asc; m_PPN = ppn; } } return Status; } ///////////////////////////////////////////// /*! * \param None * * <br> * Initialize variable related to timing noise */ void PulsarSpectrum::InitTimingNoise() { if (::getenv("PULSAR_OUT_TNOISE")) { std::ofstream TimingNoiseLogFile((m_PSRname + "TimingNoise.log").c_str()); TimingNoiseLogFile << "Timing Noise log file using model: " << m_TimingNoiseModel << std::endl; TimingNoiseLogFile << "tMET\tA\tS0\tS1\tS2\tf0_l\tf0_n\tf1_l\tf1_n\tf2_l\tf2_n\tPhi_l\tPhi_n" <<std::endl; TimingNoiseLogFile.close(); } //define a default mean rate of about 1 day m_TimingNoiseMeanRate = 1/86400.; // according to Poisson statistics double startTime = Spectrum::startTime(); //Determine next Timing noise event according to the rate R m_TimingNoiseRate m_TimingNoiseTimeNextEvent = startTime -log(1.-m_PSpectrumRandom->Uniform(1.0))/m_TimingNoiseMeanRate; } ///////////////////////////////////////////// /*! * \param None * * <br> * TnoiseInputTime input time where to apply noise * * Do the timing noise calculation on ephemerides */ void PulsarSpectrum::ApplyTimingNoise(double TnoiseInputTime) { double intPart=0.; //Integer part double PhaseNoNoise,PhaseWithNoise=0.; //Check for a next Timing noise event if ((TnoiseInputTime-(StartMissionDateMJD)*SecsOneDay) > m_TimingNoiseTimeNextEvent) { //interval according to Poisson statistics m_TimingNoiseTimeNextEvent+= -log(1.-m_PSpectrumRandom->Uniform(1.0))/m_TimingNoiseMeanRate; if (DEBUG) { std::cout << std::setprecision(30)<<"Timing Noise Event!Next Event at t=" << m_TimingNoiseTimeNextEvent << " |dt=" << m_TimingNoiseTimeNextEvent -(TnoiseInputTime-(StartMissionDateMJD)*SecsOneDay) <<std::endl; } //Timing noise managing... double S0=0.; double S1=0.; double S2=0.; if (m_TimingNoiseModel ==1) // Timing Noise #1 { m_f2 = 0; PhaseNoNoise = getTurns(TnoiseInputTime); PhaseNoNoise = modf(PhaseNoNoise,&intPart); // phase for linear evolution if ( PhaseNoNoise <0.) PhaseNoNoise+=1.; m_TimingNoiseActivity = 6.6 + 0.6*log10(m_pdot) + m_PSpectrumRandom->Gaus(0,0.5); //estimate an f2 double Sign = m_PSpectrumRandom->Uniform(); if (Sign > 0.5) m_f2 = ((m_f0*6.*std::pow(10.,m_TimingNoiseActivity))*1e-24); else m_f2 = -1.0*((m_f0*6.*std::pow(10.,m_TimingNoiseActivity))*1e-24); } else if ((m_TimingNoiseModel >1) && (m_TimingNoiseModel < 5)) // Timing Noise RW -Cordes-Downs { m_f2 = 0.; double tempPhi0 = m_phi0; m_phi0 = 0.; double tempF0 = m_f0; m_f0 = m_f0NoNoise; double tempF1 = m_f1; m_f1 = m_f1NoNoise; PhaseNoNoise = getTurns(TnoiseInputTime); PhaseNoNoise = modf(PhaseNoNoise,&intPart); // phase for linear evolution if ( PhaseNoNoise <0.) PhaseNoNoise+=1.; //Determine Crab RMS double dt_days = (TnoiseInputTime-(StartMissionDateMJD)*SecsOneDay)/SecsOneDay; double s_rms_crab = 0.012*pow((dt_days/1628),1.5); //Activity parameter //m_TimingNoiseActivity = -1.37+0.71*log10(m_pdot*1E15); //double s_rms = pow(10.0,m_TimingNoiseActivity)*s_rms_crab; m_TimingNoiseActivity = -1.37+0.71*log(m_pdot*1E15); double s_rms = exp(m_TimingNoiseActivity)*s_rms_crab; if (m_TimingNoiseModel ==2) //Case 1 :PN { S0 = (3.7*3.7*s_rms*s_rms)*(2/(SecsOneDay*dt_days)); m_TimingNoiseRMS = std::sqrt((S0/m_TimingNoiseMeanRate)); m_phi0 = tempPhi0+m_PSpectrumRandom->Gaus(0,m_TimingNoiseRMS); // std::cout << std::setprecision(30) << "A="<<m_TimingNoiseActivity<<" dt"<<dt_days << " s_rms" << s_rms << //" S0 " << S0 << " RMS " << m_TimingNoiseRMS << " phi0 " << m_phi0 << std::endl; } else if (m_TimingNoiseModel ==3) //Case 2 :PN { S1 =(15.5*15.5*s_rms*s_rms)*(12./pow((SecsOneDay*dt_days),3)); m_TimingNoiseRMS = std::sqrt((S1/m_TimingNoiseMeanRate)); m_f0 = tempF0+m_PSpectrumRandom->Gaus(0,m_TimingNoiseRMS); //std::cout << std::setprecision(30) << "A="<<m_TimingNoiseActivity<<" dt"<<dt_days << " s_rms" << s_rms << //" S1 " << S1 << " RMS " << m_TimingNoiseRMS << " f0 " << m_f0 << std::endl; } else if (m_TimingNoiseModel ==4) //Case 3 :SN { S2 =(23.7*23.7*s_rms*s_rms)*(120./pow((SecsOneDay*dt_days),5)); m_TimingNoiseRMS = std::sqrt((S2/m_TimingNoiseMeanRate)); m_f1 = tempF1+m_PSpectrumRandom->Gaus(0,m_TimingNoiseRMS); //std::cout << std::setprecision(30) << "A="<<m_TimingNoiseActivity<<" dt"<<dt_days << " s_rms" << s_rms << // " S2 " << S2 << " RMS " << m_TimingNoiseRMS << " f1 " << m_f1 << std::endl; } } if ((DEBUG) || (::getenv("PULSAR_OUT_TNOISE"))) { PhaseWithNoise = getTurns(TnoiseInputTime); PhaseWithNoise = modf(PhaseWithNoise,&intPart); // phase for linear evolution if ( PhaseWithNoise <0.) PhaseWithNoise+=1.; } if (::getenv("PULSAR_OUT_TNOISE")) { std::ofstream TimingNoiseLogFile((m_PSRname + "TimingNoise.log").c_str(),std::ios::app); m_f2NoNoise = 0.; double ft_l = GetFt(TnoiseInputTime,m_f0NoNoise,m_f1NoNoise,m_f2NoNoise); double ft_n = GetFt(TnoiseInputTime,m_f0,m_f1,m_f2); double ft1_l = GetF1t(TnoiseInputTime,m_f1NoNoise,m_f2NoNoise); double ft1_n = GetF1t(TnoiseInputTime,m_f1,m_f2); double ft2_l = m_f2NoNoise;// double ft2_n = m_f2;// TimingNoiseLogFile << std::setprecision(30) << TnoiseInputTime-(StartMissionDateMJD)*SecsOneDay << "\t" << m_TimingNoiseActivity << "\t" << S0 << "\t" << S1 << "\t" << S2 << "\t" <<ft_l << "\t" << ft_n << "\t" <<ft1_l << "\t" << ft1_n << "\t" <<ft2_l << "\t" << ft2_n << "\t" << PhaseNoNoise << "\t" << PhaseWithNoise << std::endl; } if (DEBUG) { std::cout << std::setprecision(30) << " Activity=" << m_TimingNoiseActivity << "f2=" << m_f2 << " PN=" << PhaseWithNoise << " dPhi=" << PhaseWithNoise-PhaseNoNoise <<std::endl; } } } ///////////////////////////////////////////// /*! * \param None * * <br> * This method check if the current time is within valid ephemerides */ void PulsarSpectrum::CheckEphemeridesValidity(double EphCheckTime, double initTurns) { //Checks whether ephemerides (period,pdot, etc..) are within validity ranges if (((EphCheckTime/SecsOneDay) < m_t0Init) || ((EphCheckTime/SecsOneDay) > m_t0End)) { if (m_OutputLevel>1) { WriteToLog("WARNING! Time is out of range of validity for pulsar "+std::string(m_PSRname) +": Switching to new ephemerides set..."); } for (unsigned int e=0; e < m_t0Vect.size();e++) if (((EphCheckTime/SecsOneDay) > m_t0InitVect[e]) && ((EphCheckTime/SecsOneDay) < m_t0EndVect[e])) { m_t0Init = m_t0InitVect[e]; m_t0 = m_t0Vect[e]; m_t0End = m_t0EndVect[e]; m_f0 = m_f0Vect[e]; m_f1 = m_f1Vect[e]; m_f2 = m_f2Vect[e]; m_f0NoNoise = m_f0Vect[e]; m_f1NoNoise = m_f1Vect[e]; m_f2NoNoise = m_f2Vect[e]; m_period = m_periodVect[e]; m_pdot = m_pdotVect[e]; m_p2dot = m_p2dotVect[e]; m_phi0 = m_phi0Vect[e]; if (m_OutputLevel>1) { WriteToLog("Valid Ephemerides set found:"); char temp[200]; sprintf(temp,"MJD(%d-%d) --> Epoch t0 = MJD %d",m_t0Init,m_t0End,m_t0); WriteToLog(std::string(temp)); sprintf(temp,"f0: %.f Hz | f1: %.e Hz/s | f2 %.e Hz/s2 ",m_f0,m_f1,m_f2); WriteToLog(std::string(temp)); sprintf(temp,"P0: %.f s | P1: %.e s/s | P2 %.e s/s2 ",m_period,m_pdot,m_p2dot); WriteToLog(std::string(temp)); } //Re-instantiate PulsarSim and SpectObj delete m_Pulsar; m_Pulsar = new PulsarSim(m_PSRname, m_seed, m_flux, m_enphmin, m_enphmax, m_period); if (m_model == 1) { delete m_spectrum; m_spectrum = new SpectObj(m_Pulsar->PSRPhenom(double(m_ppar0), m_ppar1,m_ppar2,m_ppar3,m_ppar4),1); m_spectrum->SetAreaDetector(EventSource::totalArea()); } m_N0 = m_N0 + initTurns - getTurns(EphCheckTime); //Number of turns at next t0 double intN0; double N0frac = modf(m_N0,&intN0); // Start time for interval m_N0 = m_N0 - N0frac; if (m_OutputLevel > 1) { std::cout << std::setprecision(20) << " Turns now are " << initTurns << " ; at t0 " << m_N0 << std::endl; } //m_phi0 = m_phi0 - N0frac; if (DEBUG) { std::cout << std::setprecision(20) << " At Next t0 Number of Turns will be: " << m_N0 << std::endl; } } else { if (m_OutputLevel>1) { WriteToLog("WARNING! Valid ephemerides not found!Proceeding with the old ones"); } } } } ///////////////////////////////////////////// /*! * \param None * * <br> * This method saves the relevant information in a file, named SimPulsar_spin.txt. * The format of this ASCII file is such that it can be given to gtpulsardb to produce * a D4-compatible FITS file, that can be used with pulsePhase */ int PulsarSpectrum::saveDbTxtFile() { int Flag = 0; std::string DbOutputFileName = "SimPulsars_spin.txt"; std::ifstream DbInputFile; //Checks if the file exists DbInputFile.open(DbOutputFileName.c_str(), std::ios::in); if (! DbInputFile.is_open()) { Flag = 0; } else { Flag = 1; } DbInputFile.close(); if (DEBUG) { std::cout << "Saving Pulsar ephemerides on file " << DbOutputFileName << std::endl; } std::ofstream DbOutputFile; if (Flag == 0) { DbOutputFile.open(DbOutputFileName.c_str(), std::ios::out); DbOutputFile << "# Simulated pulsars output file generated by PulsarSpectrum." << std::endl; DbOutputFile << "SPIN_PARAMETERS\n"; DbOutputFile << "EPHSTYLE = FREQ\n\n# Then, a column header." << std::endl; DbOutputFile << "PSRNAME RA DEC EPOCH_INT EPOCH_FRAC TOAGEO_INT TOAGEO_FRAC TOABARY_INT TOABARY_FRAC "; DbOutputFile << "F0 F1 F2 RMS VALID_SINCE VALID_UNTIL BINARY_FLAG SOLAR_SYSTEM_EPHEMERIS OBSERVER_CODE" <<std::endl; DbOutputFile.close(); } //Writes out the infos of the file DbOutputFile.open(DbOutputFileName.c_str(),std::ios::app); double tempInt, tempFract; for (unsigned int ep = 0; ep < m_periodVect.size(); ep++) { DbOutputFile << "\"" << m_PSRname << std::setprecision(10) << "\" " << m_RA << " " << m_dec << " "; tempFract = modf(m_t0Vect[ep],&tempInt); DbOutputFile << std::setprecision (8) << tempInt << " " << tempFract << " "; tempFract = getDecorrectedTime(m_txbaryVect[ep]*SecsOneDay)/SecsOneDay; tempFract = modf(tempFract,&tempInt); DbOutputFile << std::setprecision (8) << tempInt << " " << tempFract << " "; tempFract = modf(m_txbaryVect[ep],&tempInt); DbOutputFile << std::setprecision (8) << tempInt << " " << tempFract << " "; std::string BinFlag; if (m_BinaryFlag==0) BinFlag = "F"; else if (m_BinaryFlag==1) BinFlag = "T"; std::string SolarEph; if (::getenv("PULSAR_EPH")) { const char * soleph = ::getenv("PULSAR_EPH"); SolarEph = " \"" + std::string(soleph) + "\""; } else { SolarEph = " \"JPL DE405\""; } DbOutputFile << std::setprecision(14) << m_f0Vect[ep] << " " << m_f1Vect[ep] << " " << m_f2Vect[ep] << " " << m_TimingNoiseRMS*1e3 << " " << m_t0InitVect[ep] << " " << m_t0EndVect[ep] << " " << BinFlag << SolarEph << " MR" << std::endl; } DbOutputFile.close(); if (DEBUG) if (Flag == 0) { std::cout << "Database Output file created from scratch " << std::endl; } else { std::cout << "Appendended data to existing Database output file" << std::endl; } return Flag; } ///////////////////////////////////////////// /*! * \param NameFileToCheck * * <br> * This method simply check the file and return an exception */ void PulsarSpectrum::CheckFileExistence(std::string NameFileToCheck) { std::ifstream FileToCheck; FileToCheck.open(NameFileToCheck.c_str(), std::ios::in); if (!FileToCheck.is_open()) { throw "Error!Cannot open file"; } FileToCheck.close(); } ///////////////////////////////////////////// /*! * \param None * * <br> * This method saves the relevant orbital parameters in a file, named SimPulsar_bin.txt. * The format of this ASCII file is such that it can be given to gtpulsardb to produce * a D4-compatible FITS file, that can be used with pulsePhase */ int PulsarSpectrum::saveBinDbTxtFile() { int Flag = 0; std::string DbBinOutputFileName = "SimPulsars_bin.txt"; std::ifstream DbBinInputFile; //Checks if the file exists DbBinInputFile.open(DbBinOutputFileName.c_str(), std::ios::in); if (! DbBinInputFile.is_open()) { Flag = 0; } else { Flag = 1; } DbBinInputFile.close(); if (DEBUG) { std::cout << "Saving Pulsar Orbital Data on file " << DbBinOutputFileName << std::endl; } std::ofstream DbBinOutputFile; if (Flag == 0) { DbBinOutputFile.open(DbBinOutputFileName.c_str(), std::ios::out); DbBinOutputFile << "# Simulated pulsars orbital data output file generated by PulsarSpectrum." << std::endl; DbBinOutputFile << "ORBITAL_PARAMETERS\nEPHSTYLE = DD /Simplified model\n# This file can be converted to a D4 fits file using:" << std::endl; DbBinOutputFile << "# >gtpulsardb SimPulsars_bin.txt" << std::endl; DbBinOutputFile << "PSRNAME PB PBDOT A1 XDOT ECC ECCDOT OM OMDOT T0 GAMMA SHAPIRO_R SHAPIRO_S OBSERVER_CODE SOLAR_SYSTEM_EPHEMERIS" << std::endl;; DbBinOutputFile.close(); } //Writes out the infos of the file DbBinOutputFile.open(DbBinOutputFileName.c_str(),std::ios::app); DbBinOutputFile << "\"" << m_PSRname << "\" "; // pulsar name DbBinOutputFile << std::setprecision(10) << m_Porb << " " << m_Porb_dot << " "; // Orbital period and derivative DbBinOutputFile << std::setprecision(10) << m_asini << " " << m_xdot << " "; // Projected semi-mayor axis and derivative DbBinOutputFile << std::setprecision(10) << m_ecc << " " << m_ecc_dot << " "; // Eccentricity and derivative DbBinOutputFile << std::setprecision(10) << m_omega << " " << m_omega_dot << " "; // Long. Periastron and derivative DbBinOutputFile << std::setprecision(10) << m_t0PeriastrMJD << " " << m_gamma << " "; // t0 of Periastron and PPN gamma //Shapiro Parameters DbBinOutputFile << std::setprecision(10) << m_shapiro_r << " " << m_shapiro_s; //Shapiro Parameters std::string SolarEph; if (::getenv("PULSAR_EPH")) { const char * soleph = ::getenv("PULSAR_EPH"); SolarEph = " \"" + std::string(soleph) + "\""; } else { SolarEph = " \"JPL DE405\""; } DbBinOutputFile << " MR "<<SolarEph<<std::endl;// Observer code and ephemerides DbBinOutputFile.close(); //In this case a summary D4 file is created std::ofstream DbSumInputFile("SimPulsars_summary.txt"); DbSumInputFile << "SimPulsars_spin.txt\nSimPulsars_bin.txt" <<std::endl; DbSumInputFile.close(); if (DEBUG) if (Flag == 0) { std::cout << "Database for Binary pulsars file created from scratch " << std::endl; } else { std::cout << "Database for Binary pulsars appended to existing binary Database output file" << std::endl; } return Flag; } ///////////////////////////////////////////// /*! * \param None * * <br> * This method saves the relevant information about pulsar in a log file */ void PulsarSpectrum::WritePulsarLog() { //Write infos to Log file std::ofstream PulsarLog(m_LogFileName.c_str(),std::ios::app); PulsarLog << "** PulsarSpectrum: " << "******** PulsarSpectrum Log for pulsar" << m_PSRname << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Name : " << m_PSRname << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Position : (RA,Dec)=(" << m_RA << "," << m_dec << ") ; (l,b)=(" << m_l << "," << m_b << ")" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Flux above 100 MeV : " << m_flux << " ph/cm2/s " << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Enphmin: " << m_enphmin << " keV | Enphmax: " << m_enphmax << " keV" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl; //Write info about FT2 if (m_UseFT2 == 0) { PulsarLog << "** PulsarSpectrum: "<< "** No FT2 file used " << std::endl; } else PulsarLog << "** PulsarSpectrum: "<< "** FT2 file used " << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Start time:" << std::setprecision(30) << m_FT2_startMET << " s. MET | End time:" << m_FT2_stopMET << " s. MET" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Simulation start at " << m_Sim_startMET << " s. MET and ends at :" << m_Sim_stopMET << std::endl; PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl; //Writes down on Log all the ephemerides for (unsigned int n=0; n < m_t0Vect.size(); n++) { PulsarLog << "** PulsarSpectrum: "<< "** Ephemerides valid from " << m_t0InitVect[n] << " to " << m_t0EndVect[n] << " (MJD): " << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Epoch (MJD) : " << m_t0Vect[n] << std::endl; PulsarLog << "** PulsarSpectrum: "<< std::setprecision(8) << "** TxBary (MJD) where fiducial point (phi=0) is reached : " << m_txbaryVect[n] << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Phi0 (at Epoch t0) : " << m_phi0Vect[n] << std::endl; if (m_ephemType == "P") { PulsarLog << "** PulsarSpectrum: "<< "** Ephemerides type: PERIOD" << std::endl; PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** Period : " << m_periodVect[n] << " s. | f0: " << m_f0Vect[n] << std::endl; PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** Pdot : " << m_pdotVect[n] << " | f1: " << m_f1Vect[n] << std::endl; PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** P2dot : " << m_p2dotVect[n] << " | f2: " << m_f2Vect[n] << std::endl; } else if (m_ephemType == "F") { PulsarLog << "** PulsarSpectrum: "<< "**Ephemerides type: FREQUENCY" << std::endl; PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** Period : " << m_periodVect[n] << " s. | f0: " << m_f0Vect[n] << std::endl; PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** f1: " << m_f1Vect[n] << std::endl; PulsarLog << "** PulsarSpectrum: "<< std::setprecision(14) << "** f2: " << m_f2Vect[n] << std::endl; } } //MJDRef PulsarLog << "** PulsarSpectrum: "<< "** Mission Reference time: MJD " << StartMissionDateMJD << " (" << std::setprecision(12) << (StartMissionDateMJD+JDminusMJD)*SecsOneDay << " sec.)" << std::endl; //SimulationModel if (m_model ==1) { PulsarLog << "** PulsarSpectrum: "<< "** Model chosen : " << m_model << " --> Using Phenomenological Pulsar Model " << std::endl; } else if (m_model == 2) { PulsarLog << "** PulsarSpectrum: "<< "** Model chosen : " << m_model << " --> Using External 2-D Pulsar Shape" << std::endl; } PulsarLog << "** PulsarSpectrum: "<< "** Effective Area set to : " << m_spectrum->GetAreaDetector() << " m^2 " << std::endl; PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl; //Timing noise if (m_TimingNoiseModel == 1) // Timing model #1 - Delta8 parameter (Arzoumanian94) { PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Model : " << m_TimingNoiseModel << " (Stability parameter, Arzoumanian 1994)" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Events Mean Rate : " << m_TimingNoiseMeanRate << std::endl; } else if (m_TimingNoiseModel == 2) //Timing model #2 - PN Random Walk (Cordes-Downs 1985) { PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Model : " << m_TimingNoiseModel << " (PN Random Walk; Cordes-Downs 1985)" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Events Mean Rate : " << m_TimingNoiseMeanRate << std::endl; } else if (m_TimingNoiseModel == 3) //Timing model #3 - FN Random Walk (Cordes-Downs 1985) { PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Model : " << m_TimingNoiseModel << " (FN Random Walk; Cordes-Downs 1985)" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Events Mean Rate : " << m_TimingNoiseMeanRate << std::endl; } else if (m_TimingNoiseModel == 4) //Timing model #4 - SN Random Walk (Cordes-Downs 1985) { PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Model : " << m_TimingNoiseModel << " (SN Random Walk; Cordes-Downs 1985)" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Timing Noise Events Mean Rate : " << m_TimingNoiseMeanRate << std::endl; } //Orbital info if (m_BinaryFlag == 1) { PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Pulsar in a Binary System! Orbital Data:" << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Orbital period: " << m_Porb << " s." << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Projected major semiaxis (a * sini): " << m_asini << " lightsec." <<std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Eccentricity: " << m_ecc << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Longitude of periastron: " << m_omega << " deg." << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Epoch of Periastron (MJD): " << m_t0PeriastrMJD << std::endl; PulsarLog << "** PulsarSpectrum: "<< "** Epoch of Ascending Node (MJD): " << m_t0AscNodeMJD << std::endl; if (m_PPN ==0) PulsarLog << "** PulsarSpectrum: "<< "** No Post Newtonian Parameterization " << std::endl; PulsarLog << "** PulsarSpectrum: "<< "**************************************************" << std::endl; } PulsarLog.close(); } ////////////////////////////////////////////////////////// // no longer used ///////////////////////////////////////////////////////// double PulsarSpectrum::GetEccentricAnomaly(double mytime) { double OmegaMean = 2*M_PI/m_Porb; double dtime = (mytime-m_t0PeriastrMJD*SecsOneDay); double EccAnConst = OmegaMean*(dtime - 0.5*(m_Porb_dot/m_Porb)*dtime*dtime); double Edown = 0.; double EccAnDown = Edown-(m_ecc*std::sin(Edown))-EccAnConst; double Eup = 2*M_PI; double EccAnUp = Eup-(m_ecc*std::sin(Eup))-EccAnConst; double Emid = 0.5*(Eup + Edown); double EccAnMid = Emid-(m_ecc*std::sin(Emid))-EccAnConst; int i=0; while (fabs(EccAnMid) > 5e-7) { if ((EccAnDown*EccAnMid) < 0) { Eup = Emid; EccAnUp = EccAnMid; } else { Edown = Emid; EccAnDown = EccAnMid; } i++; Emid = 0.5*(Eup + Edown); EccAnMid = Emid-(m_ecc*std::sin(Emid))-EccAnConst; if (fabs(EccAnMid) < 5e-7) break; } return Emid; } ///////////////////////////////////////////// double PulsarSpectrum::energy(double time) { return m_spectrum->energy(time,m_enphmin)*1.0e-3; //MeV } ///////////////////////////////////////////// /*! * \param time input time for calculating f(t) * * This method computes the frequency at a given instant t * */ double PulsarSpectrum::GetFt(double time, double myf0, double myf1, double myf2) { double dt = time - m_t0*SecsOneDay; return myf0 + myf1*dt + 0.5*myf2*dt*dt; } ///////////////////////////////////////////// /*! * \param time input time for calculating f'(t) * * This method computes the frequency first derivativeat a given instant t * */ double PulsarSpectrum::GetF1t(double time, double myf1, double myf2) { double dt = time - m_t0*SecsOneDay; return myf1 + myf2*dt; } ///////////////////////////////////////////// /*! * \param input String to be parsed; * \param index Position of the parameter to be extracted from input; * * <br> * From a string contained in the XML file a parameter is extracted according to the position * specified in <i>index</i> */ std::string PulsarSpectrum::parseParamList(std::string input, unsigned int index) { std::vector<std::string> output; unsigned int i=0; int StrLength=input.length(); while (i<StrLength) { i=input.find_first_of(","); std::string f = ( input.substr(0,i).c_str() ); //std::cout << "i=" <<"sub " << f <<std::endl; input=input.substr(i+1); output.push_back(f); } if(index>=output.size()) return ""; return output[index]; } /* old code: std::string PulsarSpectrum::parseParamList(std::string input, unsigned int index) { std::vector<std::string> output; unsigned int i=0; for(;!input.empty() && i!=std::string::npos;){ i=input.find_first_of(","); std::string f = ( input.substr(0,i).c_str() ); output.push_back(f); input= input.substr(i+1); } if(index>=output.size()) return ""; return output[index]; } */ ////////////////////////////////////////////////// /*! * \param Line line to be written in the output log file * * This method writes a line into a log file */ void PulsarSpectrum::WriteToLog(std::string Line) { std::ofstream PulsarLog(m_LogFileName.c_str(),std::ios::app); PulsarLog << "** PulsarSpectrum: " << Line << std::endl; PulsarLog.close(); }
72,439
29,138
//Generated lump file. generated by Bee.NativeProgramSupport.Lumping #include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/CustomAttributeCreator.cpp" #include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/CustomAttributeDataReader.cpp" #include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/FieldLayout.cpp" #include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/GenericMetadata.cpp" #include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/GenericSharing.cpp" #include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/Il2CppGenericContextCompare.cpp" #include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/Il2CppGenericMethodHash.cpp" #include "C:/Program Files/Unity 2021.2.8f1/Editor/Data/il2cpp/libil2cpp/metadata/Il2CppSignature.cpp"
925
384
#include "Papyrus/ExtendedObjectTypes.h" auto extendedObjectTypes::RegisterTypes(VM* a_vm) -> bool { if (!a_vm) { logger::critical("Object types - couldn't get VMState"sv); return false; } a_vm->RegisterObjectType(vm_cast<RE::BGSFootstepSet>(), "FootstepSet"); logger::info("Registered footstep set object type"sv); a_vm->RegisterObjectType(vm_cast<RE::BGSLightingTemplate>(), "LightingTemplate"); logger::info("Registered lighting template object type"sv); a_vm->RegisterObjectType(vm_cast<RE::BGSDebris>(), "Debris"); logger::info("Registered debris object type"sv); return true; }
603
217
#include <bits/stdc++.h> using namespace std; int main(){ map<int, int> m; int n,k; scanf("%d%d", &n, &k); vector<int> a(n); vector<int> b(n); for(int i = 0; i<n; i++){ scanf("%d", &a[i]); b[i] = a[i]; } sort(b.rbegin(), b.rend()); for(int i = 0; i<k; i++) if(m.find(b[i]) == m.end()) m[b[i]] = 1; else m[b[i]] += 1; int sz = 0; vector<int> ans; for(int i = 0; i<n; i++){ sz++; if(m.find(a[i]) != m.end() && m[a[i]] > 0) { ans.push_back(sz); sz = 0; m[a[i]] -= 1; } if(ans.size() == k-1) break; } sz = 0; for(int i = 0; i<k; i++) sz += b[i]; printf("%d\n", sz); sz = 0; for(int i = 0; i < (k-1); i++){ printf("%d ", ans[i]); sz += ans[i]; } printf("%d\n", n-sz); return 0; }
933
435
// implementation for regularity.h #include <algebra/vector.h> #include <algebra/matrix.h> #include <numerics/eigenvalues.h> using namespace MathTL; namespace WaveletTL { template <class MASK> AutocorrelationMask<MASK>::AutocorrelationMask() { MASK a; // b(k) = \sum_m a(k+m)*a(m)/2 const int k1 = a.begin().index()[0]; const int k2 = a.rbegin().index()[0]; for (int k = k1-k2; k <= k2-k1; k++) for (int m = k1; m <= k2; m++) if (m+k >= k1 && m+k <= k2) set_coefficient(MultiIndex<int,1>(k), get_coefficient(MultiIndex<int,1>(k)) + a.get_coefficient(MultiIndex<int,1>(m)) * a.get_coefficient(MultiIndex<int,1>(m+k))/2.0); } template <class MASK> double Sobolev_regularity() { double r = 0; // setup the autocorrelation mask according to the given mask AutocorrelationMask<MASK> b; // cout << "* the autocorrelation mask of a=" << MASK() << " is " << b << endl; // setup A=(b_{2i-j})_{i,j\in\Omega} const int N = b.rbegin().index()[0]; // offset for A Matrix<double> A(2*N+1, 2*N+1); for (int i = -N; i <= N; i++) for (int j = -N; j <= N; j++) A(N+i, N+j) = b.get_coefficient(MultiIndex<int,1>(2*i-j)); cout << "A=" << endl << A << endl; // TODO: solve nonsymmetric eigenvalue problem here! return r; } }
1,330
563
//Questão: Salario com Bonus #include <iostream> #include <string> #include <iomanip> using namespace std; int main() { string NOME; float SALARIO, TOTALV, TOTAL; cin >> NOME; cout << fixed << setprecision(2); cin >> SALARIO >> TOTALV; cout << fixed << setprecision(2); cout << "TOTAL = R$ "<<((TOTALV*15)/100) + SALARIO <<endl; return 0; }
366
154
/*----------------------------------------------------------------------------*/ /* Copyright (c) FIRST 2008. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in $(WIND_BASE)/WPILib. */ /*----------------------------------------------------------------------------*/ #include "AnalogTrigger.h" #include "AnalogInput.h" //#include "NetworkCommunication/UsageReporting.h" #include "Resource.h" #include "WPIErrors.h" /** * Initialize an analog trigger from a channel. */ void AnalogTrigger::InitTrigger(uint32_t channel) { void* port = getPort(channel); int32_t status = 0; uint32_t index = 0; m_trigger = initializeAnalogTrigger(port, &index, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); m_index = index; HALReport(HALUsageReporting::kResourceType_AnalogTrigger, channel); } /** * Constructor for an analog trigger given a channel number. * * @param channel The channel number on the roboRIO to represent. 0-3 are on-board 4-7 are on the MXP port. */ AnalogTrigger::AnalogTrigger(int32_t channel) { InitTrigger(channel); } /** * Construct an analog trigger given an analog input. * This should be used in the case of sharing an analog channel between the * trigger and an analog input object. * @param channel The pointer to the existing AnalogInput object */ AnalogTrigger::AnalogTrigger(AnalogInput *input) { InitTrigger(input->GetChannel()); } AnalogTrigger::~AnalogTrigger() { int32_t status = 0; cleanAnalogTrigger(m_trigger, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Set the upper and lower limits of the analog trigger. * The limits are given in ADC codes. If oversampling is used, the units must be scaled * appropriately. * @param lower The lower limit of the trigger in ADC codes (12-bit values). * @param upper The upper limit of the trigger in ADC codes (12-bit values). */ void AnalogTrigger::SetLimitsRaw(int32_t lower, int32_t upper) { if (StatusIsFatal()) return; int32_t status = 0; setAnalogTriggerLimitsRaw(m_trigger, lower, upper, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Set the upper and lower limits of the analog trigger. * The limits are given as floating point voltage values. * @param lower The lower limit of the trigger in Volts. * @param upper The upper limit of the trigger in Volts. */ void AnalogTrigger::SetLimitsVoltage(float lower, float upper) { if (StatusIsFatal()) return; int32_t status = 0; setAnalogTriggerLimitsVoltage(m_trigger, lower, upper, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Configure the analog trigger to use the averaged vs. raw values. * If the value is true, then the averaged value is selected for the analog trigger, otherwise * the immediate value is used. * @param useAveragedValue If true, use the Averaged value, otherwise use the instantaneous reading */ void AnalogTrigger::SetAveraged(bool useAveragedValue) { if (StatusIsFatal()) return; int32_t status = 0; setAnalogTriggerAveraged(m_trigger, useAveragedValue, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Configure the analog trigger to use a filtered value. * The analog trigger will operate with a 3 point average rejection filter. This is designed to * help with 360 degree pot applications for the period where the pot crosses through zero. * @param useFilteredValue If true, use the 3 point rejection filter, otherwise use the unfiltered value */ void AnalogTrigger::SetFiltered(bool useFilteredValue) { if (StatusIsFatal()) return; int32_t status = 0; setAnalogTriggerFiltered(m_trigger, useFilteredValue, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); } /** * Return the index of the analog trigger. * This is the FPGA index of this analog trigger instance. * @return The index of the analog trigger. */ uint32_t AnalogTrigger::GetIndex() { if (StatusIsFatal()) return ~0ul; return m_index; } /** * Return the InWindow output of the analog trigger. * True if the analog input is between the upper and lower limits. * @return True if the analog input is between the upper and lower limits. */ bool AnalogTrigger::GetInWindow() { if (StatusIsFatal()) return false; int32_t status = 0; bool result = getAnalogTriggerInWindow(m_trigger, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); return result; } /** * Return the TriggerState output of the analog trigger. * True if above upper limit. * False if below lower limit. * If in Hysteresis, maintain previous state. * @return True if above upper limit. False if below lower limit. If in Hysteresis, maintain previous state. */ bool AnalogTrigger::GetTriggerState() { if (StatusIsFatal()) return false; int32_t status = 0; bool result = getAnalogTriggerTriggerState(m_trigger, &status); wpi_setErrorWithContext(status, getHALErrorMessage(status)); return result; } /** * Creates an AnalogTriggerOutput object. * Gets an output object that can be used for routing. * Caller is responsible for deleting the AnalogTriggerOutput object. * @param type An enum of the type of output object to create. * @return A pointer to a new AnalogTriggerOutput object. */ AnalogTriggerOutput *AnalogTrigger::CreateOutput(AnalogTriggerType type) { if (StatusIsFatal()) return NULL; return new AnalogTriggerOutput(this, type); }
5,529
1,685
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2017 ArangoDB GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Jan Christoph Uhde //////////////////////////////////////////////////////////////////////////////// #include <fuerte/requests.h> namespace arangodb { namespace fuerte { inline namespace v1 { std::unique_ptr<Request> createRequest(RestVerb verb, ContentType contentType) { auto request = std::make_unique<Request>(); request->header.restVerb = verb; request->header.contentType(contentType); request->header.acceptType(contentType); return request; } // For User std::unique_ptr<Request> createRequest(RestVerb verb, std::string const& path, StringMap const& parameters, VPackBuffer<uint8_t> payload) { auto request = createRequest(verb, ContentType::VPack); request->header.path = path; request->header.parameters = parameters; request->addVPack(std::move(payload)); return request; } std::unique_ptr<Request> createRequest(RestVerb verb, std::string const& path, StringMap const& parameters, VPackSlice const payload) { auto request = createRequest(verb, ContentType::VPack); request->header.path = path; request->header.parameters = parameters; request->addVPack(payload); return request; } std::unique_ptr<Request> createRequest(RestVerb verb, std::string const& path, StringMap const& parameters) { auto request = createRequest(verb, ContentType::VPack); request->header.path = path; request->header.parameters = parameters; return request; } }}} // namespace arangodb::fuerte::v1
2,422
638
//===--- LLVMLibcTidyModule.cpp - clang-tidy ------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "../ClangTidy.h" #include "../ClangTidyModule.h" #include "../ClangTidyModuleRegistry.h" #include "CalleeNamespaceCheck.h" #include "ImplementationInNamespaceCheck.h" #include "RestrictSystemLibcHeadersCheck.h" namespace clang { namespace tidy { namespace llvm_libc { class LLVMLibcModule : public ClangTidyModule { public: void addCheckFactories(ClangTidyCheckFactories &CheckFactories) override { CheckFactories.registerCheck<CalleeNamespaceCheck>( "llvmlibc-callee-namespace"); CheckFactories.registerCheck<ImplementationInNamespaceCheck>( "llvmlibc-implementation-in-namespace"); CheckFactories.registerCheck<RestrictSystemLibcHeadersCheck>( "llvmlibc-restrict-system-libc-headers"); } }; // Register the LLVMLibcTidyModule using this statically initialized variable. static ClangTidyModuleRegistry::Add<LLVMLibcModule> X("llvmlibc-module", "Adds LLVM libc standards checks."); } // namespace llvm_libc // This anchor is used to force the linker to link in the generated object file // and thus register the LLVMLibcModule. volatile int LLVMLibcModuleAnchorSource = 0; } // namespace tidy } // namespace clang
1,543
478
#include <vtkActor.h> #include <vtkCamera.h> #include <vtkLineSource.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkPointData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkStreamTracer.h> #include <vtkStructuredGrid.h> #include <vtkStructuredGridGeometryFilter.h> #include <vtkStructuredGridOutlineFilter.h> #include <vtkStructuredGridReader.h> #include <array> int main(int argc, char* argv[]) { if (argc < 2) { std::cout << "Usage: " << argv[0] << " kitchen.vtk" << std::endl; return EXIT_FAILURE; } double range[2]; vtkNew<vtkNamedColors> colors; // Set the furniture colors. std::array<unsigned char, 4> furnColor{{204, 204, 153, 255}}; colors->SetColor("Furniture", furnColor.data()); vtkNew<vtkRenderer> aren; vtkNew<vtkRenderWindow> renWin; renWin->AddRenderer(aren); vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow(renWin); // // Read data // vtkNew<vtkStructuredGridReader> reader; reader->SetFileName(argv[1]); reader->Update(); // force a read to occur reader->GetOutput()->GetLength(); double maxTime = 0.0; if (reader->GetOutput()->GetPointData()->GetScalars()) { reader->GetOutput()->GetPointData()->GetScalars()->GetRange(range); } if (reader->GetOutput()->GetPointData()->GetVectors()) { auto maxVelocity = reader->GetOutput()->GetPointData()->GetVectors()->GetMaxNorm(); maxTime = 4.0 * reader->GetOutput()->GetLength() / maxVelocity; } // // Outline around data // vtkNew<vtkStructuredGridOutlineFilter> outlineF; outlineF->SetInputConnection(reader->GetOutputPort()); vtkNew<vtkPolyDataMapper> outlineMapper; outlineMapper->SetInputConnection(outlineF->GetOutputPort()); vtkNew<vtkActor> outline; outline->SetMapper(outlineMapper); outline->GetProperty()->SetColor(colors->GetColor3d("LampBlack").GetData()); // // Set up shaded surfaces (i.e., supporting geometry) // vtkNew<vtkStructuredGridGeometryFilter> doorGeom; doorGeom->SetInputConnection(reader->GetOutputPort()); doorGeom->SetExtent(27, 27, 14, 18, 0, 11); vtkNew<vtkPolyDataMapper> mapDoor; mapDoor->SetInputConnection(doorGeom->GetOutputPort()); mapDoor->ScalarVisibilityOff(); vtkNew<vtkActor> door; door->SetMapper(mapDoor); door->GetProperty()->SetColor(colors->GetColor3d("Burlywood").GetData()); vtkNew<vtkStructuredGridGeometryFilter> window1Geom; window1Geom->SetInputConnection(reader->GetOutputPort()); window1Geom->SetExtent(0, 0, 9, 18, 6, 12); vtkNew<vtkPolyDataMapper> mapWindow1; mapWindow1->SetInputConnection(window1Geom->GetOutputPort()); mapWindow1->ScalarVisibilityOff(); vtkNew<vtkActor> window1; window1->SetMapper(mapWindow1); window1->GetProperty()->SetColor(colors->GetColor3d("SkyBlue").GetData()); window1->GetProperty()->SetOpacity(.6); vtkNew<vtkStructuredGridGeometryFilter> window2Geom; window2Geom->SetInputConnection(reader->GetOutputPort()); window2Geom->SetExtent(5, 12, 23, 23, 6, 12); vtkNew<vtkPolyDataMapper> mapWindow2; mapWindow2->SetInputConnection(window2Geom->GetOutputPort()); mapWindow2->ScalarVisibilityOff(); vtkNew<vtkActor> window2; window2->SetMapper(mapWindow2); window2->GetProperty()->SetColor(colors->GetColor3d("SkyBlue").GetData()); window2->GetProperty()->SetOpacity(.6); vtkNew<vtkStructuredGridGeometryFilter> klower1Geom; klower1Geom->SetInputConnection(reader->GetOutputPort()); klower1Geom->SetExtent(17, 17, 0, 11, 0, 6); vtkNew<vtkPolyDataMapper> mapKlower1; mapKlower1->SetInputConnection(klower1Geom->GetOutputPort()); mapKlower1->ScalarVisibilityOff(); vtkNew<vtkActor> klower1; klower1->SetMapper(mapKlower1); klower1->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData()); vtkNew<vtkStructuredGridGeometryFilter> klower2Geom; klower2Geom->SetInputConnection(reader->GetOutputPort()); klower2Geom->SetExtent(19, 19, 0, 11, 0, 6); vtkNew<vtkPolyDataMapper> mapKlower2; mapKlower2->SetInputConnection(klower2Geom->GetOutputPort()); mapKlower2->ScalarVisibilityOff(); vtkNew<vtkActor> klower2; klower2->SetMapper(mapKlower2); klower2->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData()); vtkNew<vtkStructuredGridGeometryFilter> klower3Geom; klower3Geom->SetInputConnection(reader->GetOutputPort()); klower3Geom->SetExtent(17, 19, 0, 0, 0, 6); vtkNew<vtkPolyDataMapper> mapKlower3; mapKlower3->SetInputConnection(klower3Geom->GetOutputPort()); mapKlower3->ScalarVisibilityOff(); vtkNew<vtkActor> klower3; klower3->SetMapper(mapKlower3); klower3->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData()); vtkNew<vtkStructuredGridGeometryFilter> klower4Geom; klower4Geom->SetInputConnection(reader->GetOutputPort()); klower4Geom->SetExtent(17, 19, 11, 11, 0, 6); vtkNew<vtkPolyDataMapper> mapKlower4; mapKlower4->SetInputConnection(klower4Geom->GetOutputPort()); mapKlower4->ScalarVisibilityOff(); vtkNew<vtkActor> klower4; klower4->SetMapper(mapKlower4); klower4->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData()); vtkNew<vtkStructuredGridGeometryFilter> klower5Geom; klower5Geom->SetInputConnection(reader->GetOutputPort()); klower5Geom->SetExtent(17, 19, 0, 11, 0, 0); vtkNew<vtkPolyDataMapper> mapKlower5; mapKlower5->SetInputConnection(klower5Geom->GetOutputPort()); mapKlower5->ScalarVisibilityOff(); vtkNew<vtkActor> klower5; klower5->SetMapper(mapKlower5); klower5->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData()); vtkNew<vtkStructuredGridGeometryFilter> klower6Geom; klower6Geom->SetInputConnection(reader->GetOutputPort()); klower6Geom->SetExtent(17, 19, 0, 7, 6, 6); vtkNew<vtkPolyDataMapper> mapKlower6; mapKlower6->SetInputConnection(klower6Geom->GetOutputPort()); mapKlower6->ScalarVisibilityOff(); vtkNew<vtkActor> klower6; klower6->SetMapper(mapKlower6); klower6->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData()); vtkNew<vtkStructuredGridGeometryFilter> klower7Geom; klower7Geom->SetInputConnection(reader->GetOutputPort()); klower7Geom->SetExtent(17, 19, 9, 11, 6, 6); vtkNew<vtkPolyDataMapper> mapKlower7; mapKlower7->SetInputConnection(klower7Geom->GetOutputPort()); mapKlower7->ScalarVisibilityOff(); vtkNew<vtkActor> klower7; klower7->SetMapper(mapKlower7); klower7->GetProperty()->SetColor(colors->GetColor3d("EggShell").GetData()); vtkNew<vtkStructuredGridGeometryFilter> hood1Geom; hood1Geom->SetInputConnection(reader->GetOutputPort()); hood1Geom->SetExtent(17, 17, 0, 11, 11, 16); vtkNew<vtkPolyDataMapper> mapHood1; mapHood1->SetInputConnection(hood1Geom->GetOutputPort()); mapHood1->ScalarVisibilityOff(); vtkNew<vtkActor> hood1; hood1->SetMapper(mapHood1); hood1->GetProperty()->SetColor(colors->GetColor3d("Silver").GetData()); vtkNew<vtkStructuredGridGeometryFilter> hood2Geom; hood2Geom->SetInputConnection(reader->GetOutputPort()); hood2Geom->SetExtent(19, 19, 0, 11, 11, 16); vtkNew<vtkPolyDataMapper> mapHood2; mapHood2->SetInputConnection(hood2Geom->GetOutputPort()); mapHood2->ScalarVisibilityOff(); vtkNew<vtkActor> hood2; hood2->SetMapper(mapHood2); hood2->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData()); vtkNew<vtkStructuredGridGeometryFilter> hood3Geom; hood3Geom->SetInputConnection(reader->GetOutputPort()); hood3Geom->SetExtent(17, 19, 0, 0, 11, 16); vtkNew<vtkPolyDataMapper> mapHood3; mapHood3->SetInputConnection(hood3Geom->GetOutputPort()); mapHood3->ScalarVisibilityOff(); vtkNew<vtkActor> hood3; hood3->SetMapper(mapHood3); hood3->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData()); vtkNew<vtkStructuredGridGeometryFilter> hood4Geom; hood4Geom->SetInputConnection(reader->GetOutputPort()); hood4Geom->SetExtent(17, 19, 11, 11, 11, 16); vtkNew<vtkPolyDataMapper> mapHood4; mapHood4->SetInputConnection(hood4Geom->GetOutputPort()); mapHood4->ScalarVisibilityOff(); vtkNew<vtkActor> hood4; hood4->SetMapper(mapHood4); hood4->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData()); vtkNew<vtkStructuredGridGeometryFilter> hood6Geom; hood6Geom->SetInputConnection(reader->GetOutputPort()); hood6Geom->SetExtent(17, 19, 0, 11, 16, 16); vtkNew<vtkPolyDataMapper> mapHood6; mapHood6->SetInputConnection(hood6Geom->GetOutputPort()); mapHood6->ScalarVisibilityOff(); vtkNew<vtkActor> hood6; hood6->SetMapper(mapHood6); hood6->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData()); vtkNew<vtkStructuredGridGeometryFilter> cookingPlateGeom; cookingPlateGeom->SetInputConnection(reader->GetOutputPort()); cookingPlateGeom->SetExtent(17, 19, 7, 9, 6, 6); vtkNew<vtkPolyDataMapper> mapCookingPlate; mapCookingPlate->SetInputConnection(cookingPlateGeom->GetOutputPort()); mapCookingPlate->ScalarVisibilityOff(); vtkNew<vtkActor> cookingPlate; cookingPlate->SetMapper(mapCookingPlate); cookingPlate->GetProperty()->SetColor(colors->GetColor3d("Tomato").GetData()); vtkNew<vtkStructuredGridGeometryFilter> filterGeom; filterGeom->SetInputConnection(reader->GetOutputPort()); filterGeom->SetExtent(17, 19, 7, 9, 11, 11); vtkNew<vtkPolyDataMapper> mapFilter; mapFilter->SetInputConnection(filterGeom->GetOutputPort()); mapFilter->ScalarVisibilityOff(); vtkNew<vtkActor> filter; filter->SetMapper(mapFilter); filter->GetProperty()->SetColor(colors->GetColor3d("Furniture").GetData()); // // regular streamlines // vtkNew<vtkLineSource> line; line->SetResolution(39); line->SetPoint1(0.08, 2.50, 0.71); line->SetPoint2(0.08, 4.50, 0.71); vtkNew<vtkPolyDataMapper> rakeMapper; rakeMapper->SetInputConnection(line->GetOutputPort()); vtkNew<vtkActor> rake; rake->SetMapper(rakeMapper); vtkNew<vtkStreamTracer> streamers; // streamers->DebugOn(); streamers->SetInputConnection(reader->GetOutputPort()); streamers->SetSourceConnection(line->GetOutputPort()); streamers->SetMaximumPropagation(maxTime); streamers->SetInitialIntegrationStep(.5); streamers->SetMinimumIntegrationStep(.1); streamers->SetIntegratorType(2); streamers->Update(); vtkNew<vtkPolyDataMapper> streamersMapper; streamersMapper->SetInputConnection(streamers->GetOutputPort()); streamersMapper->SetScalarRange(range); vtkNew<vtkActor> lines; lines->SetMapper(streamersMapper); lines->GetProperty()->SetColor(colors->GetColor3d("Black").GetData()); aren->TwoSidedLightingOn(); aren->AddActor(outline); aren->AddActor(door); aren->AddActor(window1); aren->AddActor(window2); aren->AddActor(klower1); aren->AddActor(klower2); aren->AddActor(klower3); aren->AddActor(klower4); aren->AddActor(klower5); aren->AddActor(klower6); aren->AddActor(klower7); aren->AddActor(hood1); aren->AddActor(hood2); aren->AddActor(hood3); aren->AddActor(hood4); aren->AddActor(hood6); aren->AddActor(cookingPlate); aren->AddActor(filter); aren->AddActor(lines); aren->AddActor(rake); aren->SetBackground(colors->GetColor3d("SlateGray").GetData()); vtkNew<vtkCamera> aCamera; aren->SetActiveCamera(aCamera); aren->ResetCamera(); aCamera->SetFocalPoint(3.505, 2.505, 1.255); aCamera->SetPosition(3.505, 24.6196, 1.255); aCamera->SetViewUp(0, 0, 1); aCamera->Azimuth(60); aCamera->Elevation(30); aCamera->Dolly(1.4); aren->ResetCameraClippingRange(); renWin->SetSize(640, 512); renWin->Render(); renWin->SetWindowName("Kitchen"); // interact with data iren->Start(); return EXIT_SUCCESS; }
11,679
4,600
#include <OpenCLInvertexIndex.h> /** * WordMapInvertedIndex::InvertedIndexMap */ const char* WordMapInvertedIndex::InvertedIndexMap::at(cl_uint i) const { return (const char*)data() + word_capacity()*i; } const char* WordMapInvertedIndex::InvertedIndexMap::operator[](cl_uint i) const { return (const char*)data() + word_capacity()*i; }
347
127
#pragma once #include "App.hpp" #include "RisingEdgeButton.h" #include "SmartCard.h" #include <LiquidCrystal_I2C.h> #include <stdint.h> #include <WString.h> class PlayerCardCreator : public App { public: PlayerCardCreator(); void init(); void run(); private: LiquidCrystal_I2C lcd; RisingEdgeButton charUpButton; RisingEdgeButton charDownButton; RisingEdgeButton walkLeftButton; RisingEdgeButton walkRightButton; RisingEdgeButton writeButton; uint8_t rfidKey[MFRC522::MF_KEY_SIZE]; SmartCard smartCard; String playerName; uint8_t charIndexUnderCursor; char *statusLine; void setupLCD(); void showControlHints(); void showName(); bool executeNameChanges(); void resetName(); bool writeNameToCard(); void clearLine(const int number); char nextChar(const char current); char prevChar(const char current); };
903
304
/* -*- C++ -*- ------------------------------------------------------------ @@COPYRIGHT@@ *-----------------------------------------------------------------------*/ /** @file */ #ifndef __CML_VECTOR_SUBVECTOR_OPS_TPP #error "vector/subvector_ops.tpp not included correctly" #endif namespace cml { template<class Sub> inline auto subvector(const readable_vector<Sub>& sub, int i) -> subvector_node<const Sub&> { return subvector_node<const Sub&>(sub.actual(), i); } template<class Sub> inline auto subvector(readable_vector<Sub>&& sub, int i) -> subvector_node<Sub&&> { return subvector_node<Sub&&>((Sub&&) sub, i); } } // namespace cml // ------------------------------------------------------------------------- // vim:ft=cpp:sw=2
745
234
#include <algorithm> #include <iterator> #include <iostream> #include "mesh.h" #include "geometry/isect_util.h" using std::copy; using std::ostream_iterator; using std::cerr; MeshTri::MeshTri(const Mesh* m, int f, const uint v[3]) : mesh(m), ti(f) { copy(v, v+3, vi); } scalar_fp ray_triangle_intersection_accel(const Ray& ray, scalar_fp max_t, const MeshTriAccel& accel) { auto u = (accel.k + 1) % 3, v = (accel.k + 2) % 3; auto denom = (ray.direction[u] * accel.nu + ray.direction[v] * accel.nv + ray.direction[accel.k]); if (fabs(denom) < 0.0001) return sfp_none; auto num = accel.nd - ray.position[u] * accel.nu - ray.position[v] * accel.nv - ray.position[accel.k]; scalar t = num / denom; if (t < EPSILON) return sfp_none; scalar_fp t_prop(t); if (max_t < t_prop) return sfp_none; scalar hu = ray.position[u] + ray.direction[u] * t; scalar hv = ray.position[v] + ray.direction[v] * t; scalar beta = hu * accel.b_nu + hv * accel.b_nv + accel.b_d; if (beta < 0) return sfp_none; scalar gamma = hu * accel.c_nu + hv * accel.c_nv + accel.c_d; if (gamma < 0) return sfp_none; scalar alpha = 1 - beta - gamma; if (alpha < 0 || alpha > 1) return sfp_none; return t_prop; } scalar_fp MeshTri::intersect(const Ray& ray, scalar_fp max_t, SubGeo& geo) const { return ray_triangle_intersection_accel(ray, max_t, mesh->accel(ti)); } Vec3 MeshTri::normal(const Vec3& point) const { return (_p(1) - _p(0)).cross(_p(2) - _p(0)).normal(); } bounds::AABB MeshTri::get_bounding_box() const { return bounds::AABB(min(min(_p(0), _p(1)), _p(2)), max(max(_p(0), _p(1)), _p(2))); } void MeshTri::texture_coord(const Vec3& pos, const Vec3& normal, scalar& uv_u, scalar& uv_v) const { const auto& accel = mesh->accel(ti); auto u = (accel.k + 1) % 3, v = (accel.k + 2) % 3; scalar hu = pos[u]; scalar hv = pos[v]; scalar beta = hu * accel.b_nu + hv * accel.b_nv + accel.b_d; scalar gamma = hu * accel.c_nu + hv * accel.c_nv + accel.c_d; scalar alpha = 1 - beta - gamma; auto uv = mesh->uv(vi[0]) * alpha + mesh->uv(vi[1]) * gamma + mesh->uv(vi[2]) * beta; uv_u = uv[0]; uv_v = uv[1]; } //////////////////////////////////////////////////////////////////////////////// bounds::AABB Mesh::get_bounding_box() const { auto bb = bounds::AABB{Vec3::zero, Vec3::zero}; return accumulate(tris.begin(), tris.end(), bb, [](const auto& bb, const auto& tri) { return bounds::AABB::box_union(bb, tri.get_bounding_box()); }); } scalar_fp Mesh::intersect(const Ray& r, scalar_fp max_t, SubGeo& subgeo) const { scalar_fp best_t = max_t; for (auto i = 0u; i < tris.size(); ++i) { auto& tri = tris[i]; auto t = tri.intersect(r, best_t, subgeo); if (t < best_t) { best_t = t; subgeo = i; } } return best_t; } Vec3 Mesh::normal(SubGeo subgeo, const Vec3& point) const { return tris[subgeo].normal(point); } void Mesh::texture_coord(SubGeo subgeo, const Vec3& pos, const Vec3& normal, scalar& u, scalar& v) const { return tris[subgeo].texture_coord(pos, normal, u, v); } //////////////////////////////////////////////////////////////////////////////// MeshTriAccel::MeshTriAccel(const Vec3& p0, const Vec3& p1, const Vec3& p2) { const auto b = p1 - p0; const auto c = p2 - p0; const auto N = b.cross(c); const auto aN = N.abs(); if (aN.x >= aN.y && aN.x >= aN.z) this->k = 0; else if (aN.y >= aN.x && aN.y >= aN.z) this->k = 1; else this->k = 2; int k = this->k; int u = (this->k + 1) % 3, v = (this->k + 2) % 3; this->nu = N[u] / N[k]; this->nv = N[v] / N[k]; this->nd = p0.dot(N) / N[k]; scalar inv_area = 1.0 / (b[u] * c[v] - b[v] * c[u]); this->b_nu = -b[v] * inv_area; this->b_nv = b[u] * inv_area; this->b_d = (b[v] * p0[u] - b[u] * p0[v]) * inv_area; this->c_nu = c[v] * inv_area; this->c_nv = -c[u] * inv_area; this->c_d = (c[u] * p0[v] - c[v] * p0[u]) * inv_area; }
4,112
1,809