text
string
size
int64
token_count
int64
/** * \file logic/wire_get_inputs.cpp * * \brief Get the number of input connections on this wire. * * \copyright Copyright 2020 Justin Handville. All rights reserved. */ #include <homesim/wire.h> using namespace homesim; using namespace std; /** * \brief Get the number of input connections associated with this wire. * * \brief return the number of inputs. */ int homesim::wire::get_inputs() const { return inputs; }
435
138
// // Created by Rui Zhou on 30/3/18. // /* * https://leetcode.com/problems/power-of-two/description/ * */ #include <codech/codech_def.h> using namespace std; //这题目好像不对 //namespace yt { // int Count(const vector<int>& nums) // { // int count = 0; // for (int i = 0;i < nums.size();i++) { // int sum = nums[i]; // if (sum>=7 && (sum % 7 ==0)) // count++; // for (int j = i+1;j<nums.size();j++) { // sum += nums[j]; // if (sum >= 7 && (sum % 7 ==0)) { // count++; // } // } // } // return count; // } //} // 判断一个数是不是2的幂 // 最高位是1,后面都是0 namespace { class Solution { public: bool isPowerOfTwo(int n) { return (n&(n-1))==0; } }; } DEFINE_CODE_TEST(231_poweroftwo) { Solution obj; { VERIFY_CASE(obj.isPowerOfTwo(1),true); VERIFY_CASE(obj.isPowerOfTwo(2),true); } }
999
406
/******************************************************************************* * Copyright (C) 2017 Udacity Inc. * * This file is part of Robotic Arm: Pick and Place project for Udacity * Robotics nano-degree program * * All Rights Reserved. ******************************************************************************/ // Author: Brandon Kinman #include <ros/ros.h> #include <ros/console.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl_ros/point_cloud.h> #include <pcl/features/normal_3d.h> #include <pcl/features/vfh.h> #include <sensor_msgs/PointCloud2.h> #include <sensor_stick/GetNormals.h> //#include <sensor_stick/GetFloatArrayFeature.h> /* * Brief: * This node generates normal features for a point cloud */ class FeatureExtractor { public: explicit FeatureExtractor(ros::NodeHandle nh) : nh_(nh) { // Define Publishers and Subscribers here cluster_in_sub_ = nh_.subscribe("cluster_in", 1, &FeatureExtractor::clusterCallback, this); normals_out_pub_ = nh_.advertise<sensor_msgs::PointCloud2>("normals_out", 1); get_normals_srv_ = nh_.advertiseService("get_normals", &FeatureExtractor::getNormalsReq, this); //get_vfh_srv_ = np_.advertiseService("get_vfh", &FeatureExtractor::getVFHReq, this); } private: ros::NodeHandle nh_; ros::Subscriber cluster_in_sub_; ros::Publisher normals_out_pub_; ros::ServiceServer get_normals_srv_; void clusterCallback(const sensor_msgs::PointCloud2& cloud_msg) { ROS_INFO("Cluster Received"); pcl::PointCloud<pcl::PointXYZ> *p_cloud = new pcl::PointCloud<pcl::PointXYZ>(); const boost::shared_ptr<pcl::PointCloud<pcl::PointXYZ> > sp_pcl_cloud(p_cloud); pcl::fromROSMsg(cloud_msg, *p_cloud); // Create the normal estimation class, and pass the input dataset to it pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne; ne.setInputCloud (sp_pcl_cloud); pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ> ()); ne.setSearchMethod (tree); // Use all neighbors in a sphere of radius 3cm ne.setRadiusSearch(0.03); // Output datasets pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>); // Compute the features ne.compute(*cloud_normals); ROS_INFO("Done!"); sensor_msgs::PointCloud2 normals_out_msg; pcl::toROSMsg(*cloud_normals, normals_out_msg); normals_out_pub_.publish(normals_out_msg); } bool getNormalsReq(sensor_stick::GetNormals::Request &req, sensor_stick::GetNormals::Response &rsp) { rsp.cluster = req.cluster; pcl::PointCloud<pcl::PointXYZ> *p_cloud = new pcl::PointCloud<pcl::PointXYZ>(); const boost::shared_ptr<pcl::PointCloud<pcl::PointXYZ> > sp_pcl_cloud(p_cloud); pcl::fromROSMsg(req.cluster, *p_cloud); // Create the normal estimation class, and pass the input dataset to it pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne; ne.setInputCloud (sp_pcl_cloud); pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ> ()); ne.setSearchMethod (tree); // Use all neighbors in a sphere of radius 3cm ne.setRadiusSearch(0.03); // Output datasets pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>); // Compute the features ne.compute(*cloud_normals); pcl::toROSMsg(*cloud_normals, rsp.cluster); return true; } }; // FeatureExtractor // bool getVFHReq(sensor_stick::GetNormals::Request &req, sensor_stick::GetNormals::Response &rsp) // { // pcl::PointCloud<pcl::PointXYZ> *p_cloud = new pcl::PointCloud<pcl::PointXYZ>(); // const boost::shared_ptr<pcl::PointCloud<pcl::PointXYZ> > sp_pcl_cloud(p_cloud); // pcl::fromROSMsg(req.cluster, *p_cloud); // // Create the normal estimation class, and pass the input dataset to it // pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne; // ne.setInputCloud (sp_pcl_cloud); // pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ> ()); // ne.setSearchMethod (tree); // // Use all neighbors in a sphere of radius 3cm // ne.setRadiusSearch(0.03); // // Output datasets // pcl::PointCloud<pcl::Normal>::Ptr cloud_normals(new pcl::PointCloud<pcl::Normal>); // // Compute the features // ne.compute(*cloud_normals); // // Create the VFH estimation class, and pass the input dataset+normals to it // pcl::VFHEstimation<pcl::PointXYZ, pcl::Normal, pcl::VFHSignature308> vfh; // vfh.setInputCloud(sp_pcl_cloud); // vfh.setInputNormals(*cloud_normals); // // alternatively, if cloud is of type PointNormal, do vfh.setInputNormals (cloud); // // Create an empty kdtree representation, and pass it to the FPFH estimation object. // // Its content will be filled inside the object, based on the given input dataset (as no other search surface is given). // vfh.setSearchMethod (tree); // // Output datasets // pcl::PointCloud<pcl::VFHSignature308>::Ptr vfhs (new pcl::PointCloud<pcl::VFHSignature308> ()); // // Compute the features // vfh.compute (*vfhs); // for(size_t i = 0; i < 308; ++i) // { // vfhs.points[0].histogram[i]; // } // } int main(int argc, char **argv) { ros::init(argc, argv, "feature_extractor"); ros::NodeHandle nh("~"); FeatureExtractor nfe(nh); // Spin until ROS is shutdown while (ros::ok()) ros::spin(); return 0; }
5,404
2,002
#include <iostream> #include "String.h" #include "String.cpp" using namespace std; using namespace HomeMadeString; int main() { // Test the default constructor String s1; // Test the conversion constructor String s2="Hello, hello!"; // Let's see the results cout<<endl<<"TESTING s1: "<<endl; s1.print(cout); cout<<endl; cout<<endl<<"TESTING s2: "<<endl; s2.print(cout); cout<<endl<<endl; // Test the copy function String::copy(s1,s2); cout<<endl<<"COPY FUNCTION TESTING: "<<endl; s1.print(cout); cout<<endl; s2.print(cout); cout<<endl; // Test the compare function cout<<endl<<"COMPARE FUNCTION TESTING: "<<endl; if(String::compare(s1,s2)) cout<<"s1 and s2 are the same!"<<endl; // Test the special constructor with two parameters String s3('-',15); cout<<endl<<"SPECIAL CONSTRUCTOR TESTING: "<<endl; s3.print(cout); cout<<endl; // Test the concatenate function and the copy constructor cout<<endl<<"CONCATENATE FUNCTION TESTING: "<<endl; String s4=String::concatenate(s2,s3); s4.print(cout); cout<<endl; // Test the GetChar function cout<<endl<<"get Char TESTING: "<<endl; for(int i=0; i<s4.getLength();i++) { cout<<s4.getChar(i); } cout<<endl; // Test the getStr function char* pStr=new char[s4.getLength()+1]; // Reserving memory for string and terminating character s4.getStr(pStr); cout<<pStr<<endl; // cout can work with strings delete[] pStr; // delete the buffer and release the allocated memory return 0; }
1,540
595
// Copyright (c) 2015 Francois Doray. // 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 <organization> 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 <COPYRIGHT HOLDER> 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 "base/string_utils.h" #include <sstream> namespace base { namespace { template <typename T> bool StringBeginsWithInternal(const T& str, const T& starting) { if (str.compare(0, starting.length(), starting) == 0) return true; return false; } template <typename T> bool StringEndsWithInternal(const T& str, const T& ending) { if (ending.length() > str.length()) return false; if (str.compare(str.length() - ending.length(), ending.length(), ending) == 0) { return true; } return false; } } // namespace std::wstring StringToWString(const std::string& string) { return std::wstring(string.begin(), string.end()); } std::string WStringToString(const std::wstring& string) { return std::string(string.begin(), string.end()); } bool StringBeginsWith(const std::string& str, const std::string& starting) { return StringBeginsWithInternal(str, starting); } bool WStringBeginsWith(const std::wstring& str, const std::wstring& starting) { return StringBeginsWithInternal(str, starting); } bool StringEndsWith(const std::string &str, const std::string &ending) { return StringEndsWithInternal(str, ending); } bool WStringEndsWith(const std::wstring& str, const std::wstring& ending) { return StringEndsWithInternal(str, ending); } std::string StringEscapeSpecialCharacter(const std::string& str) { std::stringstream ss; for (std::string::const_iterator i = str.begin(); i != str.end(); ++i) { unsigned char c = *i; if (' ' <= c && c <= '~' && c != '\\' && c != '"') { ss << c; continue; } ss << '\\'; switch (c) { case '"': ss << '"'; break; case '\\': ss << '\\'; break; case '\t': ss << 't'; break; case '\r': ss << 'r'; break; case '\n': ss << 'n'; break; default: { static char const* const hexdig = "0123456789ABCDEF"; ss << 'x'; ss << hexdig[c >> 4]; ss << hexdig[c & 0xF]; break; } } } return ss.str(); } } // namespace base
3,604
1,212
#include "class_4.h" #include "class_6.h" #include "class_1.h" #include "class_0.h" #include "class_3.h" #include "class_4.h" #include <lib_6/class_6.h> #include <lib_5/class_9.h> #include <lib_6/class_2.h> #include <lib_3/class_1.h> #include <lib_3/class_7.h> class_4::class_4() {} class_4::~class_4() {}
307
153
/** * Copyright 2014-2017 Steven T Sell (ssell@vertexfragment.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. */ #pragma once #ifndef __H__OCULAR_EDITOR_LINE_EDIT__H__ #define __H__OCULAR_EDITOR_LINE_EDIT__H__ #include <QtWidgets/qlineedit.h> //------------------------------------------------------------------------------------------ /** * \addtogroup Ocular * @{ */ namespace Ocular { /** * \addtogroup Editor * @{ */ namespace Editor { enum class LineType { String = 0, Int8, UInt8, Int16, UInt16, Int32, UInt32, Float, Double }; /** * \class LineEdit * * Helper class that automatically handles input mask, etc. setup based * on the specified LineType. */ class LineEdit : public QLineEdit { Q_OBJECT public: LineEdit(LineType type, QWidget* parent = nullptr); virtual ~LineEdit(); /** * \param[in] reset If TRUE, then the edited flag is reset back to FALSE. * \return TRUE if the user has modifed this edit (return key was pressed). */ bool wasEdited(bool reset = true); /** * */ void setInvalid(bool invalid); /** * */ int32_t asInt() const; /** * */ uint32_t asUint() const; /** * */ float asFloat() const; template<typename T> T as() const { return OcularString->fromString<T>(text().toStdString()); } protected: private slots: void contentsChanged(QString const& text); void userEdited(QString const& text); private: LineType m_Type; bool m_WasEdited; }; } /** * @} End of Doxygen Groups */ } /** * @} End of Doxygen Groups */ //------------------------------------------------------------------------------------------ #endif
2,747
756
/* ========================================================================= * * * * OpenMesh * * Copyright (c) 2001-2015, RWTH-Aachen University * * Department of Computer Graphics and Multimedia * * All rights reserved. * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * *---------------------------------------------------------------------------* * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * 1. Redistributions of source code must retain the above copyright notice, * * this list of conditions and the following disclaimer. * * * * 2. Redistributions in binary form must reproduce the above copyright * * notice, this list of conditions and the following disclaimer in the * * documentation and/or other materials provided with the distribution. * * * * 3. Neither the name of the copyright holder nor the names of its * * contributors may be used to endorse or promote products derived from * * this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * * * ========================================================================= */ /*===========================================================================*\ * * * $Revision$ * * $Date$ * * * \*===========================================================================*/ /** \file ModNormalDeviationT.hh */ //============================================================================= // // CLASS ModNormalDeviationT // //============================================================================= #ifndef OPENMESH_DECIMATER_MODNORMALDEVIATIONT_HH #define OPENMESH_DECIMATER_MODNORMALDEVIATIONT_HH //== INCLUDES ================================================================= #include <OpenMesh/Tools/Decimater/ModBaseT.hh> #include <OpenMesh/Core/Utils/Property.hh> #include <OpenMesh/Core/Geometry/NormalConeT.hh> //== NAMESPACES =============================================================== namespace OpenMesh { namespace Decimater { //== CLASS DEFINITION ========================================================= /** \brief Use Normal deviation to control decimation * * The module tracks the normals while decimating * a normal cone consisting of all normals of the * faces collapsed together is computed and if * a collapse would increase the size of * the cone to a value greater than the given value * the collapse will be illegal. * * In binary and mode, the collapse is legal if: * - The normal deviation after the collapse is lower than the given value * * In continuous mode the maximal deviation is returned */ template <class MeshT> class ModNormalDeviationT : public ModBaseT< MeshT > { public: DECIMATING_MODULE( ModNormalDeviationT, MeshT, NormalDeviation ); typedef typename Mesh::Scalar Scalar; typedef typename Mesh::Point Point; typedef typename Mesh::Normal Normal; typedef typename Mesh::VertexHandle VertexHandle; typedef typename Mesh::FaceHandle FaceHandle; typedef typename Mesh::EdgeHandle EdgeHandle; typedef NormalConeT<Scalar> NormalCone; public: /// Constructor ModNormalDeviationT(MeshT& _mesh, float _max_dev = 180.0) : Base(_mesh, true), mesh_(Base::mesh()) { set_normal_deviation(_max_dev); mesh_.add_property(normal_cones_); const bool mesh_has_normals = _mesh.has_face_normals(); _mesh.request_face_normals(); if (!mesh_has_normals) { omerr() << "Mesh has no face normals. Compute them automatically." << std::endl; _mesh.update_face_normals(); } } /// Destructor ~ModNormalDeviationT() { mesh_.remove_property(normal_cones_); mesh_.release_face_normals(); } /// Get normal deviation ( 0 .. 360 ) Scalar normal_deviation() const { return normal_deviation_ / M_PI * 180.0; } /// Set normal deviation ( 0 .. 360 ) void set_normal_deviation(Scalar _s) { normal_deviation_ = _s / static_cast<Scalar>(180.0) * static_cast<Scalar>(M_PI); } /// Allocate and init normal cones void initialize() { if (!normal_cones_.is_valid()) mesh_.add_property(normal_cones_); typename Mesh::FaceIter f_it = mesh_.faces_begin(), f_end = mesh_.faces_end(); for (; f_it != f_end; ++f_it) mesh_.property(normal_cones_, *f_it) = NormalCone(mesh_.normal(*f_it)); } /** \brief Control normals when Decimating * * Binary and Cont. mode. * * The module tracks the normals while decimating * a normal cone consisting of all normals of the * faces collapsed together is computed and if * a collapse would increase the size of * the cone to a value greater than the given value * the collapse will be illegal. * * @param _ci Collapse info data * @return Half of the normal cones size (radius in radians) */ float collapse_priority(const CollapseInfo& _ci) { // simulate collapse mesh_.set_point(_ci.v0, _ci.p1); typename Mesh::Scalar max_angle(0.0); typename Mesh::ConstVertexFaceIter vf_it(mesh_, _ci.v0); typename Mesh::FaceHandle fh, fhl, fhr; if (_ci.v0vl.is_valid()) fhl = mesh_.face_handle(_ci.v0vl); if (_ci.vrv0.is_valid()) fhr = mesh_.face_handle(_ci.vrv0); for (; vf_it.is_valid(); ++vf_it) { fh = *vf_it; if (fh != _ci.fl && fh != _ci.fr) { NormalCone nc = mesh_.property(normal_cones_, fh); nc.merge(NormalCone(mesh_.calc_face_normal(fh))); if (fh == fhl) nc.merge(mesh_.property(normal_cones_, _ci.fl)); if (fh == fhr) nc.merge(mesh_.property(normal_cones_, _ci.fr)); if (nc.angle() > max_angle) { max_angle = nc.angle(); if (max_angle > 0.5 * normal_deviation_) break; } } } // undo simulation changes mesh_.set_point(_ci.v0, _ci.p0); return (max_angle < 0.5 * normal_deviation_ ? max_angle : float( Base::ILLEGAL_COLLAPSE )); } /// set the percentage of normal deviation void set_error_tolerance_factor(double _factor) { if (_factor >= 0.0 && _factor <= 1.0) { // the smaller the factor, the smaller normal_deviation_ gets // thus creating a stricter constraint // division by error_tolerance_factor_ is for normalization Scalar normal_deviation = (normal_deviation_ * static_cast<Scalar>(180.0)/static_cast<Scalar>(M_PI) ) * _factor / this->error_tolerance_factor_; set_normal_deviation(normal_deviation); this->error_tolerance_factor_ = _factor; } } void postprocess_collapse(const CollapseInfo& _ci) { // account for changed normals typename Mesh::VertexFaceIter vf_it(mesh_, _ci.v1); for (; vf_it.is_valid(); ++vf_it) mesh_.property(normal_cones_, *vf_it). merge(NormalCone(mesh_.normal(*vf_it))); // normal cones of deleted triangles typename Mesh::FaceHandle fh; if (_ci.vlv1.is_valid()) { fh = mesh_.face_handle(mesh_.opposite_halfedge_handle(_ci.vlv1)); if (fh.is_valid()) mesh_.property(normal_cones_, fh). merge(mesh_.property(normal_cones_, _ci.fl)); } if (_ci.v1vr.is_valid()) { fh = mesh_.face_handle(mesh_.opposite_halfedge_handle(_ci.v1vr)); if (fh.is_valid()) mesh_.property(normal_cones_, fh). merge(mesh_.property(normal_cones_, _ci.fr)); } } private: Mesh& mesh_; Scalar normal_deviation_; OpenMesh::FPropHandleT<NormalCone> normal_cones_; }; //============================================================================= } // END_NS_DECIMATER } // END_NS_OPENMESH //============================================================================= #endif // OPENMESH_DECIMATER_MODNORMALDEVIATIONT_HH defined //=============================================================================
10,511
3,211
// Copyright 2017 Google LLC // // 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 // // https://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 "server.h" #include <grpc++/security/server_credentials.h> #include <grpc++/server.h> #include <grpc++/server_builder.h> #include <map> #include "absl/synchronization/mutex.h" #include "application.h" #include "buffer.h" #include "log.h" #include "proto/project_service.grpc.pb.h" #include "run.h" #include "src_hash.h" class ProjectServer : public Application, public ProjectService::Service { public: ProjectServer(int argc, char** argv) : project_(PathFromArgs(argc, argv), false), active_requests_(0), last_activity_(absl::Now()), quit_requested_(false) { if (PathFromArgs(argc, argv) != project_.aspect<ProjectRoot>()->LocalAddressPath()) { throw std::runtime_error(absl::StrCat( "Project path misalignment: ", PathFromArgs(argc, argv).string(), " ", project_.aspect<ProjectRoot>()->LocalAddressPath().string())); } server_ = grpc::ServerBuilder() .RegisterService(this) .AddListeningPort(project_.aspect<ProjectRoot>()->LocalAddress(), grpc::InsecureServerCredentials()) .BuildAndStart(); Log() << "Created server " << server_.get() << " @ " << project_.aspect<ProjectRoot>()->LocalAddress(); } int Run() override { auto done = [this]() { mu_.AssertHeld(); return active_requests_ == 0 && (quit_requested_ || (absl::Now() - last_activity_ > absl::Hours(1))); }; { absl::MutexLock lock(&mu_); while (!mu_.AwaitWithTimeout(absl::Condition(&done), absl::Duration(absl::Minutes(1)))) ; } server_->Shutdown(); return 0; } grpc::Status ConnectionHello(grpc::ServerContext* context, const ConnectionHelloRequest* req, ConnectionHelloResponse* rsp) override { rsp->set_src_hash(ced_src_hash); return grpc::Status::OK; } grpc::Status Quit(grpc::ServerContext* context, const Empty* req, Empty* rsp) override { absl::MutexLock lock(&mu_); quit_requested_ = true; return grpc::Status::OK; } grpc::Status Edit( grpc::ServerContext* context, grpc::ServerReaderWriter<EditMessage, EditMessage>* stream) override { ScopedRequest scoped_request(this); EditMessage msg; if (!stream->Read(&msg)) { return grpc::Status(grpc::INVALID_ARGUMENT, "Stream closed with no greeting"); } if (msg.type_case() != EditMessage::kClientHello) { return grpc::Status(grpc::INVALID_ARGUMENT, "First message from client must be ClientHello"); } Buffer* buffer = GetBuffer(msg.client_hello().buffer_name()); if (!buffer) { return grpc::Status(grpc::INVALID_ARGUMENT, "Unable to access requested buffer"); } Site site; auto listener = buffer->Listen( [stream, &site](const AnnotatedString& initial) { EditMessage out; auto body = out.mutable_server_hello(); body->set_site_id(site.site_id()); *body->mutable_current_state() = initial.AsProto(); stream->Write(out); }, [stream](const CommandSet* commands) { EditMessage out; *out.mutable_commands() = *commands; stream->Write(out); }); while (stream->Read(&msg)) { if (msg.type_case() != EditMessage::kCommands) { return grpc::Status(grpc::INVALID_ARGUMENT, "Expected commands after greetings"); } buffer->PushChanges(&msg.commands(), true); } CommandSet cleanup_commands; buffer->ContentSnapshot().MakeDeleteAttributesBySite(&cleanup_commands, site); buffer->PushChanges(&msg.commands(), false); return grpc::Status::OK; } private: Project project_; std::unique_ptr<grpc::Server> server_; absl::Mutex mu_; int active_requests_ GUARDED_BY(mu_); absl::Time last_activity_ GUARDED_BY(mu_); std::map<boost::filesystem::path, std::unique_ptr<Buffer>> buffers_ GUARDED_BY(mu_); bool quit_requested_ GUARDED_BY(mu_); static bool IsChildOf(boost::filesystem::path needle, boost::filesystem::path haystack) { needle = boost::filesystem::absolute(needle); haystack = boost::filesystem::absolute(haystack); if (haystack.filename() == ".") { haystack.remove_filename(); } if (!needle.has_filename()) return false; needle.remove_filename(); std::string needle_str = needle.string(); std::string haystack_str = haystack.string(); if (needle_str.length() > haystack_str.length()) return false; return std::equal(haystack_str.begin(), haystack_str.end(), needle_str.begin()); } Buffer* GetBuffer(boost::filesystem::path path) { path = boost::filesystem::absolute(path); if (!IsChildOf(path, project_.aspect<ProjectRoot>()->Path())) { Log() << "Attempt to access outside of project sandbox: " << path << " in project root " << project_.aspect<ProjectRoot>()->Path(); return nullptr; } absl::MutexLock lock(&mu_); auto it = buffers_.find(path); if (it != buffers_.end()) { return it->second.get(); } return buffers_ .emplace( path, Buffer::Builder().SetFilename(path).SetProject(&project_).Make()) .first->second.get(); } class ScopedRequest { public: explicit ScopedRequest(ProjectServer* p) : p_(p) { absl::MutexLock lock(&p_->mu_); p_->active_requests_++; p_->last_activity_ = absl::Now(); } ~ScopedRequest() { absl::MutexLock lock(&p_->mu_); p_->active_requests_--; p_->last_activity_ = absl::Now(); } private: ProjectServer* const p_; }; static boost::filesystem::path PathFromArgs(int argc, char** argv) { if (argc != 2) throw std::runtime_error("Expected path"); return argv[1]; } }; REGISTER_APPLICATION(ProjectServer); void SpawnServer(const boost::filesystem::path& ced_bin, const Project& project) { run_daemon( ced_bin, { "-mode", "ProjectServer", "-logfile", (project.aspect<ProjectRoot>()->LocalAddressPath().parent_path() / absl::StrCat(".cedlog.server.", ced_src_hash)) .string(), project.aspect<ProjectRoot>()->LocalAddressPath().string(), }); }
7,196
2,218
#include "Elite/Translater/PassManager.h" #include "Elite/CodeGen/ICodeGenContext.h" PassManager::PassManager () { } PassManager::~PassManager () { } void PassManager::NewPassList(const string& name, const vector<Pass*>& vec) { NewPassList(name, list<Pass*>(vec.begin(), vec.end())); } void PassManager::NewPassList(const string& name, const list<Pass*>& lst) { pass_lists[name] = lst; } list<Pass*>* PassManager::getPassList(const string& name) { auto idx = pass_lists.find(name); if (idx != pass_lists.end()) return &(idx->second); return NULL; } void PassManager::RunPassList(const string& name, Node* node, ICodeGenContext* ctx) { auto idx = pass_lists.find(name); if (idx != pass_lists.end()) { for (auto i : idx->second) { // 设置i为活动pass ctx->setNowPass(i); ctx->MacroMake(node); } } } void PassManager::RunPassListWithSet(const string& name, set<Node*>& nodes, ICodeGenContext* ctx) { auto idx = pass_lists.find(name); if (idx != pass_lists.end()) { for (auto i : idx->second) { // 设置i为活动pass ctx->setNowPass(i); for (auto node : nodes) ctx->MacroMake(node); } } } extern const FuncReg macro_funcs[]; extern const FuncReg macro_classes[]; extern const FuncReg macro_prescan[]; extern const FuncReg macro_pretype[]; extern const FuncReg macro_defmacro[]; void PassManager::LoadDefaultLists() { list<Pass*> prescan = { new Pass(macro_defmacro), new Pass(macro_prescan), new Pass(macro_pretype) }; list<Pass*> main = { new Pass(macro_funcs, macro_classes) }; NewPassList("prescan", prescan); NewPassList("main", main); }
1,723
594
#include "driver.h" #if EPSYSTEM_DRIVER == EPDRIVER_NULL #include "hal/library.h" bool epLibrary_Open(epLibrary *pLibrary, const char *filename) { return false; } bool epLibrary_Close(epLibrary library) { return false; } void *epLibrary_GetFunction(epLibrary library, const char *funcName) { return nullptr; } char *epLibrary_GetLastError() { return nullptr; } #else EPEMPTYFILE #endif // EPSYSTEM_DRIVER == EPDRIVER_NULL
437
170
#include "process_start.h" pid_t start_process(set_prog_start &program) { pid_t process_pid; // create new process process_pid = fork(); if (process_pid == -1) { // error of creation process LOG("Error in process_start. Function fork(), couldn't do fork, for " "program_name: " + program.name, ERROR); return 0; } else if (process_pid != 0) { // parent process // return child pid return process_pid; } else { // child process // number of process arguments(first - program name, last - NULL) int argc = program.cmd_arguments.size() + 2; // pointer to process arguments char **argv = new char *[argc]; // first argument - program name int word_length = 0; word_length = program.name.length() + 1; argv[0] = new char[word_length]; // copy program name to arguments array strncpy(argv[0], program.name.c_str(), word_length); // copy all arguments to arguments array for (int i = 1; i < argc - 1; i++) { word_length = program.cmd_arguments[i - 1].length() + 1; argv[i] = new char[word_length]; strncpy(argv[i], program.cmd_arguments[i - 1].c_str(), word_length); } // last arguments - NULL argv[argc - 1] = nullptr; // check if we need to redirect programm's stdout if (program.stdout_config_file.size() != 0) { // change file mode depending of stdout_mode config char file_mode = 0; if (program.stdout_config_truncate) { // true - truncate file_mode = 'w'; } else { // false - append file_mode = 'a'; } // open a log file if (!freopen(program.stdout_config_file.c_str(), &file_mode, stdout)) { // it doesn't open // close stdout fclose(stdout); LOG("Error in process_start. Function freopen(), couldn't open stdout " "config " "file: " + program.stdout_config_file, ERROR); } } // change run program status program.pid = getpid(); // start new process(change current process to new) if (execv(program.executable_path.c_str(), argv) == -1) { // error occurred, program isn't executed //!!! stdout stream doesn't work here(redirected to file) // change run program status program.pid = 0; // delete argv array for (int i = 0; i < argc; i++) { delete[] argv[i]; } delete[] argv; argv = nullptr; // add error info std::string error_message("Error in proscess_start. Function execv()\n"); error_message += "Couldn't start program: " + program.name + "\n"; error_message += "Executable path = " + program.executable_path + "\nError info: "; error_message.append(strerror(errno)); LOG(error_message, ERROR); exit(1); } // these line is never reached(things below just for cppchecker) delete[] argv; return -1; } }
2,975
931
#include <bits/stdc++.h> using namespace std; // Complete the maximizingXor function below. int maximizingXor(int l, int r) { // get xor of limits int LXR = L ^ R; // loop to get msb position of L^R int msbPos = 0; while (LXR) { msbPos++; LXR >>= 1; } // construct result by adding 1, // msbPos times int maxXOR = 0; int two = 1; while (msbPos--) { maxXOR += two; two <<= 1; } return maxXOR; } int main() { ofstream fout(getenv("OUTPUT_PATH")); int l; cin >> l; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int r; cin >> r; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int result = maximizingXor(l, r); fout << result << "\n"; fout.close(); return 0; }
827
327
/*========================================================================= Program: Visualization Toolkit Module: vtkToneMappingPass.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkToneMappingPass.h" #include "vtkObjectFactory.h" #include "vtkOpenGLError.h" #include "vtkOpenGLFramebufferObject.h" #include "vtkOpenGLQuadHelper.h" #include "vtkOpenGLRenderUtilities.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLShaderCache.h" #include "vtkOpenGLState.h" #include "vtkOpenGLVertexArrayObject.h" #include "vtkRenderState.h" #include "vtkRenderer.h" #include "vtkShaderProgram.h" #include "vtkTextureObject.h" vtkStandardNewMacro(vtkToneMappingPass); // ---------------------------------------------------------------------------- vtkToneMappingPass::~vtkToneMappingPass() { if (this->FrameBufferObject) { vtkErrorMacro("FrameBufferObject should have been deleted in ReleaseGraphicsResources()."); } if (this->ColorTexture) { vtkErrorMacro("ColorTexture should have been deleted in ReleaseGraphicsResources()."); } if (this->QuadHelper) { vtkErrorMacro("QuadHelper should have been deleted in ReleaseGraphicsResources()."); } } // ---------------------------------------------------------------------------- void vtkToneMappingPass::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "FrameBufferObject:"; if(this->FrameBufferObject!=nullptr) { this->FrameBufferObject->PrintSelf(os,indent); } else { os << "(none)" <<endl; } os << indent << "ColorTexture:"; if(this->ColorTexture!=nullptr) { this->ColorTexture->PrintSelf(os,indent); } else { os << "(none)" <<endl; } } // ---------------------------------------------------------------------------- void vtkToneMappingPass::Render(const vtkRenderState* s) { vtkOpenGLClearErrorMacro(); this->NumberOfRenderedProps = 0; vtkRenderer* r = s->GetRenderer(); vtkOpenGLRenderWindow* renWin = static_cast<vtkOpenGLRenderWindow*>(r->GetRenderWindow()); vtkOpenGLState* ostate = renWin->GetState(); vtkOpenGLState::ScopedglEnableDisable bsaver(ostate, GL_BLEND); vtkOpenGLState::ScopedglEnableDisable dsaver(ostate, GL_DEPTH_TEST); if (this->DelegatePass == nullptr) { vtkWarningMacro("no delegate in vtkToneMappingPass."); return; } // create FBO and texture int x, y, w, h; r->GetTiledSizeAndOrigin(&w, &h, &x, &y); if (this->ColorTexture == nullptr) { this->ColorTexture = vtkTextureObject::New(); this->ColorTexture->SetContext(renWin); this->ColorTexture->SetMinificationFilter(vtkTextureObject::Linear); this->ColorTexture->SetMagnificationFilter(vtkTextureObject::Linear); this->ColorTexture->Allocate2D(w, h, 4, VTK_FLOAT); } this->ColorTexture->Resize(w, h); if (this->FrameBufferObject == nullptr) { this->FrameBufferObject = vtkOpenGLFramebufferObject::New(); this->FrameBufferObject->SetContext(renWin); } renWin->GetState()->PushFramebufferBindings(); this->RenderDelegate(s, w, h, w, h, this->FrameBufferObject, this->ColorTexture); renWin->GetState()->PopFramebufferBindings(); if (this->QuadHelper && static_cast<unsigned int>(this->ToneMappingType) != this->QuadHelper->ShaderChangeValue) { delete this->QuadHelper; this->QuadHelper = nullptr; } if (!this->QuadHelper) { std::string FSSource = vtkOpenGLRenderUtilities::GetFullScreenQuadFragmentShaderTemplate(); vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Decl", "uniform sampler2D source;\n" "//VTK::FSQ::Decl"); vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Impl", "vec4 pixel = texture2D(source, texCoord);\n" " float Y = 0.2126 * pixel.r + 0.7152 * pixel.g + 0.0722 * pixel.b;\n" " //VTK::FSQ::Impl"); switch (this->ToneMappingType) { case Clamp: vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Impl", "float scale = min(Y, 1.0) / Y;\n" " //VTK::FSQ::Impl"); break; case Reinhard: vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Impl", "float scale = 1.0 / (Y + 1.0);\n" " //VTK::FSQ::Impl"); break; case Exponential: vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Decl", "uniform float exposure;\n"); vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Impl", "float scale = (1.0 - exp(-Y*exposure)) / Y;\n" " //VTK::FSQ::Impl"); break; } vtkShaderProgram::Substitute(FSSource, "//VTK::FSQ::Impl", "gl_FragData[0] = vec4(pixel.rgb * scale, pixel.a);"); this->QuadHelper = new vtkOpenGLQuadHelper(renWin, vtkOpenGLRenderUtilities::GetFullScreenQuadVertexShader().c_str(), FSSource.c_str(), ""); this->QuadHelper->ShaderChangeValue = this->ToneMappingType; } else { renWin->GetShaderCache()->ReadyShaderProgram(this->QuadHelper->Program); } if (!this->QuadHelper->Program || !this->QuadHelper->Program->GetCompiled()) { vtkErrorMacro("Couldn't build the shader program."); return; } this->ColorTexture->Activate(); this->QuadHelper->Program->SetUniformi("source", this->ColorTexture->GetTextureUnit()); if (this->ToneMappingType == Exponential) { this->QuadHelper->Program->SetUniformf("exposure", this->Exposure); } ostate->vtkglDisable(GL_BLEND); ostate->vtkglDisable(GL_DEPTH_TEST); ostate->vtkglViewport(x, y, w, h); ostate->vtkglScissor(x, y, w, h); this->QuadHelper->Render(); this->ColorTexture->Deactivate(); vtkOpenGLCheckErrorMacro("failed after Render"); } // ---------------------------------------------------------------------------- void vtkToneMappingPass::ReleaseGraphicsResources(vtkWindow* w) { this->Superclass::ReleaseGraphicsResources(w); if (this->QuadHelper) { delete this->QuadHelper; this->QuadHelper = nullptr; } if (this->FrameBufferObject) { this->FrameBufferObject->Delete(); this->FrameBufferObject = nullptr; } if (this->ColorTexture) { this->ColorTexture->Delete(); this->ColorTexture = nullptr; } }
6,641
2,294
// Copyright (c) 2000-2022, Heiko Bauke // 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 HOLDERS 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 "yarn4.hpp" namespace trng { // Uniform random number generator concept // Parameter and status classes const yarn4::parameter_type yarn4::LEcuyer1 = parameter_type(2001982722, 1412284257, 1155380217, 1668339922); const yarn4::parameter_type yarn4::LEcuyer2 = parameter_type(64886, 0, 0, 64322); // Random number engine concept yarn4::yarn4(yarn4::parameter_type P) : P{P} {} yarn4::yarn4(unsigned long s, yarn4::parameter_type P) : P{P} { seed(s); } void yarn4::seed() { (*this) = yarn4(); } void yarn4::seed(unsigned long s) { int64_t t(s); t %= modulus; if (t < 0) t += modulus; S.r[0] = static_cast<result_type>(t); S.r[1] = 1; S.r[2] = 1; S.r[3] = 1; } void yarn4::seed(yarn4::result_type s1, yarn4::result_type s2, yarn4::result_type s3, yarn4::result_type s4) { S.r[0] = s1 % modulus; if (S.r[0] < 0) S.r[0] += modulus; S.r[1] = s2 % modulus; if (S.r[1] < 0) S.r[1] += modulus; S.r[2] = s3 % modulus; if (S.r[2] < 0) S.r[2] += modulus; S.r[3] = s4 % modulus; if (S.r[3] < 0) S.r[3] += modulus; } // Equality comparable concept bool operator==(const yarn4 &R1, const yarn4 &R2) { return R1.P == R2.P and R1.S == R2.S; } bool operator!=(const yarn4 &R1, const yarn4 &R2) { return not(R1 == R2); } // other useful methods const char *const yarn4::name_str = "yarn4"; const char *yarn4::name() { return name_str; } const int_math::power<yarn4::modulus, yarn4::gen> yarn4::g; } // namespace trng
3,179
1,284
#ifndef PacDispCyl_HH #define PacDispCyl_HH #include <stdio.h> #include <Rtypes.h> #define STRINGSIZE 100 struct PacDispCyl { virtual ~PacDispCyl() {;} Double_t radius,thickness,lowZ,hiZ; Int_t imat; PacDispCyl():radius(-1.0),thickness(-1.0),lowZ(-1.0),hiZ(1.0){} static const char* rootnames() { return "radius/D:thick/D:lowZ/D:hiZ/D:imat/I"; } ClassDef(PacDispCyl,1) }; #endif
401
193
#include <algorithm> #include "GitCommit.h" GitCommit::GitCommit(GitRepository *repo) : GitObject(repo, "commit") { } GitCommit::GitCommit(GitRepository *repo, const std::string &fmt) : GitObject(repo, fmt) { } std::vector<unsigned char> GitCommit::serialize() { return kvlm_serialize(); } void GitCommit::deserialize(const std::vector<unsigned char> &data) { m_dct.clear(); kvlm_parse(data, 0, m_dct); } std::vector<std::string> GitCommit::get_value(const std::string &key) { auto it = m_dct.find(key); if (it == m_dct.end()) return std::vector<std::string>(); return it->second; } std::string GitCommit::replace_all(const std::string &s, const std::string &before, const std::string &after) { std::string s2 = s; size_t idx = s2.find(before); while (idx != std::string::npos) { s2.replace(idx, before.size(), after); idx = s2.find(before, idx + after.size()); } return s2; } void GitCommit::kvlm_parse(const std::vector<unsigned char> &raw, size_t start, std::map<std::string, std::vector<std::string> > &dct) { // We search for the next space and the next newline. int spc = -1; int nl = -1; const char space = ' '; const char newline = '\n'; auto it1 = std::find(raw.begin() + start, raw.end(), space); if (it1 != raw.end()) { spc = it1 - raw.begin(); } auto it2 = std::find(raw.begin() + start, raw.end(), newline); if (it2 != raw.end()) { nl = it2 - raw.begin(); } // If space appears before newline, we have a keyword. // Base case // ========= // If newline appears first (or there's no space at all, in which // case find returns -1), we assume a blank line. A blank line // means the remainder of the data is the message. if ((spc < 0) || (nl < spc)) { std::string value; value.append(raw.begin() + start + 1, raw.end()); std::vector values{value}; dct.insert({std::string(), values}); return; } // Recursive case // ============== // we read a key-value pair and recurse for the next. std::string key; key.append(raw.begin() + start, raw.begin() + spc); // Find the end of the value. Continuation lines begin with a // space, so we loop until we find a '\n' not followed by a space. size_t ending = start; while (true) { auto it3 = std::find(raw.begin() + ending + 1, raw.end(), newline); if (it3 == raw.end()) break; ending = it3 - raw.begin(); if (*(it3 + 1) != space) { break; } } // Grab the value // Also, drop the leading space on continuation lines std::string value; value.append(raw.begin() + spc + 1, raw.begin() + ending); value = replace_all(value, "\n ", "\n"); // Don't overwrite existing data contents auto it4 = dct.find(key); if (it4 != dct.end()) { it4->second.push_back(value); } else { std::vector values{value}; dct.insert({key, values}); } kvlm_parse(raw, ending + 1, dct); } std::vector<unsigned char> GitCommit::kvlm_serialize() { std::vector<unsigned char> ret; std::vector<std::string> message; for (auto it = m_dct.begin(); it != m_dct.end(); it++) { std::string key = it->first; if (key.empty()) { // Skip the message itself message = it->second; continue; } std::vector<std::string> val = it->second; for (const std::string &v : val) { for (const char &c : key) { ret.push_back(c); } ret.push_back(' '); std::string v2 = replace_all(v, "\n", "\n "); for (const char &c : v2) { ret.push_back(c); } } } // Append message ret.push_back('\n'); for (const std::string &v : message) { for (const char &c : v) { ret.push_back(c); } } return ret; }
3,592
1,478
/* * * Copyright 2006-2022, Andrea Anzani. * Distributed under the terms of the MIT License. * * Authors: * Andrea Anzani <andrea.anzani@gmail.com> */ #include "SamplerPanel.h" #include "Sample.h" #include "SamplerTrackBoost.h" #include "GlobalDef.h" #include "GfxMsg.h" #include "SamplerTrack.h" #include "Xed_Utils.h" #include "sampler_locale.h" #include "XDigit.h" #include "XHost.h" #define REMOVE 'remv' #define REMOVEALL 'rema' #define LOADEXT 'loae' #define REL_MSG 'note' #define REV_ON 'reo' #define PIT_ON 'pio' #define BOOST_ON 'boo' #define MOD 'mod' #define LOOP_ON 'loop' SamplerPanel::SamplerPanel(SamplerTrackBoost* sb): PlugPanel(), sampTrack(NULL), booster(sb) { BBox *sam_box= new BBox(BRect(10,150+17,171,210+17) ,"toolbar", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP, B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP, B_FANCY_BORDER); BBox *sampler= new BBox(BRect(8,18,172,50) ,"toolbar", B_FOLLOW_LEFT_RIGHT | B_FOLLOW_TOP, B_WILL_DRAW|B_FRAME_EVENTS|B_NAVIGABLE_JUMP, B_FANCY_BORDER); menu=new BMenu(" "); menu->AddItem(booster->getMenu()); menu->AddItem(new BMenuItem(T_SAMPLER_LOAD,new BMessage(LOADEXT))); menu->AddItem(new BMenuItem(T_SAMPLER_REMOVE,new BMessage(REMOVE))); menu->AddItem(new BMenuItem(T_SAMPLER_REMOVE_ALL,new BMessage(REMOVEALL))); BRect r(sampler->Bounds()); r.InsetBy(4,4); field=new BMenuField(r,""," ",menu); pit_box= new BBox(BRect(8,70-13,172,102-13), ""); r=(pit_box->Bounds()); r.InsetBy(4,4); r.right-=50; r.top+=2; pit_box->AddChild(pit_ck=new BCheckBox(r,"",T_SAMPLER_STRECH,new BMessage(PIT_ON))); pit_ck->SetValue(0); pit_ck->SetFontSize(12); pit_box->AddChild(shift=new XDigit(BRect(120,5,120+36,5+21), VID_EMPTY, "sampler_shift_xdigit", new BMessage(MOD),1,32)); r=(pit_box->Frame()); r.OffsetBy(0,38); AddChild(pit_box); pit_box= new BBox(r, "2"); r=(pit_box->Bounds()); r.InsetBy(4,4); r.right-=50; r.top+=2; pit_box->AddChild(boost_ck=new BCheckBox(r,"",T_SAMPLER_BOOST,new BMessage(BOOST_ON))); boost_ck->SetValue(0); boost_ck->SetFontSize(12); pit_box->AddChild(depth=new XDigit(BRect(120,5,120+36,5+21), VID_EMPTY, "sampler_boost", new BMessage(REL_MSG),1,4)); r=(pit_box->Frame()); r.OffsetBy(0,38); AddChild(pit_box); pit_box= new BBox(r, "3"); r=(pit_box->Bounds()); r.InsetBy(4,4); r.right -= 75; r.top += 2; pit_box->AddChild(rev = new BCheckBox(r,"rev_check",T_SAMPLER_REVERSE,new BMessage(TRACK_REV))); rev->SetValue(0); rev->SetFontSize(12); rev->ResizeToPreferred(); r.OffsetBy(r.Width(), 0); pit_box->AddChild(loop_ck = new BCheckBox(r,"loop_check","Loop", new BMessage(LOOP_ON))); loop_ck->SetValue(0); loop_ck->SetFontSize(12); loop_ck->ResizeToPreferred(); AddChild(pit_box); sw=new SampleView(BRect(1,1,159,58), XUtils::GetBitmap(18)); sam_box->AddChild(sw); sampler->AddChild(field); AddChild(sampler); AddChild(sam_box); my_sample=NULL; rev->SetValue(false); menu->Superitem()->SetLabel(T_SAMPLER_NOSELECTED); } void SamplerPanel::ResetToTrack(Track* trk) { //qui magari un bel check dell'ID ?? PlugPanel::ResetToTrack(trk); SetTrack((SamplerTrack*)trk); } void SamplerPanel::AttachedToWindow() { PlugPanel::AttachedToWindow(); depth->SetTarget(this); shift->SetTarget((BView*)this); pit_ck->SetTarget(this); rev->SetTarget(this); menu->SetTargetForItems(this); boost_ck->SetTarget(this); loop_ck->SetTarget(this); field->SetDivider(0); } void SamplerPanel::SetTrack(SamplerTrack *tr) { if(!Window()) return; sampTrack = tr; if(Window()->Lock()){ if(tr == NULL || tr->getSample() == NULL) { sw->Init(NULL, false, false); shift->UpdateValue(16, true); pit_ck->SetValue(false); boost_ck->SetValue(false); loop_ck->SetValue(false); menu->Superitem()->SetLabel(T_SAMPLER_NOSELECTED); depth->UpdateValue(1, true); } else { SetTitle(tr->getName()); my_sample=tr->getSample(); sw->Init(my_sample, tr->isReversed(), 1.0f); menu->Superitem()->SetLabel(my_sample->GetName()); shift->UpdateValue(tr->getResample(), true); pit_ck->SetValue(tr->isResampleEnable()); boost_ck->SetValue(tr->isBoostEnable()); loop_ck->SetValue(tr->IsLoopEnable()); rev->SetValue(tr->isReversed()); depth->UpdateValue((int32)tr->amp, true); sw->SetBoost(tr->amp); } Window()->Unlock(); } } void SamplerPanel::MessageReceived(BMessage* message) { switch(message->what) { case LOOP_ON: if(sampTrack == NULL) return; sampTrack->SetLoopEnable((bool)loop_ck->Value()); break; case BOOST_ON: if(sampTrack==NULL) return; sampTrack->setBoostEnable((bool)boost_ck->Value()); if(!boost_ck->Value()) { sampTrack->amp=1.0; sw->SetBoost(sampTrack->amp); return; } //else continue (without break!) case REL_MSG: if(sampTrack==NULL) return; if(!sampTrack->isBoostEnable()) return; sampTrack->amp=(float)depth->GetValue(); sw->SetBoost(sampTrack->amp); break; case TRACK_SAMP_EXT: booster->ChangeSample(message->FindInt16("sample"));//ok break; case MOD: if(sampTrack==NULL) return; XHost::Get()->SendMessage(X_LockSem,NULL); sampTrack->setResample(shift->GetValue()); XHost::Get()->SendMessage(X_UnLockSem,NULL); break; case PIT_ON: if(sampTrack==NULL) return; XHost::Get()->SendMessage(X_LockSem,NULL); sampTrack->setResampleEnable((bool)pit_ck->Value()); XHost::Get()->SendMessage(X_UnLockSem,NULL); break; case TRACK_REV: if(sampTrack==NULL) return; sampTrack->setReversed(rev->Value()); sw->SetReversed(rev->Value()); break; case LOADEXT: booster->LoadSample(); break; case REMOVEALL: booster->RemoveAll(); break; case REMOVE: booster->RemoveSample(((SamplerTrack*)sampTrack)->getSample()); break; case B_REFS_RECEIVED: //ok { entry_ref ref; if(message->FindRef("refs",&ref)==B_OK) { booster->RefReceived(ref,sampTrack); booster->RefreshSelected(); } } break; default: PlugPanel::MessageReceived(message); break; } }
6,128
2,903
/** * urls/resolver.cpp * * Copyright (c) 2019-2021 Yuriy Lisovskiy */ #include "./resolver.h" __URLS_BEGIN__ std::function<std::unique_ptr<http::IResponse>(http::IRequest*, conf::Settings*)> resolve( const std::string& path, const std::vector<std::shared_ptr<IPattern>>& urlpatterns ) { std::function<std::unique_ptr<http::IResponse>(http::IRequest*, conf::Settings*)> fn = nullptr; for (const auto& url_pattern : urlpatterns) { if (url_pattern->match(path)) { fn = [url_pattern]( http::IRequest* request, conf::Settings* settings ) -> std::unique_ptr<http::IResponse> { return url_pattern->apply(request, settings); }; break; } } return fn; } __URLS_END__
700
284
#include <gtest/gtest.h> #include <srrg_system_utils/parse_command_line.h> #include <srrg_system_utils/shell_colors.h> #include "srrg_solver/solver_core/instances.h" #include "srrg_solver/solver_core/internals/linear_solvers/instances.h" #include "srrg_solver/solver_core/solver.h" #include "srrg_solver/variables_and_factors/types_2d/instances.h" const std::string exe_name = "test_se2_icp"; #define LOG std::cerr << exe_name + "|" using namespace srrg2_core; using namespace srrg2_solver; const size_t n_meas = 1000; const size_t n_iterations = 10; int main(int argc, char** argv) { variables_and_factors_2d_registerTypes(); solver_registerTypes(); linear_solver_registerTypes(); testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); } TEST(DUMMY_DATA, SE2Point2PointErrorFactor) { using VariableType = VariableSE2Right; using VariablePtrType = std::shared_ptr<VariableType>; using FactorType = SE2Point2PointErrorFactorCorrespondenceDriven; using FactorPtrType = std::shared_ptr<FactorType>; const Vector3f t = 10 * Vector3f::Random(); Isometry2f T = geometry2d::v2t(t); const Isometry2f inv_T = T.inverse(); // declare a multi_solver Solver solver; // declare a graph, FactorGraphPtr graph(new FactorGraph); // create a variable, set an id and add it to the graph VariablePtrType pose(new VariableType); pose->setGraphId(0); graph->addVariable(pose); graph->bindFactors(); solver.setGraph(graph); // ia create two cloud that we want to align, and a vector of correspondences Point2fVectorCloud fixed_cloud; Point2fVectorCloud moving_cloud; CorrespondenceVector correspondences; fixed_cloud.reserve(n_meas); moving_cloud.reserve(n_meas); correspondences.reserve(n_meas); for (size_t i = 0; i < n_meas; ++i) { // ia create dummy measurements Point2f fixed_point, moving_point; fixed_point.coordinates().setRandom(); moving_point.coordinates() = inv_T * fixed_point.coordinates(); fixed_cloud.emplace_back(fixed_point); moving_cloud.emplace_back(moving_point); correspondences.emplace_back(Correspondence(i, i)); } // create an ICP factor, correspondence driven, set the var index, and add it to the graph FactorPtrType factor(new FactorType); factor->setVariableId(0, 0); graph->addFactor(factor); // setup the factor; factor->setFixed(fixed_cloud); factor->setMoving(moving_cloud); factor->setCorrespondences(correspondences); factor->setInformationMatrix(Matrix2f::Identity()); solver.param_max_iterations.pushBack(n_iterations); solver.param_termination_criteria.setValue(nullptr); ASSERT_EQ(graph->factors().size(), static_cast<size_t>(1)); pose->setEstimate(Isometry2f::Identity()); solver.compute(); const auto& stats = solver.iterationStats(); const auto& final_chi2 = stats.back().chi_inliers; // ia assert performed iterations are the effectively n_iterations ASSERT_EQ(stats.size(), n_iterations); // ia assert chi2 is good ASSERT_LT(final_chi2, 1e-6); // ia assert that relative error is good const auto& estimated_T = pose->estimate(); const Isometry2f diff_T = estimated_T.inverse() * T; const Vector3f diff_vector = geometry2d::t2v(diff_T); LOG << stats << std::endl; ASSERT_LT(diff_vector.x(), 1e-5); ASSERT_LT(diff_vector.y(), 1e-5); ASSERT_LT(diff_vector.z(), 1e-5); } TEST(DUMMY_DATA, SE2Point2PointWithSensorErrorFactor) { using VariableType = VariableSE2Right; using VariablePtrType = std::shared_ptr<VariableType>; using FactorType = SE2Point2PointWithSensorErrorFactorCorrespondenceDriven; using FactorPtrType = std::shared_ptr<FactorType>; const Vector3f t = 10 * Vector3f::Random(); Vector3f sensor_in_robot_v = Vector3f(0.1, 0.2, 0.5); Isometry2f sensor_in_robot = geometry2d::v2t(sensor_in_robot_v); Isometry2f ground_truth_T = geometry2d::v2t(t); Isometry2f T = ground_truth_T * sensor_in_robot; const Isometry2f inv_T = T.inverse(); // declare a multi_solver Solver solver; // declare a graph, FactorGraphPtr graph(new FactorGraph); // create a variable, set an id and add it to the graph VariablePtrType pose(new VariableType); pose->setGraphId(0); pose->setEstimate(Isometry2f::Identity()); graph->addVariable(pose); graph->bindFactors(); solver.setGraph(graph); // ia create two cloud that we want to align, and a vector of correspondences Point2fVectorCloud fixed_cloud; Point2fVectorCloud moving_cloud; CorrespondenceVector correspondences; fixed_cloud.reserve(n_meas); moving_cloud.reserve(n_meas); correspondences.reserve(n_meas); for (size_t i = 0; i < n_meas; ++i) { // ia create dummy measurements Point2f fixed_point, moving_point; moving_point.coordinates().setRandom(); fixed_point.coordinates() = inv_T * moving_point.coordinates(); fixed_cloud.emplace_back(fixed_point); moving_cloud.emplace_back(moving_point); correspondences.emplace_back(Correspondence(i, i)); } // create an ICP factor, correspondence driven, set the var index, and add it to the graph FactorPtrType factor(new FactorType); factor->setVariableId(0, 0); graph->addFactor(factor); // setup the factor; factor->setFixed(fixed_cloud); factor->setMoving(moving_cloud); factor->setCorrespondences(correspondences); factor->setInformationMatrix(Matrix2f::Identity()); factor->setSensorInRobot(sensor_in_robot); solver.param_max_iterations.pushBack(n_iterations); solver.param_termination_criteria.setValue(nullptr); ASSERT_EQ(graph->factors().size(), static_cast<size_t>(1)); solver.compute(); const auto& stats = solver.iterationStats(); const auto& final_chi2 = stats.back().chi_inliers; // ia assert performed iterations are the effectively n_iterations ASSERT_EQ(stats.size(), n_iterations); // ia assert chi2 is good ASSERT_LT(final_chi2, 1e-6); // ia assert that relative error is good const auto& estimated_T = pose->estimate(); const Isometry2f diff_T = estimated_T * ground_truth_T; const Vector3f diff_vector = geometry2d::t2v(diff_T); LOG << stats << std::endl; LOG << "sensor T : " << geometry2d::t2v(T).transpose() << std::endl; LOG << "estim T : " << geometry2d::t2v(estimated_T.inverse()).transpose() << std::endl; LOG << "GT : " << geometry2d::t2v(ground_truth_T).transpose() << std::endl; ASSERT_LT(diff_vector.x(), 1e-5); ASSERT_LT(diff_vector.y(), 1e-5); ASSERT_LT(diff_vector.z(), 1e-5); }
6,580
2,365
/////////////////////////////////////////////////////////////////////////////// // File: DDTECModuleAlgo .cc // Description: Creation of a TEC Test /////////////////////////////////////////////////////////////////////////////// #include <cmath> #include <algorithm> #include <cstdio> #include <string> #include <utility> #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DetectorDescription/Core/interface/DDLogicalPart.h" #include "DetectorDescription/Core/interface/DDSolid.h" #include "DetectorDescription/Core/interface/DDMaterial.h" #include "DetectorDescription/Core/interface/DDCurrentNamespace.h" #include "DetectorDescription/Core/interface/DDSplit.h" #include "Geometry/TrackerCommonData/plugins/DDTECModuleAlgo.h" #include "CLHEP/Units/GlobalPhysicalConstants.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" DDTECModuleAlgo::DDTECModuleAlgo() { LogDebug("TECGeom") << "DDTECModuleAlgo info: Creating an instance"; } DDTECModuleAlgo::~DDTECModuleAlgo() {} void DDTECModuleAlgo::initialize(const DDNumericArguments & nArgs, const DDVectorArguments & vArgs, const DDMapArguments & , const DDStringArguments & sArgs, const DDStringVectorArguments & vsArgs) { idNameSpace = DDCurrentNamespace::ns(); genMat = sArgs["GeneralMaterial"]; DDName parentName = parent().name(); LogDebug("TECGeom") << "DDTECModuleAlgo debug: Parent " << parentName << " NameSpace " << idNameSpace << " General Material " << genMat; ringNo = (int)nArgs["RingNo"]; moduleThick = nArgs["ModuleThick"]; detTilt = nArgs["DetTilt"]; fullHeight = nArgs["FullHeight"]; dlTop = nArgs["DlTop"]; dlBottom = nArgs["DlBottom"]; dlHybrid = nArgs["DlHybrid"]; rPos = nArgs["RPos"]; standardRot = sArgs["StandardRotation"]; isRing6 = (ringNo == 6); LogDebug("TECGeom") << "DDTECModuleAlgo debug: ModuleThick " << moduleThick << " Detector Tilt " << detTilt/CLHEP::deg << " Height " << fullHeight << " dl(Top) " << dlTop << " dl(Bottom) " << dlBottom << " dl(Hybrid) " << dlHybrid << " rPos " << rPos << " standrad rotation " << standardRot; frameWidth = nArgs["FrameWidth"]; frameThick = nArgs["FrameThick"]; frameOver = nArgs["FrameOver"]; LogDebug("TECGeom") << "DDTECModuleAlgo debug: Frame Width " << frameWidth << " Thickness " << frameThick << " Overlap " << frameOver; topFrameMat = sArgs["TopFrameMaterial"]; topFrameHeight = nArgs["TopFrameHeight"]; topFrameTopWidth= nArgs["TopFrameTopWidth"]; topFrameBotWidth= nArgs["TopFrameBotWidth"]; topFrameThick = nArgs["TopFrameThick"]; topFrameZ = nArgs["TopFrameZ"]; LogDebug("TECGeom") << "DDTECModuleAlgo debug: Top Frame Material " << topFrameMat << " Height " << topFrameHeight << " Top Width " << topFrameTopWidth << " Bottom Width " << topFrameTopWidth << " Thickness " << topFrameThick <<" positioned at" << topFrameZ; double resizeH =0.96; sideFrameMat = sArgs["SideFrameMaterial"]; sideFrameThick = nArgs["SideFrameThick"]; sideFrameLWidth = nArgs["SideFrameLWidth"]; sideFrameLHeight = resizeH*nArgs["SideFrameLHeight"]; sideFrameLtheta = nArgs["SideFrameLtheta"]; sideFrameRWidth = nArgs["SideFrameRWidth"]; sideFrameRHeight = resizeH*nArgs["SideFrameRHeight"]; sideFrameRtheta = nArgs["SideFrameRtheta"]; siFrSuppBoxWidth = vArgs["SiFrSuppBoxWidth"]; siFrSuppBoxHeight = vArgs["SiFrSuppBoxHeight"]; siFrSuppBoxYPos = vArgs["SiFrSuppBoxYPos"]; siFrSuppBoxThick = nArgs["SiFrSuppBoxThick"]; siFrSuppBoxMat = sArgs["SiFrSuppBoxMaterial"]; sideFrameZ = nArgs["SideFrameZ"]; LogDebug("TECGeom") << "DDTECModuleAlgo debug : Side Frame Material " << sideFrameMat << " Thickness " << sideFrameThick << " left Leg's Width: " << sideFrameLWidth << " left Leg's Height: " << sideFrameLHeight << " left Leg's tilt(theta): " << sideFrameLtheta << " right Leg's Width: " << sideFrameRWidth << " right Leg's Height: " << sideFrameRHeight << " right Leg's tilt(theta): " << sideFrameRtheta << "Supplies Box's Material: " << siFrSuppBoxMat << " positioned at" << sideFrameZ; for (int i= 0; i < (int)(siFrSuppBoxWidth.size());i++){ LogDebug("TECGeom") << " Supplies Box" << i << "'s Width: " << siFrSuppBoxWidth[i] << " Supplies Box" << i <<"'s Height: " << siFrSuppBoxHeight[i] << " Supplies Box" << i << "'s y Position: " << siFrSuppBoxYPos[i]; } waferMat = sArgs["WaferMaterial"]; sideWidthTop = nArgs["SideWidthTop"]; sideWidthBottom= nArgs["SideWidthBottom"]; waferRot = sArgs["WaferRotation"]; waferPosition = nArgs["WaferPosition"]; LogDebug("TECGeom") << "DDTECModuleAlgo debug: Wafer Material " << waferMat << " Side Width Top" << sideWidthTop << " Side Width Bottom" << sideWidthBottom << " and positioned at "<<waferPosition << " positioned with rotation" << " matrix:" << waferRot; activeMat = sArgs["ActiveMaterial"]; activeHeight = nArgs["ActiveHeight"]; waferThick = nArgs["WaferThick"]; activeRot = sArgs["ActiveRotation"]; activeZ = nArgs["ActiveZ"]; backplaneThick = nArgs["BackPlaneThick"]; LogDebug("TECGeom") << "DDTECModuleAlgo debug: Active Material " << activeMat << " Height " << activeHeight << " rotated by " << activeRot << " translated by (0,0," << -0.5 * backplaneThick << ")" << " Thickness/Z" << waferThick-backplaneThick << "/" << activeZ; hybridMat = sArgs["HybridMaterial"]; hybridHeight = nArgs["HybridHeight"]; hybridWidth = nArgs["HybridWidth"]; hybridThick = nArgs["HybridThick"]; hybridZ = nArgs["HybridZ"]; LogDebug("TECGeom") << "DDTECModuleAlgo debug: Hybrid Material " << hybridMat << " Height " << hybridHeight << " Width " << hybridWidth << " Thickness " << hybridThick << " Z" << hybridZ; pitchMat = sArgs["PitchMaterial"]; pitchHeight = nArgs["PitchHeight"]; pitchThick = nArgs["PitchThick"]; pitchWidth = nArgs["PitchWidth"]; pitchZ = nArgs["PitchZ"]; pitchRot = sArgs["PitchRotation"]; LogDebug("TECGeom") << "DDTECModuleAlgo debug: Pitch Adapter Material " << pitchMat << " Height " << pitchHeight << " Thickness " << pitchThick << " position with " << " rotation " << pitchRot << " at Z" << pitchZ; bridgeMat = sArgs["BridgeMaterial"]; bridgeWidth = nArgs["BridgeWidth"]; bridgeThick = nArgs["BridgeThick"]; bridgeHeight = nArgs["BridgeHeight"]; bridgeSep = nArgs["BridgeSeparation"]; LogDebug("TECGeom") << "DDTECModuleAlgo debug: Bridge Material " << bridgeMat << " Width " << bridgeWidth << " Thickness " << bridgeThick << " Height " << bridgeHeight << " Separation "<< bridgeSep; siReenforceWidth = vArgs["SiReenforcementWidth"]; siReenforceHeight = vArgs["SiReenforcementHeight"]; siReenforceYPos = vArgs["SiReenforcementPosY"]; siReenforceThick = nArgs["SiReenforcementThick"]; siReenforceMat = sArgs["SiReenforcementMaterial"]; LogDebug("TECGeom") << "FALTBOOT DDTECModuleAlgo debug : Si-Reenforcement Material " << sideFrameMat << " Thickness " << siReenforceThick; for (int i= 0; i < (int)(siReenforceWidth.size());i++){ LogDebug("TECGeom") << " SiReenforcement" << i << "'s Width: " << siReenforceWidth[i] << " SiReenforcement" << i << "'s Height: " << siReenforceHeight[i] << " SiReenforcement" << i << "'s y Position: " <<siReenforceYPos[i]; } inactiveDy = 0; inactivePos = 0; if(ringNo > 3){ inactiveDy = nArgs["InactiveDy"]; inactivePos = nArgs["InactivePos"]; inactiveMat = sArgs["InactiveMaterial"]; } noOverlapShift = nArgs["NoOverlapShift"]; //Everything that is normal/stereo specific comes here isStereo = (int)nArgs["isStereo"] == 1; if(!isStereo){ LogDebug("TECGeom") << "This is a normal module, in ring "<<ringNo<<"!"; } else { LogDebug("TECGeom") << "This is a stereo module, in ring "<<ringNo<<"!"; posCorrectionPhi= nArgs["PosCorrectionPhi"]; topFrame2LHeight = nArgs["TopFrame2LHeight"]; topFrame2RHeight = nArgs["TopFrame2RHeight"]; topFrame2Width = nArgs["TopFrame2Width"]; LogDebug("TECGeom") << "Phi Position corrected by " << posCorrectionPhi << "*rad"; LogDebug("TECGeom") << "DDTECModuleAlgo debug: stereo Top Frame 2nd Part left Heigt " << topFrame2LHeight << " right Height " << topFrame2RHeight << " Width " << topFrame2Width ; sideFrameLWidthLow = nArgs["SideFrameLWidthLow"]; sideFrameRWidthLow = nArgs["SideFrameRWidthLow"]; LogDebug("TECGeom") << " left Leg's lower Width: " << sideFrameLWidthLow << " right Leg's lower Width: " << sideFrameRWidthLow; // posCorrectionR = nArgs["PosCorrectionR"]; //LogDebug("TECGeom") << "Stereo Module Position Correction with R = " << posCorrectionR; } } void DDTECModuleAlgo::doPos(const DDLogicalPart& toPos, const DDLogicalPart& mother, int copyNr, double x, double y, double z, const std::string& rotName, DDCompactView& cpv) { DDTranslation tran(z, x, y); DDRotation rot; std::string rotstr = DDSplit(rotName).first; std::string rotns; if (rotstr != "NULL") { rotns = DDSplit(rotName).second; rot = DDRotation(DDName(rotstr, rotns)); } else { rot = DDRotation(); } cpv.position(toPos, mother, copyNr, tran, rot); LogDebug("TECGeom") << "DDTECModuleAlgo test: " << toPos.name() << " positioned in "<< mother.name() << " at " << tran << " with " << rot; } void DDTECModuleAlgo::doPos(DDLogicalPart toPos, double x, double y, double z, std::string rotName, DDCompactView& cpv) { int copyNr = 1; if (isStereo) copyNr = 2; // This has to be done so that the Mother coordinate System of a Tub resembles // the coordinate System of a Trap or Box. z += rPos; if(isStereo){ // z is x , x is y //z+= rPos*sin(posCorrectionPhi); <<- this is already corrected with the r position! x+= rPos*sin(posCorrectionPhi); } if (rotName == "NULL") rotName = standardRot; doPos(std::move(toPos),parent(),copyNr,x,y,z,rotName, cpv); } void DDTECModuleAlgo::execute(DDCompactView& cpv) { LogDebug("TECGeom") << "==>> Constructing DDTECModuleAlgo..."; //declarations double tmp; double dxdif, dzdif; double dxbot, dxtop; // topfr; //positions double xpos, ypos, zpos; //dimensons double bl1, bl2; double h1; double dx, dy, dz; double thet; //names std::string idName; std::string name; std::string tag("Rphi"); if (isStereo) tag = "Stereo"; //usefull constants const double topFrameEndZ = 0.5 * (-waferPosition + fullHeight) + pitchHeight + hybridHeight - topFrameHeight; DDName parentName = parent().name(); idName = parentName.name(); LogDebug("TECGeom") << "==>> " << idName << " parent " << parentName << " namespace " << idNameSpace; DDSolid solid; //set global parameters DDName matname(DDSplit(genMat).first, DDSplit(genMat).second); DDMaterial matter(matname); dzdif = fullHeight + topFrameHeight; if(isStereo) dzdif += 0.5*(topFrame2LHeight+topFrame2RHeight); dxbot = 0.5*dlBottom + frameWidth - frameOver; dxtop = 0.5*dlHybrid + frameWidth - frameOver; // topfr = 0.5*dlBottom * sin(detTilt); if (isRing6) { dxbot = dxtop; dxtop = 0.5*dlTop + frameWidth - frameOver; // topfr = 0.5*dlTop * sin(detTilt); } dxdif = dxtop - dxbot; //Frame Sides // left Frame name = idName + "SideFrameLeft"; matname = DDName(DDSplit(sideFrameMat).first, DDSplit(sideFrameMat).second); matter = DDMaterial(matname); h1 = 0.5 * sideFrameThick; dz = 0.5 * sideFrameLHeight; bl1 = bl2 = 0.5 * sideFrameLWidth; thet = sideFrameLtheta; //for stereo modules if(isStereo) bl1 = 0.5 * sideFrameLWidthLow; solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet, 0, h1, bl1, bl1, 0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", "<<thet<<", 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; DDLogicalPart sideFrameLeft(solid.ddname(), matter, solid); //translate xpos = - 0.5*topFrameBotWidth +bl2+ tan(fabs(thet)) * dz; ypos = sideFrameZ; zpos = topFrameEndZ -dz; //flip ring 6 if (isRing6){ zpos *= -1; xpos -= 2*tan(fabs(thet)) * dz; // because of the flip the tan(..) to be in the other direction } //the stereo modules are on the back of the normal ones... if(isStereo) { xpos = - 0.5*topFrameBotWidth + bl2*cos(detTilt) + dz*sin(fabs(thet)+detTilt)/cos(fabs(thet)); xpos = -xpos; zpos = topFrameEndZ -topFrame2LHeight- 0.5*sin(detTilt)*(topFrameBotWidth - topFrame2Width)-dz*cos(detTilt+fabs(thet))/cos(fabs(thet))+bl2*sin(detTilt)-0.1*CLHEP::mm; } //position doPos(sideFrameLeft,xpos,ypos,zpos,waferRot, cpv); //right Frame name = idName + "SideFrameRight"; matname = DDName(DDSplit(sideFrameMat).first, DDSplit(sideFrameMat).second); matter = DDMaterial(matname); h1 = 0.5 * sideFrameThick; dz = 0.5 * sideFrameRHeight; bl1 = bl2 = 0.5 * sideFrameRWidth; thet = sideFrameRtheta; if(isStereo) bl1 = 0.5 * sideFrameRWidthLow; solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet, 0, h1, bl1, bl1, 0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", "<<thet<<", 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; DDLogicalPart sideFrameRight(solid.ddname(), matter, solid); //translate xpos = 0.5*topFrameBotWidth -bl2- tan(fabs(thet)) * dz; ypos = sideFrameZ; zpos = topFrameEndZ -dz ; if (isRing6){ zpos *= -1; xpos += 2*tan(fabs(thet)) * dz; // because of the flip the tan(..) has to be in the other direction } if(isStereo){ xpos = 0.5*topFrameBotWidth - bl2*cos(detTilt) - dz*sin(fabs(detTilt-fabs(thet)))/cos(fabs(thet)); xpos = -xpos; zpos = topFrameEndZ -topFrame2RHeight+ 0.5*sin(detTilt)*(topFrameBotWidth - topFrame2Width)-dz*cos(detTilt-fabs(thet))/cos(fabs(thet))-bl2*sin(detTilt)-0.1*CLHEP::mm; } //position it doPos(sideFrameRight,xpos,ypos,zpos,waferRot, cpv); //Supplies Box(es) for (int i= 0; i < (int)(siFrSuppBoxWidth.size());i++){ name = idName + "SuppliesBox" + std::to_string(i); matname = DDName(DDSplit(siFrSuppBoxMat).first, DDSplit(siFrSuppBoxMat).second); matter = DDMaterial(matname); h1 = 0.5 * siFrSuppBoxThick; dz = 0.5 * siFrSuppBoxHeight[i]; bl1 = bl2 = 0.5 * siFrSuppBoxWidth[i]; thet = sideFrameRtheta; if(isStereo) thet = -atan(fabs(sideFrameRWidthLow-sideFrameRWidth)/(2*sideFrameRHeight)-tan(fabs(thet))); // ^-- this calculates the lower left angel of the tipped trapezoid, which is the SideFframe... solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet,0, h1, bl1, bl1, 0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", 0, 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; DDLogicalPart siFrSuppBox(solid.ddname(), matter, solid); //translate xpos = 0.5*topFrameBotWidth -sideFrameRWidth - bl1-siFrSuppBoxYPos[i]*tan(fabs(thet)); ypos = sideFrameZ*(0.5+(siFrSuppBoxThick/sideFrameThick)); //via * so I do not have to worry about the sign of sideFrameZ zpos = topFrameEndZ - siFrSuppBoxYPos[i]; if (isRing6){ xpos += 2*fabs(tan(thet))* siFrSuppBoxYPos[i]; // the flipped issue again zpos *= -1; } if(isStereo){ xpos = 0.5*topFrameBotWidth - (sideFrameRWidth+bl1)*cos(detTilt) -sin(fabs(detTilt-fabs(thet)))*(siFrSuppBoxYPos[i]+dz*(1/cos(thet)- cos(detTilt))+bl1*sin(detTilt)); xpos =-xpos; zpos = topFrameEndZ - topFrame2RHeight - 0.5*sin(detTilt)*(topFrameBotWidth - topFrame2Width) - siFrSuppBoxYPos[i]-sin(detTilt)*sideFrameRWidth; } //position it; doPos(siFrSuppBox,xpos,ypos,zpos,waferRot,cpv); } //The Hybrid name = idName + "Hybrid"; matname = DDName(DDSplit(hybridMat).first, DDSplit(hybridMat).second); matter = DDMaterial(matname); dx = 0.5 * hybridWidth; dy = 0.5 * hybridThick; dz = 0.5 * hybridHeight; solid = DDSolidFactory::box(DDName(name, idNameSpace), dx, dy, dz); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Box made of " << matname << " of dimensions " << dx << ", " << dy << ", " << dz; DDLogicalPart hybrid(solid.ddname(), matter, solid); ypos = hybridZ; zpos = 0.5 * (-waferPosition + fullHeight + hybridHeight)+pitchHeight; if (isRing6) zpos *=-1; //position it doPos(hybrid,0,ypos,zpos,"NULL", cpv); // Wafer name = idName + tag +"Wafer"; matname = DDName(DDSplit(waferMat).first, DDSplit(waferMat).second); matter = DDMaterial(matname); bl1 = 0.5 * dlBottom; bl2 = 0.5 * dlTop; h1 = 0.5 * waferThick; dz = 0.5 * fullHeight; solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl1, bl1, 0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", 0, 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; DDLogicalPart wafer(solid.ddname(), matter, solid); ypos = activeZ; zpos =-0.5 * waferPosition;// former and incorrect topFrameHeight; if (isRing6) zpos *= -1; doPos(wafer,0,ypos,zpos,waferRot,cpv); // Active name = idName + tag +"Active"; matname = DDName(DDSplit(activeMat).first, DDSplit(activeMat).second); matter = DDMaterial(matname); bl1 -= sideWidthBottom; bl2 -= sideWidthTop; dz = 0.5 * (waferThick-backplaneThick); // inactive backplane h1 = 0.5 * activeHeight; if (isRing6) { //switch bl1 <->bl2 tmp = bl2; bl2 =bl1; bl1 = tmp; } solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl2, bl1, 0, h1, bl2, bl1, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", 0, 0, " << h1 << ", " << bl2 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl1 << ", 0"; DDLogicalPart active(solid.ddname(), matter, solid); doPos(active, wafer, 1, -0.5 * backplaneThick,0,0, activeRot, cpv); // from the definition of the wafer local axes and doPos() routine //inactive part in rings > 3 if(ringNo > 3){ inactivePos -= fullHeight-activeHeight; //inactivePos is measured from the beginning of the _wafer_ name = idName + tag +"Inactive"; matname = DDName(DDSplit(inactiveMat).first, DDSplit(inactiveMat).second); matter = DDMaterial(matname); bl1 = 0.5*dlBottom-sideWidthBottom + ((0.5*dlTop-sideWidthTop-0.5*dlBottom+sideWidthBottom)/activeHeight) *(activeHeight-inactivePos-inactiveDy); bl2 = 0.5*dlBottom-sideWidthBottom + ((0.5*dlTop-sideWidthTop-0.5*dlBottom+sideWidthBottom)/activeHeight) *(activeHeight-inactivePos+inactiveDy); dz = 0.5 * (waferThick-backplaneThick); // inactive backplane h1 = inactiveDy; if (isRing6) { //switch bl1 <->bl2 tmp = bl2; bl2 =bl1; bl1 = tmp; } solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl2, bl1, 0, h1, bl2, bl1, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", 0, 0, " << h1 << ", " << bl2 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl1 << ", 0"; DDLogicalPart inactive(solid.ddname(), matter, solid); ypos = inactivePos - 0.5*activeHeight; doPos(inactive,active, 1, ypos,0,0, "NULL", cpv); // from the definition of the wafer local axes and doPos() routine } //Pitch Adapter name = idName + "PA"; matname = DDName(DDSplit(pitchMat).first, DDSplit(pitchMat).second); matter = DDMaterial(matname); if (!isStereo) { dx = 0.5 * pitchWidth; dy = 0.5 * pitchThick; dz = 0.5 * pitchHeight; solid = DDSolidFactory::box(DDName(name, idNameSpace), dx, dy, dz); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Box made of " << matname <<" of dimensions " << dx << ", " << dy << ", " << dz; } else { dz = 0.5 * pitchWidth; h1 = 0.5 * pitchThick; bl1 = 0.5 * pitchHeight + 0.5 * dz * sin(detTilt); bl2 = 0.5 * pitchHeight - 0.5 * dz * sin(detTilt); double thet = atan((bl1-bl2)/(2.*dz)); solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet, 0, h1, bl1, bl1, 0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", " << thet/CLHEP::deg << ", 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; } xpos = 0; ypos = pitchZ; zpos = 0.5 * (-waferPosition + fullHeight + pitchHeight); if (isRing6) zpos *= -1; if(isStereo) xpos = 0.5 * fullHeight * sin(detTilt); DDLogicalPart pa(solid.ddname(), matter, solid); if(isStereo)doPos(pa, xpos, ypos,zpos, pitchRot, cpv); else doPos(pa, xpos, ypos,zpos, "NULL", cpv); //Top of the frame name = idName + "TopFrame"; matname = DDName(DDSplit(topFrameMat).first, DDSplit(topFrameMat).second); matter = DDMaterial(matname); h1 = 0.5 * topFrameThick; dz = 0.5 * topFrameHeight; bl1 = 0.5 * topFrameBotWidth; bl2 = 0.5 * topFrameTopWidth; if (isRing6) { // ring 6 faces the other way! bl1 = 0.5 * topFrameTopWidth; bl2 = 0.5 * topFrameBotWidth; } solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl1, bl1,0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", 0, 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; DDLogicalPart topFrame(solid.ddname(), matter, solid); if(isStereo){ name = idName + "TopFrame2"; //additional object to build the not trapzoid geometry of the stereo topframes dz = 0.5 * topFrame2Width; h1 = 0.5 * topFrameThick; bl1 = 0.5 * topFrame2LHeight; bl2 = 0.5 * topFrame2RHeight; double thet = atan((bl1-bl2)/(2.*dz)); solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, thet, 0, h1, bl1, bl1, 0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", " << thet/CLHEP::deg << ", 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; } // Position the topframe ypos = topFrameZ; zpos = 0.5 * (-waferPosition + fullHeight - topFrameHeight)+ pitchHeight + hybridHeight; if(isRing6){ zpos *=-1; } doPos(topFrame, 0,ypos,zpos,"NULL", cpv); if(isStereo){ //create DDLogicalPart topFrame2(solid.ddname(), matter, solid); zpos -= 0.5*(topFrameHeight + 0.5*(topFrame2LHeight+topFrame2RHeight)); doPos(topFrame2, 0,ypos,zpos,pitchRot, cpv); } //Si - Reencorcement for (int i= 0; i < (int)(siReenforceWidth.size());i++){ name = idName + "SiReenforce" + std::to_string(i); matname = DDName(DDSplit(siReenforceMat).first, DDSplit(siReenforceMat).second); matter = DDMaterial(matname); h1 = 0.5 * siReenforceThick; dz = 0.5 * siReenforceHeight[i]; bl1 = bl2 = 0.5 * siReenforceWidth[i]; solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl1, bl1, 0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", 0, 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; DDLogicalPart siReenforce(solid.ddname(), matter, solid); //translate xpos =0 ; ypos = sideFrameZ; zpos = topFrameEndZ -dz -siReenforceYPos[i]; if (isRing6) zpos *= -1; if(isStereo){ xpos = (-siReenforceYPos[i]+0.5*fullHeight)*sin(detTilt); // thet = detTilt; // if(topFrame2RHeight > topFrame2LHeight) thet *= -1; // zpos -= topFrame2RHeight + sin(thet)*(sideFrameRWidth + 0.5*dlTop); zpos -= topFrame2RHeight + sin (fabs(detTilt))* 0.5*topFrame2Width; } doPos(siReenforce,xpos,ypos,zpos,waferRot, cpv); } //Bridge if (bridgeMat != "None") { name = idName + "Bridge"; matname = DDName(DDSplit(bridgeMat).first, DDSplit(bridgeMat).second); matter = DDMaterial(matname); bl2 = 0.5*bridgeSep + bridgeWidth; bl1 = bl2 - bridgeHeight * dxdif / dzdif; h1 = 0.5 * bridgeThick; dz = 0.5 * bridgeHeight; solid = DDSolidFactory::trap(DDName(name,idNameSpace), dz, 0, 0, h1, bl1, bl1, 0, h1, bl2, bl2, 0); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Trap made of " << matname << " of dimensions " << dz << ", 0, 0, " << h1 << ", " << bl1 << ", " << bl1 << ", 0, " << h1 << ", " << bl2 << ", " << bl2 << ", 0"; DDLogicalPart bridge(solid.ddname(), matter, solid); name = idName + "BridgeGap"; matname = DDName(DDSplit(genMat).first, DDSplit(genMat).second); matter = DDMaterial(matname); bl1 = 0.5*bridgeSep; solid = DDSolidFactory::box(DDName(name,idNameSpace), bl1, h1, dz); LogDebug("TECGeom") << "DDTECModuleAlgo test:\t" << solid.name() << " Box made of " << matname << " of dimensions " << bl1 << ", " << h1 << ", " << dz; DDLogicalPart bridgeGap(solid.ddname(), matter, solid); cpv.position(bridgeGap, bridge, 1, DDTranslation(0.0, 0.0, 0.0), DDRotation()); LogDebug("TECGeom") << "DDTECModuleAlgo test: " << bridgeGap.name() << " number 1 positioned in " << bridge.name() << " at (0,0,0) with no rotation"; } LogDebug("TECGeom") << "<<== End of DDTECModuleAlgo construction ..."; }
26,955
10,743
#include "../main/catch.hpp" #include "config/device/DeviceConfigParser.hpp" #include <typeinfo> #include <iostream> #include <string.h> using namespace std; TEST_CASE("DeviceConfigParser") { DeviceConfigParser parser; SECTION("should parse semicolon-separated-values to DeviceConfig") { // given: // version;id;name;type_int;port;wire_color_int;debounce const char* line = "1.0;103;test device name;2;16;4;100;45"; // when DeviceConfig* device = parser.parse(line); // then REQUIRE(device != nullptr); REQUIRE(device->getId() == 103); REQUIRE(strcmp(device->getName(), "test device name") == 0); REQUIRE(device->getDeviceType() == DeviceType::DIGITAL_OUTPUT); REQUIRE(device->getPortNumber() == 16); REQUIRE(device->getWireColor() == WireColor::BLUE); REQUIRE(device->getDebounceMs() == 100); REQUIRE(device->getPjonId() == 45); } SECTION("should return null if version is not supported (1.0 for now)") { // given: // version;id;name;type_int;port;wire_color_int;debounce const char* line = "2.0;103;test device name;2;16;4;100;44"; // when DeviceConfig* device = parser.parse(line); // then REQUIRE(device == nullptr); } }
1,328
463
/* * Copyright (c) 2019 Opticks Team. All Rights Reserved. * * This file is part of Opticks * (see https://bitbucket.org/simoncblyth/opticks). * * 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 <vector> #include "OXPPNS.hh" #include <optixu/optixu_math_namespace.h> #include <optixu/optixu_aabb_namespace.h> #include "plog/Severity.h" class RayTraceConfig ; class Opticks ; class OContext ; //class GGeo ; //class GGeoBase ; class GGeoLib ; class GMergedMesh ; class GBuffer ; template <typename S> class NPY ; // used by OEngine::initGeometry /** OGeo ===== Canonical OGeo instance resides in OScene and is instanciated and has its *convert* called from OScene::init. OScene::convert loops over the GMergedMesh within GGeo converting them into OptiX geometry groups. The first GMergedMesh is assumed to be non-instanced, the remainder are expected to be instanced with appropriate transform and identity buffers. Details of geometry tree are documented with the OGeo::convert method. **/ #include "OGeoStat.hh" struct OGeometry ; #include "OXRAP_API_EXPORT.hh" class OXRAP_API OGeo { public: /* struct OGeometry { optix::Geometry g ; #if OPTIX_VERSION >= 60000 optix::GeometryTriangles gt ; #endif bool isGeometry() const ; bool isGeometryTriangles() const ; }; */ static const plog::Severity LEVEL ; static const char* ACCEL ; OGeo(OContext* ocontext, Opticks* ok, GGeoLib* geolib ); void setTopGroup(optix::Group top); void setVerbose(bool verbose=true); std::string description() const ; public: void convert(); private: void init(); void convertMergedMesh(unsigned i); void dumpStats(const char* msg="OGeo::dumpStats"); public: template <typename T> static optix::Buffer CreateInputUserBuffer(optix::Context& ctx, NPY<T>* src, unsigned elementSize, const char* name, const char* ctxname_informational, unsigned verbosity); public: template <typename T> optix::Buffer createInputBuffer(GBuffer* buf, RTformat format, unsigned int fold, const char* name, bool reuse=false); template <typename T, typename S> optix::Buffer createInputBuffer(NPY<S>* buf, RTformat format, unsigned int fold, const char* name, bool reuse=false); template <typename T> optix::Buffer createInputUserBuffer(NPY<T>* src, unsigned elementSize, const char* name); public: optix::GeometryGroup makeGlobalGeometryGroup(GMergedMesh* mm); optix::Group makeRepeatedAssembly(GMergedMesh* mm, bool lod ); private: void setTransformMatrix(optix::Transform& xform, const float* tdata ) ; optix::Acceleration makeAcceleration(const char* accel, bool accel_props=false); optix::Material makeMaterial(); OGeometry* makeOGeometry(GMergedMesh* mergedmesh, unsigned lod); optix::GeometryInstance makeGeometryInstance(OGeometry* geometry, optix::Material material, unsigned instance_index); optix::GeometryGroup makeGeometryGroup(optix::GeometryInstance gi, optix::Acceleration accel ); private: optix::Geometry makeAnalyticGeometry(GMergedMesh* mergedmesh, unsigned lod); optix::Geometry makeTriangulatedGeometry(GMergedMesh* mergedmesh, unsigned lod); #if OPTIX_VERSION >= 60000 optix::GeometryTriangles makeGeometryTriangles(GMergedMesh* mm, unsigned lod); #endif private: void dump(const char* msg, const float* m); private: // input references OContext* m_ocontext ; optix::Context m_context ; optix::Group m_top ; Opticks* m_ok ; int m_gltf ; GGeoLib* m_geolib ; unsigned m_verbosity ; private: // for giving "context names" to GPU buffer uploads const char* getContextName() const ; unsigned m_mmidx ; unsigned m_lodidx ; const char* m_top_accel ; const char* m_ggg_accel ; const char* m_assembly_accel ; const char* m_instance_accel ; private: // locals RayTraceConfig* m_cfg ; std::vector<OGeoStat> m_stats ; };
4,795
1,544
#include <L/src/engine/Engine.h> #include <L/src/rendering/Renderer.h> #include <L/src/system/System.h> #include <L/src/system/Window.h> #include <L/src/text/String.h> #include "xlib.h" static class XWindow* instance(nullptr); L::Symbol xlib_window_type("xlib"); class XWindow : public L::Window { protected: ::Display* _xdisplay; ::Window _xwindow; public: XWindow() { L::String tmp; L::System::call("xdpyinfo | grep 'dimensions:' | grep -o '[[:digit:]]\\+'", tmp); L::Array<L::String> res(tmp.explode('\n')); if(res.size() >= 2) { _screen_width = L::ston<10, uint32_t>(res[0]); _screen_height = L::ston<10, uint32_t>(res[1]); } } void update() { L_SCOPE_MARKER("Window update"); XEvent xev; XWindowAttributes gwa; while(opened() && XPending(_xdisplay)) { XNextEvent(_xdisplay, &xev); Window::Event e {}; switch(xev.type) { case Expose: XGetWindowAttributes(_xdisplay, _xwindow, &gwa); if(_width != uint32_t(gwa.width) || _height != uint32_t(gwa.height)) { e.type = Event::Type::Resize; _width = e.coords.x = gwa.width; _height = e.coords.y = gwa.height; } break; case MotionNotify: _cursor_x = xev.xmotion.x; _cursor_y = xev.xmotion.y; break; case ClientMessage: // It's the close operation close(); break; } if(e.type!=Event::Type::None) { _events.push(e); } } } void open(const char* title, uint32_t width, uint32_t height, uint32_t flags) override { L_SCOPE_MARKER("XWindow::open"); if(opened()) { L::error("xlib: Trying to reopen window"); } _width = width; _height = height; _flags = flags; if((_xdisplay = XOpenDisplay(nullptr)) == nullptr) { L::error("Cannot open X server display."); } { // Create window ::Window root = DefaultRootWindow(_xdisplay); int scr = DefaultScreen(_xdisplay); int depth = DefaultDepth(_xdisplay, scr); Visual* visual = DefaultVisual(_xdisplay, scr); XSetWindowAttributes swa {}; swa.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask; _xwindow = XCreateWindow(_xdisplay, root, 0, 0, width, height, 0, depth, InputOutput, visual, CWColormap | CWEventMask, &swa); } { // Activate window close events Atom wm_delete_window(XInternAtom(_xdisplay, "WM_DELETE_WINDOW", 0)); XSetWMProtocols(_xdisplay, _xwindow, &wm_delete_window, 1); } XMapWindow(_xdisplay, _xwindow); XStoreName(_xdisplay, _xwindow, title); if(flags & nocursor) { const char pixmap_data(0); Pixmap pixmap(XCreateBitmapFromData(_xdisplay, _xwindow, &pixmap_data, 1, 1)); XColor color; Cursor cursor(XCreatePixmapCursor(_xdisplay, pixmap, pixmap, &color, &color, 0, 0)); XDefineCursor(_xdisplay, _xwindow, cursor); } _opened = true; XlibWindowData window_data; window_data.type = xlib_window_type; window_data.display = _xdisplay; window_data.window = _xwindow; L::Renderer::get()->init(&window_data); } void close() override { L_ASSERT(_opened); XDestroyWindow(_xdisplay, _xwindow); XCloseDisplay(_xdisplay); _opened = false; } void title(const char*) override { L::warning("Setting window title is unsupported for X windows"); } void resize(uint32_t, uint32_t) override { L::warning("Resizing window is unsupported for X windows"); } }; void xlib_module_init() { instance = L::Memory::new_type<XWindow>(); L::Engine::add_parallel_update([]() { instance->update(); }); }
3,740
1,326
#include "../../Engine/Input/InputEvent.h" #include "../../Engine/Input/InputManager.h" #include "../Components/CWeapon.h" #include "../../Engine/Math.h" #include "../UI/WLifebar.h" #include "../Components/HeadersComponents.h" #include "../../Engine/Audio/Audiosource.h" #include "../../Engine/Input/Controller.h" #include "EShipControllable.h" Ptr<EShipControllable> EShipControllable::Create() { Ptr<EShipControllable> p = new EShipControllable(); p->mThis = p.UpCast<Entity>(); return p; } Ptr<EShipControllable> EShipControllable::Create(const Transform2D& Tranform2D, float MaxLinearAcceleration, float MaxAngularAcceleration, float LinearInertiaSec, float AngularInertiaSec) { Ptr<EShipControllable> p = new EShipControllable(Tranform2D, MaxLinearAcceleration, MaxAngularAcceleration, LinearInertiaSec, AngularInertiaSec); p->mThis = p.UpCast<Entity>(); return p; } EShipControllable::EShipControllable(const Transform2D& Tranform2D, float MaxLinearAcceleration, float MaxAngularAcceleration, float LinearInertiaSec, float AngularInertiaSec) { mType = EntityType::ENTITY_SHIPCONTROLLABLE; SetTransform(Tranform2D); SetTickMovement(true); SetMaxLinearAcc(MaxLinearAcceleration); SetMaxAngularAcc(MaxAngularAcceleration); SetLinearInertia(LinearInertiaSec); SetAngularInertia(AngularInertiaSec); mInputActivated = true; ActivateMovementController(); } void EShipControllable::Init() { EShip::Init(); // All the inputs events that a controllable ship should observe std::vector<InputEvent::TEvent> EventsToObserve; EventsToObserve.push_back(InputEvent::EVENT_KEY_UP_PRESSED); EventsToObserve.push_back(InputEvent::EVENT_KEY_UP_RELEASED); EventsToObserve.push_back(InputEvent::EVENT_KEY_RIGHT_PRESSED); EventsToObserve.push_back(InputEvent::EVENT_KEY_RIGHT_RELEASED); EventsToObserve.push_back(InputEvent::EVENT_KEY_LEFT_PRESSED); EventsToObserve.push_back(InputEvent::EVENT_KEY_LEFT_RELEASED); EventsToObserve.push_back(InputEvent::EVENT_KEY_SPACE_PRESSED); EventsToObserve.push_back(InputEvent::EVENT_KEY_SPACE_RELEASED); EventsToObserve.push_back(InputEvent::EVENT_KEY_TAB_PRESSED); EventsToObserve.push_back(InputEvent::EVENT_KEY_TAB_RELEASED); // Pass these events to the InputMananger IInputManagerObserver::Instance()->AddObserver((mThis.DownCast<EShipControllable>()).UpCast<IIMObserver>(), EventsToObserve); } void EShipControllable::Update(float elapsed) { EShip::Update(elapsed); } void EShipControllable::Render() { EShip::Render(); } void EShipControllable::ManageEvent(const InputEvent& Event) { // How to manage the input event if (mInputActivated) { InputEvent::TEvent TypeEvent = Event.GetTEvent(); switch (TypeEvent) { case InputEvent::EVENT_NONE: { break; } case InputEvent::EVENT_MOUSE_RIGHT_CLICK: { break; } case InputEvent::EVENT_MOUSE_LEFT_CLICK: { break; } case InputEvent::EVENT_KEY_SPACE_PRESSED: { if (IsPrimaryWeaponActive()) { GetPrimaryWeaponComp()->Fire(GetProjectileSpawnPos(), GetRotation()); SetPrimaryWeaponActive(false); } break; } case InputEvent::EVENT_KEY_SPACE_RELEASED: { SetPrimaryWeaponActive(true); break; } case InputEvent::EVENT_KEY_TAB_PRESSED: { if (IsSecondaryWeaponActive()) { GetSecondaryWeaponComp()->Fire(GetProjectileSpawnPos(), GetRotation()); SetSecondaryWeaponActive(false); } break; } case InputEvent::EVENT_KEY_TAB_RELEASED: { SetSecondaryWeaponActive(true); break; } case InputEvent::EVENT_KEY_UP_PRESSED: { if(IsMovementControllerActivated()) { DeactivateLinearInertia(); SetLinearSteering(vec2(GetForwardVector().x * GetMaxLinearAcc(), GetForwardVector().y* GetMaxLinearAcc())); } break; } case InputEvent::EVENT_KEY_UP_RELEASED: { if (IsMovementControllerActivated()) { ActivateLinearInertia(); } break; } case InputEvent::EVENT_KEY_DOWN_PRESSED: { break; } case InputEvent::EVENT_KEY_RIGHT_PRESSED: { if (IsMovementControllerActivated()) { DeactivateAngularInertia(); SetAngularSteering(-GetMaxAngularAcc()); SetTurnDirection(-1); } break; } case InputEvent::EVENT_KEY_RIGHT_RELEASED: { if (IsMovementControllerActivated()) { ActivateAngularInertia(); } break; } case InputEvent::EVENT_KEY_LEFT_PRESSED: { if (IsMovementControllerActivated()) { DeactivateAngularInertia(); SetAngularSteering(GetMaxAngularAcc()); SetTurnDirection(1); } break; } case InputEvent::EVENT_KEY_LEFT_RELEASED: { if (IsMovementControllerActivated()) { ActivateAngularInertia(); } break; } default: break; } } }
5,620
1,767
/*problem C*/ #include<stdio.h> #include<string.h> int main(){ int n; scanf("%d",&n); int a[n]; int sum=0; for(int i=0;i<n;i++){ scanf("%d",&a[i]); sum+=a[i]; } float tbc=(float)sum/n; int kq=0; for(int i=0;i<n;i++){ if(a[i]>tbc){ kq+=a[i]; } } if(kq==0){ printf("-1"); return 0; } printf("%d",kq); }
330
200
/** * @file * @author __AUTHOR_NAME__ <mail@host.com> * @copyright 2021 __COMPANY_LTD__ * @license <a href="https://opensource.org/licenses/MIT">MIT License</a> */ #ifndef ZEN_RENDERER_PIPELINES_EVENTS_BIND_HPP #define ZEN_RENDERER_PIPELINES_EVENTS_BIND_HPP #include <string> namespace Zen { namespace Events { /** * The Pipeline Bind Event. * * This event is dispatched by a Pipeline when it is bound by the PipelineManager. * * @since 0.0.0 * * @param pipeline Pointer to the pipeline that was bound. * @param currentShader Pointer to the shader that was set as being current. */ const std::string PIPELINE_BIND = "pipelinebind"; } // namespace Events } // namespace Zen #endif
702
265
#include<Windows.h> #include"MyGame.h" int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MyGame *game = new MyGame(nCmdShow); game->InitGame(); game->GameRun(); return 0; }
226
92
/* ********************************************************** * Copyright (c) 2017-2020 Google, 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 Google, 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 VMWARE, INC. 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. */ /* This trace analyzer requires access to the modules.log file and the * libraries and binary from the traced execution in order to obtain further * information about each instruction than was stored in the trace. * It does not support online use, only offline. */ #include "dr_api.h" #include "view.h" #include <algorithm> #include <iomanip> #include <iostream> #include <vector> const std::string view_t::TOOL_NAME = "View tool"; analysis_tool_t * view_tool_create(const std::string &module_file_path, uint64_t skip_refs, uint64_t sim_refs, const std::string &syntax, unsigned int verbose, const std::string &alt_module_dir) { return new view_t(module_file_path, skip_refs, sim_refs, syntax, verbose, alt_module_dir); } view_t::view_t(const std::string &module_file_path, uint64_t skip_refs, uint64_t sim_refs, const std::string &syntax, unsigned int verbose, const std::string &alt_module_dir) : module_file_path_(module_file_path) , knob_verbose_(verbose) , instr_count_(0) , knob_skip_refs_(skip_refs) , knob_sim_refs_(sim_refs) , knob_syntax_(syntax) , knob_alt_module_dir_(alt_module_dir) , num_disasm_instrs_(0) { } std::string view_t::initialize() { if (module_file_path_.empty()) return "Module file path is missing"; dcontext_.dcontext = dr_standalone_init(); std::string error = directory_.initialize_module_file(module_file_path_); if (!error.empty()) return "Failed to initialize directory: " + error; module_mapper_ = module_mapper_t::create(directory_.modfile_bytes_, nullptr, nullptr, nullptr, nullptr, knob_verbose_, knob_alt_module_dir_); module_mapper_->get_loaded_modules(); error = module_mapper_->get_last_error(); if (!error.empty()) return "Failed to load binaries: " + error; dr_disasm_flags_t flags = DR_DISASM_ATT; if (knob_syntax_ == "intel") { flags = DR_DISASM_INTEL; } else if (knob_syntax_ == "dr") { flags = DR_DISASM_DR; } else if (knob_syntax_ == "arm") { flags = DR_DISASM_ARM; } disassemble_set_syntax(flags); return ""; } bool view_t::process_memref(const memref_t &memref) { if (instr_count_ < knob_skip_refs_ || instr_count_ >= (knob_skip_refs_ + knob_sim_refs_)) { if (type_is_instr(memref.instr.type) || memref.data.type == TRACE_TYPE_INSTR_NO_FETCH) ++instr_count_; return true; } if (memref.marker.type == TRACE_TYPE_MARKER) { switch (memref.marker.marker_type) { case TRACE_MARKER_TYPE_FILETYPE: if (TESTANY(OFFLINE_FILE_TYPE_ARCH_ALL, memref.marker.marker_value) && !TESTANY(build_target_arch_type(), memref.marker.marker_value)) { error_string_ = std::string("Architecture mismatch: trace recorded on ") + trace_arch_string(static_cast<offline_file_type_t>( memref.marker.marker_value)) + " but tool built for " + trace_arch_string(build_target_arch_type()); return false; } break; case TRACE_MARKER_TYPE_TIMESTAMP: std::cerr << "<marker: timestamp " << memref.marker.marker_value << ">\n"; break; case TRACE_MARKER_TYPE_CPU_ID: // We include the thread ID here under the assumption that we will always // see a cpuid marker on a thread switch. To avoid that assumption // we would want to track the prior tid and print out a thread switch // message whenever it changes. std::cerr << "<marker: tid " << memref.marker.tid << " on core " << memref.marker.marker_value << ">\n"; break; case TRACE_MARKER_TYPE_KERNEL_EVENT: std::cerr << "<marker: kernel xfer to handler>\n"; break; case TRACE_MARKER_TYPE_KERNEL_XFER: std::cerr << "<marker: syscall xfer>\n"; break; default: // We ignore other markers such as call/ret profiling for now. break; } return true; } if (!type_is_instr(memref.instr.type) && memref.data.type != TRACE_TYPE_INSTR_NO_FETCH) return true; ++instr_count_; app_pc mapped_pc; app_pc orig_pc = (app_pc)memref.instr.addr; mapped_pc = module_mapper_->find_mapped_trace_address(orig_pc); if (!module_mapper_->get_last_error().empty()) { error_string_ = "Failed to find mapped address for " + to_hex_string(memref.instr.addr) + ": " + module_mapper_->get_last_error(); return false; } std::string disasm; auto cached_disasm = disasm_cache_.find(mapped_pc); if (cached_disasm != disasm_cache_.end()) { disasm = cached_disasm->second; } else { // MAX_INSTR_DIS_SZ is set to 196 in core/ir/disassemble.h but is not // exported so we just use the same value here. char buf[196]; byte *next_pc = disassemble_to_buffer( dcontext_.dcontext, mapped_pc, orig_pc, /*show_pc=*/true, /*show_bytes=*/true, buf, BUFFER_SIZE_ELEMENTS(buf), /*printed=*/nullptr); if (next_pc == nullptr) { error_string_ = "Failed to disassemble " + to_hex_string(memref.instr.addr); return false; } disasm = buf; disasm_cache_.insert({ mapped_pc, disasm }); } // XXX: For now we print the disassembly of instructions only. We should extend // this tool to annotate load/store operations with the entries recorded in // the offline trace. std::cerr << disasm; ++num_disasm_instrs_; return true; } bool view_t::print_results() { std::cerr << TOOL_NAME << " results:\n"; std::cerr << std::setw(15) << num_disasm_instrs_ << " : total disassembled instructions\n"; return true; }
7,724
2,518
#include "C:/opencv/opencv-4.5.1/modules/imgproc/src/precomp.hpp" #include "C:/opencv/opencv-4.5.1/modules/imgproc/src/color_hsv.simd.hpp"
140
68
/********************************************** Parker Dunn (pgdunn@bu.edu) EC 504 Final Project Testbench for my first version of rp_heap.h ***********************************************/ #include <iostream> #include "rp_heap.h" using namespace std; int main() { rp_heap* myHeap = new rp_heap(); int size = 10; int heap_extract; /// creating a bunch of things to push int elements[size][2]; for (int i = 1; i < (size+1); i++) { elements[i-1][0] = i; // KEY elements[i-1][1] = i*10; // DATA } for (int j = 0; j < size; j++) myHeap->push(elements[j][1], elements[j][0]); cout << "\nThe size of myHeap is " << myHeap->size() << "\n" << endl; cout << "\nExtracting 4 Nodes now..." << endl; for (int j = 0; j < 4; j++) { heap_extract = myHeap->extract_min(); cout << "Extraction #" << (j+1) << ": " << heap_extract << endl; } cout << "\nTime to decrease some keys..." << endl; myHeap->decreaseKey(10, 5); myHeap->decreaseKey(9, 8); cout << "\n"; for (int j = 4; j < size; j++) { heap_extract = myHeap->extract_min(); cout << "Extraction #" << (j+1) << ": " << heap_extract << endl; } return 0; }
1,212
486
/* Copyright (c) 2002-2008 MySQL AB, 2008, 2009 Sun Microsystems, Inc. Use is subject to license terms. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /********************************************************************** This file contains the implementation of error and warnings related - Whenever an error or warning occurred, it pushes it to a warning list that the user can retrieve with SHOW WARNINGS or SHOW ERRORS. - For each statement, we return the number of warnings generated from this command. Note that this can be different from @@warning_count as we reset the warning list only for questions that uses a table. This is done to allow on to do: INSERT ...; SELECT @@warning_count; SHOW WARNINGS; (If we would reset after each command, we could not retrieve the number of warnings) - When client requests the information using SHOW command, then server processes from this list and returns back in the form of resultset. Supported syntaxes: SHOW [COUNT(*)] ERRORS [LIMIT [offset,] rows] SHOW [COUNT(*)] WARNINGS [LIMIT [offset,] rows] SELECT @@warning_count, @@error_count; ***********************************************************************/ #include "mysql_priv.h" #include "sp_rcontext.h" /* Store a new message in an error object This is used to in group_concat() to register how many warnings we actually got after the query has been executed. */ void MYSQL_ERROR::set_msg(THD *thd, const char *msg_arg) { msg= strdup_root(&thd->warn_root, msg_arg); } /* Reset all warnings for the thread SYNOPSIS mysql_reset_errors() thd Thread handle force Reset warnings even if it has been done before IMPLEMENTATION Don't reset warnings if this has already been called for this query. This may happen if one gets a warning during the parsing stage, in which case push_warnings() has already called this function. */ void mysql_reset_errors(THD *thd, bool force) { DBUG_ENTER("mysql_reset_errors"); if (thd->query_id != thd->warn_id || force) { thd->warn_id= thd->query_id; free_root(&thd->warn_root,MYF(0)); bzero((char*) thd->warn_count, sizeof(thd->warn_count)); if (force) thd->total_warn_count= 0; thd->warn_list.empty(); thd->row_count= 1; // by default point to row 1 } DBUG_VOID_RETURN; } /* Push the warning/error to error list if there is still room in the list SYNOPSIS push_warning() thd Thread handle level Severity of warning (note, warning, error ...) code Error number msg Clear error message RETURN pointer on MYSQL_ERROR object */ MYSQL_ERROR *push_warning(THD *thd, MYSQL_ERROR::enum_warning_level level, uint code, const char *msg) { MYSQL_ERROR *err= 0; DBUG_ENTER("push_warning"); DBUG_PRINT("enter", ("code: %d, msg: %s", code, msg)); DBUG_ASSERT(code != 0); DBUG_ASSERT(msg != NULL); if (level == MYSQL_ERROR::WARN_LEVEL_NOTE && !(thd->options & OPTION_SQL_NOTES)) DBUG_RETURN(0); if (thd->query_id != thd->warn_id && !thd->spcont) mysql_reset_errors(thd, 0); thd->got_warning= 1; /* Abort if we are using strict mode and we are not using IGNORE */ if ((int) level >= (int) MYSQL_ERROR::WARN_LEVEL_WARN && thd->really_abort_on_warning()) { /* Avoid my_message() calling push_warning */ bool no_warnings_for_error= thd->no_warnings_for_error; sp_rcontext *spcont= thd->spcont; thd->no_warnings_for_error= 1; thd->spcont= NULL; thd->killed= THD::KILL_BAD_DATA; my_message(code, msg, MYF(0)); thd->spcont= spcont; thd->no_warnings_for_error= no_warnings_for_error; /* Store error in error list (as my_message() didn't do it) */ level= MYSQL_ERROR::WARN_LEVEL_ERROR; } if (thd->handle_error(code, msg, level)) DBUG_RETURN(NULL); if (thd->spcont && thd->spcont->handle_error(code, level, thd)) { DBUG_RETURN(NULL); } query_cache_abort(&thd->net); if (thd->warn_list.elements < thd->variables.max_error_count) { /* We have to use warn_root, as mem_root is freed after each query */ if ((err= new (&thd->warn_root) MYSQL_ERROR(thd, code, level, msg))) thd->warn_list.push_back(err, &thd->warn_root); } thd->warn_count[(uint) level]++; thd->total_warn_count++; DBUG_RETURN(err); } /* Push the warning/error to error list if there is still room in the list SYNOPSIS push_warning_printf() thd Thread handle level Severity of warning (note, warning, error ...) code Error number msg Clear error message */ void push_warning_printf(THD *thd, MYSQL_ERROR::enum_warning_level level, uint code, const char *format, ...) { va_list args; char warning[MYSQL_ERRMSG_SIZE]; DBUG_ENTER("push_warning_printf"); DBUG_PRINT("enter",("warning: %u", code)); DBUG_ASSERT(code != 0); DBUG_ASSERT(format != NULL); va_start(args,format); my_vsnprintf(warning, sizeof(warning), format, args); va_end(args); push_warning(thd, level, code, warning); DBUG_VOID_RETURN; } /* Send all notes, errors or warnings to the client in a result set SYNOPSIS mysqld_show_warnings() thd Thread handler levels_to_show Bitmap for which levels to show DESCRIPTION Takes into account the current LIMIT RETURN VALUES FALSE ok TRUE Error sending data to client */ const LEX_STRING warning_level_names[]= { { C_STRING_WITH_LEN("Note") }, { C_STRING_WITH_LEN("Warning") }, { C_STRING_WITH_LEN("Error") }, { C_STRING_WITH_LEN("?") } }; bool mysqld_show_warnings(THD *thd, ulong levels_to_show) { List<Item> field_list; DBUG_ENTER("mysqld_show_warnings"); field_list.push_back(new Item_empty_string("Level", 7)); field_list.push_back(new Item_return_int("Code",4, MYSQL_TYPE_LONG)); field_list.push_back(new Item_empty_string("Message",MYSQL_ERRMSG_SIZE)); if (thd->protocol->send_fields(&field_list, Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF)) DBUG_RETURN(TRUE); MYSQL_ERROR *err; SELECT_LEX *sel= &thd->lex->select_lex; SELECT_LEX_UNIT *unit= &thd->lex->unit; ha_rows idx= 0; Protocol *protocol=thd->protocol; unit->set_limit(sel); List_iterator_fast<MYSQL_ERROR> it(thd->warn_list); while ((err= it++)) { /* Skip levels that the user is not interested in */ if (!(levels_to_show & ((ulong) 1 << err->level))) continue; if (++idx <= unit->offset_limit_cnt) continue; if (idx > unit->select_limit_cnt) break; protocol->prepare_for_resend(); protocol->store(warning_level_names[err->level].str, warning_level_names[err->level].length, system_charset_info); protocol->store((uint32) err->code); protocol->store(err->msg, (uint) strlen(err->msg), system_charset_info); if (protocol->write()) DBUG_RETURN(TRUE); } my_eof(thd); DBUG_RETURN(FALSE); }
7,616
2,708
/** * @file fisheyeStereoCalibrate.cpp * @brief mex interface for cv::fisheye::stereoCalibrate * @ingroup calib3d * @author Amro * @date 2017 */ #include "mexopencv.hpp" #include "opencv2/calib3d.hpp" using namespace std; using namespace cv; namespace { /** Create a new MxArray from stereo calibration results. * @param K1 First camera matrix. * @param D1 Distortion coefficients of first camera. * @param K2 Second camera matrix. * @param D2 Distortion coefficients of second camera. * @param R Rotation matrix between the cameras coordinate systems. * @param T Translation vector between the cameras coordinate systems. * @param rms Re-projection error. * @return output MxArray struct object. */ MxArray toStruct(const Mat& K1, const Mat& D1, const Mat& K2, const Mat& D2, const Mat& R, const Mat& T, double rms) { const char* fieldnames[] = {"cameraMatrix1", "distCoeffs1", "cameraMatrix2", "distCoeffs2", "R", "T", "reprojErr"}; MxArray s = MxArray::Struct(fieldnames, 7); s.set("cameraMatrix1", K1); s.set("distCoeffs1", D1); s.set("cameraMatrix2", K2); s.set("distCoeffs2", D2); s.set("R", R); s.set("T", T); s.set("reprojErr", rms); return s; } } /** * Main entry called from Matlab * @param nlhs number of left-hand-side arguments * @param plhs pointers to mxArrays in the left-hand-side * @param nrhs number of right-hand-side arguments * @param prhs pointers to mxArrays in the right-hand-side */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { // Check the number of arguments nargchk(nrhs>=4 && (nrhs%2)==0 && nlhs<=1); // Argument vector vector<MxArray> rhs(prhs, prhs+nrhs); // Option processing Mat K1, D1, K2, D2; int flags = cv::CALIB_FIX_INTRINSIC; TermCriteria criteria(TermCriteria::COUNT+TermCriteria::EPS, 100, DBL_EPSILON); for (int i=4; i<nrhs; i+=2) { string key(rhs[i].toString()); if (key == "CameraMatrix1") K1 = rhs[i+1].toMat(CV_64F); else if (key == "DistCoeffs1") D1 = rhs[i+1].toMat(CV_64F); else if (key == "CameraMatrix2") K2 = rhs[i+1].toMat(CV_64F); else if (key == "DistCoeffs2") D2 = rhs[i+1].toMat(CV_64F); else if (key == "UseIntrinsicGuess") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_USE_INTRINSIC_GUESS); else if (key == "RecomputeExtrinsic") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_RECOMPUTE_EXTRINSIC); else if (key == "CheckCond") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_CHECK_COND); else if (key == "FixSkew") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_SKEW); else if (key == "FixK1") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K1); else if (key == "FixK2") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K2); else if (key == "FixK3") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K3); else if (key == "FixK4") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_K4); else if (key == "FixIntrinsic") UPDATE_FLAG(flags, rhs[i+1].toBool(), cv::fisheye::CALIB_FIX_INTRINSIC); else if (key == "Criteria") criteria = rhs[i+1].toTermCriteria(); else mexErrMsgIdAndTxt("mexopencv:error", "Unrecognized option %s", key.c_str()); } // Process vector<vector<Point3d> > objectPoints(MxArrayToVectorVectorPoint3<double>(rhs[0])); vector<vector<Point2d> > imagePoints1(MxArrayToVectorVectorPoint<double>(rhs[1])); vector<vector<Point2d> > imagePoints2(MxArrayToVectorVectorPoint<double>(rhs[2])); Size imageSize(rhs[3].toSize()); Mat R, T; double rms = fisheye::stereoCalibrate(objectPoints, imagePoints1, imagePoints2, K1, D1, K2, D2, imageSize, R, T, flags, criteria); plhs[0] = toStruct(K1, D1, K2, D2, R, T, rms); }
4,124
1,558
// Copyright (c) 2018-2020, The TurtleCoin Developers // // Please see the included LICENSE file for more information. #include <emscripten/bind.h> #include <stdio.h> #include <stdlib.h> #include <turtlecoin-crypto.h> using namespace emscripten; struct Keys { std::string publicKey; std::string secretKey; }; struct PreparedSignatures { std::vector<std::string> signatures; std::string key; }; /* Most of the redefintions below are the result of the methods returning a bool instead of the value we need or issues with method signatures having a uint64_t */ std::string cn_soft_shell_slow_hash_v0(const std::string data, const int height) { return Core::Cryptography::cn_soft_shell_slow_hash_v0(data, height); } std::string cn_soft_shell_slow_hash_v1(const std::string data, const int height) { return Core::Cryptography::cn_soft_shell_slow_hash_v1(data, height); } std::string cn_soft_shell_slow_hash_v2(const std::string data, const int height) { return Core::Cryptography::cn_soft_shell_slow_hash_v2(data, height); } std::vector<std::string> generateRingSignatures( const std::string prefixHash, const std::string keyImage, const std::vector<std::string> publicKeys, const std::string transactionSecretKey, const int realOutputIndex) { std::vector<std::string> signatures; bool success = Core::Cryptography::generateRingSignatures( prefixHash, keyImage, publicKeys, transactionSecretKey, realOutputIndex, signatures); return signatures; } PreparedSignatures prepareRingSignatures( const std::string prefixHash, const std::string keyImage, const std::vector<std::string> publicKeys, const int realOutputIndex) { std::vector<std::string> signatures; std::string k; bool success = Core::Cryptography::prepareRingSignatures(prefixHash, keyImage, publicKeys, realOutputIndex, signatures, k); PreparedSignatures result; result.signatures = signatures; result.key = k; return result; } PreparedSignatures prepareRingSignaturesK( const std::string prefixHash, const std::string keyImage, const std::vector<std::string> publicKeys, const int realOutputIndex, const std::string k) { std::vector<std::string> signatures; bool success = Core::Cryptography::prepareRingSignatures(prefixHash, keyImage, publicKeys, realOutputIndex, k, signatures); PreparedSignatures result; result.signatures = signatures; result.key = k; return result; } Keys generateViewKeysFromPrivateSpendKey(const std::string secretKey) { std::string viewSecretKey; std::string viewPublicKey; Core::Cryptography::generateViewKeysFromPrivateSpendKey(secretKey, viewSecretKey, viewPublicKey); Keys keys; keys.publicKey = viewPublicKey; keys.secretKey = viewSecretKey; return keys; } Keys generateKeys() { std::string secretKey; std::string publicKey; Core::Cryptography::generateKeys(secretKey, publicKey); Keys keys; keys.publicKey = publicKey; keys.secretKey = secretKey; return keys; } Keys generateDeterministicSubwalletKeys(const std::string basePrivateKey, const size_t walletIndex) { std::string newPrivateKey; std::string newPublicKey; Keys keys; Core::Cryptography::generateDeterministicSubwalletKeys(basePrivateKey, walletIndex, keys.secretKey, keys.publicKey); return keys; } std::string secretKeyToPublicKey(const std::string secretKey) { std::string publicKey; bool success = Core::Cryptography::secretKeyToPublicKey(secretKey, publicKey); return publicKey; } std::string generateKeyDerivation(const std::string publicKey, const std::string secretKey) { std::string derivation; bool success = Core::Cryptography::generateKeyDerivation(publicKey, secretKey, derivation); return derivation; } std::string generateKeyDerivationScalar(const std::string publicKey, const std::string secretKey, size_t outputIndex) { return Core::Cryptography::generateKeyDerivationScalar(publicKey, secretKey, outputIndex); } std::string derivationToScalar(const std::string derivation, size_t outputIndex) { return Core::Cryptography::derivationToScalar(derivation, outputIndex); } std::string derivePublicKey(const std::string derivation, const size_t outputIndex, const std::string publicKey) { std::string derivedKey; bool success = Core::Cryptography::derivePublicKey(derivation, outputIndex, publicKey, derivedKey); return derivedKey; } std::string scalarDerivePublicKey(const std::string derivationScalar, const std::string publicKey) { std::string derivedKey; bool success = Core::Cryptography::derivePublicKey(derivationScalar, publicKey, derivedKey); return derivedKey; } std::string deriveSecretKey(const std::string derivation, const size_t outputIndex, const std::string secretKey) { return Core::Cryptography::deriveSecretKey(derivation, outputIndex, secretKey); } std::string scalarDeriveSecretKey(const std::string derivationScalar, const std::string secretKey) { return Core::Cryptography::deriveSecretKey(derivationScalar, secretKey); } std::string underivePublicKey(const std::string derivation, const size_t outputIndex, const std::string derivedKey) { std::string publicKey; bool success = Core::Cryptography::underivePublicKey(derivation, outputIndex, derivedKey, publicKey); return publicKey; } std::vector<std::string> completeRingSignatures( const std::string transactionSecretKey, const int realOutputIndex, const std::string k, const std::vector<std::string> signatures) { std::vector<std::string> completeSignatures; for (auto sig : signatures) { completeSignatures.push_back(sig); } bool success = Core::Cryptography::completeRingSignatures(transactionSecretKey, realOutputIndex, k, completeSignatures); return completeSignatures; } std::vector<std::string> restoreRingSignatures( const std::string derivation, const size_t output_index, const std::vector<std::string> partialSigningKeys, const int realOutput, const std::string k, const std::vector<std::string> signatures) { std::vector<std::string> completeSignatures; for (auto sig : signatures) { completeSignatures.push_back(sig); } bool success = Core::Cryptography::restoreRingSignatures( derivation, output_index, partialSigningKeys, realOutput, k, completeSignatures); return completeSignatures; } EMSCRIPTEN_BINDINGS(signatures) { function("cn_fast_hash", &Core::Cryptography::cn_fast_hash); function("cn_slow_hash_v0", &Core::Cryptography::cn_slow_hash_v0); function("cn_slow_hash_v1", &Core::Cryptography::cn_slow_hash_v1); function("cn_slow_hash_v2", &Core::Cryptography::cn_slow_hash_v2); function("cn_lite_slow_hash_v0", &Core::Cryptography::cn_lite_slow_hash_v0); function("cn_lite_slow_hash_v1", &Core::Cryptography::cn_lite_slow_hash_v1); function("cn_lite_slow_hash_v2", &Core::Cryptography::cn_lite_slow_hash_v2); function("cn_dark_slow_hash_v0", &Core::Cryptography::cn_dark_slow_hash_v0); function("cn_dark_slow_hash_v1", &Core::Cryptography::cn_dark_slow_hash_v1); function("cn_dark_slow_hash_v2", &Core::Cryptography::cn_dark_slow_hash_v2); function("cn_dark_lite_slow_hash_v0", &Core::Cryptography::cn_dark_lite_slow_hash_v0); function("cn_dark_lite_slow_hash_v1", &Core::Cryptography::cn_dark_lite_slow_hash_v1); function("cn_dark_lite_slow_hash_v2", &Core::Cryptography::cn_dark_lite_slow_hash_v2); function("cn_turtle_slow_hash_v0", &Core::Cryptography::cn_turtle_slow_hash_v0); function("cn_turtle_slow_hash_v1", &Core::Cryptography::cn_turtle_slow_hash_v1); function("cn_turtle_slow_hash_v2", &Core::Cryptography::cn_turtle_slow_hash_v2); function("cn_turtle_lite_slow_hash_v0", &Core::Cryptography::cn_turtle_lite_slow_hash_v0); function("cn_turtle_lite_slow_hash_v1", &Core::Cryptography::cn_turtle_lite_slow_hash_v1); function("cn_turtle_lite_slow_hash_v2", &Core::Cryptography::cn_turtle_lite_slow_hash_v2); function("cn_soft_shell_slow_hash_v0", &cn_soft_shell_slow_hash_v0); function("cn_soft_shell_slow_hash_v1", &cn_soft_shell_slow_hash_v1); function("cn_soft_shell_slow_hash_v2", &cn_soft_shell_slow_hash_v2); function("chukwa_slow_hash", &Core::Cryptography::chukwa_slow_hash); function("tree_depth", &Core::Cryptography::tree_depth); function("tree_hash", &Core::Cryptography::tree_hash); function("tree_branch", &Core::Cryptography::tree_branch); function("tree_hash_from_branch", &Core::Cryptography::tree_hash_from_branch); function("generateRingSignatures", &generateRingSignatures); function("prepareRingSignatures", &prepareRingSignatures); function("prepareRingSignaturesK", &prepareRingSignaturesK); function("completeRingSignatures", &completeRingSignatures); function("checkRingSignature", &Core::Cryptography::checkRingSignature); function( "generatePrivateViewKeyFromPrivateSpendKey", &Core::Cryptography::generatePrivateViewKeyFromPrivateSpendKey); function("generateViewKeysFromPrivateSpendKey", &generateViewKeysFromPrivateSpendKey); function("generateKeys", &generateKeys); function("generateDeterministicSubwalletKeys", &generateDeterministicSubwalletKeys); function("checkKey", &Core::Cryptography::checkKey); function("secretKeyToPublicKey", &secretKeyToPublicKey); function("generateKeyDerivation", &generateKeyDerivation); function("generateKeyDerivationScalar", &generateKeyDerivationScalar); function("derivationToScalar", &derivationToScalar); function("derivePublicKey", &derivePublicKey); function("deriveSecretKey", &deriveSecretKey); function("scalarDerivePublicKey", &scalarDerivePublicKey); function("scalarDeriveSecretKey", &scalarDeriveSecretKey); function("underivePublicKey", &underivePublicKey); function("generateSignature", &Core::Cryptography::generateSignature); function("checkSignature", &Core::Cryptography::checkSignature); function("generateKeyImage", &Core::Cryptography::generateKeyImage); function("scalarmultKey", &Core::Cryptography::scalarmultKey); function("hashToEllipticCurve", &Core::Cryptography::hashToEllipticCurve); function("scReduce32", &Core::Cryptography::scReduce32); function("hashToScalar", &Core::Cryptography::hashToScalar); /* Multisig Methods */ function("calculateMultisigPrivateKeys", &Core::Cryptography::calculateMultisigPrivateKeys); function("calculateSharedPrivateKey", &Core::Cryptography::calculateSharedPrivateKey); function("calculateSharedPublicKey", &Core::Cryptography::calculateSharedPublicKey); function("generatePartialSigningKey", &Core::Cryptography::generatePartialSigningKey); function("restoreKeyImage", &Core::Cryptography::restoreKeyImage); function("restoreRingSignatures", &restoreRingSignatures); register_vector<std::string>("VectorString"); value_object<Keys>("Keys").field("secretKey", &Keys::secretKey).field("publicKey", &Keys::publicKey); value_object<PreparedSignatures>("Keys") .field("signatures", &PreparedSignatures::signatures) .field("key", &PreparedSignatures::key); }
11,359
3,675
// // GPUAttributeValueVec1Float.cpp // G3M // // Created by DIEGO RAMIRO GOMEZ-DECK on 1/4/19. // #include "GPUAttributeValueVec1Float.hpp" GPUAttributeValueVec1Float::GPUAttributeValueVec1Float(IFloatBuffer* buffer, int arrayElementSize, int index, int stride, bool normalized) : GPUAttributeValueVecFloat(buffer, 1, arrayElementSize, index, stride, normalized) { }
724
171
// SPDX-License-Identifier: Apache-2.0 // Copyright (C) 2018 IBM Corp. #include "config.h" extern "C" { #include "test/mbox.h" #include "test/system.h" } #include "vpnor/test/tmpd.hpp" #include <cassert> #include <experimental/filesystem> #include "vpnor/backend.h" static const auto BLOCK_SIZE = 4096; static const auto ERASE_SIZE = BLOCK_SIZE; static const auto WINDOW_SIZE = 2 * BLOCK_SIZE; static const auto MEM_SIZE = WINDOW_SIZE; static const auto N_WINDOWS = 1; static const auto PNOR_SIZE = 4 * BLOCK_SIZE; const std::string toc[] = { "partition01=ONE,00001000,00002000,80,ECC,READONLY", "partition02=TWO,00002000,00004000,80,ECC,READONLY", }; static const uint8_t get_info[] = {0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static const uint8_t request_one[] = {0x04, 0x01, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static const uint8_t response_one[] = {0x04, 0x01, 0xfe, 0xff, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; static const uint8_t request_two[] = {0x04, 0x02, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static const uint8_t response_two[] = {0x04, 0x02, 0xfe, 0xff, 0x02, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; namespace test = openpower::virtual_pnor::test; int main() { struct mbox_context* ctx; system_set_reserved_size(MEM_SIZE); system_set_mtd_sizes(PNOR_SIZE, ERASE_SIZE); ctx = mbox_create_frontend_context(N_WINDOWS, WINDOW_SIZE); test::VpnorRoot root(&ctx->backend, toc, BLOCK_SIZE); int rc = mbox_command_dispatch(ctx, get_info, sizeof(get_info)); assert(rc == 1); rc = mbox_command_dispatch(ctx, request_one, sizeof(request_one)); assert(rc == 1); rc = mbox_cmp(ctx, response_one, sizeof(response_one)); assert(rc == 0); rc = mbox_command_dispatch(ctx, request_two, sizeof(request_two)); assert(rc == 1); rc = mbox_cmp(ctx, response_two, sizeof(response_two)); assert(rc == 0); return rc; }
2,465
1,150
#ifndef _YGP_RNG_HPP_ #define _YGP_RNG_HPP_ #include"configure.hpp" #include<cstdint> BEGIN_NAMESPACE_YGP template<typename _Tp> class rng/*range*/ { public: using t=_Tp; struct iterator { t tc,td; iterator(t B,t D):tc{B},td{D}{} t operator++(){return tc+=td;} t operator--(){return tc-=td;} const t& operator*()const{return tc;} bool operator==(const iterator& an)const{return tc==an.tc;} bool operator!=(const iterator& an)const{return tc!=an.tc;} }; t b,e,d; explicit rng(t E) { b=0,e=E,d=1; } explicit rng(t B,t E,t D=1):b{B},e{E},d{D}{} iterator begin()const { return iterator{b,d}; } iterator end()const { return iterator{e,d}; } }; /*Usage: for(auto i:rng(begin,end))//[begin,end)*/ END_NAMESPACE_YGP #endif
958
349
/* * Copyright (c) 2016, Yung-Yu Chen <yyc@solvcon.net> * BSD 3-Clause License, see LICENSE.txt */ #include <cstdint> #include <type_traits> #include <gtest/gtest.h> #include "march/core/types.hpp" using namespace march; TEST(typesTest, TypeId) { DataTypeId val; val = type_to<bool>::id; EXPECT_EQ(val, MH_BOOL); val = type_to<int8_t>::id; EXPECT_EQ(val, MH_INT8); val = type_to<uint8_t>::id; EXPECT_EQ(val, MH_UINT8); val = type_to<int16_t>::id; EXPECT_EQ(val, MH_INT16); val = type_to<uint16_t>::id; EXPECT_EQ(val, MH_UINT16); val = type_to<int32_t>::id; EXPECT_EQ(val, MH_INT32); val = type_to<uint32_t>::id; EXPECT_EQ(val, MH_UINT32); val = type_to<int64_t>::id; EXPECT_EQ(val, MH_INT64); val = type_to<uint64_t>::id; EXPECT_EQ(val, MH_UINT64); val = type_to<float>::id; EXPECT_EQ(val, MH_FLOAT); val = type_to<double>::id; EXPECT_EQ(val, MH_DOUBLE); val = type_to<std::complex<float>>::id; EXPECT_EQ(val, MH_CFLOAT); val = type_to<std::complex<double>>::id; EXPECT_EQ(val, MH_CDOUBLE); } TEST(typesTest, cpptype) { static_assert(std::is_same<id_to<MH_BOOL>::type, bool>::value, "bad bool"); static_assert(std::is_same<id_to<MH_INT8>::type, int8_t>::value, "bad int8"); static_assert(std::is_same<id_to<MH_UINT8>::type, uint8_t>::value, "bad uint8"); static_assert(std::is_same<id_to<MH_INT16>::type, int16_t>::value, "bad int16"); static_assert(std::is_same<id_to<MH_UINT16>::type, uint16_t>::value, "bad uint16"); static_assert(std::is_same<id_to<MH_INT32>::type, int32_t>::value, "bad int32"); static_assert(std::is_same<id_to<MH_UINT32>::type, uint32_t>::value, "bad uint32"); static_assert(std::is_same<id_to<MH_INT64>::type, int64_t>::value, "bad int64"); static_assert(std::is_same<id_to<MH_UINT64>::type, uint64_t>::value, "bad uint64"); static_assert(std::is_same<id_to<MH_FLOAT>::type, float>::value, "bad float"); static_assert(std::is_same<id_to<MH_DOUBLE>::type, double>::value, "bad double"); static_assert(std::is_same<id_to<MH_CFLOAT>::type, std::complex<float>>::value, "bad cfloat"); static_assert(std::is_same<id_to<MH_CDOUBLE>::type, std::complex<double>>::value, "bad cdouble"); } // vim: set ff=unix fenc=utf8 nobomb et sw=4 ts=4:
2,327
1,066
#if !defined(DLM_CL_SKIP_VENDOR_NVIDIA) #include "dlm/env/macro.h" DLM_CMODULE_START #include "cl/cl_ext_nvidia.h" DLM_CMODULE_END #include "dlm/cl/device.hpp" #include "dlm/cl/controllers.hpp" using namespace dlmcl; static void getPCITopology(DeviceInfo &info, cl_device_id device) noexcept { // undocumented Nvidia API #define CL_DEVICE_PCI_BUS_ID_NV 0x4008 #define CL_DEVICE_PCI_SLOT_ID_NV 0x4009 cl_int bus = -1; cl_int slot = -1; cl_int err = clGetDeviceInfo (device, CL_DEVICE_PCI_BUS_ID_NV, sizeof(bus), &bus, NULL); if (err != CL_SUCCESS) return; err = clGetDeviceInfo(device, CL_DEVICE_PCI_SLOT_ID_NV, sizeof(slot), &slot, NULL); if (err != CL_SUCCESS) return; info.topology.bus = bus; info.topology.dev = (slot >> 3) & 0xff; info.topology.fn = slot & 0x7; } static void getMemoryArchitecture(DeviceInfo &info, cl_device_id device) noexcept { cl_bool isSMA; const cl_int err = clGetDeviceInfo(device, CL_DEVICE_INTEGRATED_MEMORY_NV, sizeof(isSMA), &isSMA, NULL); if (err == CL_SUCCESS) info.memory.isSMA = (isSMA != 0); } static void getMemoryCaps(DeviceInfo &info, cl_device_id device) noexcept { cl_uint warp; const cl_int err = clGetDeviceInfo(device, CL_DEVICE_WARP_SIZE_NV, sizeof(warp), &warp, NULL); if (err == CL_SUCCESS) info.compute.warp = warp; } DeviceInfo NvidiaController::getInfo(cl_device_id device) noexcept { DeviceInfo info = GenericController::getInfo(device); getPCITopology(info, device); getMemoryArchitecture(info, device); getMemoryCaps(info, device); return info; } const char* NvidiaController::getCompilationOptions(cl_device_id device, enum OPTIMIZATION_LEVEL level) noexcept { static const char opts[] = "-cl-fast-relaxed-math -cl-no-signed-zeros -cl-mad-enable -D DLM_NVIDIA"; return opts; } #endif // DLM_CL_SKIP_VENDOR_NVIDIA
1,913
768
#include "nmos/node_resource.h" #include "cpprest/host_utils.h" #include "cpprest/uri_builder.h" #include "nmos/is04_versions.h" #include "nmos/resource.h" namespace nmos { // See https://github.com/AMWA-TV/nmos-discovery-registration/blob/v1.2/schemas/node.json nmos::resource make_node(const nmos::id& id, const nmos::settings& settings) { using web::json::value; using web::json::value_from_elements; using web::json::value_of; const auto hostname = !nmos::fields::host_name(settings).empty() ? nmos::fields::host_name(settings) : web::http::experimental::host_name(); auto data = details::make_resource_core(id, settings); auto uri = web::uri_builder() .set_scheme(U("http")) .set_host(nmos::fields::host_address(settings)) .set_port(nmos::fields::node_port(settings)) .to_uri(); data[U("href")] = value::string(uri.to_string()); data[U("hostname")] = value::string(hostname); data[U("api")][U("versions")] = value_from_elements(nmos::is04_versions::from_settings(settings) | boost::adaptors::transformed(make_api_version)); const auto at_least_one_host_address = value_of({ value::string(nmos::fields::host_address(settings)) }); const auto& host_addresses = settings.has_field(nmos::fields::host_addresses) ? nmos::fields::host_addresses(settings) : at_least_one_host_address.as_array(); for (const auto& host_address : host_addresses) { value endpoint; endpoint[U("host")] = host_address; endpoint[U("port")] = uri.port(); endpoint[U("protocol")] = value::string(uri.scheme()); web::json::push_back(data[U("api")][U("endpoints")], endpoint); } data[U("caps")] = value::object(); data[U("services")] = value::array(); data[U("clocks")] = value::array(); data[U("interfaces")] = value::array(); return{ is04_versions::v1_3, types::node, data, false }; } }
2,051
667
//Leetcode Problem No 1002 Find Common Characters //Solution written by Xuqiang Fang on 5 Mar, 2019 #include <iostream> #include <vector> #include <string> #include <algorithm> #include <unordered_map> #include <unordered_set> #include <stack> #include <queue> using namespace std; class Solution{ public: vector<string> commonChars(vector<string>& A){ const int n = A.size(); auto ans = helper(A[0]); for(int i=1; i<n; ++i){ auto tmp = helper(A[i]); for(int j=0; j<26; ++j){ ans[j] = min(ans[j], tmp[j]); } } vector<string> ret; for(int i=0; i<26; ++i){ while(ans[i] > 0){ string s; char c = (char)('a'+i); s.push_back(c); ret.push_back(s); ans[i]--; } } return ret; } private: vector<int> helper(string& a){ vector<int> ans(26, 0); for(auto& c : a) ans[c-'a']++; return ans; } }; int main(){ Solution s; vector<string> A {"bella", "label", "roller"}; auto ans = s.commonChars(A); for(auto& a : ans){ cout << a << " "; } cout << endl; A = {"cool", "lock", "cook"}; ans = s.commonChars(A); for(auto& a : ans){ cout << a << " "; } cout << endl; return 0; }
1,187
499
#include "include/MMVII_all.h" namespace MMVII { /* ========================== */ /* cDataIm2D */ /* ========================== */ template <class Type> cDataIm2D<Type>::cDataIm2D(const cPt2di & aP0,const cPt2di & aP1,Type * aRawDataLin,eModeInitImage aModeInit) : cDataTypedIm<Type,2> (aP0,aP1,aRawDataLin,aModeInit) { mRawData2D = cMemManager::Alloc<tVal*>(cRectObj<2>::Sz().y()) -Y0(); for (int aY=Y0() ; aY<Y1() ; aY++) mRawData2D[aY] = tBI::mRawDataLin + (aY-Y0()) * SzX() - X0(); } template <class Type> cDataIm2D<Type>::~cDataIm2D() { cMemManager::Free(mRawData2D+Y0()); } template <class Type> int cDataIm2D<Type>::VI_GetV(const cPt2di& aP) const { return GetV(aP); } template <class Type> double cDataIm2D<Type>::VD_GetV(const cPt2di& aP) const { return GetV(aP); } template <class Type> void cDataIm2D<Type>::VI_SetV(const cPt2di& aP,const int & aV) { SetVTrunc(aP,aV); } template <class Type> void cDataIm2D<Type>::VD_SetV(const cPt2di& aP,const double & aV) { SetVTrunc(aP,aV); } /* ========================== */ /* cIm2D */ /* ========================== */ template <class Type> cIm2D<Type>::cIm2D(const cPt2di & aP0,const cPt2di & aP1,Type * aRawDataLin,eModeInitImage aModeInit) : mSPtr(new cDataIm2D<Type>(aP0,aP1,aRawDataLin,aModeInit)), mPIm (mSPtr.get()) { } template <class Type> cIm2D<Type>::cIm2D(const cPt2di & aSz,Type * aRawDataLin,eModeInitImage aModeInit) : cIm2D<Type> (cPt2di(0,0),aSz,aRawDataLin,aModeInit) { } template <class Type> cIm2D<Type> cIm2D<Type>::FromFile(const std::string & aName) { cDataFileIm2D aFileIm = cDataFileIm2D::Create(aName); cIm2D<Type> aRes(aFileIm.Sz()); aRes.Read(aFileIm,cPt2di(0,0)); return aRes; } template <class Type> cIm2D<Type> cIm2D<Type>::Dup() const { cIm2D<Type> aRes(DIm().P0(),DIm().P1()); DIm().DupIn(aRes.DIm()); return aRes; } #define INSTANTIATE_IM2D(Type)\ template class cIm2D<Type>;\ template class cDataIm2D<Type>; INSTANTIATE_IM2D(tINT1) INSTANTIATE_IM2D(tINT2) INSTANTIATE_IM2D(tINT4) INSTANTIATE_IM2D(tU_INT1) INSTANTIATE_IM2D(tU_INT2) INSTANTIATE_IM2D(tU_INT4) INSTANTIATE_IM2D(tREAL4) INSTANTIATE_IM2D(tREAL8) INSTANTIATE_IM2D(tREAL16) };
2,268
1,066
#include "stdafx.h" /* * Copyright (c) 2007-2012 SlimDX Group * * 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 <dinput.h> #include "CapabilitiesDI.h" #include "Guids.h" #include "DeviceSubType.h" using namespace System; namespace SlimDX { namespace DirectInput { Capabilities::Capabilities( const DIDEVCAPS &caps ) { axesCount = caps.dwAxes; buttonCount = caps.dwButtons; povCount = caps.dwPOVs; ffSamplePeriod = caps.dwFFSamplePeriod; ffMinTimeResolution = caps.dwFFMinTimeResolution; ffDriverVersion = caps.dwFFDriverVersion; firmwareRevision = caps.dwFirmwareRevision; hardwareRevision = caps.dwHardwareRevision; flags = static_cast<DeviceFlags>( caps.dwFlags ); type = static_cast<DeviceType>( caps.dwDevType ); subType = caps.dwDevType >> 8; if( ( caps.dwDevType & DIDEVTYPE_HID ) != 0 ) hid = true; else hid = false; } } }
1,944
709
#include <QtTest> #include <circuits/nand2.h> #include <circuits/nor2.h> #include <circuits/or2.h> #include "circuittest.h" #define TEST_ELEMENT(CLASS_NAME, FUNCTION) \ CLASS_NAME circuit;\ const bool i[] = {true, true, false, false};\ const bool j[] = {true, false, true, false};\ \ const QList<QString>& output = circuit.outputs();\ const QList<QString>& input = circuit.inputs();\ const QString& firstPortName = input[0];\ const QString& secondPortName = input[1];\ const QString& outputPortName = output[0];\ \ for (int k = 0; k != sizeof(i) / sizeof(bool); ++k)\ {\ circuit.setSignal(firstPortName, i[k]);\ circuit.setSignal(secondPortName, j[k]);\ QCOMPARE(FUNCTION, circuit.state(outputPortName));\ } void CircuitTest::nand2Test() { TEST_ELEMENT(NAnd2, !(i[k] && j[k])); } void CircuitTest::nor2Test() { TEST_ELEMENT(NOr2, !(i[k] || j[k])); } void CircuitTest::or2Test() { TEST_ELEMENT(Or2, i[k] || j[k]); } QTEST_MAIN(CircuitTest)
1,031
413
/*---------------------------------------------------------------------------*\ Copyright (C) 2011 OpenFOAM Foundation ------------------------------------------------------------------------------- License This file is part of CAELUS. CAELUS is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. CAELUS is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CAELUS. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // template<class TrackingData> inline bool CML::smoothData::update ( const smoothData& svf, const scalar scale, const scalar tol, TrackingData& td ) { if (!valid(td) || (value_ < VSMALL)) { // My value not set - take over neighbour value_ = svf.value()/scale; // Something changed - let caller know return true; } else if (svf.value() > (1 + tol)*scale*value_) { // Neighbour is too big for me - Up my value value_ = svf.value()/scale; // Something changed - let caller know return true; } else { // Neighbour is not too big for me or change is too small // Nothing changed return false; } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // inline CML::smoothData::smoothData() : value_(-GREAT) {} inline CML::smoothData::smoothData(const scalar value) : value_(value) {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // template<class TrackingData> inline bool CML::smoothData::valid(TrackingData& td) const { return value_ > -SMALL; } template<class TrackingData> inline bool CML::smoothData::sameGeometry ( const polyMesh&, const smoothData&, const scalar, TrackingData& td ) const { return true; } template<class TrackingData> inline void CML::smoothData::leaveDomain ( const polyMesh&, const polyPatch&, const label, const point&, TrackingData& td ) {} template<class TrackingData> inline void CML::smoothData::transform ( const polyMesh&, const tensor&, TrackingData& td ) {} template<class TrackingData> inline void CML::smoothData::enterDomain ( const polyMesh&, const polyPatch&, const label, const point&, TrackingData& td ) {} template<class TrackingData> inline bool CML::smoothData::updateCell ( const polyMesh&, const label, const label, const smoothData& svf, const scalar tol, TrackingData& td ) { // Take over info from face if more than deltaRatio larger return update(svf, td.maxRatio, tol, td); } template<class TrackingData> inline bool CML::smoothData::updateFace ( const polyMesh&, const label, const label, const smoothData& svf, const scalar tol, TrackingData& td ) { // Take over information from cell without any scaling (scale = 1.0) return update(svf, 1.0, tol, td); } // Update this (face) with coupled face information. template<class TrackingData> inline bool CML::smoothData::updateFace ( const polyMesh&, const label, const smoothData& svf, const scalar tol, TrackingData& td ) { // Take over information from coupled face without any scaling (scale = 1.0) return update(svf, 1.0, tol, td); } template <class TrackingData> inline bool CML::smoothData::equal ( const smoothData& rhs, TrackingData& td ) const { return operator==(rhs); } // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // inline void CML::smoothData::operator= ( const scalar value ) { value_ = value; } inline bool CML::smoothData::operator== ( const smoothData& rhs ) const { return value_ == rhs.value(); } inline bool CML::smoothData::operator!= ( const smoothData& rhs ) const { return !(*this == rhs); } // ************************************************************************* //
4,503
1,456
#include "adlik_serving/framework/manager/boarding_loop.h" #include "adlik_serving/framework/manager/boarding_functor.h" #include "cub/env/concurrent/auto_lock.h" namespace adlik { namespace serving { BoardingLoop::BoardingLoop() { // auto action = [this] { this->poll(); }; // loop.reset(new cub::LoopThread(action, 10 * 1000 /* ms */)); } void BoardingLoop::poll() { auto action = [this] { cub::AutoLock lock(this->mu); BoardingFunctor f(this->ROLE(ManagedStore)); f(streams); }; loop.reset(new cub::LoopThread(action, 10 * 1000 /* ms */)); // cub::AutoLock lock(mu); // BoardingFunctor f(ROLE(ManagedStore)); // f(streams); } void BoardingLoop::update(ModelStream& stream) { cub::AutoLock lock(mu); streams.push_back(stream); } } // namespace serving } // namespace adlik
816
302
/* * Copyright (c) 2014 Hackdirt Ltd. * Author: David Petrie (david@davidpetrie.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 "hdCheckbox.h" hdCheckbox::hdCheckbox(const char *textureOnNormal, const char *textureOnOver, const char *textureOffNormal, const char *textureOffOver, hdGameWorld* gameWorld) : hdReceiver(gameWorld, true) { // create two buttons m_onButton = new hdButton(textureOnNormal, textureOnOver, textureOnOver); m_offButton = new hdButton(textureOffNormal, textureOffOver, textureOffOver); m_activeButton = m_onButton; m_callbackObject = NULL; m_valueChangedCallback = NULL; } hdCheckbox::~hdCheckbox() { if (m_onButton) delete m_onButton; if (m_offButton) delete m_offButton; } void hdCheckbox::SetAs2DBox(const float& x, const float& y, const float& w, const float& h) { m_onButton->SetAs2DBox(x, y, w, h); m_offButton->SetAs2DBox(x, y, w, h); } void hdCheckbox::AddValueChangedListener(void *obj, void (*func)(void *, void *)) { m_callbackObject = obj; m_valueChangedCallback = func; } bool hdCheckbox::MouseDown(float x, float y) { if (!this->isEnabled()) return false; if (this->IsHidden()) return false; return m_activeButton->MouseDown(x, y); } bool hdCheckbox::MouseOver(float x, float y) { if (!this->isEnabled()) return false; if (this->IsHidden()) return false; return m_activeButton->MouseOver(x, y); } bool hdCheckbox::MouseUp(float x, float y) { bool res; if (!this->isEnabled()) return false; if (this->IsHidden()) return false; res = m_activeButton->MouseUp(x, y); if (res) { Toggle(); if (m_callbackObject != NULL && m_valueChangedCallback != NULL) { (*m_valueChangedCallback)(m_callbackObject, this); } } return res; } bool hdCheckbox::MouseDoubleClick(float x, float y) { if (!this->isEnabled()) return false; if (this->IsHidden()) return false; return m_activeButton->MouseDoubleClick(x, y); } void hdCheckbox::Toggle() { if (m_activeButton == m_onButton) m_activeButton = m_offButton; else m_activeButton = m_onButton; } void hdCheckbox::SetOn() { hdAssert(m_onButton != NULL); m_activeButton = m_onButton; } void hdCheckbox::SetOff() { hdAssert(m_offButton != NULL); m_activeButton = m_offButton; } void hdCheckbox::Draw() const { m_activeButton->Draw(); } bool hdCheckbox::IsOn() const { return (m_activeButton == m_onButton); }
3,564
1,130
//Author:LanceYu #include<cstring> #include<cmath> #include<cstdio> #include<cctype> #include<cstdlib> #include<ctime> #include<vector> #include<iostream> #include<string> #include<queue> #include<set> #include<algorithm> #include<complex> #include<stack> #include<bitset> #include<iomanip> #define ll long long using namespace std; const double clf=1e-8; const int MMAX=0x7fffffff; const int INF=0xfffffff; const int mod=1e9+7; struct node{ int hz=0,ori; }x[10001]; bool cmp(const node a,const node b) { return a.hz>b.hz; } int main() { ios::sync_with_stdio(false); //freopen("C:\\Users\\LENOVO\\Desktop\\in.txt","r",stdin); //freopen("C:\\Users\\LENOVO\\Desktop\\out.txt","w",stdout); string s; cin>>s; int i=0,n,t; for(int i=0;i<10001;i++) x[i].ori=i; for(int i=0;i<s.length();i++) if(s[i]==',') s[i]=' '; istringstream ss(s); while(ss>>t) x[t].hz++; sort(x,x+10001,cmp); cin>>t; for(int i=0;i<t;i++) { if(i==0)cout<<x[i].ori; else cout<<","<<x[i].ori; } return 0; }
1,005
497
/* * Copyright (c) 2020 International Business Machines * All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * * Authors: Nikolas Ioannou (nio@zurich.ibm.com), * Kornilios Kourtis (kou@zurich.ibm.com, kornilios@gmail.com) * */ #include <stdio.h> #include <signal.h> #include "util/debug.h" #include "uDepot/rwlock-pagefault-trt.hh" #include "trt/uapi/trt.hh" namespace udepot { static struct sigaction oldact_g; static void sigsegv_handler(int sig, siginfo_t *siginfo, void *uctx) { UDEPOT_DBG("Got SIGSEGV!\n"); trt::Task *t = &trt::T::self(); if (t->rwpf_rb_set != 1) { //trt_err("SIGSEGV without rollback set. Calling old handler\n"); return (oldact_g.sa_sigaction(sig, siginfo, uctx)); } /* MAYBE TODO: register and check address for faults */ //siglongjmp(t->rwpf_rb_jmp, 1); longjmp(t->rwpf_rb_jmp, 1); } rwlock_pagefault_trt::rwlock_pagefault_trt() : rwpf_trt_ao_(nullptr) { pthread_spin_init(&rwpf_trt_lock_, 0); } rwlock_pagefault_trt::~rwlock_pagefault_trt() {} int rwlock_pagefault_trt::init() { struct sigaction sa = {0}; sa.sa_sigaction = sigsegv_handler; sa.sa_flags = SA_SIGINFO; if (sigaction(SIGSEGV, &sa, &oldact_g) == -1) { perror("sigaction"); return errno; } return 0; } // the read_lock() part void rwlock_pagefault_trt::rd_enter() { for (;;) { bool ok = rwlock_pagefault_base::rd_try_lock(); if (ok) { return; } // failed: there is a resize in-progress: sleep trt::Waitset ws; trt::Future future; // use a move constructor under the lock for getting the async object // reference. If there no reference exists, retry. The future will // subscribe to the async objet under the lock, so we are sure that it's // not getting away. bool retry = false; pthread_spin_lock(&rwpf_trt_lock_); if (rwpf_trt_ao_ == nullptr) retry = true; else future = trt::Future(rwpf_trt_ao_, &ws, nullptr); pthread_spin_unlock(&rwpf_trt_lock_); if (retry) continue; // wait trt::Future *f__ __attribute__((unused)) = ws.wait_(); assert(f__ == &future); assert(future.get_val() == 0xbeef); future.drop_ref(); } } void rwlock_pagefault_trt::rd_exit() { rwlock_pagefault_base::rd_unlock(); } void rwlock_pagefault_trt::write_enter() { // before we start draining readers, we need a few things first. // first, we should be the only writer -- other writers are assumed to be // excluded externally. assert(rwpf_trt_ao_ == nullptr); // Allocate an async object. It will be deallocated when it's reference // count reaches zero. // // Since readers are not blocked yet, the lock is probably not needed. // But, I take it anyway since we are already on the slow path. pthread_spin_lock(&rwpf_trt_lock_); rwpf_trt_ao_ = trt::AsyncObj::allocate(); if (rwpf_trt_ao_ == nullptr) { perror("malloc"); abort(); } pthread_spin_unlock(&rwpf_trt_lock_); // start draining readers rwlock_pagefault_base::wr_enter(); } void rwlock_pagefault_trt::write_wait_readers() { while (!rwlock_pagefault_base::wr_ready()) trt::T::yield(); } void rwlock_pagefault_trt::write_exit() { trt::AsyncObj *old_ao = nullptr; // remove the AsyncObj reference under the lock pthread_spin_lock(&rwpf_trt_lock_); std::swap(old_ao, rwpf_trt_ao_); pthread_spin_unlock(&rwpf_trt_lock_); // let readers pass rwlock_pagefault_base::wr_exit(); // notify readers sleeping assert(old_ao != nullptr); trt::T::notify(old_ao, 0xbeef, trt::NotifyPolicy::LastTaskScheduler); } } // end namespace udepot
3,519
1,473
#pragma once #include "vnh.hpp" namespace vuh { class core { public: core() : _res(vhn::Result::eSuccess) { } explicit core(vhn::Result res) : _res(res) { } public: virtual vhn::Result error() const { return _res; }; virtual bool success() const { return vhn::Result::eSuccess == _res; } virtual std::string error_to_string() const { return vhn::to_string(_res); }; protected: vhn::Result _res; ///< result of vulkan's api }; }
517
165
#include "Currency.hpp" using namespace std; Currency::Currency() { type = ItemType::ITEM_TYPE_CURRENCY; symbol = '$'; status = ItemStatus::ITEM_STATUS_UNCURSED; status_identified = true; } Currency::~Currency() { } // Currency is always generated uncursed and shouldn't ever be set to another // status. void Currency::set_status(const ItemStatus status_to_ignore) { } void Currency::set_status_identified(const bool new_status_identified) { } bool Currency::additional_item_attributes_match(ItemPtr item) const { return true; } bool Currency::get_type_always_stacks() const { return true; } Item* Currency::clone() { return new Currency(*this); } ClassIdentifier Currency::internal_class_identifier() const { return ClassIdentifier::CLASS_ID_CURRENCY; } #ifdef UNIT_TESTS #include "unit_tests/Currency_test.cpp" #endif
848
304
#include "../../_Interface.hpp" #include "../EnvironmentHeader.hpp" template<typename Ty> class shadow_class { public: using DataType = volatile Ty; DataType _data; }; atom<s64>::atom() { assert(_mem_sz >= sizeof(shadow_class<s64>)); new (_mem) volatile s64(0); } atom<s64>::atom(const atom<s64>& rhs) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<s64>*); shadow_self._data = shadow_rhs._data; } atom<s64>::atom(s64 v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); shadow_self._data = v; } atom<s64>::~atom() { } s64 atom<s64>::get() const { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); return shadow_self._data; } void atom<s64>::set(s64 v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); shadow_self._data = v; } atom<s64>& atom<s64>::operator =(const atom<s64>& rhs) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<s64>*); shadow_self._data = shadow_rhs._data; return *this; } atom<s64>& atom<s64>::operator =(s64 v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); shadow_self._data = v; return *this; } s64 atom<s64>::operator ++() { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); u64 ret = InterlockedIncrement(reinterpret_cast<volatile u64*>(&shadow_self._data)); return (s64)ret; } s64 atom<s64>::operator ++(int) { s64 ret = operator ++(); return ret - 1; } s64 atom<s64>::operator --() { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); u64 ret = InterlockedDecrement(reinterpret_cast<volatile u64*>(&shadow_self._data)); return (s64)ret; } s64 atom<s64>::operator --(int) { s64 ret = operator --(); return ret + 1; } s64 atom<s64>::weak_add(s64 v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); return shadow_self._data += v; } s64 atom<s64>::exchange(s64 replace) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); u64 ret = InterlockedExchange(reinterpret_cast<volatile u64*>(&shadow_self._data), (u64)replace); return (s64)ret; } s64 atom<s64>::compare_exchange(s64 expected, s64 replace) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<s64>*); u64 ret = InterlockedCompareExchange(reinterpret_cast<volatile u64*>(&shadow_self._data), (u64)replace, (u64)expected); return (s64)ret; } atom<u64>::atom() { assert(_mem_sz >= sizeof(shadow_class<u64>)); new (_mem) volatile u64(0); } atom<u64>::atom(const atom<u64>& rhs) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<u64>*); shadow_self._data = shadow_rhs._data; } atom<u64>::atom(u64 v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); shadow_self._data = v; } atom<u64>::~atom() { } u64 atom<u64>::get() const { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); return shadow_self._data; } void atom<u64>::set(u64 v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); shadow_self._data = v; } atom<u64>& atom<u64>::operator =(const atom<u64>& rhs) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<u64>*); shadow_self._data = shadow_rhs._data; return *this; } atom<u64>& atom<u64>::operator =(u64 v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); shadow_self._data = v; return *this; } u64 atom<u64>::operator ++() { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); u64 ret = InterlockedIncrement(&shadow_self._data); return ret; } u64 atom<u64>::operator ++(int) { u64 ret = operator ++(); return ret - 1; } u64 atom<u64>::operator --() { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); u64 ret = InterlockedDecrement(&shadow_self._data); return ret; } u64 atom<u64>::operator --(int) { u64 ret = operator --(); return ret + 1; } u64 atom<u64>::weak_add(s64 v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); return shadow_self._data += v; } u64 atom<u64>::exchange(u64 replace) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); u64 ret = InterlockedExchange(&shadow_self._data, replace); return ret; } u64 atom<u64>::compare_exchange(u64 expected, u64 replace) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<u64>*); u64 ret = InterlockedCompareExchange(&shadow_self._data, replace, expected); return ret; } atom<void*>::atom() { assert(_mem_sz >= sizeof(shadow_class<void*>)); new (_mem) volatile void*(nullptr); } atom<void*>::atom(const atom<void*>& rhs) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*); auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<void*>*); shadow_self._data = shadow_rhs._data; } atom<void*>::atom(void* v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*); shadow_self._data = v; } atom<void*>::~atom() { } void* atom<void*>::get() const { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*); return shadow_self._data; } void atom<void*>::set(void* v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*); shadow_self._data = v; } atom<void*>& atom<void*>::operator =(const atom<void*>& rhs) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*); auto& shadow_rhs = *pointer_convert(rhs._mem, 0, shadow_class<void*>*); shadow_self._data = shadow_rhs._data; return *this; } atom<void*>& atom<void*>::operator =(void* v) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*); shadow_self._data = v; return *this; } void* atom<void*>::exchange(void* replace) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*); void* ret = InterlockedExchangePointer(&shadow_self._data, replace); return (void*)ret; } void* atom<void*>::compare_exchange(void* expected, void* replace) { auto& shadow_self = *pointer_convert(_mem, 0, shadow_class<void*>*); void* ret = InterlockedCompareExchangePointer(&shadow_self._data, replace, expected); return (void*)ret; }
6,617
2,724
/* * Copyright (c) Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #include <proxygen/lib/http/codec/compress/HPACKDecodeBuffer.h> #include <limits> #include <memory> #include <proxygen/lib/http/codec/compress/Huffman.h> using folly::IOBuf; using proxygen::HPACK::DecodeError; using std::unique_ptr; namespace proxygen { void HPACKDecodeBuffer::EOB_LOG(std::string msg, DecodeError code) const { if (endOfBufferIsError_ || code != DecodeError::BUFFER_UNDERFLOW) { LOG(ERROR) << msg; } else { VLOG(4) << msg; } } bool HPACKDecodeBuffer::empty() { return remainingBytes_ == 0; } uint8_t HPACKDecodeBuffer::next() { CHECK_GT(remainingBytes_, 0); // in case we are the end of an IOBuf, peek() will move to the next one uint8_t byte = peek(); cursor_.skip(1); remainingBytes_--; return byte; } uint8_t HPACKDecodeBuffer::peek() { CHECK_GT(remainingBytes_, 0); if (cursor_.length() == 0) { cursor_.peek(); } return *cursor_.data(); } DecodeError HPACKDecodeBuffer::decodeLiteral(folly::fbstring& literal) { return decodeLiteral(7, literal); } DecodeError HPACKDecodeBuffer::decodeLiteral(uint8_t nbit, folly::fbstring& literal) { literal.clear(); if (remainingBytes_ == 0) { EOB_LOG("remainingBytes_ == 0"); return DecodeError::BUFFER_UNDERFLOW; } auto byte = peek(); uint8_t huffmanCheck = uint8_t(1 << nbit); bool huffman = byte & huffmanCheck; // extract the size uint64_t size; DecodeError result = decodeInteger(nbit, size); if (result != DecodeError::NONE) { EOB_LOG("Could not decode literal size", result); return result; } if (size > remainingBytes_) { EOB_LOG(folly::to<std::string>( "size(", size, ") > remainingBytes_(", remainingBytes_, ")")); return DecodeError::BUFFER_UNDERFLOW; } if (size > maxLiteralSize_) { LOG(ERROR) << "Literal too large, size=" << size; return DecodeError::LITERAL_TOO_LARGE; } const uint8_t* data; unique_ptr<IOBuf> tmpbuf; // handle the case where the buffer spans multiple buffers if (cursor_.length() >= size) { data = cursor_.data(); cursor_.skip(size); } else { // temporary buffer to pull the chunks together tmpbuf = IOBuf::create(size); // pull() will move the cursor cursor_.pull(tmpbuf->writableData(), size); data = tmpbuf->data(); } if (huffman) { static auto& huffmanTree = huffman::huffTree(); huffmanTree.decode(data, size, literal); } else { literal.append((const char*)data, size); } remainingBytes_ -= size; return DecodeError::NONE; } DecodeError HPACKDecodeBuffer::decodeInteger(uint64_t& integer) { return decodeInteger(8, integer); } DecodeError HPACKDecodeBuffer::decodeInteger(uint8_t nbit, uint64_t& integer) { if (remainingBytes_ == 0) { EOB_LOG("remainingBytes_ == 0"); return DecodeError::BUFFER_UNDERFLOW; } uint8_t byte = next(); uint8_t mask = HPACK::NBIT_MASKS[nbit]; // remove the first (8 - nbit) bits byte = byte & mask; integer = byte; if (byte != mask) { // the value fit in one byte return DecodeError::NONE; } uint64_t f = 1; uint32_t fexp = 0; do { if (remainingBytes_ == 0) { EOB_LOG("remainingBytes_ == 0"); return DecodeError::BUFFER_UNDERFLOW; } byte = next(); if (fexp > 64) { // overflow in factorizer, f > 2^64 LOG(ERROR) << "overflow fexp=" << fexp; return DecodeError::INTEGER_OVERFLOW; } uint64_t add = (byte & 127) * f; if (std::numeric_limits<uint64_t>::max() - integer <= add) { // overflow detected - we disallow uint64_t max. LOG(ERROR) << "overflow integer=" << integer << " add=" << add; return DecodeError::INTEGER_OVERFLOW; } integer += add; f = f << 7; fexp += 7; } while (byte & 128); return DecodeError::NONE; } namespace HPACK { std::ostream& operator<<(std::ostream& os, DecodeError err) { return os << static_cast<uint32_t>(err); } } // namespace HPACK } // namespace proxygen
4,200
1,531
#include <c10/core/dispatch/KernelRegistration.h> #include "caffe2/operators/experimental/c10/schemas/concat.h" #include "caffe2/utils/math.h" #include "caffe2/core/tensor.h" using caffe2::BaseContext; using caffe2::CPUContext; using caffe2::Tensor; using caffe2::TensorCPU; using std::vector; namespace caffe2 { namespace { template <class DataType, class Context> void concat_op_cpu_impl( at::ArrayRef<C10Tensor> inputs, const C10Tensor& output_, const C10Tensor& split_, int axis, int add_axis) { Tensor output(output_); Tensor split(split_); CPUContext context; split.Resize(vector<int64_t>(1, inputs.size())); int* axis_data = split.template mutable_data<int>(); int adj_size = Tensor(inputs[0]).dim() + (add_axis ? 1 : 0); int canonical_axis = caffe2::canonical_axis_index_(axis, adj_size); CAFFE_ENFORCE_LT(canonical_axis, adj_size, "Axis not in input ndim range."); for (int i = 1; i < inputs.size(); ++i) { CAFFE_ENFORCE( Tensor(inputs[i]).dtype() == Tensor(inputs[0]).dtype(), "All inputs must have the same type, expected: ", Tensor(inputs[0]).dtype().name(), " but got: ", Tensor(inputs[i]).dtype().name(), " for input: ", i); } int before = 1, after = 1; vector<int64_t> output_dims(Tensor(inputs[0]).sizes().vec()); for (int i = 0; i < Tensor(inputs[0]).dim(); ++i) { if (i == canonical_axis && !add_axis) { continue; } int dim = Tensor(inputs[0]).dim32(i); if (i < canonical_axis) { before *= dim; } else { // i > canonical_axis || i == canonical_axis && add_axis after *= dim; } // check the input dims are compatible. for (int j = 1; j < inputs.size(); ++j) { int dim_j = Tensor(inputs[j]).dim32(i); CAFFE_ENFORCE( dim == dim_j, "Expect dimension = ", dim, " got ", dim_j, " at axis = ", i, " for input: ", j, ". The input tensors can only have different dimensions " "when arg 'add_axis' = 0 and along the axis = ", canonical_axis, " <", Tensor(inputs[0]).sizes(), "> vs <", Tensor(inputs[j]).sizes(), ">."); } } int output_channels = 0; for (int i = 0; i < inputs.size(); ++i) { axis_data[i] = add_axis ? 1 : Tensor(inputs[i]).dim32(canonical_axis); output_channels += axis_data[i]; } if (add_axis) { output_dims.insert(output_dims.begin() + canonical_axis, output_channels); } else { output_dims[canonical_axis] = output_channels; } output.Resize(output_dims); size_t output_offset = 0; for (int i = 0; i < inputs.size(); ++i) { Tensor input(inputs[i]); auto axis_dim = add_axis ? 1 : input.dim32(canonical_axis); caffe2::math::CopyMatrix<Context>( input.itemsize(), before, axis_dim * after, input.raw_data(), axis_dim * after, static_cast<char*>(output.raw_mutable_data(Tensor(inputs[0]).dtype())) + output_offset, output_channels * after, static_cast<Context*>(&context), Tensor(inputs[0]).dtype().copy()); output_offset += axis_dim * after * input.itemsize(); } } } // namespace } // namespace caffe2 namespace c10 { C10_REGISTER_KERNEL(caffe2::ops::Concat) .kernel(&caffe2::concat_op_cpu_impl<float, CPUContext>) .dispatchKey(c10::DeviceTypeId::CPU); } // namespace c10
3,489
1,290
#include "SyntaxHighlighter.h" // TODO http://www.kate-editor.org/syntax/3.9/isocpp.xml SyntaxHighlighter::SyntaxHighlighter(QTextDocument* parent) : QSyntaxHighlighter(parent) { HighlightingRule rule; { QTextCharFormat quotationFormat; quotationFormat.setForeground(Qt::darkRed); rule.pattern = QRegExp("\".*\""); rule.pattern.setMinimal(true); rule.format = quotationFormat; mRules.append(rule); rule.pattern = QRegExp("'.*'"); rule.pattern.setMinimal(true); rule.format = quotationFormat; mRules.append(rule); rule.pattern = QRegExp("<[^\\s<]+>"); rule.format = quotationFormat; mRules.append(rule); } mKeywordFormat.setForeground(Qt::blue); static const char* keywords[] = { "__abstract", "__alignof", "__asm", "__assume", "__based", "__box", "__cdecl", "__declspec", "__delegate", "__event", "__fastcall", "__forceinline", "__gc", "__hook", "__identifier", "__if_exists", "__if_not_exists", "__inline", "__int16", "__int32", "__int64", "__int8", "__interface", "__leave", "__m128", "__m128d", "__m128i", "__m256", "__m256d", "__m256i", "__m64", "__multiple_inheritance", "__nogc", "__noop", "__pin", "__property", "__raise", "__sealed", "__single_inheritance", "__stdcall", "__super", "__thiscall", "__try_cast", "__unaligned", "__unhook", "__uuidof", "__value", "__vectorcall", "__virtual_inheritance", "__w64", "__wchar_t", "abstract", "array", "auto", "bool", "break", "case", "catch", "char", "class", "const", "const_cast", "continue", "decltype", "default", "delegate", "delete", "deprecated", "dllexport", "dllimport", "do", "double", "dynamic_cast", "each", "else", "event", "explicit", "extern", "false", "finally", "float", "for", "friend", "friend_as", "gcnew", "generic", "goto", "if", "in", "initonly", "inline", "int", "interface", "interior_ptr", "literal", "long", "mutable", "naked", "namespace", "new", "noinline", "noreturn", "nothrow", "novtable", "nullptr", "operator", "private", "property", "protected", "public", "ref", "register", "reinterpret_cast", "return", "safecast", "sealed", "selectany", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread", "throw", "true", "try", "typedef", "typename", "union", "unsigned", "using", "uuid", "value", "virtual", "void", "volatile", "wchar_t", "while" }; for (const char* keyword : keywords) { QString pattern = QString("\\b%1\\b").arg(keyword); rule.pattern = QRegExp(pattern); rule.format = mKeywordFormat; mRules.append(rule); } static const char* preprocKeywords[] = { "#define", "#error", "#import", "#undef", "#elif", "#if", "#include", "#using", "#else", "#ifdef", "#line", "#endif", "#ifndef", "#pragma" }; for (const char* preprocKeyword : preprocKeywords) { QString pattern = QString("(\\b|^)%1\\b").arg(preprocKeyword); rule.pattern = QRegExp(pattern); rule.format = mKeywordFormat; mRules.append(rule); } { QTextCharFormat numberFormat; numberFormat.setForeground(Qt::red); rule.pattern = QRegExp("\\b[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?f?\\b"); rule.format = numberFormat; mRules.append(rule); rule.pattern = QRegExp("\\b0x[0-9a-fA-F]+U?L?L?\\b"); rule.format = numberFormat; mRules.append(rule); rule.pattern = QRegExp("\\b[0-9]+\\b"); rule.format = numberFormat; mRules.append(rule); } { QTextCharFormat singleLineCommentFormat; singleLineCommentFormat.setForeground(Qt::darkGreen); rule.pattern = QRegExp("//[^\n]*"); rule.format = singleLineCommentFormat; mRules.append(rule); } mMultiLineCommentFormat.setForeground(Qt::darkGreen); mCommentStart = QRegExp("/\\*"); mCommentEnd = QRegExp("\\*/"); } SyntaxHighlighter::~SyntaxHighlighter() { } void SyntaxHighlighter::highlightBlock(const QString &text) { for (const HighlightingRule& rule : mRules) { QRegExp expression(rule.pattern); int index = expression.indexIn(text); while (index >= 0) { int length = expression.matchedLength(); setFormat(index, length, rule.format); index = expression.indexIn(text, index + length); } } setCurrentBlockState(0); int startIndex = 0; if (previousBlockState() != 1) { startIndex = mCommentStart.indexIn(text); } while (startIndex >= 0) { int endIndex = mCommentEnd.indexIn(text, startIndex); int commentLength; if (endIndex == -1) { setCurrentBlockState(1); commentLength = text.length() - startIndex; } else { commentLength = endIndex - startIndex + mCommentEnd.matchedLength(); } setFormat(startIndex, commentLength, mMultiLineCommentFormat); startIndex = mCommentStart.indexIn(text, startIndex + commentLength); } }
5,335
1,782
// This is the initialisation support code for the QtCore module. // // Copyright (c) 2021 Riverbank Computing Limited <info@riverbankcomputing.com> // // This file is part of PyQt6. // // This file may be used under the terms of the GNU General Public License // version 3.0 as published by the Free Software Foundation and appearing in // the file LICENSE included in the packaging of this file. Please review the // following information to ensure the GNU General Public License version 3.0 // requirements will be met: http://www.gnu.org/copyleft/gpl.html. // // If you do not wish to use this file under the terms of the GPL version 3.0 // then you may purchase a commercial license. For more information contact // info@riverbankcomputing.com. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. #include <Python.h> #include "qpycore_api.h" #include "qpycore_public_api.h" #include "qpycore_pyqtslotproxy.h" #include "qpycore_qobject_helpers.h" #include "sipAPIQtCore.h" #include <QCoreApplication> // Set if any QCoreApplication (or sub-class) instance was created from Python. bool qpycore_created_qapp; // This is called to clean up on exit. It is done in case the QCoreApplication // dealloc code hasn't been called. static PyObject *cleanup_on_exit(PyObject *, PyObject *) { pyqt6_cleanup_qobjects(); // Never destroy a QCoreApplication if we didn't create it (eg. if we are // embedded in a C++ application). if (qpycore_created_qapp) { QCoreApplication *app = QCoreApplication::instance(); if (app) { Py_BEGIN_ALLOW_THREADS delete app; Py_END_ALLOW_THREADS } } Py_INCREF(Py_None); return Py_None; } // Perform any required initialisation. void qpycore_init() { // We haven't created a QCoreApplication instance. qpycore_created_qapp = false; // Export the private helpers, ie. those that should not be used by // external handwritten code. sipExportSymbol("qtcore_qt_metaobject", (void *)qpycore_qobject_metaobject); sipExportSymbol("qtcore_qt_metacall", (void *)qpycore_qobject_qt_metacall); sipExportSymbol("qtcore_qt_metacast", (void *)qpycore_qobject_qt_metacast); sipExportSymbol("qtcore_qobject_sender", (void *)PyQtSlotProxy::lastSender); // Export the public API. sipExportSymbol("pyqt6_cleanup_qobjects", (void *)pyqt6_cleanup_qobjects); sipExportSymbol("pyqt6_err_print", (void *)pyqt6_err_print); sipExportSymbol("pyqt6_from_argv_list", (void *)pyqt6_from_argv_list); sipExportSymbol("pyqt6_from_qvariant_by_type", (void *)pyqt6_from_qvariant_by_type); sipExportSymbol("pyqt6_get_connection_parts", (void *)pyqt6_get_connection_parts); sipExportSymbol("pyqt6_get_pyqtsignal_parts", (void *)pyqt6_get_pyqtsignal_parts); sipExportSymbol("pyqt6_get_pyqtslot_parts", (void *)pyqt6_get_pyqtslot_parts); sipExportSymbol("pyqt6_get_qmetaobject", (void *)pyqt6_get_qmetaobject); sipExportSymbol("pyqt6_get_signal_signature", (void *)pyqt6_get_signal_signature); sipExportSymbol("pyqt6_register_from_qvariant_convertor", (void *)pyqt6_register_from_qvariant_convertor); sipExportSymbol("pyqt6_register_to_qvariant_convertor", (void *)pyqt6_register_to_qvariant_convertor); sipExportSymbol("pyqt6_register_to_qvariant_data_convertor", (void *)pyqt6_register_to_qvariant_data_convertor); sipExportSymbol("pyqt6_update_argv_list", (void *)pyqt6_update_argv_list); // Register the cleanup function. static PyMethodDef cleanup_md = { "_qtcore_cleanup", cleanup_on_exit, METH_NOARGS, SIP_NULLPTR }; sipRegisterExitNotifier(&cleanup_md); }
3,908
1,326
//***************************************************************************** // Copyright 2017-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** // NOTE: This file follows nGraph format style. // Follows nGraph naming convention for public APIs only, else MLIR naming // convention. #pragma once #include <memory> #include <mlir/ExecutionEngine/ExecutionEngine.h> #include <mlir/IR/Builders.h> #include <mlir/IR/Module.h> #include <mlir/IR/Types.h> #include "contrib/mlir/backend/backend.hpp" #include "contrib/mlir/runtime/runtime.hpp" namespace ngraph { namespace runtime { namespace ngmlir { struct StaticMemRef { void* allocatedPtr; void* alignedPtr; int64_t offset; int64_t shapeAndStrides[]; }; struct UnrankedMemRef { int64_t rank; StaticMemRef* memRefDescPtr; }; /// A CPU Runtime is an MLIR runtime that owns an MLIR context and a module /// The module should be in LLVM dialect and ready to be lowered via an MLIR /// ExecutionEngine. The runtime owns the context and must out-live any MLIR /// code Compilation and execution. class MLIRCPURuntime : public MLIRRuntime { public: /// Executes a pre-compiled subgraph void run(const std::vector<MemRefArg>& args, bool firstIteration) override; private: void run_internal(const std::vector<MemRefArg>& args, bool firstIteration); // Bind external tensors to MLIR module entry point void bindArguments(const std::vector<MemRefArg>& args); // Invokes an MLIR module entry point with bound arguments void execute(bool firstIteration); // Cleans up allocated args void cleanup(); /// Helper to create memref arguments for MLIR function signature llvm::SmallVector<void*, 8> allocateMemrefArgs(); /// Helper to allocate a default MemRef descriptor for LLVM. Handles static /// shapes /// only for now. StaticMemRef* allocateDefaultMemrefDescriptor(size_t); private: // Pointers to externally allocated memory for sub-graph's input and output // tensors. const std::vector<MemRefArg>* m_externalTensors; // Arguments for the MLIR function generated for the nGraph sub-graph. llvm::SmallVector<void*, 8> m_invokeArgs; std::unique_ptr<::mlir::ExecutionEngine> m_engine; std::vector<size_t> m_ranks; }; } } }
3,457
882
#include "kazbase/logging.h" #include "spindash.h" #include "character.h" #include "world.h" void sdCharacterLeftPressed(SDuint character) { Character* c = Character::get(character); c->move_left(); } void sdCharacterRightPressed(SDuint character) { Character* c = Character::get(character); c->move_right(); } void sdCharacterUpPressed(SDuint character) { Character* c = Character::get(character); c->move_up(); } void sdCharacterDownPressed(SDuint character) { Character* c = Character::get(character); c->move_down(); } void sdCharacterJumpPressed(SDuint character) { Character* c = Character::get(character); c->jump(); } SDDirection sdCharacterFacingDirection(SDuint character) { Character* c = Character::get(character); return c->facing(); } SDAnimationState sdCharacterAnimationState(SDuint character) { Character* c = Character::get(character); return c->animation_state(); } SDfloat sdCharacterGetWidth(SDuint character) { Character* c = Character::get(character); return c->width(); } SDbool sdCharacterIsGrounded(SDuint character) { Character* c = Character::get(character); return c->is_grounded(); } SDbool sdObjectIsCharacter(SDuint object) { Character* c = Character::get(object); return (c) ? true: false; } void sdCharacterSetGroundSpeed(SDuint character, SDfloat value) { Character* c = Character::get(character); c->set_ground_speed(value); } SDfloat sdCharacterGetGroundSpeed(SDuint character) { Character* c = Character::get(character); return c->ground_speed(); } void sdCharacterEnableSkill(SDuint character, sdSkill skill) { Character* c = Character::get(character); c->enable_skill(skill); } void sdCharacterDisableSkill(SDuint character, sdSkill skill) { Character* c = Character::get(character); c->disable_skill(skill); } SDbool sdCharacterSkillEnabled(SDuint character, sdSkill skill) { Character* c = Character::get(character); return c->skill_enabled(skill); } SDfloat sdCharacterGetSpindashCharge(SDuint character) { Character* c = Character::get(character); return c->spindash_charge(); } void sdCharacterOverrideSetting(const char* setting, float value) { Character::override_setting(setting, value); } void sdObjectDestroy(SDuint entity) { Object* obj = Object::get(entity); if(!obj) { L_WARN("sdObjectDestroy: No such object"); return; } obj->world()->destroy_object(entity); } void sdObjectSetPosition(SDuint object, SDfloat x, SDfloat y) { Object* obj = Object::get(object); obj->set_position(x, y); } void sdObjectGetPosition(SDuint object, SDfloat* x, SDfloat* y) { Object* obj = Object::get(object); *x = obj->position().x; *y = obj->position().y; } SDfloat sdObjectGetPositionX(SDuint object) { Object* obj = Object::get(object); return obj->position().x; } SDfloat sdObjectGetPositionY(SDuint object) { Object* obj = Object::get(object); return obj->position().y; } SDfloat sdObjectGetSpeedX(SDuint object) { Object* obj = Object::get(object); return obj->velocity().x; } SDfloat sdObjectGetSpeedY(SDuint object) { Object* obj = Object::get(object); return obj->velocity().y; } void sdObjectSetSpeedX(SDuint object, SDfloat x) { Object* obj = Object::get(object); obj->set_velocity(x, obj->velocity().y); } void sdObjectSetSpeedY(SDuint object, SDfloat y) { Object* obj = Object::get(object); obj->set_velocity(obj->velocity().x, y); } void sdObjectSetFixed(SDuint object, SDbool value) { Object* obj = Object::get(object); obj->set_fixed(value); } SDfloat sdObjectGetRotation(SDuint object) { Object* obj = Object::get(object); return obj->rotation(); } SDuint sdBoxCreate(SDuint world_id, SDfloat width, SDfloat height) { World* world = World::get(world_id); return world->new_box(width, height); } SDuint sdSpringCreate(SDuint world_id, SDfloat angle, SDfloat power) { World* world = World::get(world_id); return world->new_spring(power, angle); } /** @brief Creates a new physical world This function creates an empty world ready to start accepting new entities and polygons. */ SDuint sdWorldCreate() { return World::create(); } /** \brief Destroys a world * * \param world - The world to destroy * * Destroys a world and its contents (polygons, entities etc.) */ void sdWorldDestroy(SDuint world) { World::destroy(world); } void sdWorldAddTriangle(SDuint world_id, kmVec2* points) { World* world = World::get(world_id); if(!world) { //Log error return; } world->add_triangle(points[0], points[1], points[2]); } void sdWorldAddBox(SDuint world_id, kmVec2* points) { World* world = World::get(world_id); if(!world) { //Log error return; } world->add_box(points[0], points[1], points[2], points[3]); } void sdWorldAddMesh(SDuint world_id, SDuint num_triangles, kmVec2* points) { for(SDuint i = 0; i < num_triangles; ++i) { kmVec2 tri[3]; kmVec2Assign(&tri[0], &points[i * 3]); kmVec2Assign(&tri[1], &points[(i * 3) + 1]); kmVec2Assign(&tri[2], &points[(i * 3) + 2]); sdWorldAddTriangle(world_id, tri); } } void sdWorldRemoveTriangles(SDuint world_id) { World* world = World::get(world_id); assert(world); world->remove_all_triangles(); } void sdWorldStep(SDuint world_id, SDfloat dt) { World* world = World::get(world_id); if(!world) { //Log error return; } world->update(dt); } SDuint64 sdWorldGetStepCounter(SDuint world_id) { World* world = World::get(world_id); return world->step_counter(); } /** * Mainly for testing, constructs a loop out of triangles */ void sdWorldConstructLoop(SDuint world, SDfloat left, SDfloat top, SDfloat width) { SDfloat thickness = width * 0.1; SDfloat height = width; SDfloat radius = (width - (thickness * 2)) / 2.0; kmVec2 tmp; const SDuint slices = 40; //Generate the points of a circle std::vector<kmVec2> circle_points; for(SDuint i = 0; i < slices; ++i) { SDfloat a = kmDegreesToRadians((360.0 / SDfloat(slices)) * (SDfloat)i); kmVec2Fill(&tmp, radius * cos(a), radius * sin(a)); tmp.x += (left + radius) + thickness; tmp.y += (top - radius) - thickness; circle_points.push_back(tmp); } //Now, build the surrounding triangles kmVec2 points[3]; /*kmVec2Fill(&points[0], left, top - height); //Bottom left of loop kmVec2Fill(&points[1], left + width, top - height); //Bottom right of loop kmVec2Fill(&points[2], circle_points[0].x, circle_points[0].y); sdWorldAddTriangle(world, points);*/ for(SDuint i = 0; i < slices / 4; ++i) { kmVec2Fill(&points[0], circle_points[i].x, circle_points[i].y); kmVec2Fill(&points[1], left + width, top); //Top right of loop kmVec2Fill(&points[2], circle_points[i + 1].x, circle_points[i + 1].y); sdWorldAddTriangle(world, points); } for(SDuint i = slices / 4; i < ((slices / 4) * 2); ++i) { kmVec2Fill(&points[0], circle_points[i].x, circle_points[i].y); kmVec2Fill(&points[1], left, top); //Top left of loop kmVec2Fill(&points[2], circle_points[i+1].x, circle_points[i+1].y); sdWorldAddTriangle(world, points); } /* for(SDuint i = (slices / 4) * 2; i < ((slices / 4) * 3); ++i) { kmVec2Fill(&points[0], circle_points[i].x, circle_points[i].y); kmVec2Fill(&points[1], left, top - height); //Bottom right of the loop kmVec2Fill(&points[2], circle_points[i+1].x, circle_points[i+1].y); sdWorldAddTriangle(world, points); }*/ for(SDuint i = (slices / 4) * 3; i < slices ; ++i) { kmVec2Fill(&points[0], circle_points[i].x, circle_points[i].y); kmVec2Fill(&points[1], left + width, top - height); //Bottom right of the loop if(i < slices -1 ) { kmVec2Fill(&points[2], circle_points[i+1].x, circle_points[i+1].y); } else { kmVec2Fill(&points[2], circle_points[0].x, circle_points[0].y); } sdWorldAddTriangle(world, points); } } void sdWorldSetCompileGeometryCallback(SDuint world_id, SDCompileGeometryCallback callback, void* data) { World* world = World::get(world_id); world->set_compile_callback(callback, data); } void sdWorldSetRenderGeometryCallback(SDuint world_id, SDRenderGeometryCallback callback, void* data) { World* world = World::get(world_id); world->set_render_callback(callback, data); } void sdWorldRender(SDuint world_id) { World* world = World::get(world_id); return world->render(); } void sdWorldDebugEnable(SDuint world_id) { World* world = World::get(world_id); return world->enable_debug_mode(); } void sdWorldDebugStep(SDuint world_id, double step) { World* world = World::get(world_id); return world->debug_step(step); } void sdWorldDebugDisable(SDuint world_id) { World* world = World::get(world_id); return world->disable_debug_mode(); } SDbool sdWorldDebugIsEnabled(SDuint world_id) { World* world = World::get(world_id); return world->debug_mode_enabled(); } void sdWorldCameraTarget(SDuint world_id, SDuint object) { World* world = World::get(world_id); world->set_camera_target(object); } void sdWorldCameraGetPosition(SDuint world_id, SDfloat* x, SDfloat* y) { World* world = World::get(world_id); const kmVec2& pos = world->camera_position(); *x = pos.x; *y = pos.y; } void sdWorldSetObjectCollisionCallback(SDuint world_id, ObjectCollisionCallback callback, void* user_data) { /* * Sets the callback which is called when a collision is detected between two objects. * * We bind the user data to the callback here so we don't have to worry about it later. */ World* world = World::get(world_id); using namespace std::placeholders; InternalObjectCollisionCallback cb = std::bind(callback, _1, _2, _3, _4, user_data); world->set_object_collision_callback(cb); }
10,164
3,432
/* system2 runs a shell command in the background and return the PID. I stole this piece of code from https://stackoverflow.com/questions/22802902/how-to-get-pid-of-process-executed-with-system-command-in-c and modified it a little bit to fit my needs system2() does not pauses like system(). It is therefore easier to get the PID from the submitted process. */ #include "TypeDefinitions.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <iostream> #include "system2.h" PID_t system2(const char * command) { //std::cout << command << "\n"; int p_stdin[2]; int p_stdout[2]; PID_t pid; if (pipe(p_stdin) == -1) return -1; if (pipe(p_stdout) == -1) { close(p_stdin[0]); close(p_stdin[1]); return -1; } pid = fork(); if (pid < 0) { close(p_stdin[0]); close(p_stdin[1]); close(p_stdout[0]); close(p_stdout[1]); return pid; } else if (pid == 0) { close(p_stdin[1]); dup2(p_stdin[0], 0); close(p_stdout[0]); dup2(p_stdout[1], 1); dup2(::open("/dev/null", O_RDONLY), 2); /// Close all other descriptors for the safety sake. for (int i = 3; i < 4096; ++i) ::close(i); setsid(); execl("/bin/sh", "sh", "-c", command, NULL); _exit(1); } close(p_stdin[0]); close(p_stdout[1]); //std::cout << "pid = " << pid << std::endl; return pid; }
1,523
583
#include "Graphics.hpp" #include "../PHL.hpp" #include <stdio.h> #include <stdlib.h> #include <string.h> #include "../Resources.hpp" PHL_Surface db = {0}; PHL_Surface backBuffer = {0}; PHL_Surface dbAlt = {0}; PHL_Surface backBufferAlt = {0}; const int cWidth = 320; const int cHeight = 240; Screen scrnTop = { GFX_TOP, GFX_LEFT, 400, 240 }; Screen scrnBottom = { GFX_BOTTOM, GFX_LEFT, cWidth, cHeight }; Screen* activeScreen = nullptr; // Where graphics get rendered to #ifdef _3DS Screen* debugScreen = nullptr; // Bottom screen console, for debugging (or swapping screen locations) #endif PHL_Rect offset; void PHL_GraphicsInit() { gfxInitDefault(); //Initialize console on top screen. Using NULL as the second argument tells the console library to use the internal console structure as current one //gfxSet3D(false); //consoleDebugInit(debugDevice_CONSOLE); activeScreen = &scrnBottom; debugScreen = &scrnTop; PHL_ResetDrawbuffer(); //Create background image backBuffer = PHL_NewSurface(cWidth * 2, cHeight * 2); dbAlt = PHL_NewSurface(cWidth * 2, cHeight * 2); backBufferAlt = PHL_NewSurface(cWidth * 2, cHeight * 2); } void PHL_GraphicsExit() { gfxExit(); } void PHL_StartDrawing() { PHL_ResetDrawbuffer(); gfxFlushBuffers(); } void PHL_EndDrawing() { PHL_DrawOtherScreen(); gfxSwapBuffers(); gspWaitForVBlank(); } void PHL_SetDrawbuffer(PHL_Surface surf) { db = surf; offset.w = db.width; offset.h = db.height; offset.x = 0; offset.y = 0; } void PHL_ResetDrawbuffer() { db.width = activeScreen->width; db.height = activeScreen->height; db.pxdata = gfxGetFramebuffer(activeScreen->screen, activeScreen->side, NULL, NULL); offset.w = cWidth; offset.h = cHeight; offset.x = (activeScreen->width - offset.w) / 2; offset.y = (activeScreen->height - offset.h) / 2; } PHL_RGB PHL_NewRGB(uint8_t r, uint8_t g, uint8_t b) { PHL_RGB c = { r, g, b }; return c; } void PHL_SetColorKey(PHL_Surface surf, uint8_t r, uint8_t g, uint8_t b) { PHL_RGB key = { r, g, b }; surf.colorKey = key; } PHL_Surface PHL_NewSurface(uint16_t w, uint16_t h) { PHL_Surface surf; surf.width = w / 2; surf.height = h / 2; surf.pxdata = (uint8_t *) malloc(surf.width * surf.height * 3 * sizeof(uint8_t)); surf.colorKey = PHL_NewRGB(0xFF, 0x00, 0xFF); return surf; } void PHL_FreeSurface(PHL_Surface surf) { if (surf.pxdata != NULL) { free(surf.pxdata); surf.pxdata = NULL; } } PHL_Surface PHL_LoadTexture(int _img_index) { PHL_Surface surf; std::string _f_in = "romfs:/graphics/"; int fileSize = 77880; // The default filesize, in bytes (because nearly all the graphics in the game are this size) switch(_img_index) { case sprPlayer: _f_in += "test_player.bmp"; fileSize = 12342; break; case sprTile0: _f_in += "tile0.bmp"; fileSize = 1142; break; case sprProt1: _f_in += "prot1.bmp"; break; case sprTitle: _f_in += "title.bmp"; break; case sprMapG00: _f_in += "mapg00.bmp"; break; case sprMapG01: _f_in += "mapg01.bmp"; break; case sprMapG02: _f_in += "mapg02.bmp"; break; case sprMapG03: _f_in += "mapg03.bmp"; break; case sprMapG04: _f_in += "mapg04.bmp"; break; case sprMapG05: _f_in += "mapg05.bmp"; break; case sprMapG06: _f_in += "mapg06.bmp"; break; case sprMapG07: _f_in += "mapg07.bmp"; break; case sprMapG08: _f_in += "mapg08.bmp"; break; case sprMapG09: _f_in += "mapg09.bmp"; break; case sprMapG10: _f_in += "mapg10.bmp"; break; case sprMapG11: _f_in += "mapg11.bmp"; break; case sprMapG12: _f_in += "mapg12.bmp"; break; case sprMapG13: _f_in += "mapg13.bmp"; break; case sprMapG14: _f_in += "mapg14.bmp"; break; case sprMapG15: _f_in += "mapg15.bmp"; break; case sprMapG16: _f_in += "mapg16.bmp"; break; case sprMapG17: _f_in += "mapg17.bmp"; break; case sprMapG18: _f_in += "mapg18.bmp"; break; case sprMapG19: _f_in += "mapg19.bmp"; break; case sprMapG20: _f_in += "mapg20.bmp"; break; case sprMapG21: _f_in += "mapg21.bmp"; break; case sprMapG22: _f_in += "mapg22.bmp"; break; case sprMapG31: _f_in += "mapg31.bmp"; break; case sprMapG32: _f_in += "mapg32.bmp"; break; default: fileSize = 77880; } FILE * f; if ((f = fopen(_f_in.c_str(), "rb"))) { //Save bmp data uint8_t* bmpFile = (uint8_t*) malloc(fileSize * sizeof(uint8_t)); fread(bmpFile, fileSize, 1, f); fclose(f); //Create surface uint16_t w, h; memcpy(&w, &bmpFile[18], 2); memcpy(&h, &bmpFile[22], 2); surf = PHL_NewSurface(w * 2, h * 2); //Load Palette PHL_RGB palette[20][18]; int count = 0; for (int dx = 0; dx < 20; dx++) { for (int dy = 0; dy < 16; dy++) { palette[dx][dy].b = bmpFile[54 + count]; palette[dx][dy].g = bmpFile[54 + count + 1]; palette[dx][dy].r = bmpFile[54 + count + 2]; count += 4; } } //Fill pixels count = 0; for (int dx = w; dx > 0; dx--) { for (int dy = 0; dy < h; dy++) { int pix = w - dx + w * dy; int px = bmpFile[1078 + pix] / 16; int py = bmpFile[1078 + pix] % 16; //Get transparency from first palette color if (dx == w &&dy == 0) surf.colorKey = palette[0][0]; PHL_RGB c = palette[px][py]; surf.pxdata[count] = c.b; surf.pxdata[count+1] = c.g; surf.pxdata[count+2] = c.r; count += 3; } } //Cleanup free(bmpFile); } return surf; } void PHL_DrawRect(int16_t x, int16_t y, uint16_t w, uint16_t h, PHL_RGB col) { // Everything is stored in memory at 2x size; Halve it for the 3ds port if (x < 0 || y < 0 || x+w > db.width || y+h > db.height) return; //Shrink values for small 3ds screen //x /= 2; //y /= 2; x += offset.x; y += offset.y; //w /= 2; //h /= 2; s16 x2 = x + w; s16 y2 = y + h; //Keep drawing within screen if (x < offset.x) { x = offset.x; } if (y < offset.y) { y = offset.y; } if (x2 > offset.x + offset.w) { x2 = offset.x + offset.w; } if (y2 > offset.y + offset.h) { y2 = offset.y + offset.h; } w = x2 - x; h = y2 - y; u32 p = ((db.height - h - y) + (x * db.height)) * 3; for (int i = 0; i < w; i++) { for (int a = 0; a < h; a++) { db.pxdata[p] = col.b; db.pxdata[p+1] = col.g; db.pxdata[p+2] = col.r; p += 3; } p += (db.height - h) * 3; } } void PHL_DrawSurface(int16_t x, int16_t y, PHL_Surface surf) { PHL_DrawSurfacePart(x, y, 0, 0, surf.width * 2, surf.height * 2, surf); } void PHL_DrawSurfacePart(int16_t x, int16_t y, int16_t cropx, int16_t cropy, int16_t cropw, int16_t croph, PHL_Surface surf) { if (surf.pxdata != NULL) { /* // Everything is stored in memory at 2x size; Halve it for the 3ds port x = (int) x / 2; y = (int) y / 2; cropx = cropx / 2; cropy = cropy / 2; cropw /= 2; croph /= 2; */ if (x > offset.w || y > offset.h || x + cropw < 0 || y + croph < 0) { //image is outside of screen, so don't bother drawing } else { //Crop pixels that are outside of screen if (x < 0) { cropx += -(x); cropw -= -(x); x = 0; } if (y < 0) { cropy += -(y); croph -= -(y); y = 0; } //3DS exclusive optimization /* //if (roomDarkness == 1) { //if (1) { int cornerX = 0;// (herox / 2) - 80; int cornerY = 0;// (heroy / 2) + 10 - 80; if (x < cornerX) { cropx += cornerX - x; cropw -= cornerX - x; x = cornerX; } if (y < cornerY) { cropy += cornerY - y; croph -= cornerY - y; y = cornerY; } if (x + cropw > cornerX + 160) { cropw -= (x + cropw) - (cornerX + 160); } if (y + croph > cornerY + 160) { croph -= (y + croph) - (cornerY + 160); } //}*/ if (x + cropw > offset.w) cropw -= (x + cropw) - (offset.w); if (y + croph > offset.h) croph -= (y + croph) - (offset.h); // Adjust the canvas' position based on the new offsets x += offset.x; y += offset.y; // Find the first color and pixel that we're dealing with before we update the rest of the canvas uint32_t p = ((offset.h - croph - y) + (x * offset.h)) * 3; uint32_t c = ((surf.height - cropy - croph) + surf.height * cropx) * 3; // Loop through every single pixel (draw columns from left to right, top to bottom) of the final output canvas and store the correct color at each pixel for (int i = 0; i < cropw; i++) { for (int a = 0; a < croph; a++) { if (surf.colorKey.r != surf.pxdata[c + 2] || surf.colorKey.g != surf.pxdata[c + 1] || surf.colorKey.b != surf.pxdata[c]) { // Only update this pixel's color if necessary db.pxdata[p] = surf.pxdata[c]; db.pxdata[p + 1] = surf.pxdata[c + 1]; db.pxdata[p + 2] = surf.pxdata[c + 2]; } c += 3; p += 3; } // Skip drawing for all of the columns of pixels that we've cropped out (one pixel = 3 bytes of data {r,g,b}) p += (offset.h - croph) * 3; c += (surf.height - croph) * 3; } } } } void PHL_DrawBackground(PHL_Background back, PHL_Background fore) { PHL_DrawSurface(0, 0, backBuffer); } void PHL_UpdateBackground(PHL_Background back, PHL_Background fore) { PHL_SetDrawbuffer(backBuffer); /* int xx, yy; for (yy = 0; yy < 12; yy++) { for (xx = 0; xx < 16; xx++) { //Draw Background tiles PHL_DrawSurfacePart(xx * 40, yy * 40, back.tileX[xx][yy] * 40, back.tileY[xx][yy] * 40, 40, 40, images[imgTiles]); //Only draw foreground tile if not a blank tile if (fore.tileX[xx][yy] != 0 || fore.tileY[xx][yy] != 0) { PHL_DrawSurfacePart(xx * 40, yy * 40, fore.tileX[xx][yy] * 40, fore.tileY[xx][yy] * 40, 40, 40, images[imgTiles]); } } } */ PHL_ResetDrawbuffer(); } //3DS exclusive. Changes which screen to draw on void swapScreen(gfxScreen_t screen, gfx3dSide_t side) { //Clear old screen PHL_StartDrawing(); PHL_DrawRect(0, 0, 640, 480, PHL_NewRGB(0, 0, 0)); PHL_EndDrawing(); PHL_StartDrawing(); PHL_DrawRect(0, 0, 640, 480, PHL_NewRGB(0, 0, 0)); PHL_EndDrawing(); if (screen == GFX_TOP) { activeScreen = &scrnTop; debugScreen = &scrnBottom; } else { activeScreen = &scrnBottom; debugScreen = &scrnTop; } PHL_ResetDrawbuffer(); } void PHL_DrawOtherScreen() { PHL_ResetAltDrawbuffer(); //printf(":wagu: :nodding: :nodding2: :slownod: :hypernodding: :wagu2: :oj100: :revolving_hearts: "); } void PHL_ResetAltDrawbuffer() { dbAlt.width = debugScreen->width; dbAlt.height = debugScreen->height; dbAlt.pxdata = gfxGetFramebuffer(debugScreen->screen, debugScreen->side, NULL, NULL); offset.w = cWidth; offset.h = cHeight; offset.x = (debugScreen->width - offset.w) / 2; offset.y = (debugScreen->height - offset.h) / 2; }
13,271
4,969
#include "Color.h" Color::Color(Mesh *mesh): MeshDecorator(mesh) { } Color::~Color() { } void Color::AddMeshProperties() { MeshDecorator::AddMeshProperties(); ColorFeatures(); } void Color::ColorFeatures() { std::cout << "Added the Color Features" << std::endl; }
289
113
#include<iostream> #include<vector> #include<algorithm> #include<queue> #include<cstring> using namespace std; int dots, cons, start; bool is_visited[1001]; int matrix[1001][1001]; /* const int MAX = 1000 + 1; int N, M, V; int adjacent[MAX][MAX]; bool visited[MAX]; queue<int> q; void DFS(int idx) { cout << idx << " "; for(int i=1; i<=N; i++) if (adjacent[idx][i] && !visited[i]) { visited[i] = 1; DFS(i); } } */ void dfs(int now){ cout << now << ' '; for(int i = 1; i <= dots; i++){ if(matrix[now][i] && !is_visited[i]){ //never visited is_visited[i] = true; dfs(i); } } } /* void BFS(int idx) { q.push(idx); visited[idx] = 1; while (!q.empty()) { idx = q.front(); q.pop(); cout << idx << " "; for(int i=1; i<=N; i++) if (adjacent[idx][i] && !visited[i]) { visited[i] = 1; q.push(i); } } } */ void bfs(int idx){ queue<int> q; q.push(idx); is_visited[idx] = true; while(!q.empty()){ idx = q.front(); q.pop(); cout << idx << ' '; for(int i = 1; i <= dots; i++){ if(matrix[idx][i] && !is_visited[i]){ //never visited is_visited[i] = true; q.push(i); } } } } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> dots >> cons >> start; for(int i = 0; i < cons; i++){ int from, to; cin >> from >> to; matrix[from][to] = 1; matrix[to][from] = 1; } is_visited[start] = true; dfs(start); cout << endl; memset(is_visited, false, sizeof(bool) * 1005); bfs(start); cout << endl; return 0; }
1,988
732
#include "header/basic/test_macro.h" #include "header/model/wtg_models/wt_turbine_model/wt_turbine_model_test.h" #include "header/basic/utility.h" #include "header/steps_namespace.h" #include "header/model/wtg_models/wt_generator_model/wt3g0.h" #include "header/model/wtg_models/wt_aerodynamic_model/aerd0.h" #include <cstdlib> #include <cstring> #include <istream> #include <iostream> #include <cstdio> #include <cmath> #ifdef ENABLE_STEPS_TEST using namespace std; WT_TURBINE_MODEL_TEST::WT_TURBINE_MODEL_TEST() { TEST_ADD(WT_TURBINE_MODEL_TEST::test_get_model_type); TEST_ADD(WT_TURBINE_MODEL_TEST::test_set_get_damping); TEST_ADD(WT_TURBINE_MODEL_TEST::test_get_standard_psse_string); TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_underspeed_mode); TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_mppt_mode); TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_overspeed_mode); TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_underspeed_mode); TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_mppt_mode); TEST_ADD(WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_overspeed_mode); } void WT_TURBINE_MODEL_TEST::setup() { WTG_MODEL_TEST::setup(); DYNAMIC_MODEL_DATABASE& dmdb = default_toolkit.get_dynamic_model_database(); WT_GENERATOR* wt_gen = get_test_wt_generator(); wt_gen->set_p_generation_in_MW(28.0); wt_gen->set_rated_power_per_wt_generator_in_MW(1.5); wt_gen->set_number_of_lumped_wt_generators(20); WT3G0 genmodel(default_toolkit); genmodel.set_device_id(wt_gen->get_device_id()); genmodel.set_converter_activer_current_command_T_in_s(0.2); genmodel.set_converter_reactiver_voltage_command_T_in_s(0.2); genmodel.set_KPLL(20.0); genmodel.set_KIPLL(10.0); genmodel.set_PLLmax(0.1); LVPL lvpl; lvpl.set_low_voltage_in_pu(0.5); lvpl.set_high_voltage_in_pu(0.8); lvpl.set_gain_at_high_voltage(20.0); genmodel.set_LVPL(lvpl); genmodel.set_HVRC_voltage_in_pu(0.8); genmodel.set_HVRC_current_in_pu(20.0); genmodel.set_LVPL_max_rate_of_active_current_change(0.2); genmodel.set_LVPL_voltage_sensor_T_in_s(0.1); dmdb.add_model(&genmodel); AERD0 aeromodel(default_toolkit); aeromodel.set_device_id(wt_gen->get_device_id()); aeromodel.set_number_of_pole_pairs(2); aeromodel.set_generator_to_turbine_gear_ratio(100.0); aeromodel.set_gear_efficiency(1.0); aeromodel.set_turbine_blade_radius_in_m(25.0); aeromodel.set_nominal_wind_speed_in_mps(13.0); aeromodel.set_nominal_air_density_in_kgpm3(1.25); aeromodel.set_air_density_in_kgpm3(1.25); aeromodel.set_turbine_speed_mode(WT_UNDERSPEED_MODE); aeromodel.set_C1(0.22); aeromodel.set_C2(116.0); aeromodel.set_C3(0.4); aeromodel.set_C4(5.0); aeromodel.set_C5(12.5); aeromodel.set_C6(0.0); aeromodel.set_C1(0.5176); aeromodel.set_C2(116.0); aeromodel.set_C3(0.4); aeromodel.set_C4(5.0); aeromodel.set_C5(21.0); aeromodel.set_C6(0.0068); dmdb.add_model(&aeromodel); } void WT_TURBINE_MODEL_TEST::tear_down() { WTG_MODEL_TEST::tear_down(); } void WT_TURBINE_MODEL_TEST::test_get_model_type() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); TEST_ASSERT(model->get_model_type()=="WT TURBINE"); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::test_set_get_damping() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); model->set_damping_in_pu(0.0); TEST_ASSERT(fabs(model->get_damping_in_pu()-0.0)<FLOAT_EPSILON); model->set_damping_in_pu(1.0); TEST_ASSERT(fabs(model->get_damping_in_pu()-1.0)<FLOAT_EPSILON); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::test_get_standard_psse_string() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); model->get_standard_psse_string(); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_underspeed_mode() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt"); run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_underspeed_mode(); default_toolkit.close_log_file(); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_mppt_mode() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt"); run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_mppt_mode(); default_toolkit.close_log_file(); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_overspeed_mode() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt"); run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_overspeed_mode(); default_toolkit.close_log_file(); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_underspeed_mode() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt"); run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_underspeed_mode(); default_toolkit.close_log_file(); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_mppt_mode() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt"); run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_mppt_mode(); default_toolkit.close_log_file(); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::test_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_overspeed_mode() { WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); if(model!=NULL) { show_test_information_for_function_of_class(__FUNCTION__,model->get_model_name()+"_TEST"); default_toolkit.open_log_file("test_log/"+model->get_model_name()+"_"+__FUNCTION__+".txt"); run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_overspeed_mode(); default_toolkit.close_log_file(); } else TEST_ASSERT(false); } void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_underspeed_mode() { ostringstream osstream; double delt = 0.001; default_toolkit.set_dynamic_simulation_time_step_in_s(delt); WT_GENERATOR* genptr = get_test_wt_generator(); if(genptr==NULL) cout<<"Fatal error. No WT_GENERATOR is found in "<<__FUNCTION__<<endl; WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); if(genmodel==NULL) cout<<"Fatal error. No WT_GENERATOR_MODEL is found in "<<__FUNCTION__<<endl; genmodel->initialize(); WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model(); aeromodel->set_turbine_speed_mode(WT_UNDERSPEED_MODE); WT_TURBINE_MODEL*model = get_test_wt_turbine_model(); osstream<<"Model:"<<model->get_standard_psse_string()<<endl; default_toolkit.show_information_with_leading_time_stamp(osstream); default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt); double generator_speed; model->initialize(); generator_speed = model->get_generator_speed_in_pu(); export_meter_title(); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } model->run(UPDATE_MODE); export_meter_values(); } apply_1deg_pitch_angle_increase(); model->run(UPDATE_MODE); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } model->run(UPDATE_MODE); export_meter_values(); } } void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_mppt_mode() { ostringstream osstream; double delt = 0.001; default_toolkit.set_dynamic_simulation_time_step_in_s(delt); WT_GENERATOR* genptr = get_test_wt_generator(); if(genptr==NULL) cout<<"Fatal error. No WT_GENERATOR is found in "<<__FUNCTION__<<endl; WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); if(genmodel==NULL) cout<<"Fatal error. No WT_GENERATOR_MODEL is found in "<<__FUNCTION__<<endl; genmodel->initialize(); WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model(); aeromodel->set_turbine_speed_mode(WT_MPPT_MODE); WT_TURBINE_MODEL*model = get_test_wt_turbine_model(); osstream<<"Model:"<<model->get_standard_psse_string()<<endl; default_toolkit.show_information_with_leading_time_stamp(osstream); default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt); double generator_speed; model->initialize(); generator_speed = model->get_generator_speed_in_pu(); export_meter_title(); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } model->run(UPDATE_MODE); export_meter_values(); } apply_1deg_pitch_angle_increase(); model->run(UPDATE_MODE); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } model->run(UPDATE_MODE); export_meter_values(); } } void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_pitch_angle_increase_in_overspeed_mode() { ostringstream osstream; double delt = 0.001; default_toolkit.set_dynamic_simulation_time_step_in_s(delt); WT_GENERATOR* genptr = get_test_wt_generator(); if(genptr==NULL) cout<<"Fatal error. No WT_GENERATOR is found in "<<__FUNCTION__<<endl; WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); if(genmodel==NULL) cout<<"Fatal error. No WT_GENERATOR_MODEL is found in "<<__FUNCTION__<<endl; genmodel->initialize(); WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model(); aeromodel->set_turbine_speed_mode(WT_OVERSPEED_MODE); WT_TURBINE_MODEL*model = get_test_wt_turbine_model(); osstream<<"Model:"<<model->get_standard_psse_string()<<endl; default_toolkit.show_information_with_leading_time_stamp(osstream); default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt); double generator_speed; model->initialize(); generator_speed = model->get_generator_speed_in_pu(); export_meter_title(); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } model->run(UPDATE_MODE); export_meter_values(); } apply_1deg_pitch_angle_increase(); model->run(UPDATE_MODE); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } model->run(UPDATE_MODE); export_meter_values(); } } void WT_TURBINE_MODEL_TEST::apply_1deg_pitch_angle_increase() { WT_AERODYNAMIC_MODEL* aero_model = get_test_wt_aerodynamic_model(); if (aero_model != NULL) aero_model->set_initial_pitch_angle_in_deg(aero_model->get_initial_pitch_angle_in_deg() + 1.0); else { cout << "Fatal error. No WT_AERODYNAMIC_MODEL is found in " << __FUNCTION__ << endl; return; } } void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_underspeed_mode() { ostringstream osstream; double delt = 0.001; default_toolkit.set_dynamic_simulation_time_step_in_s(delt); WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); genmodel->initialize(); WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model(); aeromodel->set_turbine_speed_mode(WT_UNDERSPEED_MODE); WT_TURBINE_MODEL*model = get_test_wt_turbine_model(); osstream<<"Model:"<<model->get_standard_psse_string()<<endl; default_toolkit.show_information_with_leading_time_stamp(osstream); default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt); double generator_speed; model->initialize(); generator_speed = model->get_generator_speed_in_pu(); export_meter_title(); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { genmodel->run(INTEGRATE_MODE); model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); } apply_10_percent_power_order_drop(); genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { genmodel->run(INTEGRATE_MODE); model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); } } void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_mppt_mode() { ostringstream osstream; double delt = 0.001; default_toolkit.set_dynamic_simulation_time_step_in_s(delt); WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); genmodel->initialize(); WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model(); aeromodel->set_turbine_speed_mode(WT_MPPT_MODE); WT_TURBINE_MODEL*model = get_test_wt_turbine_model(); osstream<<"Model:"<<model->get_standard_psse_string()<<endl; default_toolkit.show_information_with_leading_time_stamp(osstream); default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt); double generator_speed; model->initialize(); generator_speed = model->get_generator_speed_in_pu(); export_meter_title(); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { genmodel->run(INTEGRATE_MODE); model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); } apply_10_percent_power_order_drop(); genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { genmodel->run(INTEGRATE_MODE); model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); } } void WT_TURBINE_MODEL_TEST::run_step_response_of_wt_turbine_model_with_generator_power_order_drop_in_overspeed_mode() { ostringstream osstream; double delt = 0.001; default_toolkit.set_dynamic_simulation_time_step_in_s(delt); WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); genmodel->initialize(); WT_AERODYNAMIC_MODEL* aeromodel = get_test_wt_aerodynamic_model(); aeromodel->set_turbine_speed_mode(WT_OVERSPEED_MODE); WT_TURBINE_MODEL*model = get_test_wt_turbine_model(); osstream<<"Model:"<<model->get_standard_psse_string()<<endl; default_toolkit.show_information_with_leading_time_stamp(osstream); default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-2.0*delt); double generator_speed; model->initialize(); generator_speed = model->get_generator_speed_in_pu(); export_meter_title(); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>1.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { genmodel->run(INTEGRATE_MODE); model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); } apply_10_percent_power_order_drop(); genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); while(true) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()+delt); if(default_toolkit.get_dynamic_simulation_time_in_s()>6.0+FLOAT_EPSILON) { default_toolkit.set_dynamic_simulation_time_in_s(default_toolkit.get_dynamic_simulation_time_in_s()-delt); break; } generator_speed = model->get_generator_speed_in_pu(); while(true) { genmodel->run(INTEGRATE_MODE); model->run(INTEGRATE_MODE); if(fabs(generator_speed-model->get_generator_speed_in_pu())>1e-6) generator_speed = model->get_generator_speed_in_pu(); else break; } genmodel->run(UPDATE_MODE); model->run(UPDATE_MODE); export_meter_values(); } } void WT_TURBINE_MODEL_TEST::apply_10_percent_power_order_drop() { WT_GENERATOR_MODEL* genmodel = get_test_wt_generator_model(); double ipcmd = genmodel->get_initial_active_current_command_in_pu_based_on_mbase(); genmodel->set_initial_active_current_command_in_pu_based_on_mbase(ipcmd*0.9); } void WT_TURBINE_MODEL_TEST::export_meter_title() { ostringstream osstream; osstream<<"TIME\tPELEC\tPMECH\tTSPEED\tGSPEED\tANGLE"; default_toolkit.show_information_with_leading_time_stamp(osstream); } void WT_TURBINE_MODEL_TEST::export_meter_values() { ostringstream osstream; WT_TURBINE_MODEL* model = get_test_wt_turbine_model(); osstream<<setw(10)<<setprecision(6)<<fixed<<default_toolkit.get_dynamic_simulation_time_in_s()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_wt_generator_active_power_generation_in_MW()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_mechanical_power_in_pu_from_wt_aerodynamic_model()*model->get_mbase_in_MVA()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_turbine_speed_in_pu()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_generator_speed_in_pu()<<"\t" <<setw(10)<<setprecision(6)<<fixed<<model->get_rotor_angle_in_deg(); default_toolkit.show_information_with_leading_time_stamp(osstream); } #endif
26,783
10,234
#include <boost/spirit/home/qi/auxiliary/attr_cast.hpp>
56
24
/* * Copyright (c) 2012-2019 Devin Smith <devin@devinsmith.net> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <curl/curl.h> #include <curl/easy.h> #include <cstring> #include <cstdlib> #include <string> #include "services/http.h" #include "utils/logging.h" namespace http { /* HTTP Services version 1.102 (06-17-2019) */ struct http_context { HttpRequest *req; HttpResponse *resp; }; /* Modern Chrome on Windows 10 */ static const char *chrome_win10_ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.90 Safari/537.36"; #ifdef _WIN32 #define WAITMS(x) Sleep(x) #else /* Portable sleep for platforms other than Windows. */ #define WAITMS(x) \ struct timeval wait { 0, (x) * 1000 }; \ (void)select(0, NULL, NULL, NULL, &wait); #endif void http_lib_startup(void) { curl_global_init(CURL_GLOBAL_ALL); } void http_lib_shutdown(void) { } HttpExecutor::HttpExecutor() { m_multi_handle = curl_multi_init(); } HttpExecutor::~HttpExecutor() { curl_multi_cleanup(m_multi_handle); } /* Private generic response reading function */ static size_t dk_httpread(char *ptr, size_t size, size_t nmemb, HttpResponse *hr) { size_t totalsz = size * nmemb; if (strstr(ptr, "HTTP/1.1 100 Continue")) return totalsz; hr->body.append((char *)ptr, totalsz); return totalsz; } const char * http_get_error_str(int error_code) { return curl_easy_strerror((CURLcode)error_code); } static int curl_debug_func(CURL *hnd, curl_infotype info, char *data, size_t len, http_context *ctx) { std::string hdr; std::string::size_type n; switch (info) { case CURLINFO_HEADER_OUT: if (ctx->req->verbose()) { std::string verb(data, len); log_msgraw(0, "H>: %s", verb.c_str()); } ctx->req->req_hdrs.append(data, len); break; case CURLINFO_TEXT: if (ctx->req->verbose()) { std::string verb(data, len); log_msgraw(0, "T: %s", verb.c_str()); } break; case CURLINFO_HEADER_IN: hdr = std::string(data, len); if (ctx->req->verbose()) { log_msgraw(0, "H<: %s", hdr.c_str()); } n = hdr.find('\r'); if (n != std::string::npos) { hdr.erase(n); } n = hdr.find('\n'); if (n != std::string::npos) { hdr.erase(n); } ctx->resp->headers.push_back(hdr); break; case CURLINFO_DATA_IN: if (ctx->req->verbose()) { std::string verb(data, len); log_msgraw(0, "<: %s", verb.c_str()); } break; case CURLINFO_DATA_OUT: if (ctx->req->verbose()) { std::string verb(data, len); log_msgraw(0, ">: %s", verb.c_str()); } break; default: break; } return 0; } static CURLcode easy_perform(CURLM *mhnd, CURL *hnd) { CURLcode result = CURLE_OK; CURLMcode mcode = CURLM_OK; int done = 0; /* bool */ if (curl_multi_add_handle(mhnd, hnd)) { return CURLE_FAILED_INIT; } while (!done && mcode == 0) { int still_running = 0; int rc; mcode = curl_multi_wait(mhnd, NULL, 0, 1000, &rc); if (mcode == 0) { if (rc == 0) { long sleep_ms; /* If it returns without any file descriptor instantly, we need to * avoid busy looping during periods where it has nothing particular * to wait for. */ curl_multi_timeout(mhnd, &sleep_ms); if (sleep_ms) { if (sleep_ms > 1000) sleep_ms = 1000; WAITMS(sleep_ms); } } mcode = curl_multi_perform(mhnd, &still_running); } /* Only read still-running if curl_multi_perform returns ok */ if (!mcode && still_running == 0) { CURLMsg *msg = curl_multi_info_read(mhnd, &rc); if (msg) { result = msg->data.result; done = 1; } } } if (mcode != 0) { if ((int)mcode == CURLM_OUT_OF_MEMORY) result = CURLE_OUT_OF_MEMORY; else result = CURLE_BAD_FUNCTION_ARGUMENT; } curl_multi_remove_handle(mhnd, hnd); return result; } void HttpRequest::set_content(const char *content_type) { std::string ctype_hdr = "Content-Type: "; ctype_hdr.append(content_type); m_headers = curl_slist_append(m_headers, ctype_hdr.c_str()); } HttpResponse HttpRequest::exec(const char *method, const char *data, HttpExecutor& executor) { struct http_context ctx; HttpResponse resp; if (strcmp(method, "GET") == 0) { curl_easy_setopt(m_handle, CURLOPT_HTTPGET, 1); } else if (strcmp(method, "POST") == 0) { curl_easy_setopt(m_handle, CURLOPT_POST, 1); } else { curl_easy_setopt(m_handle, CURLOPT_CUSTOMREQUEST, method); } if (data != NULL) { curl_easy_setopt(m_handle, CURLOPT_POSTFIELDS, data); curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, (long)strlen(data)); } else { curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, 0); } curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str()); curl_easy_setopt(m_handle, CURLOPT_HTTPHEADER, m_headers); curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_user_agent.c_str()); ctx.resp = &resp; ctx.req = this; curl_easy_setopt(m_handle, CURLOPT_DEBUGFUNCTION, curl_debug_func); curl_easy_setopt(m_handle, CURLOPT_DEBUGDATA, &ctx); curl_easy_setopt(m_handle, CURLOPT_VERBOSE, 1); curl_easy_setopt(m_handle, CURLOPT_FAILONERROR, 0); /* Verification of SSL is disabled on Windows. This is a limitation of * curl */ curl_easy_setopt(m_handle, CURLOPT_SSL_VERIFYHOST, 0); curl_easy_setopt(m_handle, CURLOPT_SSL_VERIFYPEER, 0); curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, &resp); curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION, dk_httpread); CURLcode res = easy_perform(executor.handle(), m_handle); if (res != CURLE_OK) { log_tmsg(0, "Failure performing request"); } curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &resp.status_code); curl_easy_getinfo(m_handle, CURLINFO_TOTAL_TIME, &elapsed); resp.elapsed = elapsed; return resp; } static size_t write_file(void *ptr, size_t size, size_t nmemb, FILE *stream) { size_t written = fwrite(ptr, size, nmemb, stream); return written; } bool HttpRequest::get_file(const char *file) { FILE *fp; fp = fopen(file, "w"); if (fp == NULL) { return false; } bool ret = get_file_fp(fp); fclose(fp); return ret; } bool HttpRequest::get_file_fp(FILE *fp) { long status_code; curl_easy_setopt(m_handle, CURLOPT_HTTPGET, 1); curl_easy_setopt(m_handle, CURLOPT_POSTFIELDSIZE, 0); curl_easy_setopt(m_handle, CURLOPT_URL, m_url.c_str()); curl_easy_setopt(m_handle, CURLOPT_HTTPHEADER, m_headers); curl_easy_setopt(m_handle, CURLOPT_USERAGENT, m_user_agent.c_str()); curl_easy_setopt(m_handle, CURLOPT_FAILONERROR, 0); curl_easy_setopt(m_handle, CURLOPT_WRITEDATA, fp); curl_easy_setopt(m_handle, CURLOPT_WRITEFUNCTION, write_file); curl_easy_setopt(m_handle, CURLOPT_FOLLOWLOCATION, 1L); CURLcode res = easy_perform(HttpExecutor::default_instance().handle(), m_handle); if (res != CURLE_OK) { log_tmsg(0, "Failure performing request"); } curl_easy_getinfo(m_handle, CURLINFO_RESPONSE_CODE, &status_code); curl_easy_getinfo(m_handle, CURLINFO_TOTAL_TIME, &elapsed); return true; } HttpRequest::HttpRequest(const std::string &url, bool verbose) : m_headers(NULL), m_url(url), m_verbose(verbose), m_user_agent(chrome_win10_ua) { m_handle = curl_easy_init(); } void HttpRequest::set_cert(const std::string &cert, const std::string &key) { curl_easy_setopt(m_handle, CURLOPT_SSLCERT, cert.c_str()); curl_easy_setopt(m_handle, CURLOPT_SSLKEY, key.c_str()); } void HttpRequest::set_basic_auth(const std::string &user, const std::string &pass) { curl_easy_setopt(m_handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_easy_setopt(m_handle, CURLOPT_USERNAME, user.c_str()); curl_easy_setopt(m_handle, CURLOPT_PASSWORD, pass.c_str()); } void HttpRequest::set_ntlm(const std::string &username, const std::string& password) { curl_easy_setopt(m_handle, CURLOPT_HTTPAUTH, CURLAUTH_NTLM); curl_easy_setopt(m_handle, CURLOPT_USERNAME, username.c_str()); curl_easy_setopt(m_handle, CURLOPT_PASSWORD, password.c_str()); } void HttpRequest::add_header(const char *key, const char *value) { char maxheader[2048]; snprintf(maxheader, sizeof(maxheader), "%s: %s", key, value); m_headers = curl_slist_append(m_headers, maxheader); } HttpRequest::~HttpRequest() { curl_easy_cleanup(m_handle); curl_slist_free_all(m_headers); } } // namespace http
9,153
3,618
/* Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related documentation without an express license agreement from NVIDIA CORPORATION is strictly prohibited. */ #include "engine/core/math/so3.hpp" #include <vector> #include "engine/core/constants.hpp" #include "engine/core/math/quaternion.hpp" #include "engine/core/math/types.hpp" #include "engine/gems/math/test_utils.hpp" #include "gtest/gtest.h" namespace isaac { TEST(SO3, composition) { SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 1.0, 3.0)); SO3d rot2 = SO3d::FromAngleAxis(1.7, Vector3d(1.0, 1.0, 3.0)); SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(1.0, 1.0, 3.0)); SO3d rot4 = SO3d::FromAngleAxis(0.535, Vector3d(1.0, 1.0, 3.0)); EXPECT_NEAR((rot1 * rot2 * rot3 * rot4).angle(), SO3d::FromAngleAxis(rot1.angle() + rot2.angle() + rot3.angle() + rot4.angle(), Vector3d(1.0, 1.0, 3.0)).angle(), 1e-7); } TEST(SO3, angle) { SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 0.0, 0.0)); SO3d rot2 = SO3d::FromAngleAxis(-1.7, Vector3d(0.0, 1.0, 0.0)); SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(0.0, 0.0, 1.0)); SO3d rot4 = SO3d::FromAngleAxis(-0.535, Vector3d(1.0, 1.0, 1.0)); EXPECT_NEAR(rot1.angle(), 1.1, 1e-7); EXPECT_NEAR(rot2.angle(), 1.7, 1e-7); EXPECT_NEAR(rot3.angle(), 2.5, 1e-7); EXPECT_NEAR(rot4.angle(), 0.535, 1e-7); } TEST(SO3, inverse) { SO3d rot1 = SO3d::FromAngleAxis(1.1, Vector3d(1.0, 0.0, 0.0)); SO3d rot2 = SO3d::FromAngleAxis(1.7, Vector3d(0.0, 1.0, 0.0)); SO3d rot3 = SO3d::FromAngleAxis(2.5, Vector3d(0.0, 0.0, 1.0)); SO3d rot4 = SO3d::FromAngleAxis(0.535, Vector3d(1.0, 1.0, 1.0)); EXPECT_NEAR(rot1.inverse().angle(), rot1.angle(), 1e-7); EXPECT_NEAR(rot2.inverse().angle(), rot2.angle(), 1e-7); EXPECT_NEAR(rot3.inverse().angle(), rot3.angle(), 1e-7); EXPECT_NEAR(rot4.inverse().angle(), rot4.angle(), 1e-7); EXPECT_NEAR((rot1.inverse().axis()+rot1.axis()).norm(), 0.0, 1e-7) << rot1.axis() << " vs " << rot1.inverse().axis(); EXPECT_NEAR((rot2.inverse().axis()+rot2.axis()).norm(), 0.0, 1e-7) << rot2.axis() << " vs " << rot2.inverse().axis(); EXPECT_NEAR((rot3.inverse().axis()+rot3.axis()).norm(), 0.0, 1e-7) << rot3.axis() << " vs " << rot3.inverse().axis(); EXPECT_NEAR((rot4.inverse().axis()+rot4.axis()).norm(), 0.0, 1e-7) << rot4.axis() << " vs " << rot4.inverse().axis(); } TEST(SO3, vector) { Vector3d vec1 = SO3d::FromAngleAxis(Pi<double>/2, Vector3d(0.0, 0.0, 1.0)) * Vector3d(1.0, 2.0, 3.0); EXPECT_NEAR(vec1.x(), -2.0, 1e-7); EXPECT_NEAR(vec1.y(), 1.0, 1e-7); EXPECT_NEAR(vec1.z(), 3.0, 1e-7); } TEST(SO3, euler_angles) { enum EulerAngles { kRoll = 0, kPitch = 1, kYaw = 2 }; constexpr double roll = 1.1; constexpr double pitch = 1.7; constexpr double yaw = 2.5; SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0)); SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0)); SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0)); SO3d rot4 = rot1 * rot2 *rot3; Vector3d rot1_euler = rot1.eulerAnglesRPY(); Vector3d rot2_euler = rot2.eulerAnglesRPY(); Vector3d rot3_euler = rot3.eulerAnglesRPY(); Vector3d rot4_euler = rot4.eulerAnglesRPY(); EXPECT_NEAR(rot1_euler[kRoll], roll, 1e-7); EXPECT_NEAR(rot1_euler[kPitch], 0.0, 1e-7); EXPECT_NEAR(rot1_euler[kYaw], 0.0, 1e-7); EXPECT_NEAR(rot2_euler[kRoll], 0.0, 1e-7); EXPECT_NEAR(rot2_euler[kPitch], pitch, 1e-7); EXPECT_NEAR(rot2_euler[kYaw], 0.0, 1e-7); EXPECT_NEAR(rot3_euler[kRoll], 0.0, 1e-7); EXPECT_NEAR(rot3_euler[kPitch], 0.0, 1e-7); EXPECT_NEAR(rot3_euler[kYaw], yaw, 1e-7); EXPECT_NEAR(rot4_euler[kRoll], roll, 1e-7); EXPECT_NEAR(rot4_euler[kPitch], pitch, 1e-7); EXPECT_NEAR(rot4_euler[kYaw], yaw, 1e-7); } TEST(SO3, euler_angles_close_zero) { enum EulerAngles { kRoll = 0, kPitch = 1, kYaw = 2 }; for (double roll = -Pi<double> * 0.25; roll < Pi<double> * 0.25; roll += Pi<double> * 0.05) { for (double pitch = -Pi<double> * 0.25; pitch < Pi<double> * 0.25; pitch += Pi<double> * 0.05) { for (double yaw = -Pi<double> * 0.25; yaw < Pi<double> * 0.25; yaw += Pi<double> * 0.05) { const SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0)); const SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0)); const SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0)); const SO3d rot4 = rot1 * rot2 *rot3; const Vector3d rot4_euler = rot4.eulerAnglesRPY(); EXPECT_NEAR(rot4_euler[kRoll], roll, 1e-7); EXPECT_NEAR(rot4_euler[kPitch], pitch, 1e-7); EXPECT_NEAR(rot4_euler[kYaw], yaw, 1e-7); } } } } TEST(SO3, euler_angles_conversion) { enum EulerAngles { kRoll = 0, kPitch = 1, kYaw = 2 }; constexpr double roll = 1.1; constexpr double pitch = 1.7; constexpr double yaw = 2.5; const SO3d so3 = SO3d::FromEulerAnglesRPY(roll, pitch, yaw); const Vector3d euler_angles = so3.eulerAnglesRPY(); EXPECT_NEAR(euler_angles[kRoll], roll, 1e-7); EXPECT_NEAR(euler_angles[kPitch], pitch, 1e-7); EXPECT_NEAR(euler_angles[kYaw], yaw, 1e-7); } TEST(SO3, rotation_jacobian) { Vector3d v = Vector3d::Random(); for (double roll = -Pi<double> * 0.25; roll < Pi<double> * 0.25; roll += Pi<double> * 0.05) { for (double pitch = -Pi<double> * 0.25; pitch < Pi<double> * 0.25; pitch += Pi<double> * 0.05) { for (double yaw = -Pi<double> * 0.25; yaw < Pi<double> * 0.25; yaw += Pi<double> * 0.05) { const SO3d rot1 = SO3d::FromAngleAxis(roll, Vector3d(1.0, 0.0, 0.0)); const SO3d rot2 = SO3d::FromAngleAxis(pitch, Vector3d(0.0, 1.0, 0.0)); // const SO3d rot3 = SO3d::FromAngleAxis(yaw, Vector3d(0.0, 0.0, 1.0)); const SO3d rot4 = rot1 * rot2; Matrix<double, 3, 4> result_a = rot4.vectorRotationJacobian(v); Matrix<double, 3, 4> result_b = rot1.matrix() * rot2.vectorRotationJacobian(v); Matrix<double, 3, 4> result_c = (QuaternionProductMatrixLeft(rot1.quaternion()) * result_b.transpose()).transpose(); for (int j = 0; j < result_a.cols(); j++) { ISAAC_EXPECT_VEC_NEAR(result_a.col(j), result_c.col(j), 1e-3); } } } } } } // namespace isaac
6,620
3,209
/** * This file is part of ORB-SLAM3 * * Copyright (C) 2017-2020 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza. * Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza. * * ORB-SLAM3 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ORB-SLAM3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with ORB-SLAM3. * If not, see <http://www.gnu.org/licenses/>. */ #include<iostream> #include<algorithm> #include<fstream> #include<chrono> #include<vector> #include<queue> #include<thread> #include<mutex> #include<ros/ros.h> #include<cv_bridge/cv_bridge.h> #include<sensor_msgs/Imu.h> #include<opencv2/core/core.hpp> #include"../../../include/System.h" #include"../include/ImuTypes.h" #include <geometry_msgs/PoseStamped.h> using namespace std; class ImuGrabber { public: ImuGrabber(){}; void GrabImu(const sensor_msgs::ImuConstPtr &imu_msg); queue<sensor_msgs::ImuConstPtr> imuBuf; std::mutex mBufMutex; }; class ImageGrabber { ros::NodeHandle nh; //定义句柄初始化 ros::Publisher pub1,pub_tcw; //定义发布者 public: ImageGrabber(ORB_SLAM3::System* pSLAM, ImuGrabber *pImuGb, const bool bClahe): mpSLAM(pSLAM), mpImuGb(pImuGb), mbClahe(bClahe),nh("~") { pub_tcw= nh.advertise<geometry_msgs::PoseStamped> ("CameraPose", 10); } void GrabImage(const sensor_msgs::ImageConstPtr& msg); cv::Mat GetImage(const sensor_msgs::ImageConstPtr &img_msg); void SyncWithImu(); queue<sensor_msgs::ImageConstPtr> img0Buf; std::mutex mBufMutex; ORB_SLAM3::System* mpSLAM; ImuGrabber *mpImuGb; const bool mbClahe; cv::Ptr<cv::CLAHE> mClahe = cv::createCLAHE(3.0, cv::Size(8, 8)); }; int main(int argc, char **argv) { ros::init(argc, argv, "Mono_Inertial"); ros::NodeHandle n("~"); ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Info); bool bEqual = false; if(argc < 1 || argc > 2) { cerr << endl << "Usage: rosrun ORB_SLAM3 Mono_Inertial path_to_vocabulary path_to_settings [do_equalize]" << endl; ros::shutdown(); return 1; } if(argc==1) { std::string sbEqual(argv[3]); if(sbEqual == "true") bEqual = true; } string ORBvoc_path = "/home/lin/code/ORB_SLAM3/Vocabulary/ORBvoc.txt"; string config_path = "/home/lin/code/ORB_SLAM3/Examples/ROS/ORB_SLAM3/src/cam_inertial.yaml"; // Create SLAM system. It initializes all system threads and gets ready to process frames. ORB_SLAM3::System SLAM(ORBvoc_path,config_path,ORB_SLAM3::System::IMU_MONOCULAR,true); ImuGrabber imugb; ImageGrabber igb(&SLAM,&imugb,bEqual); // TODO // Maximum delay, 5 seconds ros::Subscriber sub_imu = n.subscribe("/android/imu", 1000, &ImuGrabber::GrabImu, &imugb); ros::Subscriber sub_img0 = n.subscribe("/usb_cam/image_raw", 100, &ImageGrabber::GrabImage,&igb); std::thread sync_thread(&ImageGrabber::SyncWithImu,&igb); ros::spin(); return 0; } void ImageGrabber::GrabImage(const sensor_msgs::ImageConstPtr &img_msg) { mBufMutex.lock(); if (!img0Buf.empty()) img0Buf.pop(); img0Buf.push(img_msg); mBufMutex.unlock(); } cv::Mat ImageGrabber::GetImage(const sensor_msgs::ImageConstPtr &img_msg) { // Copy the ros image message to cv::Mat. cv_bridge::CvImageConstPtr cv_ptr; try { cv_ptr = cv_bridge::toCvShare(img_msg, sensor_msgs::image_encodings::MONO8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); } if(cv_ptr->image.type()==0) { return cv_ptr->image.clone(); } else { std::cout << "Error type" << std::endl; return cv_ptr->image.clone(); } } void ImageGrabber::SyncWithImu() { while(1) { cv::Mat im; double tIm = 0; if (!img0Buf.empty()&&!mpImuGb->imuBuf.empty()) { tIm = img0Buf.front()->header.stamp.toSec(); if(tIm>mpImuGb->imuBuf.back()->header.stamp.toSec()) continue; { this->mBufMutex.lock(); im = GetImage(img0Buf.front()); img0Buf.pop(); this->mBufMutex.unlock(); } vector<ORB_SLAM3::IMU::Point> vImuMeas; mpImuGb->mBufMutex.lock(); // if(!mpImuGb->imuBuf.empty()) // { // // Load imu measurements from buffer // vImuMeas.clear(); // while(!mpImuGb->imuBuf.empty() && mpImuGb->imuBuf.front()->header.stamp.toSec()<=tIm) // { // double t = mpImuGb->imuBuf.front()->header.stamp.toSec(); // cv::Point3f acc(mpImuGb->imuBuf.front()->linear_acceleration.x, mpImuGb->imuBuf.front()->linear_acceleration.y, mpImuGb->imuBuf.front()->linear_acceleration.z); // cv::Point3f gyr(mpImuGb->imuBuf.front()->angular_velocity.x, mpImuGb->imuBuf.front()->angular_velocity.y, mpImuGb->imuBuf.front()->angular_velocity.z); // vImuMeas.push_back(ORB_SLAM3::IMU::Point(acc,gyr,t)); // mpImuGb->imuBuf.pop(); // } // } // 时间对齐 if(!mpImuGb->imuBuf.empty()) { // Load imu measurements from buffer vImuMeas.clear(); static bool time_flag = true; static auto TIME_OFFSET = 0.0; if(time_flag){ TIME_OFFSET = mpImuGb->imuBuf.front()->header.stamp.toSec()-tIm; time_flag = false; } cout<<"imu_time: "<<setprecision(11)<<mpImuGb->imuBuf.front()->header.stamp.toSec()-TIME_OFFSET<<endl; cout<<"image_time: "<<setprecision(11)<<tIm<<endl; cout<<"---------------"<<endl; while(!mpImuGb->imuBuf.empty() && mpImuGb->imuBuf.front()->header.stamp.toSec()-TIME_OFFSET<=tIm) { double t = mpImuGb->imuBuf.front()->header.stamp.toSec() - TIME_OFFSET; cv::Point3f acc(mpImuGb->imuBuf.front()->linear_acceleration.x, mpImuGb->imuBuf.front()->linear_acceleration.y, mpImuGb->imuBuf.front()->linear_acceleration.z); cv::Point3f gyr(mpImuGb->imuBuf.front()->angular_velocity.x, mpImuGb->imuBuf.front()->angular_velocity.y, mpImuGb->imuBuf.front()->angular_velocity.z); cout<<"imudata: "<< t<<" "<<acc.x<<" "<<acc.y<<" "<<acc.z<<" "<<gyr.x<<" "<<gyr.y<<" "<<gyr.z<<endl; vImuMeas.push_back(ORB_SLAM3::IMU::Point(acc,gyr,t)); mpImuGb->imuBuf.pop(); } } mpImuGb->mBufMutex.unlock(); if(mbClahe) mClahe->apply(im,im); cv::resize(im,im,cv::Size(640,480)); // if(cv::waitKey(10)=='q') // break; cv::Mat Tcw; Tcw = mpSLAM->TrackMonocular(im,tIm,vImuMeas); if(!Tcw.empty()) { cv::Mat Twc =Tcw.inv(); cv::Mat RWC= Twc.rowRange(0,3).colRange(0,3); cv::Mat tWC= Twc.rowRange(0,3).col(3); Eigen::Matrix<double,3,3> eigMat ; eigMat <<RWC.at<float>(0,0),RWC.at<float>(0,1),RWC.at<float>(0,2), RWC.at<float>(1,0),RWC.at<float>(1,1),RWC.at<float>(1,2), RWC.at<float>(2,0),RWC.at<float>(2,1),RWC.at<float>(2,2); Eigen::Quaterniond q(eigMat); geometry_msgs::PoseStamped tcw_msg; tcw_msg.pose.position.x=tWC.at<float>(0); tcw_msg.pose.position.y=tWC.at<float>(1); tcw_msg.pose.position.z=tWC.at<float>(2); tcw_msg.pose.orientation.x=q.x(); tcw_msg.pose.orientation.y=q.y(); tcw_msg.pose.orientation.z=q.z(); tcw_msg.pose.orientation.w=q.w(); pub_tcw.publish(tcw_msg); } else { cout<<"Twc is empty ..."<<endl; } } std::chrono::milliseconds tSleep(1); std::this_thread::sleep_for(tSleep); } } void ImuGrabber::GrabImu(const sensor_msgs::ImuConstPtr &imu_msg) { mBufMutex.lock(); imuBuf.push(imu_msg); mBufMutex.unlock(); return; }
8,354
3,588
#include "DataStreamException.h" DataStreamException::DataStreamException(const char * message) : BaseException(message) { }
131
39
// Copyright (c) 2016 Vittorio Romeo // License: AFL 3.0 | https://opensource.org/licenses/AFL-3.0 // http://vittorioromeo.info | vittorio.romeo@outlook.com #pragma once #include "./static_if.hpp" namespace impl { namespace action { struct a_continue { }; struct a_break { }; } template <typename TItr, typename TAcc, typename TAction> struct state { constexpr auto iteration() const noexcept { return TItr{}; } constexpr auto accumulator() const noexcept { return TAcc{}; } constexpr auto next_action() const noexcept { return TAction{}; } template <typename TNewAcc> constexpr auto continue_(TNewAcc) const noexcept; constexpr auto continue_() const noexcept; template <typename TNewAcc> constexpr auto break_(TNewAcc) const noexcept; constexpr auto break_() const noexcept; }; template <typename TItr, typename TAcc, typename TAction> constexpr auto make_state(TItr, TAcc, TAction) { return state<TItr, TAcc, TAction>{}; } template <typename TState, typename TAcc, typename TAction> constexpr auto advance_state(TState s, TAcc a, TAction na) { return make_state(sz_v<s.iteration() + 1>, a, na); } template <typename TItr, typename TAcc, typename TAction> template <typename TNewAcc> constexpr auto state<TItr, TAcc, TAction>::continue_( // . TNewAcc new_acc) const noexcept { return advance_state(*this, new_acc, action::a_continue{}); } template <typename TItr, typename TAcc, typename TAction> constexpr auto state<TItr, TAcc, TAction>::continue_( // . ) const noexcept { return continue_(accumulator()); } template <typename TItr, typename TAcc, typename TAction> template <typename TNewAcc> constexpr auto state<TItr, TAcc, TAction>::break_( // . TNewAcc new_acc) const noexcept { return advance_state(*this, new_acc, action::a_break{}); } template <typename TItr, typename TAcc, typename TAction> constexpr auto state<TItr, TAcc, TAction>::break_( // . ) const noexcept { return break_(accumulator()); } }
2,346
732
#include "manager.h" #include "commonhdr.h" #include "log.h" #include "caseinfomodel.h" #include "monitor.h" #include "iocontextwrapper.h" #include "datamanager.h" #include "logtext.h" #include "caseinfomodel.h" Manager::Manager(QObject *parent) : QObject(parent) { dataMgr_ = std::make_shared<DataManager>(); logText_ = std::make_shared<LogText>(); iocWrapper_ = std::make_shared<IOContextWrapper>(); monitor_ = std::make_shared<Monitor>(*iocWrapper_); thread_ = std::make_shared<MonitorThread>(*iocWrapper_, *monitor_, dataMgr_, this); dataMgr_->setMonitorThread(thread_); connect(logText_.get(), &LogText::addLog, this, &Manager::onAddLogText); connect(monitor_.get(), &Monitor::addText, this, &Manager::onAddMonitorText); connect(thread_.get(), &MonitorThread::enableRunButton, this, &Manager::onEnabledRunButton); connect(thread_.get(), &MonitorThread::enableStopButton, this, &Manager::onEnabledStopButton); connect(this, &Manager::stopProcess, thread_.get(), &MonitorThread::onStopProcess); } Manager::~Manager() { } void Manager::setDataMgr(CaseInfoModel* pModel) { model_ = pModel; pModel->setDataManger(dataMgr_); } void Manager::onAddMonitorText(const QString& s) { Q_EMIT addMonitorText(s); } void Manager::onEnabledRunButton(bool b) { Q_EMIT setEnabledRunButton(b); } void Manager::onEnabledStopButton(bool b) { Q_EMIT setEnabledStopButton(b); } void Manager::onAddLogText(const QString& s) { Q_EMIT addLogText(s); } QString Manager::getRootDir() { try { return QString::fromStdString(dataMgr_->getRootDir()); } catch (std::exception& e) { BOOST_LOG(processLog::get()) << e.what() << std::endl; return ""; } } void Manager::setRootDir(const QString& rootDir) { try { dataMgr_->setRootDir(rootDir.toStdString()); } catch (std::exception& e) { BOOST_LOG(processLog::get()) << e.what() << std::endl; } } QString Manager::getCases() { try { return QString::fromStdString(dataMgr_->getCases()); } catch (std::exception& e) { BOOST_LOG(processLog::get()) << e.what() << std::endl; } return {}; } void Manager::onCaseTextChanged(const QString& text) { try { auto listStr = text.split('\n', QString::SkipEmptyParts); std::set<std::string> cases; for(auto i = 0; i<listStr.size(); ++i) { QString s = listStr[i].trimmed(); cases.insert(s.toStdString()); } dataMgr_->clearCases(); dataMgr_->refine(cases); if(model_) { model_->updateData(); } } catch (std::exception& ec) { BOOST_LOG(processLog::get()) << ec.what() << std::endl; } } void Manager::start() { thread_->start(); } void Manager::stop() { Q_EMIT stopProcess(); }
2,924
1,043
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "Constants.hh" #include <fstream> #include <string> #define DEFINE_STRING(name, value) const std::string name { value }; const std::wstring name ## W { L ## value }; uint64_t Constants::_UniqueId { 0 }; namespace Constants { const std::string TIMESTAMP { "TIMESTAMP" }; const std::string PreciseTimeStamp { "PreciseTimeStamp" }; namespace Compression { const std::string lz4hc { "lz4hc" }; } // namespace Compression namespace EventCategory { const std::string Counter { "counter" }; const std::string Trace { "trace" }; } // namespace EventCategory namespace AzurePropertyNames { DEFINE_STRING(Namespace, "namespace") DEFINE_STRING(EventName, "eventname") DEFINE_STRING(EventVersion, "eventversion") DEFINE_STRING(EventCategory, "eventcategory") DEFINE_STRING(BlobVersion, "version") DEFINE_STRING(BlobFormat, "format") DEFINE_STRING(DataSize, "datasizeinbytes") DEFINE_STRING(BlobSize, "blobsizeinbytes") DEFINE_STRING(MonAgentVersion, "monagentversion") DEFINE_STRING(CompressionType, "compressiontype") DEFINE_STRING(MinLevel, "minlevel") DEFINE_STRING(AccountMoniker, "accountmoniker") DEFINE_STRING(Endpoint, "endpoint") DEFINE_STRING(OnbehalfFields, "onbehalffields") DEFINE_STRING(OnbehalfServiceId, "onbehalfid") DEFINE_STRING(OnbehalfAnnotations, "onbehalfannotations") } // namespace AzurePropertyNames uint64_t UniqueId() { static std::string digits { "0123456789ABCDEFabcdef" }; if (!Constants::_UniqueId) { std::ifstream bootid("/proc/sys/kernel/random/boot_id", std::ifstream::in); if (bootid.is_open()) { uint64_t id = 0; int nybbles = 16; while (nybbles && bootid.good()) { char c = bootid.get(); size_t pos = digits.find(c); if (pos != std::string::npos) { if (pos > 15) { pos -= 6; } id <<= 4; id += pos; nybbles--; } } if (id == 0) { id = 1; // Backstop in case something got weird } Constants::_UniqueId = id; } else { Constants::_UniqueId = 1; // Backstop in case something got weird } } return Constants::_UniqueId; } } // namespace Constants // vim: se sw=8 :
2,211
857
#include <iostream> #define SAMPLE_RATE 44100 using namespace std; /* Buffer Lineare ---------------------------------------------------------- */ float D_LinBuffer(float *buffer, int D, float x) { int i; for(i = D-1; i >= 1; i--) buffer[i] = buffer[i-1]; buffer[0] = x; return buffer[D-1]; } int main() { int i, D; const int N = 2000; float rit = 0.005, *buffer, *y, x[N]; for (i = 0; i < N; i++) x[i] = 2 * ((float)rand() / (float)RAND_MAX) - 1; D = (int)(rit*SAMPLE_RATE); buffer = (float *)calloc(D, sizeof(float)); y = (float *)calloc(N, sizeof(float)); for (i = 0; i < D; i++) buffer[i] = 0; for (i = 0; i < N; i++) y[i] = D_LinBuffer(buffer, D, x[i]); cout << "Posizione x y: " << endl << endl; for (i = 0; i < N; i++) cout << i + 1 << ": " << x[i] << " " << y[i] << endl; return 0; }
967
421
// (C) Copyright Gennadiy Rozental 2005-2014. // Use, modification, and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision$ // // Description : implements model of generic parameter with dual naming // *************************************************************************** #ifndef BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP #define BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP // Boost.Runtime.Parameter #include <boost/test/utils/runtime/config.hpp> #include <boost/test/utils/runtime/validation.hpp> #include <boost/test/utils/runtime/cla/dual_name_parameter.hpp> namespace boost { namespace BOOST_TEST_UTILS_RUNTIME_PARAM_NAMESPACE { namespace cla { // ************************************************************************** // // ************** dual_name_policy ************** // // ************************************************************************** // BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE dual_name_policy::dual_name_policy() { m_primary.accept_modifier( prefix = BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "--" ) ); m_secondary.accept_modifier( prefix = BOOST_TEST_UTILS_RUNTIME_PARAM_CSTRING_LITERAL( "-" ) ); } //____________________________________________________________________________// namespace { template<typename K> inline void split( string_name_policy& snp, char_name_policy& cnp, cstring src, K const& k ) { cstring::iterator sep = std::find( src.begin(), src.end(), BOOST_TEST_UTILS_RUNTIME_PARAM_LITERAL( '|' ) ); if( sep != src.begin() ) snp.accept_modifier( k = cstring( src.begin(), sep ) ); if( sep != src.end() ) cnp.accept_modifier( k = cstring( sep+1, src.end() ) ); } } // local namespace BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void dual_name_policy::set_prefix( cstring src ) { split( m_primary, m_secondary, src, prefix ); } //____________________________________________________________________________// BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void dual_name_policy::set_name( cstring src ) { split( m_primary, m_secondary, src, name ); } //____________________________________________________________________________// BOOST_TEST_UTILS_RUNTIME_PARAM_INLINE void dual_name_policy::set_separator( cstring src ) { split( m_primary, m_secondary, src, separator ); } //____________________________________________________________________________// } // namespace cla } // namespace BOOST_TEST_UTILS_RUNTIME_PARAM_NAMESPACE } // namespace boost #endif // BOOST_TEST_UTILS_RUNTIME_CLA_DUAL_NAME_PARAMETER_IPP
2,910
1,002
// File MCORE/MSynchronizer.cpp #include "MCOREExtern.h" #include "MSynchronizer.h" #include "MException.h" #if !M_NO_MULTITHREADING MSynchronizer::Locker::Locker(const MSynchronizer& s) : m_synchronizer(const_cast<MSynchronizer&>(s)), m_locked(false) { m_synchronizer.Lock(); m_locked = true; } MSynchronizer::Locker::Locker(const MSynchronizer& s, long timeout) : m_synchronizer(const_cast<MSynchronizer&>(s)), m_locked(false) { m_locked = m_synchronizer.LockWithTimeout(timeout); } MSynchronizer::Locker::~Locker() M_NO_THROW { if ( m_locked ) m_synchronizer.Unlock(); } MSynchronizer::~MSynchronizer() M_NO_THROW { #if (M_OS & M_OS_WIN32) if ( m_handle != 0 ) CloseHandle(m_handle); #elif (M_OS & M_OS_POSIX) // In Pthreads there are pthread_mutex_t and pthread_cond_t types for synchronization objects, they are destroyed in the derived classes #else #error "No implementation of semaphore exists for this OS" #endif } #if (M_OS & M_OS_WIN32) bool MSynchronizer::LockWithTimeout(long timeout) { M_ASSERT(m_handle != 0); switch( ::WaitForSingleObject(m_handle, timeout < 0 ? INFINITE : timeout) ) { case WAIT_OBJECT_0: return true; case WAIT_TIMEOUT: break; default: M_ASSERT(0); // An unknown code was returned once. Throw error in this case. case WAIT_FAILED: MESystemError::ThrowLastSystemError(); M_ENSURED_ASSERT(0); } return false; } #endif #if (M_OS & M_OS_WIN32) bool MSynchronizer::DoWaitForMany(long timeout, unsigned* which, MSynchronizer* p1, MSynchronizer* p2, MSynchronizer* p3, MSynchronizer* p4, MSynchronizer* p5) { M_ASSERT(p1 != NULL && p2 != NULL); HANDLE handles [ 5 ]; handles[0] = p1->m_handle; handles[1] = p2->m_handle; DWORD handlesCount; if ( p3 != NULL ) { handles[2] = p3->m_handle; if ( p4 != NULL ) { handles[3] = p4->m_handle; if ( p5 != NULL ) { handles[4] = p5->m_handle; handlesCount = 5; } else handlesCount = 4; } else { M_ASSERT(p5 == NULL); handlesCount = 3; } } else { M_ASSERT(p4 == NULL && p5 == NULL); handlesCount = 2; } DWORD ret = ::WaitForMultipleObjects(handlesCount, handles, ((which == NULL) ? TRUE : FALSE), timeout < 0 ? INFINITE : static_cast<DWORD>(timeout)); M_COMPILED_ASSERT(WAIT_OBJECT_0 == 0); // below code depends on it if ( ret <= (WAIT_OBJECT_0 + 5) ) { if ( which != NULL ) *which = ret; return true; } if ( ret != WAIT_TIMEOUT ) { M_ASSERT(ret == WAIT_FAILED); // WAIT_ABANDONED_x is not supported MESystemError::ThrowLastSystemError(); M_ENSURED_ASSERT(0); } return false; } #endif #endif
3,236
1,096
// Copyright 2018 The Dawn 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 <gtest/gtest.h> #include "dawn/common/RefCounted.h" #include "dawn/common/Result.h" namespace { template <typename T, typename E> void TestError(Result<T, E>* result, E expectedError) { EXPECT_TRUE(result->IsError()); EXPECT_FALSE(result->IsSuccess()); std::unique_ptr<E> storedError = result->AcquireError(); EXPECT_EQ(*storedError, expectedError); } template <typename T, typename E> void TestSuccess(Result<T, E>* result, T expectedSuccess) { EXPECT_FALSE(result->IsError()); EXPECT_TRUE(result->IsSuccess()); const T storedSuccess = result->AcquireSuccess(); EXPECT_EQ(storedSuccess, expectedSuccess); // Once the success is acquired, result has an empty // payload and is neither in the success nor error state. EXPECT_FALSE(result->IsError()); EXPECT_FALSE(result->IsSuccess()); } static int dummyError = 0xbeef; static float dummySuccess = 42.0f; static const float dummyConstSuccess = 42.0f; class AClass : public RefCounted { public: int a = 0; }; // Tests using the following overload of TestSuccess make // local Ref instances to dummySuccessObj. Tests should // ensure any local Ref objects made along the way continue // to point to dummySuccessObj. template <typename T, typename E> void TestSuccess(Result<Ref<T>, E>* result, T* expectedSuccess) { EXPECT_FALSE(result->IsError()); EXPECT_TRUE(result->IsSuccess()); // AClass starts with a reference count of 1 and stored // on the stack in the caller. The result parameter should // hold the only other reference to the object. EXPECT_EQ(expectedSuccess->GetRefCountForTesting(), 2u); const Ref<T> storedSuccess = result->AcquireSuccess(); EXPECT_EQ(storedSuccess.Get(), expectedSuccess); // Once the success is acquired, result has an empty // payload and is neither in the success nor error state. EXPECT_FALSE(result->IsError()); EXPECT_FALSE(result->IsSuccess()); // Once we call AcquireSuccess, result no longer stores // the object. storedSuccess should contain the only other // reference to the object. EXPECT_EQ(storedSuccess->GetRefCountForTesting(), 2u); } // Result<void, E*> // Test constructing an error Result<void, E> TEST(ResultOnlyPointerError, ConstructingError) { Result<void, int> result(std::make_unique<int>(dummyError)); TestError(&result, dummyError); } // Test moving an error Result<void, E> TEST(ResultOnlyPointerError, MovingError) { Result<void, int> result(std::make_unique<int>(dummyError)); Result<void, int> movedResult(std::move(result)); TestError(&movedResult, dummyError); } // Test returning an error Result<void, E> TEST(ResultOnlyPointerError, ReturningError) { auto CreateError = []() -> Result<void, int> { return {std::make_unique<int>(dummyError)}; }; Result<void, int> result = CreateError(); TestError(&result, dummyError); } // Test constructing a success Result<void, E> TEST(ResultOnlyPointerError, ConstructingSuccess) { Result<void, int> result; EXPECT_TRUE(result.IsSuccess()); EXPECT_FALSE(result.IsError()); } // Test moving a success Result<void, E> TEST(ResultOnlyPointerError, MovingSuccess) { Result<void, int> result; Result<void, int> movedResult(std::move(result)); EXPECT_TRUE(movedResult.IsSuccess()); EXPECT_FALSE(movedResult.IsError()); } // Test returning a success Result<void, E> TEST(ResultOnlyPointerError, ReturningSuccess) { auto CreateError = []() -> Result<void, int> { return {}; }; Result<void, int> result = CreateError(); EXPECT_TRUE(result.IsSuccess()); EXPECT_FALSE(result.IsError()); } // Result<T*, E*> // Test constructing an error Result<T*, E> TEST(ResultBothPointer, ConstructingError) { Result<float*, int> result(std::make_unique<int>(dummyError)); TestError(&result, dummyError); } // Test moving an error Result<T*, E> TEST(ResultBothPointer, MovingError) { Result<float*, int> result(std::make_unique<int>(dummyError)); Result<float*, int> movedResult(std::move(result)); TestError(&movedResult, dummyError); } // Test returning an error Result<T*, E> TEST(ResultBothPointer, ReturningError) { auto CreateError = []() -> Result<float*, int> { return {std::make_unique<int>(dummyError)}; }; Result<float*, int> result = CreateError(); TestError(&result, dummyError); } // Test constructing a success Result<T*, E> TEST(ResultBothPointer, ConstructingSuccess) { Result<float*, int> result(&dummySuccess); TestSuccess(&result, &dummySuccess); } // Test moving a success Result<T*, E> TEST(ResultBothPointer, MovingSuccess) { Result<float*, int> result(&dummySuccess); Result<float*, int> movedResult(std::move(result)); TestSuccess(&movedResult, &dummySuccess); } // Test returning a success Result<T*, E> TEST(ResultBothPointer, ReturningSuccess) { auto CreateSuccess = []() -> Result<float*, int*> { return {&dummySuccess}; }; Result<float*, int*> result = CreateSuccess(); TestSuccess(&result, &dummySuccess); } // Tests converting from a Result<TChild*, E> TEST(ResultBothPointer, ConversionFromChildClass) { struct T { int a; }; struct TChild : T {}; TChild child; T* childAsT = &child; { Result<T*, int> result(&child); TestSuccess(&result, childAsT); } { Result<TChild*, int> resultChild(&child); Result<T*, int> result(std::move(resultChild)); TestSuccess(&result, childAsT); } { Result<TChild*, int> resultChild(&child); Result<T*, int> result = std::move(resultChild); TestSuccess(&result, childAsT); } } // Result<const T*, E> // Test constructing an error Result<const T*, E> TEST(ResultBothPointerWithConstResult, ConstructingError) { Result<const float*, int> result(std::make_unique<int>(dummyError)); TestError(&result, dummyError); } // Test moving an error Result<const T*, E> TEST(ResultBothPointerWithConstResult, MovingError) { Result<const float*, int> result(std::make_unique<int>(dummyError)); Result<const float*, int> movedResult(std::move(result)); TestError(&movedResult, dummyError); } // Test returning an error Result<const T*, E*> TEST(ResultBothPointerWithConstResult, ReturningError) { auto CreateError = []() -> Result<const float*, int> { return {std::make_unique<int>(dummyError)}; }; Result<const float*, int> result = CreateError(); TestError(&result, dummyError); } // Test constructing a success Result<const T*, E*> TEST(ResultBothPointerWithConstResult, ConstructingSuccess) { Result<const float*, int> result(&dummyConstSuccess); TestSuccess(&result, &dummyConstSuccess); } // Test moving a success Result<const T*, E*> TEST(ResultBothPointerWithConstResult, MovingSuccess) { Result<const float*, int> result(&dummyConstSuccess); Result<const float*, int> movedResult(std::move(result)); TestSuccess(&movedResult, &dummyConstSuccess); } // Test returning a success Result<const T*, E*> TEST(ResultBothPointerWithConstResult, ReturningSuccess) { auto CreateSuccess = []() -> Result<const float*, int> { return {&dummyConstSuccess}; }; Result<const float*, int> result = CreateSuccess(); TestSuccess(&result, &dummyConstSuccess); } // Result<Ref<T>, E> // Test constructing an error Result<Ref<T>, E> TEST(ResultRefT, ConstructingError) { Result<Ref<AClass>, int> result(std::make_unique<int>(dummyError)); TestError(&result, dummyError); } // Test moving an error Result<Ref<T>, E> TEST(ResultRefT, MovingError) { Result<Ref<AClass>, int> result(std::make_unique<int>(dummyError)); Result<Ref<AClass>, int> movedResult(std::move(result)); TestError(&movedResult, dummyError); } // Test returning an error Result<Ref<T>, E> TEST(ResultRefT, ReturningError) { auto CreateError = []() -> Result<Ref<AClass>, int> { return {std::make_unique<int>(dummyError)}; }; Result<Ref<AClass>, int> result = CreateError(); TestError(&result, dummyError); } // Test constructing a success Result<Ref<T>, E> TEST(ResultRefT, ConstructingSuccess) { AClass success; Ref<AClass> refObj(&success); Result<Ref<AClass>, int> result(std::move(refObj)); TestSuccess(&result, &success); } // Test moving a success Result<Ref<T>, E> TEST(ResultRefT, MovingSuccess) { AClass success; Ref<AClass> refObj(&success); Result<Ref<AClass>, int> result(std::move(refObj)); Result<Ref<AClass>, int> movedResult(std::move(result)); TestSuccess(&movedResult, &success); } // Test returning a success Result<Ref<T>, E> TEST(ResultRefT, ReturningSuccess) { AClass success; auto CreateSuccess = [&success]() -> Result<Ref<AClass>, int> { return Ref<AClass>(&success); }; Result<Ref<AClass>, int> result = CreateSuccess(); TestSuccess(&result, &success); } class OtherClass { public: int a = 0; }; class Base : public RefCounted {}; class Child : public OtherClass, public Base {}; // Test constructing a Result<Ref<TChild>, E> TEST(ResultRefT, ConversionFromChildConstructor) { Child child; Ref<Child> refChild(&child); Result<Ref<Base>, int> result(std::move(refChild)); TestSuccess<Base>(&result, &child); } // Test copy constructing Result<Ref<TChild>, E> TEST(ResultRefT, ConversionFromChildCopyConstructor) { Child child; Ref<Child> refChild(&child); Result<Ref<Child>, int> resultChild(std::move(refChild)); Result<Ref<Base>, int> result(std::move(resultChild)); TestSuccess<Base>(&result, &child); } // Test assignment operator for Result<Ref<TChild>, E> TEST(ResultRefT, ConversionFromChildAssignmentOperator) { Child child; Ref<Child> refChild(&child); Result<Ref<Child>, int> resultChild(std::move(refChild)); Result<Ref<Base>, int> result = std::move(resultChild); TestSuccess<Base>(&result, &child); } // Result<T, E> // Test constructing an error Result<T, E> TEST(ResultGeneric, ConstructingError) { Result<std::vector<float>, int> result(std::make_unique<int>(dummyError)); TestError(&result, dummyError); } // Test moving an error Result<T, E> TEST(ResultGeneric, MovingError) { Result<std::vector<float>, int> result(std::make_unique<int>(dummyError)); Result<std::vector<float>, int> movedResult(std::move(result)); TestError(&movedResult, dummyError); } // Test returning an error Result<T, E> TEST(ResultGeneric, ReturningError) { auto CreateError = []() -> Result<std::vector<float>, int> { return {std::make_unique<int>(dummyError)}; }; Result<std::vector<float>, int> result = CreateError(); TestError(&result, dummyError); } // Test constructing a success Result<T, E> TEST(ResultGeneric, ConstructingSuccess) { Result<std::vector<float>, int> result({1.0f}); TestSuccess(&result, {1.0f}); } // Test moving a success Result<T, E> TEST(ResultGeneric, MovingSuccess) { Result<std::vector<float>, int> result({1.0f}); Result<std::vector<float>, int> movedResult(std::move(result)); TestSuccess(&movedResult, {1.0f}); } // Test returning a success Result<T, E> TEST(ResultGeneric, ReturningSuccess) { auto CreateSuccess = []() -> Result<std::vector<float>, int> { return {{1.0f}}; }; Result<std::vector<float>, int> result = CreateSuccess(); TestSuccess(&result, {1.0f}); } } // anonymous namespace
13,250
3,955
#include "statsmodel.h" StatsModel::StatsModel(QObject *parent) : QObject(parent) { }
88
34
#include <cfloat> #include <cmath> #include <cstdlib> #include <cstdio> #include <cstring> #include <ctime> #include <map> #include <algorithm> #include <random> #include <chrono> #if defined _MSC_VER #include <direct.h> #elif defined __GNUC__ #include <sys/types.h> #include <sys/stat.h> #endif #include "../lib/config.h" #include "../lib/vptree.h" #include "../lib/sptree.h" #include "responsive_tsne.h" using namespace std; using namespace panene; double getEEFactor(int iter, const Config& config) { if (config.use_ee) { if (config.use_periodic) { if (iter % config.periodic_cycle < config.periodic_duration) return config.ee_factor; return 1.0; } if (iter < config.ee_iter) return config.ee_factor; } return 1.0; } // Perform Responsive t-SNE with Progressive KDTree void ResponsiveTSNE::run(double* X, size_t N, size_t D, double* Y, size_t no_dims, double perplexity, double theta, int rand_seed, bool skip_random_init, size_t max_iter, size_t stop_lying_iter, size_t mom_switch_iter, Config& config) { // Set random seed if (skip_random_init != true) { if (rand_seed >= 0) { printf("Using random seed: %d\n", rand_seed); srand((unsigned int)rand_seed); } else { printf("Using current time as random seed...\n"); srand((unsigned int)time(NULL)); } } // Determine whether we are using an exact algorithm if (N - 1 < 3 * perplexity) { printf("Perplexity too large for the number of data points!\n"); exit(1); } printf("Using no_dims = %d, perplexity = %f, and theta = %f\n", no_dims, perplexity, theta); if (theta == .0) { printf("Exact TSNE is not supported!"); exit(-1); } // Set learning parameters float total_time = .0; clock_t start, end; double momentum = config.momentum, final_momentum = .8; double eta = config.eta; double* dY = (double*)malloc(N * no_dims * sizeof(double)); if (dY == NULL) { printf("Memory allocation failed!\n"); exit(1); } // Allocate some memory double* uY = (double*)malloc(N * no_dims * sizeof(double)); double* gains = (double*)malloc(N * no_dims * sizeof(double)); if (uY == NULL || gains == NULL) { printf("Memory allocation failed!\n"); exit(1); } for (int i = 0; i < N * no_dims; i++) uY[i] = .0; for (int i = 0; i < N * no_dims; i++) gains[i] = 1.0; start = clock(); // Initialize data source Source source((size_t)N, (size_t)D, X); // Initialize KNN table size_t K = (size_t)(perplexity * 3); Sink sink(N, K + 1); ProgressiveKNNTable<ProgressiveKDTreeIndex<Source>, Sink> table( &source, &sink, K + 1, IndexParams(config.num_trees), SearchParams(config.num_checks, 0, 0, config.cores), TreeWeight(config.add_point_weight, config.update_index_weight), TableWeight(config.tree_weight, config.table_weight)); // Normalize input data (to prevent numerical problems) zeroMean(X, N, D); double max_X = .0; for (int i = 0; i < N * D; i++) { if (fabs(X[i]) > max_X) max_X = fabs(X[i]); } for (int i = 0; i < N * D; i++) X[i] /= max_X; // Initialize solution (randomly) if (skip_random_init != true) { srand(0); for (int i = 0; i < N * no_dims; i++) Y[i] = randn() * .0001; } end = clock(); total_time += (float)(end - start) / CLOCKS_PER_SEC; printf("took %f for setup\n", total_time); config.event_log("initialization", total_time); // Perform main training loop size_t ops = config.ops; vector<map<size_t, double>> neighbors(N); // neighbors[i] has exact K items vector<map<size_t, double>> similarities(N); // may have more due to asymmetricity of neighborhoodship printf("training start\n"); float old_ee_factor = 1.0f; start = clock(); for (int iter = 0; iter < max_iter; iter++) { float start_perplex = 0, end_perplex = 0; float table_time = 0; float ee_factor = getEEFactor(iter, config); if (old_ee_factor != ee_factor) { float ratio = ee_factor / old_ee_factor; printf("EE changed, ratio = %3f\n", ratio); for (auto &sim : similarities) { for (auto &kv : sim) { kv.second *= ratio; } } } old_ee_factor = ee_factor; if (table.getSize() < N) { start_perplex = clock(); updateSimilarity(&table, neighbors, similarities, Y, no_dims, perplexity, K, ops, ee_factor); end_perplex = clock(); } int n = table.getSize(); computeGradient(similarities, Y, n, no_dims, dY, theta, ee_factor); // Update gains for (int i = 0; i < n * no_dims; i++) gains[i] = (sign(dY[i]) != sign(uY[i])) ? (gains[i] + .2) : (gains[i] * .8); for (int i = 0; i < n * no_dims; i++) if (gains[i] < .01) gains[i] = .01; // Perform gradient update (with momentum and gains) for (int i = 0; i < n * no_dims; i++) uY[i] = momentum * uY[i] - eta * gains[i] * dY[i]; for (int i = 0; i < n * no_dims; i++) Y[i] = Y[i] + uY[i]; double grad_sum = 0; for (int i = 0; i < n * no_dims; i++) { grad_sum += dY[i] * dY[i]; } // Make solution zero-mean zeroMean(Y, n, no_dims); if(iter == mom_switch_iter) momentum = final_momentum; // Print out progress if (iter > 0 && (iter % config.log_per == 0 || iter == max_iter - 1)) { end = clock(); double C = .0; C = evaluateError(similarities, Y, N, no_dims, theta, ee_factor); // doing approximate computation here! printf("Iteration %d: error is %f (total=%4.2f seconds, perplex=%4.2f seconds, tree=%4.2f seconds, ee_factor=%2.1f) grad_sum is %4.6f\n", iter, C, (float)(end - start) / CLOCKS_PER_SEC, (end_perplex - start_perplex) / CLOCKS_PER_SEC, table_time, ee_factor, grad_sum); total_time += (float)(end - start) / CLOCKS_PER_SEC; config.event_log("iter", iter, C, total_time); config.save_embedding(iter, Y); start = clock(); } } // Clean up memory free(dY); free(uY); free(gains); printf("Fitting performed in %4.2f seconds.\n", total_time); } void ResponsiveTSNE::updateSimilarity(Table *table, vector<map<size_t, double>>& neighbors, vector<map<size_t, double>>& similarities, double* Y, size_t no_dims, double perplexity, size_t K, size_t ops, float ee_factor) { if (perplexity > K) printf("Perplexity should be lower than K!\n"); // Update the KNNTable clock_t start = clock(); UpdateResult ar = table->run(ops); clock_t end = clock(); float table_time = (end - start) / CLOCKS_PER_SEC; /* We need to compute val_P for points that are 1) newly inserted (points in ar.addPointResult) 2) updated (points in ar.updatePointResult) ar.updatedIds has the ids of the updated points. The ids of the newly added points can be computed by comparing table.getSize() and ar.addPointResult */ // collect all ids that need to be updated vector<size_t> updated; vector<double> p(K); map<size_t, map<size_t, double>> old; for (size_t i = table->getSize() - ar.addPointResult; i < table->getSize(); ++i) { // point i has been newly inserted. ar.updatedIds.insert(i); // for newly added points, we set its initial position to the mean of its neighbors std::vector<size_t> indices(K + 1); table->getNeighbors(i, indices); for (size_t j = i * no_dims; j < (i + 1) * no_dims; ++j) { Y[j] = 0; } for (size_t k = 0; k < K; ++k) { for (size_t j = 0; j < no_dims; ++j) { Y[i * no_dims + j] += Y[indices[k + 1] * no_dims + j] / K; } } } for (size_t uid : ar.updatedIds) { // the neighbors of uid has been updated std::vector<size_t> indices(K + 1); std::vector<double> distances(K + 1); table->getNeighbors(uid, indices); table->getDistances(uid, distances); bool found = false; double beta = 1.0; double min_beta = -DBL_MAX; double max_beta = DBL_MAX; double tol = 1e-5; int iter = 0; double sum_P; // Iterate until we found a good perplexity while (!found && iter < 200) { // Compute Gaussian kernel row for (int m = 0; m < K; m++) p[m] = exp(-beta * distances[m + 1] * distances[m + 1]); // Compute entropy of current row sum_P = DBL_MIN; for (int m = 0; m < K; m++) sum_P += p[m]; double H = .0; for (int m = 0; m < K; m++) H += beta * (distances[m + 1] * distances[m + 1] * p[m]); H = (H / sum_P) + log(sum_P); // Evaluate whether the entropy is within the tolerance level double Hdiff = H - log(perplexity); if (Hdiff < tol && -Hdiff < tol) { found = true; } else { if (Hdiff > 0) { min_beta = beta; if (max_beta == DBL_MAX || max_beta == -DBL_MAX) beta *= 2.0; else beta = (beta + max_beta) / 2.0; } else { max_beta = beta; if (min_beta == -DBL_MAX || min_beta == DBL_MAX) beta /= 2.0; else beta = (beta + min_beta) / 2.0; } } // Update iteration counter iter++; } for (unsigned int m = 0; m < K; m++) p[m] /= sum_P; old[uid] = neighbors[uid]; neighbors[uid].clear(); for (unsigned int m = 0; m < K; m++) { neighbors[uid][indices[m + 1]] = p[m] * ee_factor; } } for (size_t Aid : ar.updatedIds) { // point A // neighbors changed, we need to keep the similarities symmetric // the neighbors of uid has been updated for (auto &it : neighbors[Aid]) { // point B size_t Bid = it.first; double sAB = it.second; double sBA = 0; if (neighbors[Bid].count(Aid) > 0) sBA = neighbors[Bid][Aid]; similarities[Aid][Bid] = (sAB + sBA) / 2; similarities[Bid][Aid] = (sAB + sBA) / 2; } for (auto &it : old[Aid]) { size_t oldBid = it.first; if (neighbors[Aid].count(oldBid) > 0) continue; // exit points double sAB = 0; double sBA = 0; if (neighbors[oldBid].count(Aid) > 0) sBA = neighbors[oldBid][Aid]; if (sBA == 0) { similarities[Aid].erase(oldBid); similarities[oldBid].erase(Aid); } else { similarities[Aid][oldBid] = (sAB + sBA) / 2; similarities[oldBid][Aid] = (sAB + sBA) / 2; } } } //for(auto &it: similarities[0]) { //printf("[%d] %lf\n", it.first, it.second); //} } // Compute gradient of the t-SNE cost function (using Barnes-Hut algorithm) void ResponsiveTSNE::computeGradient(vector<map<size_t, double>>& similarities, double* Y, size_t N, size_t D, double* dC, double theta, float ee_factor) { // Construct space-partitioning tree on current map SPTree* tree = new SPTree(D, Y, N); // Compute all terms required for t-SNE gradient double sum_Q = .0; double* pos_f = (double*)calloc(N * D, sizeof(double)); double* neg_f = (double*)calloc(N * D, sizeof(double)); if (pos_f == NULL || neg_f == NULL) { printf("Memory allocation failed!\n"); exit(1); } tree->computeEdgeForces(similarities, N, pos_f, ee_factor); for (int n = 0; n < N; n++) tree->computeNonEdgeForces(n, theta, neg_f + n * D, &sum_Q); // Compute final t-SNE gradient for (int i = 0; i < N * D; i++) { dC[i] = pos_f[i] - (neg_f[i] / sum_Q); } free(pos_f); free(neg_f); delete tree; } // Evaluate t-SNE cost function (approximately) double ResponsiveTSNE::evaluateError(vector<map<size_t, double>>& similarities, double *Y, size_t N, size_t D, double theta, float ee_factor) { // Get estimate of normalization term SPTree* tree = new SPTree(D, Y, N); double* buff = (double*)calloc(D, sizeof(double)); double sum_Q = .0; for (int n = 0; n < N; n++) tree->computeNonEdgeForces(n, theta, buff, &sum_Q); // Loop over all edges to compute t-SNE error int ind1 = 0, ind2; double C = .0, Q; double sum_P = .0; int j = 0; for (auto &p : similarities) { if (j >= N) break; j++; for (auto &it : p) { sum_P += it.second; } } sum_P /= ee_factor; j = 0; for (auto &p : similarities) { if (j >= N) break; for (auto &it : p) { Q = .0; ind2 = it.first * D; for (int d = 0; d < D; d++) buff[d] = Y[ind1 + d]; for (int d = 0; d < D; d++) buff[d] -= Y[ind2 + d]; for (int d = 0; d < D; d++) Q += buff[d] * buff[d]; Q = (1.0 / (1.0 + Q)) / sum_Q; C += it.second / sum_P * log((it.second / sum_P + FLT_MIN) / (Q + FLT_MIN)); } ind1 += D; j++; } // Clean up memory free(buff); delete tree; return C; } // Makes data zero-mean void ResponsiveTSNE::zeroMean(double* X, size_t N, size_t D) { // Compute data mean double* mean = (double*)calloc(D, sizeof(double)); if (mean == NULL) { printf("Memory allocation failed!\n"); exit(1); } int nD = 0; for (int n = 0; n < N; n++) { for (int d = 0; d < D; d++) { mean[d] += X[nD + d]; } nD += D; } for (int d = 0; d < D; d++) { mean[d] /= (double)N; } // Subtract data mean nD = 0; for (int n = 0; n < N; n++) { for (int d = 0; d < D; d++) { X[nD + d] -= mean[d]; } nD += D; } free(mean); mean = NULL; } // Generates a Gaussian random number double ResponsiveTSNE::randn() { double x, y, radius; do { x = 2 * (rand() / ((double)RAND_MAX + 1)) - 1; y = 2 * (rand() / ((double)RAND_MAX + 1)) - 1; radius = (x * x) + (y * y); } while ((radius >= 1.0) || (radius == 0.0)); radius = sqrt(-2 * log(radius) / radius); x *= radius; y *= radius; return x; }
14,880
5,370
/** * Copyright (c) 2017-present, Facebook, 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 "CPUFunction.h" #include "glow/Graph/Context.h" #include "glow/Support/Compiler.h" #include "glow/Support/Memory.h" using namespace glow; CPUFunction::CPUFunction(std::unique_ptr<llvm::orc::GlowJIT> JIT, const runtime::RuntimeBundle &runtimeBundle) : JIT_(std::move(JIT)), runtimeBundle_(runtimeBundle) {} CPUFunction::~CPUFunction() { alignedFree(runtimeBundle_.constants); } void CPUFunction::allocateMutableBuffersOnDevice() { baseActivationsAddress_ = (uint8_t *)alignedAlloc( runtimeBundle_.activationsMemSize, TensorAlignment); baseMutableWeightVarsAddress_ = (uint8_t *)alignedAlloc( runtimeBundle_.mutableWeightVarsMemSize, TensorAlignment); } void CPUFunction::copyInputsToDevice(Context &ctx) { // Copy Placeholders into allocated memory. for (auto PH : ctx.pairs()) { auto payload = PH.second->getUnsafePtr(); auto symbolInfo = runtimeBundle_.symbolTable.find(std::string(PH.first->getName())); assert(symbolInfo != runtimeBundle_.symbolTable.end() && "Symbol not found"); auto addr = symbolInfo->second.offset; auto numBytes = symbolInfo->second.size; // copy PH to allocated memory. memcpy(baseMutableWeightVarsAddress_ + addr, payload, numBytes); } } void CPUFunction::copyOutputsFromDevice(Context &ctx) { // Copy placeholders from device back into context. for (auto PH : ctx.pairs()) { auto symbolInfo = runtimeBundle_.symbolTable.find(std::string(PH.first->getName())); auto payload = baseMutableWeightVarsAddress_ + symbolInfo->second.offset; auto numBytes = symbolInfo->second.size; auto addr = PH.second->getUnsafePtr(); // copy PH from allocated memory. memcpy(addr, payload, numBytes); } } void CPUFunction::freeAllocations() { alignedFree(baseMutableWeightVarsAddress_); alignedFree(baseActivationsAddress_); } void CPUFunction::execute(Context &ctx) { copyFunctionToDevice(); copyConstantsToDevice(); allocateMutableBuffersOnDevice(); copyInputsToDevice(ctx); auto sym = JIT_->findSymbol("jitmain"); assert(sym && "Unable to JIT the code!"); using JitFuncType = void (*)(uint8_t * constantWeightVars, uint8_t * mutableWeightVars, uint8_t * activations); auto address = sym.getAddress(); if (address) { JitFuncType funcPtr = reinterpret_cast<JitFuncType>(address.get()); funcPtr(runtimeBundle_.constants, baseMutableWeightVarsAddress_, baseActivationsAddress_); copyOutputsFromDevice(ctx); } else { GLOW_ASSERT(false && "Error getting address."); } freeAllocations(); }
3,239
989
#include <unistd.h> #include <cctype> #include <sstream> #include <iostream> #include <string> #include <vector> #include "process.h" #include "linux_parser.h" using std::string; using std::to_string; using std::vector; // TODO: Return this process's ID int Process::Pid() { return pid_; } // TODO: Return this process's CPU utilization float Process::CpuUtilization() { return cpu_util_ = LinuxParser::Cpuutilization(pid_); } // TODO: Return the command that generated this process string Process::Command() { return cmd_; } // TODO: Return this process's memory utilization string Process::Ram() { //std::cout << "ram : " << ram_ << "\n"; return ram_ = LinuxParser::Ram(pid_); } // TODO: Return the user (name) that generated this process string Process::User() { return Process::user_; } // TODO: Return the age of this process (in seconds) long int Process::UpTime() { return uptime_ = LinuxParser::Uptime(pid_); } // TODO: Overload the "less than" comparison operator for Process objects bool Process::operator<(Process & a) { return a.CpuUtilization() < CpuUtilization(); }
1,097
339
/*============================================================================= Copyright (c) 2001-2014 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ /////////////////////////////////////////////////////////////////////////////// // // Yet another calculator example! This time, we will compile to a simple // virtual machine. This is actually one of the very first Spirit example // circa 2000. Now, it's ported to Spirit2 (and X3). // // [ JDG Sometime 2000 ] pre-boost // [ JDG September 18, 2002 ] spirit1 // [ JDG April 8, 2007 ] spirit2 // [ JDG February 18, 2011 ] Pure attributes. No semantic actions. // [ JDG April 9, 2014 ] Spirit X3 (from qi calc6) // /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // Uncomment this if you want to enable debugging //#define BOOST_SPIRIT_X3_DEBUG #if defined(_MSC_VER) # pragma warning(disable: 4345) #endif #include <boost/config/warning_disable.hpp> #include <boost/spirit/home/x3.hpp> #include <boost/spirit/home/x3/support/ast/variant.hpp> #include <boost/fusion/include/adapt_struct.hpp> #include <iostream> #include <string> #include <list> #include <numeric> namespace x3 = boost::spirit::x3; namespace client { namespace ast { /////////////////////////////////////////////////////////////////////////// // The AST /////////////////////////////////////////////////////////////////////////// struct nil {}; struct signed_; struct expression; struct operand : x3::variant< nil , unsigned int , x3::forward_ast<signed_> , x3::forward_ast<expression> > { using base_type::base_type; using base_type::operator=; }; struct signed_ { char sign; operand operand_; }; struct operation { char operator_; operand operand_; }; struct expression { operand first; std::list<operation> rest; }; // print function for debugging inline std::ostream& operator<<(std::ostream& out, nil) { out << "nil"; return out; } }} BOOST_FUSION_ADAPT_STRUCT( client::ast::signed_, (char, sign) (client::ast::operand, operand_) ) BOOST_FUSION_ADAPT_STRUCT( client::ast::operation, (char, operator_) (client::ast::operand, operand_) ) BOOST_FUSION_ADAPT_STRUCT( client::ast::expression, (client::ast::operand, first) (std::list<client::ast::operation>, rest) ) namespace client { /////////////////////////////////////////////////////////////////////////// // The Virtual Machine /////////////////////////////////////////////////////////////////////////// enum byte_code { op_neg, // negate the top stack entry op_add, // add top two stack entries op_sub, // subtract top two stack entries op_mul, // multiply top two stack entries op_div, // divide top two stack entries op_int, // push constant integer into the stack }; class vmachine { public: vmachine(unsigned stackSize = 4096) : stack(stackSize) , stack_ptr(stack.begin()) { } int top() const { return stack_ptr[-1]; }; void execute(std::vector<int> const& code); private: std::vector<int> stack; std::vector<int>::iterator stack_ptr; }; void vmachine::execute(std::vector<int> const& code) { std::vector<int>::const_iterator pc = code.begin(); stack_ptr = stack.begin(); while (pc != code.end()) { switch (*pc++) { case op_neg: stack_ptr[-1] = -stack_ptr[-1]; break; case op_add: --stack_ptr; stack_ptr[-1] += stack_ptr[0]; break; case op_sub: --stack_ptr; stack_ptr[-1] -= stack_ptr[0]; break; case op_mul: --stack_ptr; stack_ptr[-1] *= stack_ptr[0]; break; case op_div: --stack_ptr; stack_ptr[-1] /= stack_ptr[0]; break; case op_int: *stack_ptr++ = *pc++; break; } } } /////////////////////////////////////////////////////////////////////////// // The Compiler /////////////////////////////////////////////////////////////////////////// struct compiler { typedef void result_type; std::vector<int>& code; compiler(std::vector<int>& code) : code(code) {} void operator()(ast::nil) const { BOOST_ASSERT(0); } void operator()(unsigned int n) const { code.push_back(op_int); code.push_back(n); } void operator()(ast::operation const& x) const { boost::apply_visitor(*this, x.operand_); switch (x.operator_) { case '+': code.push_back(op_add); break; case '-': code.push_back(op_sub); break; case '*': code.push_back(op_mul); break; case '/': code.push_back(op_div); break; default: BOOST_ASSERT(0); break; } } void operator()(ast::signed_ const& x) const { boost::apply_visitor(*this, x.operand_); switch (x.sign) { case '-': code.push_back(op_neg); break; case '+': break; default: BOOST_ASSERT(0); break; } } void operator()(ast::expression const& x) const { boost::apply_visitor(*this, x.first); for (ast::operation const& oper : x.rest) { (*this)(oper); } } }; /////////////////////////////////////////////////////////////////////////////// // The calculator grammar /////////////////////////////////////////////////////////////////////////////// namespace calculator_grammar { using x3::uint_; using x3::char_; struct expression_class; struct term_class; struct factor_class; x3::rule<expression_class, ast::expression> const expression("expression"); x3::rule<term_class, ast::expression> const term("term"); x3::rule<factor_class, ast::operand> const factor("factor"); auto const expression_def = term >> *( (char_('+') > term) | (char_('-') > term) ) ; auto const term_def = factor >> *( (char_('*') > factor) | (char_('/') > factor) ) ; auto const factor_def = uint_ | '(' > expression > ')' | (char_('-') > factor) | (char_('+') > factor) ; BOOST_SPIRIT_DEFINE( expression = expression_def , term = term_def , factor = factor_def ); struct expression_class { // Our error handler template <typename Iterator, typename Exception, typename Context> x3::error_handler_result on_error(Iterator&, Iterator const& last, Exception const& x, Context const& context) { std::cout << "Error! Expecting: " << x.which() << " here: \"" << std::string(x.where(), last) << "\"" << std::endl ; return x3::error_handler_result::fail; } }; auto calculator = expression; } using calculator_grammar::calculator; } /////////////////////////////////////////////////////////////////////////////// // Main program /////////////////////////////////////////////////////////////////////////////// int main() { std::cout << "/////////////////////////////////////////////////////////\n\n"; std::cout << "Expression parser...\n\n"; std::cout << "/////////////////////////////////////////////////////////\n\n"; std::cout << "Type an expression...or [q or Q] to quit\n\n"; typedef std::string::const_iterator iterator_type; typedef client::ast::expression ast_expression; typedef client::compiler compiler; std::string str; while (std::getline(std::cin, str)) { if (str.empty() || str[0] == 'q' || str[0] == 'Q') break; client::vmachine mach; // Our virtual machine std::vector<int> code; // Our VM code auto& calc = client::calculator; // Our grammar ast_expression expression; // Our program (AST) compiler compile(code); // Compiles the program std::string::const_iterator iter = str.begin(); std::string::const_iterator end = str.end(); boost::spirit::x3::ascii::space_type space; bool r = phrase_parse(iter, end, calc, space, expression); if (r && iter == end) { std::cout << "-------------------------\n"; std::cout << "Parsing succeeded\n"; compile(expression); mach.execute(code); std::cout << "\nResult: " << mach.top() << std::endl; std::cout << "-------------------------\n"; } else { std::string rest(iter, end); std::cout << "-------------------------\n"; std::cout << "Parsing failed\n"; std::cout << "-------------------------\n"; } } std::cout << "Bye... :-) \n\n"; return 0; }
10,622
3,011
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/mlir/tfrt/saved_model/saved_model.h" #include "absl/strings/match.h" #include "mlir/IR/Dialect.h" // from @llvm-project #include "mlir/Parser/Parser.h" // from @llvm-project #include "tensorflow/compiler/mlir/tensorflow/dialect_registration.h" #include "tensorflow/compiler/mlir/tfrt/translate/import_model.h" #include "tensorflow/core/lib/core/status_test_util.h" #include "tensorflow/core/platform/resource_loader.h" #include "tensorflow/core/platform/test.h" namespace tensorflow { namespace { TEST(SavedModelTest, MapSignatures) { std::string saved_model_mlir_path = tensorflow::GetDataDependencyFilepath( "tensorflow/compiler/mlir/tfrt/tests/saved_model/testdata/test.mlir"); mlir::DialectRegistry registry; mlir::RegisterAllTensorFlowDialects(registry); mlir::MLIRContext context(registry); auto module = mlir::parseSourceFile(saved_model_mlir_path, &context); ASSERT_TRUE(module); std::vector<std::string> inputs; std::vector<std::pair<tensorflow::DataType, tensorflow::PartialTensorShape>> in_specs; std::vector<std::string> outputs; std::vector<std::pair<tensorflow::DataType, tensorflow::PartialTensorShape>> out_specs; std::vector<mlir::Operation*> bound_inputs; TF_ASSERT_OK(MapFunctionSignaturesFromTFSavedModelMLIR( module.get(), [&](const TFRTSavedModelSignatureInfo& sig_info) { // Only check the signature of "serving_default". if (sig_info.func_name != "serving_default") return; transform(sig_info.input_names, std::back_inserter(inputs), [](llvm::StringRef x) { return x.str(); }); in_specs.assign(sig_info.input_specs.begin(), sig_info.input_specs.end()); transform(sig_info.output_names, std::back_inserter(outputs), [](llvm::StringRef x) { return x.str(); }); out_specs.assign(sig_info.output_specs.begin(), sig_info.output_specs.end()); bound_inputs.assign(sig_info.bound_inputs.begin(), sig_info.bound_inputs.end()); })); ASSERT_EQ(inputs.size(), 1); EXPECT_EQ(inputs[0], "x"); ASSERT_EQ(outputs.size(), 1); EXPECT_EQ(outputs[0], "r"); ASSERT_EQ(in_specs.size(), 1); ASSERT_EQ(in_specs[0].first, tensorflow::DT_INT32); ASSERT_TRUE(in_specs[0].second.IsIdenticalTo(PartialTensorShape({1, 3}))); ASSERT_EQ(out_specs.size(), 1); ASSERT_EQ(out_specs[0].first, tensorflow::DT_INT32); ASSERT_TRUE(out_specs[0].second.IsIdenticalTo(PartialTensorShape({1, 1}))); ASSERT_EQ(bound_inputs.size(), 2); auto global_tensor = llvm::cast<mlir::tf_saved_model::GlobalTensorOp>(bound_inputs[0]); auto asset = llvm::cast<mlir::tf_saved_model::AssetOp>(bound_inputs[1]); EXPECT_EQ(global_tensor.sym_name(), "y"); EXPECT_EQ(asset.sym_name(), "z"); } TEST(SavedModelTest, CompileToBEF) { std::string saved_model_mlir_path = tensorflow::GetDataDependencyFilepath( "tensorflow/compiler/mlir/tfrt/tests/saved_model/testdata/test.mlir"); mlir::DialectRegistry registry; mlir::RegisterAllTensorFlowDialects(registry); mlir::MLIRContext context(registry); auto module = mlir::parseSourceFile(saved_model_mlir_path, &context); ASSERT_TRUE(module); tfrt::BefBuffer bef_buffer; TfrtCompileOptions options; TF_ASSERT_OK(ConvertTfMlirToBef(options, module.get(), &bef_buffer)); } // TODO(b/162442824): Add a SavedModel test that covers the error pass. } // namespace } // namespace tensorflow
4,189
1,474
#include <string> #include <regex> #include <iostream> #include "grammar.hpp" // [START] Include nodes #include "nodes/node.hpp" #include "nodes/node_list.hpp" #include "nodes/boolean.hpp" #include "nodes/scope_fn.hpp" #include "nodes/scope.hpp" #include "nodes/line.hpp" #include "nodes/value_list.hpp" #include "nodes/literal_new_line.hpp" #include "nodes/attribute.hpp" #include "nodes/attributes.hpp" #include "nodes/tag_statement.hpp" #include "nodes/text_literal_content.hpp" #include "nodes/escaped.hpp" #include "nodes/comment.hpp" #include "nodes/scoped_key_value_pairs.hpp" #include "nodes/key_value_pair.hpp" #include "nodes/unary_expr.hpp" #include "nodes/binary_expr.hpp" #include "nodes/each.hpp" #include "nodes/with.hpp" #include "nodes/conditional.hpp" #include "nodes/variable_name.hpp" #include "nodes/variable.hpp" #include "nodes/scope.hpp" // [END] Include nodes namespace { // Helper function to turn a maybe rule (one element, made optional with a ?) into its value or a default template<typename T> std::function<T(const peg::SemanticValues&)> optional(T default_value) { return [=](const peg::SemanticValues &sv) -> T { if (sv.size() > 0) { return sv[0].get<T>(); } else { return default_value; } }; } // Helper to turn plural rules (one element, repeated with + or *) into a vector of a given type template<typename T> std::function<std::vector<T>(const peg::SemanticValues&)> repeated() { return [](const peg::SemanticValues& sv) -> std::vector<T> { std::vector<T> contents; for (unsigned int n = 0; n < sv.size(); n++) { contents.push_back(sv[n].get<T>()); } return contents; }; } } Grammar::Grammar() : emerald_parser(syntax) { emerald_parser["ROOT"] = [](const peg::SemanticValues& sv) -> NodePtr { NodePtrs nodes = sv[0].get<NodePtrs>(); return NodePtr(new NodeList(nodes, "\n")); }; emerald_parser["line"] = [](const peg::SemanticValues& sv) -> NodePtr { NodePtr line = sv[0].get<NodePtr>(); return NodePtr(new Line(line)); }; emerald_parser["value_list"] = [](const peg::SemanticValues& sv) -> NodePtr { NodePtr keyword = sv[0].get<NodePtr>(); NodePtrs literals = sv[1].get<NodePtrs>(); return NodePtr(new ValueList(keyword, literals)); }; emerald_parser["literal_new_line"] = [](const peg::SemanticValues& sv) -> NodePtr { NodePtr inline_lit_str = sv[0].get<NodePtr>(); return NodePtr(new LiteralNewLine(inline_lit_str)); }; emerald_parser["pair_list"] = [](const peg::SemanticValues& sv) -> NodePtr { NodePtrs nodes; std::string base_keyword = sv[0].get<std::string>(); std::vector<const peg::SemanticValues> semantic_values = sv[1].get<std::vector<const peg::SemanticValues>>(); std::transform(semantic_values.begin(), semantic_values.end(), nodes.begin(), [=](const peg::SemanticValues& svs) { NodePtrs pairs = svs[0].get<NodePtrs>(); return NodePtr(new ScopedKeyValuePairs(base_keyword, pairs)); }); return NodePtr(new NodeList(nodes, "\n")); }; emerald_parser["scoped_key_value_pairs"] = repeated<const peg::SemanticValues>(); emerald_parser["scoped_key_value_pair"] = [](const peg::SemanticValues& sv) -> const peg::SemanticValues { return sv; }; emerald_parser["key_value_pair"] = [](const peg::SemanticValues& sv) -> NodePtr { std::string key = sv[0].get<std::string>(); NodePtr value = sv[1].get<NodePtr>(); return NodePtr(new KeyValuePair(key, value)); }; emerald_parser["comment"] = [](const peg::SemanticValues& sv) -> NodePtr { NodePtr text_content = sv[0].get<NodePtr>(); return NodePtr(new Comment(text_content)); }; emerald_parser["maybe_id_name"] = optional<std::string>(""); emerald_parser["class_names"] = repeated<std::string>(); emerald_parser["tag_statement"] = [](const peg::SemanticValues& sv) -> NodePtr { std::string tag_name = sv[0].get<std::string>(); std::string id_name = sv[1].get<std::string>(); std::vector<std::string> class_names = sv[2].get<std::vector<std::string>>(); NodePtr body = sv[3].get<NodePtr>(); NodePtr attributes = sv[4].get<NodePtr>(); NodePtr nested = sv[5].get<NodePtr>(); return NodePtr( new TagStatement(tag_name, id_name, class_names, body, attributes, nested)); }; emerald_parser["attr_list"] = [](const peg::SemanticValues& sv) -> NodePtr { NodePtrs nodes = sv[0].get<NodePtrs>(); return NodePtr(new Attributes(nodes)); }; emerald_parser["attribute"] = [](const peg::SemanticValues& sv) -> NodePtr { std::string key = sv[0].get<std::string>(); NodePtr value = sv[1].get<NodePtr>(); return NodePtr(new Attribute(key, value)); }; emerald_parser["escaped"] = [](const peg::SemanticValues& sv) -> NodePtr { return NodePtr(new Escaped(sv.str())); }; emerald_parser["maybe_negation"] = optional<bool>(false); emerald_parser["negation"] = [](const peg::SemanticValues& sv) -> bool { return true; }; emerald_parser["unary_expr"] = [](const peg::SemanticValues& sv) -> BooleanPtr { bool negated = sv[0].get<bool>(); BooleanPtr expr = sv[1].get<BooleanPtr>(); return BooleanPtr(new UnaryExpr(negated, expr)); }; emerald_parser["binary_expr"] = [](const peg::SemanticValues& sv) -> BooleanPtr { BooleanPtr lhs = sv[0].get<BooleanPtr>(); std::string op_str = sv[1].get<peg::SemanticValues>().str(); BooleanPtr rhs = sv[2].get<BooleanPtr>(); BinaryExpr::Operator op; if (op_str == BinaryExpr::OR_STR) { op = BinaryExpr::Operator::OR; } else if (op_str == BinaryExpr::AND_STR) { op = BinaryExpr::Operator::AND; } else { throw "Invalid operator: " + op_str; } return BooleanPtr(new BinaryExpr(lhs, op, rhs)); }; emerald_parser["boolean_expr"] = [](const peg::SemanticValues& sv) -> BooleanPtr { return sv[0].get<BooleanPtr>(); }; emerald_parser["maybe_key_name"] = optional<std::string>(""); emerald_parser["each"] = [](const peg::SemanticValues& sv) -> ScopeFnPtr { std::string collection_name = sv[0].get<std::string>(); std::string val_name = sv[1].get<std::string>(); std::string key_name = sv[2].get<std::string>(); return ScopeFnPtr(new Each(collection_name, val_name, key_name)); }; emerald_parser["with"] = [](const peg::SemanticValues& sv) -> ScopeFnPtr { std::string var_name = sv[0].get<std::string>(); return ScopeFnPtr(new With(var_name)); }; emerald_parser["given"] = [](const peg::SemanticValues& sv) -> ScopeFnPtr { BooleanPtr condition = sv[0].get<BooleanPtr>(); return ScopeFnPtr(new Conditional(true, condition)); }; emerald_parser["unless"] = [](const peg::SemanticValues& sv) -> ScopeFnPtr { BooleanPtr condition = sv[0].get<BooleanPtr>(); return ScopeFnPtr(new Conditional(false, condition)); }; emerald_parser["scope_fn"] = [](const peg::SemanticValues& sv) -> ScopeFnPtr { return sv[0].get<ScopeFnPtr>(); }; emerald_parser["variable_name"] = [](const peg::SemanticValues& sv) -> BooleanPtr { std::string name = sv.str(); return BooleanPtr(new VariableName(name)); }; emerald_parser["variable"] = [](const peg::SemanticValues& sv) -> NodePtr { std::string name = sv.token(0); return NodePtr(new Variable(name)); }; emerald_parser["scope"] = [](const peg::SemanticValues& sv) -> NodePtr { ScopeFnPtr scope_fn = sv[0].get<ScopeFnPtr>(); NodePtr body = sv[1].get<NodePtr>(); return NodePtr(new Scope(scope_fn, body)); }; // Repeated Nodes const std::vector<std::string> repeated_nodes = { "statements", "literal_new_lines", "key_value_pairs", "ml_lit_str_quoteds", "ml_templess_lit_str_qs", "inline_literals", "il_lit_str_quoteds", "attributes" }; for (std::string repeated_node : repeated_nodes) { emerald_parser[repeated_node.c_str()] = repeated<NodePtr>(); } // Wrapper Nodes const std::vector<std::string> wrapper_nodes = { "statement", "text_content", "ml_lit_str_quoted", "ml_templess_lit_str_q", "inline_literal", "il_lit_str_quoted", "nested_tag" }; for (std::string wrapper_node : wrapper_nodes) { emerald_parser[wrapper_node.c_str()] = [](const peg::SemanticValues& sv) -> NodePtr { return sv[0].get<NodePtr>(); }; } // Literals const std::vector<std::string> literals = { "multiline_literal", "inline_lit_str", "inline_literals_node" }; for (std::string string_rule : literals) { emerald_parser[string_rule.c_str()] = [](const peg::SemanticValues& sv) -> NodePtr { NodePtrs body = sv[0].get<NodePtrs>(); return NodePtr(new NodeList(body, "")); }; } // Literal Contents const std::vector<std::string> literal_contents = { "ml_lit_content", "il_lit_content", "il_lit_str_content" }; for (std::string string_rule_content : literal_contents) { emerald_parser[string_rule_content.c_str()] = [](const peg::SemanticValues& sv) -> NodePtr { return NodePtr(new TextLiteralContent(sv.str())); }; } const std::vector<std::string> optional_nodes = { "maybe_text_content", "maybe_nested_tag", "maybe_attr_list" }; for (std::string rule_name : optional_nodes) { emerald_parser[rule_name.c_str()] = optional<NodePtr>(NodePtr()); } // Terminals const std::vector<std::string> terminals = { "attr", "tag", "class_name", "id_name", "key_name" }; for (std::string rule_name : terminals) { emerald_parser[rule_name.c_str()] = [](const peg::SemanticValues& sv) -> std::string { return sv.str(); }; } emerald_parser.enable_packrat_parsing(); } Grammar& Grammar::get_instance() { static Grammar instance; return instance; } peg::parser Grammar::get_parser() { return emerald_parser; } bool Grammar::valid(const std::string &input) { std::string output; emerald_parser.parse(input.c_str(), output); return output.length() == input.length(); }
10,313
3,571
#include <iostream> //#include <boost/gil/gil_all.hpp> #include <OpenEXR/ImfRgbaFile.h> #include <OpenEXR/ImfArray.h> /* template <typename View> void apply(const View& view) { Imf::RgbaInputFile file ( "sample.exr" ); Imath::Box2i dw = file.dataWindow(); int width = dw.max.x - dw.min.x + 1; int height = dw.max.y - dw.min.y + 1; std::cout << width << "x" << height << std::endl; Imf::Array2D<Imf::Rgba> pixels; pixels.resizeErase (height, width); file.setFrameBuffer( &pixels[0][0] - dw.min.x - dw.min.y * width, 1, width ); file.readPixels (dw.min.y, dw.max.y); std::vector<pixel<bits8,layout<typename color_space_type<View>::type> > > row(view.width()); JSAMPLE* row_address=(JSAMPLE*)&row.front(); for(int y=0;y<view.height();++y) { io_error_if(jpeg_read_scanlines(&_cinfo,(JSAMPARRAY)&row_address,1)!=1, "jpeg_reader::apply(): fail to read JPEG file"); std::copy(row.begin(),row.end(),view.row_begin(y)); } } */ int main() { Imf::RgbaInputFile file ( "sample.exr" ); Imath::Box2i dw = file.dataWindow(); int width = dw.max.x - dw.min.x + 1; int height = dw.max.y - dw.min.y + 1; std::cout << width << "x" << height << std::endl; Imf::Array2D<Imf::Rgba> pixels; pixels.resizeErase (height, width); file.setFrameBuffer( &pixels[0][0] - dw.min.x - dw.min.y * width, 1, width ); file.readPixels (dw.min.y, dw.max.y); }
1,400
597
// Copyright 2013 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 "content/browser/media/capture/aura_window_capture_machine.h" #include <algorithm> #include <utility> #include "base/logging.h" #include "base/metrics/histogram.h" #include "cc/output/copy_output_request.h" #include "cc/output/copy_output_result.h" #include "components/display_compositor/gl_helper.h" #include "content/browser/compositor/image_transport_factory.h" #include "content/browser/media/capture/desktop_capture_device_uma_types.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/power_save_blocker.h" #include "media/base/video_capture_types.h" #include "media/base/video_util.h" #include "media/capture/content/thread_safe_capture_oracle.h" #include "media/capture/content/video_capture_oracle.h" #include "skia/ext/image_operations.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/aura/client/screen_position_client.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/aura/window_observer.h" #include "ui/aura/window_tree_host.h" #include "ui/base/cursor/cursors_aura.h" #include "ui/compositor/compositor.h" #include "ui/compositor/dip_util.h" #include "ui/compositor/layer.h" #include "ui/wm/public/activation_client.h" namespace content { AuraWindowCaptureMachine::AuraWindowCaptureMachine() : desktop_window_(NULL), screen_capture_(false), weak_factory_(this) {} AuraWindowCaptureMachine::~AuraWindowCaptureMachine() {} void AuraWindowCaptureMachine::Start( const scoped_refptr<media::ThreadSafeCaptureOracle>& oracle_proxy, const media::VideoCaptureParams& params, const base::Callback<void(bool)> callback) { // Starts the capture machine asynchronously. BrowserThread::PostTaskAndReplyWithResult( BrowserThread::UI, FROM_HERE, base::Bind(&AuraWindowCaptureMachine::InternalStart, base::Unretained(this), oracle_proxy, params), callback); } bool AuraWindowCaptureMachine::InternalStart( const scoped_refptr<media::ThreadSafeCaptureOracle>& oracle_proxy, const media::VideoCaptureParams& params) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // The window might be destroyed between SetWindow() and Start(). if (!desktop_window_) return false; // If the associated layer is already destroyed then return failure. ui::Layer* layer = desktop_window_->layer(); if (!layer) return false; DCHECK(oracle_proxy); oracle_proxy_ = oracle_proxy; capture_params_ = params; // Update capture size. UpdateCaptureSize(); // Start observing compositor updates. aura::WindowTreeHost* const host = desktop_window_->GetHost(); ui::Compositor* const compositor = host ? host->compositor() : nullptr; if (!compositor) return false; compositor->AddAnimationObserver(this); power_save_blocker_.reset( PowerSaveBlocker::Create( PowerSaveBlocker::kPowerSaveBlockPreventDisplaySleep, PowerSaveBlocker::kReasonOther, "DesktopCaptureDevice is running").release()); return true; } void AuraWindowCaptureMachine::Stop(const base::Closure& callback) { // Stops the capture machine asynchronously. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &AuraWindowCaptureMachine::InternalStop, base::Unretained(this), callback)); } void AuraWindowCaptureMachine::InternalStop(const base::Closure& callback) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Cancel any and all outstanding callbacks owned by external modules. weak_factory_.InvalidateWeakPtrs(); power_save_blocker_.reset(); // Stop observing compositor and window events. if (desktop_window_) { if (aura::WindowTreeHost* host = desktop_window_->GetHost()) { if (ui::Compositor* compositor = host->compositor()) compositor->RemoveAnimationObserver(this); } desktop_window_->RemoveObserver(this); desktop_window_ = NULL; cursor_renderer_.reset(); } callback.Run(); } void AuraWindowCaptureMachine::MaybeCaptureForRefresh() { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&AuraWindowCaptureMachine::Capture, // Use of Unretained() is safe here since this task must run // before InternalStop(). base::Unretained(this), base::TimeTicks())); } void AuraWindowCaptureMachine::SetWindow(aura::Window* window) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!desktop_window_); desktop_window_ = window; cursor_renderer_.reset(new CursorRendererAura(window, kCursorAlwaysEnabled)); // Start observing window events. desktop_window_->AddObserver(this); // We must store this for the UMA reporting in DidCopyOutput() as // desktop_window_ might be destroyed at that point. screen_capture_ = window->IsRootWindow(); IncrementDesktopCaptureCounter(screen_capture_ ? SCREEN_CAPTURER_CREATED : WINDOW_CAPTURER_CREATED); } void AuraWindowCaptureMachine::UpdateCaptureSize() { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (oracle_proxy_ && desktop_window_) { ui::Layer* layer = desktop_window_->layer(); oracle_proxy_->UpdateCaptureSize(ui::ConvertSizeToPixel( layer, layer->bounds().size())); } cursor_renderer_->Clear(); } void AuraWindowCaptureMachine::Capture(base::TimeTicks event_time) { DCHECK_CURRENTLY_ON(BrowserThread::UI); // Do not capture if the desktop window is already destroyed. if (!desktop_window_) return; scoped_refptr<media::VideoFrame> frame; media::ThreadSafeCaptureOracle::CaptureFrameCallback capture_frame_cb; // TODO(miu): Need to fix this so the compositor is providing the presentation // timestamps and damage regions, to leverage the frame timestamp rewriting // logic. http://crbug.com/492839 const base::TimeTicks start_time = base::TimeTicks::Now(); media::VideoCaptureOracle::Event event; if (event_time.is_null()) { event = media::VideoCaptureOracle::kActiveRefreshRequest; event_time = start_time; } else { event = media::VideoCaptureOracle::kCompositorUpdate; } if (oracle_proxy_->ObserveEventAndDecideCapture( event, gfx::Rect(), event_time, &frame, &capture_frame_cb)) { std::unique_ptr<cc::CopyOutputRequest> request = cc::CopyOutputRequest::CreateRequest(base::Bind( &AuraWindowCaptureMachine::DidCopyOutput, weak_factory_.GetWeakPtr(), frame, event_time, start_time, capture_frame_cb)); gfx::Rect window_rect = gfx::Rect(desktop_window_->bounds().width(), desktop_window_->bounds().height()); request->set_area(window_rect); desktop_window_->layer()->RequestCopyOfOutput(std::move(request)); } } void AuraWindowCaptureMachine::DidCopyOutput( scoped_refptr<media::VideoFrame> video_frame, base::TimeTicks event_time, base::TimeTicks start_time, const CaptureFrameCallback& capture_frame_cb, std::unique_ptr<cc::CopyOutputResult> result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); static bool first_call = true; const bool succeeded = ProcessCopyOutputResponse( video_frame, event_time, capture_frame_cb, std::move(result)); const base::TimeDelta capture_time = base::TimeTicks::Now() - start_time; // The two UMA_ blocks must be put in its own scope since it creates a static // variable which expected constant histogram name. if (screen_capture_) { UMA_HISTOGRAM_TIMES(kUmaScreenCaptureTime, capture_time); } else { UMA_HISTOGRAM_TIMES(kUmaWindowCaptureTime, capture_time); } if (first_call) { first_call = false; if (screen_capture_) { IncrementDesktopCaptureCounter(succeeded ? FIRST_SCREEN_CAPTURE_SUCCEEDED : FIRST_SCREEN_CAPTURE_FAILED); } else { IncrementDesktopCaptureCounter(succeeded ? FIRST_WINDOW_CAPTURE_SUCCEEDED : FIRST_WINDOW_CAPTURE_FAILED); } } // If ProcessCopyOutputResponse() failed, it will not run |capture_frame_cb|, // so do that now. if (!succeeded) capture_frame_cb.Run(video_frame, event_time, false); } bool AuraWindowCaptureMachine::ProcessCopyOutputResponse( scoped_refptr<media::VideoFrame> video_frame, base::TimeTicks event_time, const CaptureFrameCallback& capture_frame_cb, std::unique_ptr<cc::CopyOutputResult> result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); if (!desktop_window_) { VLOG(1) << "Ignoring CopyOutputResult: Capture target has gone away."; return false; } if (result->IsEmpty()) { VLOG(1) << "CopyOutputRequest failed: No texture or bitmap in result."; return false; } if (result->size().IsEmpty()) { VLOG(1) << "CopyOutputRequest failed: Zero-area texture/bitmap result."; return false; } DCHECK(video_frame); // Compute the dest size we want after the letterboxing resize. Make the // coordinates and sizes even because we letterbox in YUV space // (see CopyRGBToVideoFrame). They need to be even for the UV samples to // line up correctly. // The video frame's visible_rect() and the result's size() are both physical // pixels. gfx::Rect region_in_frame = media::ComputeLetterboxRegion( video_frame->visible_rect(), result->size()); region_in_frame = gfx::Rect(region_in_frame.x() & ~1, region_in_frame.y() & ~1, region_in_frame.width() & ~1, region_in_frame.height() & ~1); if (region_in_frame.IsEmpty()) { VLOG(1) << "Aborting capture: Computed empty letterboxed content region."; return false; } ImageTransportFactory* factory = ImageTransportFactory::GetInstance(); display_compositor::GLHelper* gl_helper = factory->GetGLHelper(); if (!gl_helper) { VLOG(1) << "Aborting capture: No GLHelper available for YUV readback."; return false; } cc::TextureMailbox texture_mailbox; std::unique_ptr<cc::SingleReleaseCallback> release_callback; result->TakeTexture(&texture_mailbox, &release_callback); DCHECK(texture_mailbox.IsTexture()); if (!texture_mailbox.IsTexture()) { VLOG(1) << "Aborting capture: Failed to take texture from mailbox."; return false; } gfx::Rect result_rect(result->size()); if (!yuv_readback_pipeline_ || yuv_readback_pipeline_->scaler()->SrcSize() != result_rect.size() || yuv_readback_pipeline_->scaler()->SrcSubrect() != result_rect || yuv_readback_pipeline_->scaler()->DstSize() != region_in_frame.size()) { yuv_readback_pipeline_.reset(gl_helper->CreateReadbackPipelineYUV( display_compositor::GLHelper::SCALER_QUALITY_FAST, result_rect.size(), result_rect, region_in_frame.size(), true, true)); } cursor_renderer_->SnapshotCursorState(region_in_frame); yuv_readback_pipeline_->ReadbackYUV( texture_mailbox.mailbox(), texture_mailbox.sync_token(), video_frame->visible_rect(), video_frame->stride(media::VideoFrame::kYPlane), video_frame->data(media::VideoFrame::kYPlane), video_frame->stride(media::VideoFrame::kUPlane), video_frame->data(media::VideoFrame::kUPlane), video_frame->stride(media::VideoFrame::kVPlane), video_frame->data(media::VideoFrame::kVPlane), region_in_frame.origin(), base::Bind(&CopyOutputFinishedForVideo, weak_factory_.GetWeakPtr(), event_time, capture_frame_cb, video_frame, base::Passed(&release_callback))); media::LetterboxYUV(video_frame.get(), region_in_frame); return true; } using CaptureFrameCallback = media::ThreadSafeCaptureOracle::CaptureFrameCallback; void AuraWindowCaptureMachine::CopyOutputFinishedForVideo( base::WeakPtr<AuraWindowCaptureMachine> machine, base::TimeTicks event_time, const CaptureFrameCallback& capture_frame_cb, const scoped_refptr<media::VideoFrame>& target, std::unique_ptr<cc::SingleReleaseCallback> release_callback, bool result) { DCHECK_CURRENTLY_ON(BrowserThread::UI); release_callback->Run(gpu::SyncToken(), false); // Render the cursor and deliver the captured frame if the // AuraWindowCaptureMachine has not been stopped (i.e., the WeakPtr is // still valid). if (machine) { if (machine->cursor_renderer_ && result) machine->cursor_renderer_->RenderOnVideoFrame(target); } else { VLOG(1) << "Aborting capture: AuraWindowCaptureMachine has gone away."; result = false; } capture_frame_cb.Run(target, event_time, result); } void AuraWindowCaptureMachine::OnWindowBoundsChanged( aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(desktop_window_ && window == desktop_window_); // Post a task to update capture size after first returning to the event loop. BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind( &AuraWindowCaptureMachine::UpdateCaptureSize, weak_factory_.GetWeakPtr())); } void AuraWindowCaptureMachine::OnWindowDestroying(aura::Window* window) { DCHECK_CURRENTLY_ON(BrowserThread::UI); InternalStop(base::Bind(&base::DoNothing)); oracle_proxy_->ReportError(FROM_HERE, "OnWindowDestroying()"); } void AuraWindowCaptureMachine::OnWindowAddedToRootWindow( aura::Window* window) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(window == desktop_window_); if (aura::WindowTreeHost* host = window->GetHost()) { if (ui::Compositor* compositor = host->compositor()) compositor->AddAnimationObserver(this); } } void AuraWindowCaptureMachine::OnWindowRemovingFromRootWindow( aura::Window* window, aura::Window* new_root) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(window == desktop_window_); if (aura::WindowTreeHost* host = window->GetHost()) { if (ui::Compositor* compositor = host->compositor()) compositor->RemoveAnimationObserver(this); } } void AuraWindowCaptureMachine::OnAnimationStep(base::TimeTicks timestamp) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!timestamp.is_null()); // HACK: The compositor invokes this observer method to step layer animation // forward. Scheduling frame capture was not the intention, and so invoking // this method does not actually indicate the content has changed. However, // this is the only reliable way to ensure all screen changes are captured, as // of this writing. // http://crbug.com/600031 // // TODO(miu): Need a better observer callback interface from the compositor // for this use case. The solution here will always capture frames at the // maximum framerate, which means CPU/GPU is being wasted on redundant // captures and quality/smoothness of animating content will suffer // significantly. // http://crbug.com/492839 Capture(timestamp); } void AuraWindowCaptureMachine::OnCompositingShuttingDown( ui::Compositor* compositor) { DCHECK_CURRENTLY_ON(BrowserThread::UI); compositor->RemoveAnimationObserver(this); } } // namespace content
15,353
4,877
#include "Playlist.h" Playlist::Playlist(const std::string &name) { // Custom consructor. static int playlistId = 1; this->name = name; this->shared = false; this->playlistId = playlistId; playlistId += 1; } int Playlist::getPlaylistId() const { // Returns playlist ID. return this->playlistId; } const std::string &Playlist::getName() const { // Returns playlist name. return this->name; } bool Playlist::isShared() const { // Returns whether the playlist is shared or not. return this->shared; } LinkedList<Song *> &Playlist::getSongs() { // Returns the list of songs. return this->songs; } void Playlist::setShared(bool shared) { // Sets whether the playlist is shared. this->shared = shared; } void Playlist::addSong(Song *song) { // Adds song to the end of the playlist this->songs.insertAtTheEnd(song); } void Playlist::dropSong(Song *song) { // Removes given song from the playlist. this->songs.removeNode(song); } void Playlist::shuffle(int seed) { // Shuffles the songs in the playlist with a given seed. this->songs.shuffle(seed); } bool Playlist::operator==(const Playlist &rhs) const { // Overloaded equality operator. return this->playlistId == rhs.playlistId && this->name == rhs.name && this->shared == rhs.shared; } bool Playlist::operator!=(const Playlist &rhs) const { // Overloaded inequality operator. return !(rhs == *this); } std::ostream &operator<<(std::ostream &os, const Playlist &playlist) { // Overloaded operator to print playlist to output stream. os << "playlistId: " << playlist.playlistId << " |"; os << " name: " << playlist.name << " |"; os << " shared: " << (playlist.shared ? "yes" : "no") << " |"; os << " songs: ["; Node<Song *> *firstSongNode = playlist.songs.getFirstNode(); Node<Song *> *songNode = firstSongNode; if (songNode) { do { os << *(songNode->data); if (songNode->next != firstSongNode) os << ", "; songNode = songNode->next; } while (songNode != firstSongNode); } os << "]"; return os; }
2,121
707
//===- unittests/BuildSystem/TempDir.cpp --------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "TempDir.h" #include "llbuild/Basic/FileSystem.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/SourceMgr.h" llbuild::TmpDir::TmpDir(llvm::StringRef namePrefix) { llvm::SmallString<256> tempDirPrefix; llvm::sys::path::system_temp_directory(true, tempDirPrefix); llvm::sys::path::append(tempDirPrefix, namePrefix); std::error_code ec = llvm::sys::fs::createUniqueDirectory( tempDirPrefix.str(), tempDir); assert(!ec); (void)ec; } llbuild::TmpDir::~TmpDir() { auto fs = basic::createLocalFileSystem(); bool result = fs->remove(tempDir.c_str()); assert(result); (void)result; } const char *llbuild::TmpDir::c_str() { return tempDir.c_str(); } std::string llbuild::TmpDir::str() const { return tempDir.str(); }
1,331
436
// Copyright (c) 2017-2018, Cryptogogue Inc. All Rights Reserved. // http://cryptogogue.com #include <padamose/AbstractVersionedBranch.h> #include <padamose/BranchInspector.h> namespace Padamose { //================================================================// // BranchInspector //================================================================// //----------------------------------------------------------------// BranchInspector::BranchInspector ( shared_ptr < AbstractVersionedBranch > branch ) : mBranch ( branch ) { } //----------------------------------------------------------------// BranchInspector::BranchInspector ( const BranchInspector& branchInspector ) : mBranch ( branchInspector.mBranch ) { } //----------------------------------------------------------------// BranchInspector::~BranchInspector () { } //----------------------------------------------------------------// size_t BranchInspector::countDependencies () const { shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock (); assert ( branch ); return branch->countDependencies (); } //----------------------------------------------------------------// size_t BranchInspector::getBaseVersion () const { shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock (); assert ( branch ); return branch->getVersion (); } //----------------------------------------------------------------// size_t BranchInspector::getImmutableTop () const { shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock (); assert ( branch ); return branch->findImmutableTop (); } //----------------------------------------------------------------// size_t BranchInspector::getTopVersion () const { shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock (); assert ( branch ); return branch->getTopVersion (); } //----------------------------------------------------------------// bool BranchInspector::hasKey ( size_t version, string key ) const { shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock (); assert ( branch ); return branch->hasKey ( version, key ); } //----------------------------------------------------------------// bool BranchInspector::isLocked () const { shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock (); assert ( branch ); return branch->isLocked (); } //----------------------------------------------------------------// bool BranchInspector::isPersistent () const { shared_ptr < AbstractVersionedBranch > branch = this->mBranch.lock (); assert ( branch ); return branch->isPersistent (); } } // namespace Padamose
2,691
679
#include <arpa/inet.h> #include <array> #include <condition_variable> #include <cstring> #include <liburing.h> #include <netdb.h> #include <signal.h> #include <string> #include <sys/socket.h> #include <thread> #include <unistd.h> #include <uring/relay.hpp> #include <vector> #define ENABLE_FIXED_BUFFERS 1 #define ENABLE_FIXED_FILE 1 #define ENABLE_SQPOLL 0 namespace urn_uring { config::config(int argc, const char* argv[]) : threads{static_cast<uint16_t>(std::thread::hardware_concurrency())} { for (int i = 1; i < argc; i++) { std::string_view arg(argv[i]); if (arg == "--threads") { threads = atoi(argv[++i]); } else if (arg == "--client.port") { client.port = argv[++i]; } else if (arg == "--peer.port") { peer.port = argv[++i]; } else { printf("unused flag: %s\n", argv[i]); } } if (!threads) { threads = 1; } std::cout << "threads = " << threads << "\nclient.port = " << client.port << "\npeer.port = " << peer.port << '\n'; } namespace { void ensure_success(int code) { if (code >= 0) { return; } fprintf(stderr, "%s\n", strerror(-code)); abort(); } struct listen_context; constexpr int32_t num_events = 16; // per thread constexpr int32_t memory_per_packet = 1024; volatile sig_atomic_t has_sigint = 0; thread_local listen_context* local_io = nullptr; enum ring_event_type { ring_event_type_invalid = 0, ring_event_type_client_rx = 1, ring_event_type_peer_rx = 2, ring_event_type_peer_tx = 3, ring_event_type_timer = 4, ring_event_MAX }; struct ring_event { ring_event_type type; int32_t index; union { struct { struct iovec iov; struct sockaddr_in address; struct msghdr message; } rx; __kernel_timespec timeout; }; }; constexpr int64_t k_statistics_timeout_ms = 5000; struct countdown_latch { countdown_latch(int64_t count) : count{count} {} void wait() { std::unique_lock<std::mutex> lock(mtx); int64_t gen = generation; if (--count == 0) { ++generation; cond.notify_all(); return; } cond.wait(lock, [&]() { return gen != generation; }); } int64_t count; int64_t generation = 0; std::mutex mtx = {}; std::condition_variable cond = {}; }; struct worker_args { urn_uring::relay* relay = nullptr; struct addrinfo* local_client_address = nullptr; struct addrinfo* local_peer_address = nullptr; int32_t thread_index = 0; countdown_latch* startup_latch = nullptr; }; struct listen_context { // Either FD or ID depending on the usage of registered fds int peer_socket = -1; int client_socket = -1; struct io_uring ring = {}; urn_uring::relay* relay = nullptr; uint8_t* messages_buffer = nullptr; std::array<ring_event, num_events> io_events = {}; std::vector<int32_t> free_event_ids = {}; int peer_socket_fd = -1; int client_socket_fd = -1; int sockets[2] = {}; worker_args worker_info = {}; struct iovec buffers_mem = {}; }; void print_address(const struct addrinfo* address) { char readable_ip[INET6_ADDRSTRLEN] = {0}; if (address->ai_family == AF_INET) { struct sockaddr_in* ipv4 = (struct sockaddr_in*) address->ai_addr; inet_ntop(ipv4->sin_family, &ipv4->sin_addr, readable_ip, sizeof(readable_ip)); printf("%s:%d\n", readable_ip, ntohs(ipv4->sin_port)); } else if (address->ai_family == AF_INET6) { struct sockaddr_in6* ipv6 = (struct sockaddr_in6*) address->ai_addr; inet_ntop(ipv6->sin6_family, &ipv6->sin6_addr, readable_ip, sizeof(readable_ip)); printf("[%s]:%d\n", readable_ip, ntohs(ipv6->sin6_port)); } } int create_udp_socket(struct addrinfo* address_list) { // quickhack: only use the first address struct addrinfo* address = address_list; int socket_fd = socket(address->ai_family, address->ai_socktype, address->ai_protocol); ensure_success(socket_fd); { int size = 4129920; ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size))); } { int size = 4129920; ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_SNDBUF, &size, sizeof(size))); } { int enable = 1; ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable))); } { int enable = 1; ensure_success(setsockopt(socket_fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable))); } return socket_fd; } void bind_socket(int fd, struct addrinfo* address) { int bind_status = bind(fd, address->ai_addr, address->ai_addrlen); if (bind_status == 0) { return; } printf("error binding socket: %s\n", strerror(bind_status)); abort(); } ring_event* alloc_event(listen_context* context, ring_event_type type) { if (context->free_event_ids.size() == 0) { printf("[thread %d] out of free events\n", context->worker_info.thread_index); abort(); return nullptr; } int32_t free_id = context->free_event_ids.back(); context->free_event_ids.pop_back(); ring_event* event = &context->io_events[free_id]; event->type = type; event->index = free_id; event->rx.iov.iov_base = &context->messages_buffer[free_id * memory_per_packet]; event->rx.iov.iov_len = memory_per_packet; event->rx.message.msg_name = &event->rx.address; event->rx.message.msg_namelen = sizeof(event->rx.address); event->rx.message.msg_iov = &event->rx.iov; event->rx.message.msg_iovlen = 1; return event; } void release_event(listen_context* context, ring_event* ev) { context->free_event_ids.push_back(ev->index); } void report_features(const struct io_uring_params* params) { uint32_t features = params->features; auto get_name = [](uint32_t feature) { switch (feature) { case IORING_FEAT_SINGLE_MMAP: return "IORING_FEAT_SINGLE_MMAP"; case IORING_FEAT_NODROP: return "IORING_FEAT_NODROP"; case IORING_FEAT_SUBMIT_STABLE: return "IORING_FEAT_SUBMIT_STABLE"; case IORING_FEAT_CUR_PERSONALITY: return "IORING_FEAT_CUR_PERSONALITY"; case IORING_FEAT_FAST_POLL: return "IORING_FEAT_FAST_POLL"; case IORING_FEAT_POLL_32BITS: return "IORING_FEAT_POLL_32BITS"; case IORING_FEAT_SQPOLL_NONFIXED: return "IORING_FEAT_SQPOLL_NONFIXED"; default: return "unknown"; } }; const uint32_t known_features[] = {IORING_FEAT_SINGLE_MMAP, IORING_FEAT_NODROP, IORING_FEAT_SUBMIT_STABLE, IORING_FEAT_CUR_PERSONALITY, IORING_FEAT_FAST_POLL, IORING_FEAT_POLL_32BITS, IORING_FEAT_SQPOLL_NONFIXED}; printf("supported features:\n"); for (uint32_t feature : known_features) { if (features & feature) { printf("\t%s\n", get_name(feature)); } } } bool is_main_worker(const listen_context* io) { return io->worker_info.thread_index == 0; } void listen_context_initialize(listen_context* io, worker_args args) { io->worker_info = args; io->relay = args.relay; struct io_uring_params params; memset(&params, 0, sizeof(params)); if (ENABLE_SQPOLL) { params.flags |= IORING_SETUP_SQPOLL; params.sq_thread_idle = 1000; printf("[thread %d] using SQPOLL\n", args.thread_index); } ensure_success(io_uring_queue_init_params(4096, &io->ring, &params)); if (is_main_worker(io)) { report_features(&params); } io->client_socket_fd = create_udp_socket(args.local_client_address); io->peer_socket_fd = create_udp_socket(args.local_peer_address); printf("[thread %d] sockets: %d %d\n", args.thread_index, io->client_socket_fd, io->peer_socket_fd); if (ENABLE_FIXED_FILE) { io->sockets[0] = io->peer_socket_fd; io->sockets[1] = io->client_socket_fd; ensure_success(io_uring_register_files(&io->ring, io->sockets, 2)); io->peer_socket = 0; io->client_socket = 1; printf("[thread %d] using fixed files\n", args.thread_index); } else { io->client_socket = io->client_socket_fd; io->peer_socket = io->peer_socket_fd; } io->messages_buffer = (uint8_t*) calloc(num_events, memory_per_packet); io->free_event_ids.reserve(num_events); for (int32_t i = 0; i < num_events; i++) { io->free_event_ids.push_back(i); } if (ENABLE_FIXED_BUFFERS) { io->buffers_mem.iov_base = io->messages_buffer; io->buffers_mem.iov_len = num_events * memory_per_packet; ensure_success(io_uring_register_buffers(&io->ring, &io->buffers_mem, 1)); printf("[thread %d] using fixed buffers\n", args.thread_index); } } struct addrinfo* bindable_address(const char* port) { struct addrinfo hints; std::memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_DGRAM; hints.ai_flags = AI_PASSIVE; struct addrinfo* addr = nullptr; ensure_success(getaddrinfo(nullptr, port, &hints, &addr)); return addr; } __kernel_timespec create_timeout(int64_t milliseconds) { __kernel_timespec spec; spec.tv_sec = milliseconds / 1000; spec.tv_nsec = (milliseconds % 1000) * 1000000; return spec; } #if ENABLE_FIXED_FILE void enable_fixed_file(struct io_uring_sqe* sqe) { sqe->flags |= IOSQE_FIXED_FILE; } #else void enable_fixed_file(struct io_uring_sqe*) {} #endif #if ENABLE_FIXED_BUFFERS void enable_fixed_buffers(struct io_uring_sqe* sqe) { // One huge slab is registered and then partitioned manually sqe->buf_index = 0; } #else void enable_fixed_buffers(struct io_uring_sqe*) {} #endif void add_recvmsg(struct io_uring* ring, ring_event* ev, int32_t socket_id) { struct io_uring_sqe* sqe = io_uring_get_sqe(ring); if (!sqe) abort(); io_uring_prep_recvmsg(sqe, socket_id, &ev->rx.message, 0); io_uring_sqe_set_data(sqe, ev); enable_fixed_file(sqe); enable_fixed_buffers(sqe); } void add_sendmsg(struct io_uring* ring, ring_event* ev, int32_t socket_id) { struct io_uring_sqe* sqe = io_uring_get_sqe(ring); if (!sqe) abort(); io_uring_prep_sendmsg(sqe, socket_id, &ev->rx.message, 0); io_uring_sqe_set_data(sqe, ev); enable_fixed_file(sqe); enable_fixed_buffers(sqe); } void add_timeout(struct io_uring* ring, ring_event* ev, int64_t milliseconds) { ev->timeout = create_timeout(milliseconds); struct io_uring_sqe* sqe = io_uring_get_sqe(ring); if (!sqe) abort(); io_uring_prep_timeout(sqe, &ev->timeout, 0, 0); io_uring_sqe_set_data(sqe, ev); } void worker(worker_args args) { auto iop = std::make_unique<listen_context>(); listen_context* io = iop.get(); local_io = io; listen_context_initialize(io, args); struct io_uring* ring = &io->ring; args.startup_latch->wait(); bind_socket(io->client_socket_fd, args.local_client_address); bind_socket(io->peer_socket_fd, args.local_peer_address); io->relay->on_thread_start(args.thread_index); { ring_event* ev = alloc_event(io, ring_event_type_client_rx); add_recvmsg(ring, ev, io->client_socket); } { ring_event* ev = alloc_event(io, ring_event_type_peer_rx); add_recvmsg(ring, ev, io->peer_socket); } if (is_main_worker(io)) { ring_event* ev = alloc_event(io, ring_event_type_timer); add_timeout(ring, ev, k_statistics_timeout_ms); } for (;;) { io_uring_submit_and_wait(ring, 1); struct io_uring_cqe* cqe; uint32_t head; uint32_t count = 0; io_uring_for_each_cqe(ring, head, cqe) { ++count; ring_event* event = (ring_event*) cqe->user_data; switch (event->type) { case ring_event_type_peer_rx: { if (cqe->res < 0) { printf("thread [%d] peer rx %s\n", args.thread_index, strerror(-cqe->res)); abort(); } const msghdr* message = &event->rx.message; uring::packet packet{(const std::byte*) message->msg_iov->iov_base, (uint32_t) cqe->res}; io->relay->on_peer_received(uring::endpoint(event->rx.address, io), packet); release_event(io, event); ring_event* rx_event = alloc_event(io, ring_event_type_peer_rx); add_recvmsg(ring, rx_event, io->peer_socket); break; } case ring_event_type_peer_tx: { uring::packet packet{(const std::byte*) event->rx.message.msg_iov->iov_base, (uint32_t) cqe->res}; io->relay->on_session_sent(packet); release_event(io, event); break; } case ring_event_type_client_rx: { if (cqe->res < 0) { printf("thread [%d] client rx: %s\n", args.thread_index, strerror(-cqe->res)); abort(); } const msghdr* message = &event->rx.message; io->relay->on_client_received( uring::endpoint(event->rx.address, io), uring::packet((const std::byte*) message->msg_iov->iov_base, cqe->res)); release_event(io, event); ring_event* rx_event = alloc_event(io, ring_event_type_client_rx); add_recvmsg(ring, rx_event, io->client_socket); break; } case ring_event_type_timer: { io->relay->on_statistics_tick(); add_timeout(ring, event, k_statistics_timeout_ms); // reuse break; } default: { printf("unhandled ev\n"); release_event(io, event); break; } } } io_uring_cq_advance(ring, count); if (has_sigint) { break; } } printf("%d worker exiting \n", io->worker_info.thread_index); io_uring_queue_exit(ring); } void handle_sigint(int) { has_sigint = 1; } } // namespace relay::relay(const urn_uring::config& conf) noexcept : config_{conf}, logic_{config_.threads, client_, peer_} {} int relay::run() noexcept { if (ENABLE_SQPOLL) { if (geteuid() != 0) { printf("SQPOLL needs sudo\n"); return 1; } } signal(SIGINT, handle_sigint); int32_t thread_count = std::max(uint16_t(1), config_.threads); struct addrinfo* local_client_address = bindable_address("3478"); struct addrinfo* local_peer_address = bindable_address("3479"); print_address(local_client_address); print_address(local_peer_address); countdown_latch latch(thread_count); auto make_worker_args = [=, &latch](int32_t thread_index) { worker_args args; args.relay = this; args.local_client_address = local_client_address; args.local_peer_address = local_peer_address; args.thread_index = thread_index; args.startup_latch = &latch; return args; }; std::vector<std::thread> worker_threads; for (int32_t i = 1; i < thread_count; i++) { worker_threads.emplace_back(worker, make_worker_args(i)); } worker_args main_thread_args = make_worker_args(0); worker(main_thread_args); printf("joining\n"); for (auto& t : worker_threads) { t.join(); } printf("joined\n"); return 0; } void uring::session::start_send(const uring::packet& packet) noexcept { listen_context* io = local_io; ring_event* tx_event = alloc_event(io, ring_event_type_peer_tx); tx_event->rx.address = client_endpoint.address; memcpy(tx_event->rx.iov.iov_base, packet.data(), packet.size()); tx_event->rx.iov.iov_len = packet.size(); add_sendmsg(&io->ring, tx_event, io->client_socket); } } // namespace urn_uring
15,219
5,915
#ifndef SQL_PARSER_FUSION_COMMON_HPP #define SQL_PARSER_FUSION_COMMON_HPP #include "sql/ast/common.hpp" #include <boost/fusion/include/adapt_struct.hpp> #endif //SQL_PARSER_FUSION_COMMON_HPP
194
91
#include "std_lib_facilities.h" int main() try{ //1 // !!Cout << "Success!\n"; //cout << "Success!\n"; //2 // !!cout << "Success!\n; //cout << "Success!\n"; //3 // !!cout << "Success" << !\n" //cout << "Success" << "!\n"; //4 // !!cout << success << '\n'; //cout << "Success" << '\n'; //5 /* !!string res=7; int res=7; vector <int> v(10); //v[5]=res; cout << "Success!\n"; */ //6 /* vector <int> v(10); // !!v(5)=7; v[5]=7; // !!if(v(5)!=7) cout << "Success!\n"; if(v[5]==7) cout << "Success!\n"; */ //7 /* // !!hianyzott a bool bool cond = true; if(cond) cout << "Success!\n"; else cout << "Fail!\n"; */ //8 // !!bool c = false; /* bool c = true; if(c) cout << "Success!\n"; else cout << "Fail!\n"; */ //9 /* string s= "ape"; // !!boo c= "fool"<s; bool c= "fool"<s; // !!if(c) if(!c) cout << "Success!\n"; */ //10 /* string s= "ape"; // !!if(s == "fool") if(s != "fool") // vagy csak if(s=="ape") cout << "Success!\n"; */ //11 /* string s = "ape"; // !!if(s == "fool") if(s != "fool") { // !!cout < "Success!\n"; cout << "Success!\n"; } */ //12 /* string s= "ape"; // !!if(s+"fool") if(s != "fool") { // !!cout < "Success!\n"; cout << "Success!\n"; } */ //13 /* vector <char> v(5); // !!for (int i=0; 0<v.size(); ++i); for(int i=0; i<v.size(); ++i); cout << "Success!\n"; */ //14 /* vector <char> v(5); for(int i=0; i<=v.size(); ++i); cout << "Success!\n"; */ //15 /* string s = "Success!\n"; // !!for(int i=0; i<6; ++i) - ez mivel 1<6 csak az elso 6 elemet iratja ki for (int i=0; i<s.size(); ++i) cout << s[i]; */ //16 /* if(true) { //then cout << "Success!\n"; cout << "Success!\n"; } else cout << "Fail!\n"; */ //17 /* int x = 2000; // !!char c = x; int c = x; if(c == 2000) cout << "Success!\n"; */ //18 /* string s = "Success!\n"; // !!for(int i=0; i<10; ++i) -erre a peldara mukodik de mi van ha az s tobb karakterlanc 10-nel ezert for (int i=0; i<s.size(); ++i) cout << s[i]; */ //19 /* // !!vector v(5); vector <int> v(5); for (int i=0; i<=v.size(); ++i); cout << "Success!\n"; */ //20 /* int i=0; int j=9; while(i<10) { // !!++j; ++i; } if(j<i) cout << "Success!\n"; */ //21 /* int x = 2; // !!double d = 5/(x-2); - eleve nemjo mert 0-val nem lehet osztani double d = 5/x; // !!if(d == 2*x+0.5) - egyik int masik double if(d != 2*x+0.5) cout << "Success!\n"; */ //22 /* // !!string <char> s = "Success!\n"; string s = "Success!\n"; // !!for (int i=0; i<=10; ++i) for (int i=0; i<s.size(); ++i) cout << s[i]; */ //23 /* int i=0; // !!hianyos j deklaracio int j=9; while(i<10) { // !!++j; ++i; } if(j<i) cout << "Success!\n"; */ //24 /* int x=4; // !!double d=5/(x–2); - '–' nem kivonas jel double d = 5/(x-2); // !!if(d = 2*x+0.5) - igy mukodik de helytelen a struktura //if(d == 2*x+0.5) - igy viszont nem mukodik if(d != 2*x+0.5) cout << "Success!\n"; */ //25 /* // !!cin << "Success!\n"; cout << "Success!\n"; */ return 0; } catch(exception& e) //out_of_range; run_time_error { cerr << "error: " << e.what() << "\n"; return 1; } catch(...) //minden { cerr << "Oops: unknown exception!\n"; return 2; }
3,244
1,753
#include "image.h" #include <stdio.h> #ifndef max #define max(a, b) (((a)>(b))?(a):(b)) #endif #ifndef min #define min(a, b) (((a)<(b))?(a):(b)) #endif unsigned char getByte(); char fileOpen(const char *); void decodeQTable(int); void strmSkip(int n); void decodeBlock(); void fileClose(); void getInfo(); void fidct(); int wordDec(int); typedef unsigned short qTable[64]; typedef struct { struct tables { unsigned char size; unsigned char code; } small[512], large[65536]; } HuffTable; void decodeHuffTable(int); typedef struct { HuffTable *huffAC, *huffDC; qTable *qTab; int dcPrev,smpx, smpy; float t[256]; }ComponentTable; ComponentTable component[4]; HuffTable huffTableAC[4], huffTableDC[4]; qTable qtable[4]; int xblock, yblock, blockx, blocky, bsize, restartInt, bfree; unsigned int dt; unsigned char *data, *bpos , *dend, eof , ssStart, ssEnd, sbits, prec , ncomp; float dctt[64]; int zigzag[64]= { 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63 }; char fileOpen(const char *filename) { FILE *stream; data = NULL; if ((stream=fopen(filename, "rb"))==NULL) return 0; else { fseek(stream, 0, SEEK_END); bsize = ftell(stream); fseek(stream, 0, SEEK_SET); data = new unsigned char[bsize]; fread(data, 1, bsize, stream); fclose(stream); return 1; } } void fileClose(void) { if (data) delete[] data; } unsigned char getByte(void) { if (bpos>=dend) { eof = 1; return 0; } else return *bpos++; } void strmSkip(int n) { unsigned char a, b; bfree+=n; dt<<=n; while (bfree>=8) { bfree-=8; b = getByte(); if (b==255) a=getByte(); dt|=(b<<bfree); } } int huffDec(HuffTable *h) { unsigned int id, n, c; id = (dt>>(23)); n = h->small[id].size; c = h->small[id].code; if (n==255) { id = (dt>>(16)); n = h->large[id].size; c = h->large[id].code; } strmSkip(n); return c; } int wordDec(int n) { int w; unsigned int s; if (n==0) return 0; else { s= (dt>>(31)); w= (dt>>(32-n)); strmSkip(n); if (s==0) w = (w|(0xffffffff<<n))+1; } return w; } void Image::getJPGInfo() { unsigned char cn, sf, qt; int i; prec = getByte(); if (prec!=8) return; height = ((getByte()<<8)+getByte()); width = ((getByte()<<8)+getByte()); ncomp = getByte(); if ((ncomp!=3)&&(ncomp!=1)) return; for (i=0;i<ncomp;i++) { cn = getByte(); sf = getByte(); qt = getByte(); component[cn-1].qTab = &qtable[qt]; component[cn-1].smpy = sf&15; component[cn-1].smpx = (sf>>4)&15; } if (component[0].smpx == 1) blockx = 8; else blockx = 16; if (component[0].smpy==1) blocky = 8; else blocky = 16; xblock=width/blockx; if ((width & (blockx-1))!=0) xblock++; yblock = height/blocky; if ((height&(blocky-1))!=0) yblock++; } void decodeHuffTable(int len) { int length[257], i, j, n, code, codelen, delta, rcode, cd, rng; unsigned char lengths[16], b, symbol[257]; HuffTable *h; len-=2; while (len>0) { b = getByte(); len--; h = &huffTableDC[0]; switch (b) { case 0: h = &huffTableDC[0]; break; case 1: h = &huffTableDC[1]; break; case 16: h = &huffTableAC[0]; break; case 17: h=&huffTableAC[1]; break; } for (i=0;i<16;i++) lengths[i] = getByte(); len -= 16; n = 0; for (i=0;i<16;i++) { len-=lengths[i]; for (j=0;j<lengths[i];j++) { symbol[n] = getByte(); length[n++] = i+1; } } code = 0; codelen = length[0]; for (i=0;i<n;i++) { rcode = code<<(16-codelen); cd = rcode>>7; if (codelen<=9) { rng = 1 <<(9-codelen); for (j=cd;j<cd+rng;j++) { h->small[j].code = (unsigned char)symbol[i]; h->small[j].size = (unsigned char)codelen; } } else { h->small[cd].size=(unsigned char)255; rng = 1<<(16-codelen); for (j=rcode;j<rcode+rng;j++) { h->large[j].code=(unsigned char)symbol[i]; h->large[j].size=(unsigned char)codelen; } } code++; delta=length[i+1]-codelen; code<<=delta; codelen+=delta; } } } void fidct(void) { float a = 0.353553385f, b = 0.490392625f, c = 0.415734798f, d = 0.277785122f, e = 0.097545162f, f = 0.461939752f, g = 0.191341713f, cd =0.6935199499f, be =0.5879377723f, bc =0.9061274529f, de =0.3753302693f, a0, f2, g2, a4, f6, g6, s0, s1, s2, s3, t0, t1, t2, t3, m0, m1, m2, m3, h0, h1, h2, h3, r0, r1, r2, r3, w; int i; for (i=0;i<64;i+=8) { if ((dctt[i+1]!=0)||(dctt[i+2]!=0)||(dctt[i+3]!=0)||(dctt[i+4]!=0)||(dctt[i+5]!=0)||(dctt[i+6]!=0)||(dctt[i+7]!=0)) { a0 = a*dctt[i]; f2 = f*dctt[i+2]; g2 = g*dctt[i+2]; a4 = a*dctt[i+4]; g6 = g*dctt[i+6]; f6 = f*dctt[i+6]; m0 = a0+a4; m1 = a0-a4; m2 = f2+g6; m3 = g2-f6; s0 = m0+m2; s1 = m1+m3; s2 = m1-m3; s3 = m0-m2; h2 = dctt[i+7]+dctt[i+1]; h3 = dctt[i+7]-dctt[i+1]; r2 = dctt[i+3]+dctt[i+5]; r3 = dctt[i+3]-dctt[i+5]; h0 = cd*dctt[i+1]; h1 = be*dctt[i+1]; r0 = be*dctt[i+5]; r1 = cd*dctt[i+3]; w = de*r3; t0 = h1+r1+e*(h3+r3)-w; t1 = h0-r0-d*(h2-r3)-w; w = bc*r2; t2 = h0+r0+c*(h3+r2)-w; t3 = h1-r1-b*(h2+r2)+w; dctt[i] = s0+t0; dctt[i+1] = s1+t1; dctt[i+2] = s2+t2; dctt[i+3] = s3+t3; dctt[i+4] = s3-t3; dctt[i+5] = s2-t2; dctt[i+6] = s1-t1; dctt[i+7] = s0-t0; } else { a0 = dctt[i]*a; dctt[i]=dctt[i+1]=dctt[i+2]=dctt[i+3]=dctt[i+4]=dctt[i+5]=dctt[i+6]=dctt[i+7]=a0; } } for (i=0;i<8;i++) { if ((dctt[8+i]!=0)||(dctt[16+i]!=0)||(dctt[24+i]!=0)||(dctt[32+i]!=0)||(dctt[40+i]!=0)||(dctt[48+i]!=0)||(dctt[56+i]!=0)) { a0 = a*dctt[i]; f2 = f*dctt[16+i]; g2 = g*dctt[16+i]; a4 = a*dctt[32+i]; g6 = g*dctt[48+i]; f6 = f*dctt[48+i]; m0 = a0+a4; m1 = a0-a4; m2 = f2+g6; m3 = g2-f6; s0 = m0+m2; s1 = m1+m3; s2 = m1-m3; s3 = m0-m2; h2 = dctt[56+i]+dctt[8+i]; h3 = dctt[56+i]-dctt[8+i]; r2 = dctt[24+i]+dctt[40+i]; r3 = dctt[24+i]-dctt[40+i]; h0 = cd*dctt[8+i]; h1 = be*dctt[8+i]; r0 = be*dctt[40+i]; r1 = cd*dctt[24+i]; w = de*r3; t0 = h1+r1+e*(h3+r3)-w; t1 = h0-r0-d*(h2-r3)-w; w = bc*r2; t2 = h0+r0+c*(h3+r2)-w; t3 = h1-r1-b*(h2+r2)+w; dctt[i] = s0+t0; dctt[i+8] = s1+t1; dctt[i+16] = s2+t2; dctt[i+24] = s3+t3; dctt[i+32] = s3-t3; dctt[i+40] = s2-t2; dctt[i+48] = s1-t1; dctt[i+56] = s0-t0; } else { a0 = dctt[i]*a; dctt[i]=dctt[i+8]=dctt[i+16]=dctt[i+24]=dctt[i+32]=dctt[i+40]=dctt[i+48]=dctt[i+56]=a0; } } } void decodeQTable(int len) { int i; unsigned char b; len-=2; while (len>0) { b = (unsigned char)getByte(); len--; if ((b&16)==0) { for (i=0;i<64;i++) qtable[b&15][i]=getByte(); len-=64; } else { for (i=0;i<64;i++) qtable[b&15][i]=((getByte()<<8)+getByte()); len-=128; } } } void decodeBlock(void) { int compn, i, j, b, p, codelen, code, cx, cy, otab[64]; qTable *qtab; for (compn=0;compn<ncomp;compn++) { qtab = component[compn].qTab; for (cy=0;cy<component[compn].smpy;cy++) { for (cx=0;cx<component[compn].smpx;cx++) { for (i=0;i<64;i++) otab[i]=0; codelen= huffDec(component[compn].huffDC); code=wordDec(codelen); otab[0] = code+component[compn].dcPrev; component[compn].dcPrev = otab[0]; i=1; while (i<64) { codelen=huffDec(component[compn].huffAC); if (codelen==0) i=64; else if (codelen==0xf0) i+=16; else { code = wordDec(codelen&15); i = i+(codelen>>4); otab[i++]=code; } } for (i=0;i<64;i++) dctt[zigzag[i]]=(float)((*qtab)[i]*otab[i]); fidct(); b=(cy<<7)+(cx<<3); p=0; for (i=0;i<8;i++) { for (j=0;j<8;j++) component[compn].t[b++]=dctt[p++]+128; b+=8; } } } } } int Image::decodeScanJPG() { int nnx, nny, i, j; int xmin, ymin, xmax, ymax, blockn, adr1, adr2; int y1, u1, v1, y2, u2, v2, u3, v3; int dux, duy, dvx, dvy; unsigned char sc, ts; float cy, cu, cv; components = int(getByte()); setFormat(GL_BGR); setInternalFormat(GL_RGB8); if (dataBuffer) deleteArray(dataBuffer); dataBuffer = new GLubyte[width*height*components]; for (i=0;i<components;i++) { sc = getByte(); ts = getByte(); component[sc-1].huffDC = &huffTableDC[ts>>4]; component[sc-1].huffAC = &huffTableAC[ts&15]; } ssStart = getByte(); ssEnd = getByte(); sbits = getByte(); if ((ssStart!=0)||(ssEnd!=63)) return 0; if (components == 3) { dux = 2+component[1].smpx-component[0].smpx; duy = 2+component[1].smpy-component[0].smpy; dvx = 2+component[2].smpx-component[0].smpx; dvy = 2+component[2].smpy-component[0].smpy; } dt = 0; bfree = 0; strmSkip(32); blockn=0; ymin=0; for (nny=0;nny<yblock;nny++) { ymax = ymin+blocky; if (ymax>height) ymax = height; xmin=0; for (nnx=0;nnx<xblock;nnx++) { xmax=xmin+blockx; if (xmax>width) xmax=width; decodeBlock(); blockn++; if ((blockn==restartInt)&&((nnx<xblock-1)||(nny<yblock-1))) { blockn=0; if (bfree!=0) strmSkip(8-bfree); if (wordDec(8)!=255) return 0; for (i=0;i<components;i++) component[i].dcPrev=0; } if (components ==3) { y1=u1=v1=0; adr1=(height-1-ymin)*width+xmin; for (i=ymin;i<ymax;i++) { adr2=adr1; adr1-=width; y2=y1; y1+=16; u3=(u1>>1)<<4; u1+=duy; v3=(v1>>1)<<4; v1+=dvy; u2=v2=0; for (j=xmin;j<xmax;j++) { int cr, cg, cb; cy=component[0].t[y2++]; cu=component[1].t[u3+(u2>>1)]-128.0f; cv=component[2].t[v3+(v2>>1)]-128.0f; cr=(int)(cy+1.402f*cv); cg=(int)(cy-0.34414f*cu-0.71414f*cv); cb=(int)(cy+1.772f*cu); dataBuffer[3*adr2] = max(0, min(255, cb)); dataBuffer[3*adr2+1] = max(0, min(255, cg)); dataBuffer[3*adr2+2] = max(0, min(255, cr)); adr2++; u2+=dux; v2+=dvx; } } } else if (components==1) { y1=0; adr1=(height-1-ymin)*width+xmin; for (i=ymin;i<ymax;i++) { adr2=adr1; adr1-=width; y2=y1; y1+=16; for (j=xmin;j<xmax;j++) { int lum=(int)component[0].t[y2++]; dataBuffer[adr2++]=max(0, min(255, lum)); } } } xmin=xmax; } ymin=ymax; } return 1; } int Image::decodeJPG() { int w; unsigned char a, hdr=0, scan=0; eof=0; bpos=data; dend=bpos+bsize; w=((getByte()<<8)+getByte()); if (w!=0xffd8) return 0; while (eof==0) { a=(unsigned char)getByte(); if (a!=0xff) return 0; a=(unsigned char)getByte(); w=((getByte()<<8)+getByte()); switch (a) { case 0xe0: if (hdr!=0) break; if (getByte()!='J') return 0; if (getByte()!='F') return 0; if (getByte()!='I') return 0; if (getByte()!='F') return 0; hdr=1; w-=4; break; case 0xc0: getJPGInfo(); w=0; break; case 0xc4: decodeHuffTable(w); w=0; break; case 0xd9: w=0; break; case 0xda: if (scan!=0) break; scan=1; if (!decodeScanJPG()) return 0; w=0; eof=1; break; case 0xdb: decodeQTable(w); w=0; break; case 0xdd: restartInt=((getByte()<<8)+getByte()); w=0; break; } while (w>2) { getByte(); w--; } } return 1; } bool Image::loadJPG(const char *filename) { int i; for (i=0;i<4;i++) component[i].dcPrev=0; restartInt=-1; if (fileOpen(filename)) { int ret= decodeJPG(); fileClose(); if (!ret) return false; return true; } else return false; }
15,059
7,049
--- client/mysql.cc.orig 2021-08-02 10:58:55 UTC +++ client/mysql.cc @@ -61,8 +61,8 @@ static char *server_version= NULL; extern "C" { #if defined(HAVE_CURSES_H) && defined(HAVE_TERM_H) -#include <curses.h> -#include <term.h> +#include <ncurses/curses.h> +#include <ncurses/term.h> #else #if defined(HAVE_TERMIOS_H) #include <termios.h> @@ -81,7 +81,7 @@ extern "C" { #endif #undef SYSV // hack to avoid syntax error #ifdef HAVE_TERM_H -#include <term.h> +#include <ncurses/term.h> #endif #endif #endif /* defined(HAVE_CURSES_H) && defined(HAVE_TERM_H) */
572
279
// Copyright (c) 2015-2020 Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/sequences/ #include <tao/seq/integer_sequence.hpp> #include <tao/seq/select.hpp> #include <type_traits> int main() { using namespace tao::seq; using S = integer_sequence< int, 4, 7, -2, 0, 3 >; using U = integer_sequence< unsigned, 42 >; static_assert( select< 0, S >::value == 4, "oops" ); static_assert( select< 1, S >::value == 7, "oops" ); static_assert( select< 2, S >::value == -2, "oops" ); static_assert( select< 3, S >::value == 0, "oops" ); static_assert( select< 4, S >::value == 3, "oops" ); static_assert( std::is_same< select< 0, S >::value_type, int >::value, "oops" ); static_assert( select< 0, U >::value == 42, "oops" ); static_assert( std::is_same< select< 0, U >::value_type, unsigned >::value, "oops" ); }
874
362
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/drive/drive_integration_service.h" #include "chrome/browser/ash/drive/drivefs_test_support.h" #include "chrome/browser/ash/file_manager/path_util.h" #include "chrome/browser/ui/app_list/search/app_list_search_test_helper.h" namespace app_list { // This class contains additional logic to set up DriveFS and enable testing for // Drive file search in the launcher. class AppListDriveSearchBrowserTest : public AppListSearchBrowserTest { public: void SetUpInProcessBrowserTestFixture() override { create_drive_integration_service_ = base::BindRepeating( &AppListDriveSearchBrowserTest::CreateDriveIntegrationService, base::Unretained(this)); service_factory_for_test_ = std::make_unique< drive::DriveIntegrationServiceFactory::ScopedFactoryForTest>( &create_drive_integration_service_); } protected: virtual drive::DriveIntegrationService* CreateDriveIntegrationService( Profile* profile) { base::ScopedAllowBlockingForTesting allow_blocking; base::FilePath mount_path = profile->GetPath().Append("drivefs"); fake_drivefs_helpers_[profile] = std::make_unique<drive::FakeDriveFsHelper>(profile, mount_path); auto* integration_service = new drive::DriveIntegrationService( profile, std::string(), mount_path, fake_drivefs_helpers_[profile]->CreateFakeDriveFsListenerFactory()); return integration_service; } private: drive::DriveIntegrationServiceFactory::FactoryCallback create_drive_integration_service_; std::unique_ptr<drive::DriveIntegrationServiceFactory::ScopedFactoryForTest> service_factory_for_test_; std::map<Profile*, std::unique_ptr<drive::FakeDriveFsHelper>> fake_drivefs_helpers_; }; // Test that Drive files can be searched. IN_PROC_BROWSER_TEST_F(AppListDriveSearchBrowserTest, DriveSearchTest) { base::ScopedAllowBlockingForTesting allow_blocking; drive::DriveIntegrationService* drive_service = drive::DriveIntegrationServiceFactory::FindForProfile(GetProfile()); ASSERT_TRUE(drive_service->IsMounted()); base::FilePath mount_path = drive_service->GetMountPointPath(); ASSERT_TRUE(base::WriteFile(mount_path.Append("my_file.gdoc"), "content")); ASSERT_TRUE( base::WriteFile(mount_path.Append("other_file.gsheet"), "content")); SearchAndWaitForProviders("my", {ResultType::kDriveSearch}); const auto results = PublishedResultsForProvider(ResultType::kDriveSearch); ASSERT_EQ(results.size(), 1u); ASSERT_TRUE(results[0]); EXPECT_EQ(base::UTF16ToASCII(results[0]->title()), "my_file"); } // Test that Drive folders can be searched. IN_PROC_BROWSER_TEST_F(AppListDriveSearchBrowserTest, DriveFolderTest) { base::ScopedAllowBlockingForTesting allow_blocking; drive::DriveIntegrationService* drive_service = drive::DriveIntegrationServiceFactory::FindForProfile(GetProfile()); ASSERT_TRUE(drive_service->IsMounted()); base::FilePath mount_path = drive_service->GetMountPointPath(); ASSERT_TRUE(base::CreateDirectory(mount_path.Append("my_folder"))); ASSERT_TRUE(base::CreateDirectory(mount_path.Append("other_folder"))); SearchAndWaitForProviders("my", {ResultType::kDriveSearch}); const auto results = PublishedResultsForProvider(ResultType::kDriveSearch); ASSERT_EQ(results.size(), 1u); ASSERT_TRUE(results[0]); EXPECT_EQ(base::UTF16ToASCII(results[0]->title()), "my_folder"); } } // namespace app_list
3,612
1,132
// // ActiveSelector.hpp // GameBT // // Created by River Liu on 15/1/2018. // Copyright © 2018 River Liu. All rights reserved. // // ActiveSelector is a Selector that actively rechecks // its children. #ifndef ActiveSelector_hpp #define ActiveSelector_hpp #include "Selector.hpp" namespace BT { class ActiveSelector : public Selector { public: ActiveSelector() : Selector("ActiveSelector") { } ActiveSelector(const std::string& _name) : Selector(_name) { } virtual ~ActiveSelector() { } inline virtual void onInitialize(Blackboard* _blackboard) override { m_CurrentChild = m_Children.end(); } virtual Status onUpdate(Blackboard* _blackboard) override { auto prev = m_CurrentChild; Selector::onInitialize(_blackboard); Status status = Selector::onUpdate(_blackboard); if (prev != m_Children.end() && prev != m_CurrentChild) { (*prev)->abort(); } return status; } inline static Behavior* create(const BehaviorParams& _params) { return new ActiveSelector; } }; } #endif /* ActiveSelector_hpp */
1,160
346
//****************************************************************************** // // Copyright (c) Microsoft. All rights reserved. // // This code is licensed under the MIT License (MIT). // // 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 "Precompiled.h" #include <ObjectModel.h> #include <MetadataScope.h> using namespace std; //#include <utility.h> //#include <WexTestClass.h> // //#define LOGFILE_OUTPUT(ftm, ...) \ // { \ // String output = L"<DebugOutput>"; \ // output += EscapeXml(String().Format(ftm, __VA_ARGS__)); \ // output += L"</DebugOutput>"; \ // WEX::Logging::Log::Xml(output); \ // } namespace ObjectModel { class DecodeMetadata : public Visitor { MetaDataConvert* _converter; wstring _currentNameSpace; ULONG GetMethodSigSize(PCCOR_SIGNATURE signature); ULONG DecodeEncodeSig(PCCOR_SIGNATURE signature, ULONG signatureLength, mdParamDef parameterToken = mdTokenNil, bool returnParameter = false, shared_ptr<ObjectModel::Symbol>* sym = nullptr); ULONG DecodeEncodeFieldSigs(PCCOR_SIGNATURE signature, ULONG signatureLength, ObjectModel::FieldInfo& elementInfo); ULONG DecodeEncodeMethodSigs(mdMethodDef methodTokenm, PCCOR_SIGNATURE signature, ULONG signatureLength, ObjectModel::MemberInfo& memberInfo); ULONG DecodeEncodeTypeSpecSigs(PCCOR_SIGNATURE signature, ULONG signatureLength, shared_ptr<ObjectModel::Symbol>* sym = nullptr); void NameFromToken(mdToken token, bool nameForParameter = true, shared_ptr<ObjectModel::Symbol>* sym = nullptr); void DecodeMetadata::DecodeParamAttrs(ULONG attrs, ObjectModel::ParameterInfo& paramInfo); public: DecodeMetadata(MetaDataConvert* converter, const wstring& currentNameSpace) : _converter(converter), _currentNameSpace(currentNameSpace) { } virtual void Visit(const shared_ptr<NameSpace>& nameSpace) { for (auto it = nameSpace->Enums.begin(); it != nameSpace->Enums.end(); it++) { (*it)->Visit(this); } for (auto it = nameSpace->Structs.begin(); it != nameSpace->Structs.end(); it++) { (*it)->Visit(this); } for (auto it = nameSpace->Delegates.begin(); it != nameSpace->Delegates.end(); it++) { (*it)->Visit(this); } for (auto it = nameSpace->Interfaces.begin(); it != nameSpace->Interfaces.end(); it++) { (*it)->Visit(this); } for (auto it = nameSpace->RuntimeClasses.begin(); it != nameSpace->RuntimeClasses.end(); it++) { (*it)->Visit(this); } for (auto it = nameSpace->ApiContracts.begin(); it != nameSpace->ApiContracts.end(); it++) { (*it)->Visit(this); } for (auto it = nameSpace->AttributeDefs.begin(); it != nameSpace->AttributeDefs.end(); it++) { (*it)->Visit(this); } } virtual void Visit(const shared_ptr<Enum>& e) { if (e->Category & ObjectModel::TypeCategory::WinRtGeneric) { return; } PopulateAttributes(e->Token, e->Attributes); wchar_t name[MaxTypeNameLen]; name[0] = 0; ULONG nameLen = 0; DWORD attrs = 0; PCCOR_SIGNATURE sig; ULONG sigLen; UVCP_CONSTANT constValue; ULONG constValueLen; e->FlagsEnum = HasAttribute(e->Token, L"System.FlagsAttribute"); size_t maxNameLen = 0; CMetadataFieldEnumerator enumFields(_converter->Scope(), e->Token); for (auto it = enumFields.begin(); it != enumFields.end(); ++it) { _converter->Scope() ->GetFieldProps(*it, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, &sig, &sigLen, nullptr, &constValue, &constValueLen); // Gather any types defined in the enumeration if (IsFdSpecialName(attrs)) { ObjectModel::FieldInfo specialTypeInfo; DecodeEncodeFieldSigs(sig, sigLen, specialTypeInfo); specialTypeInfo.ElementName = name; specialTypeInfo.IsPublic = IsFdPublic(attrs); e->SpecialNameFieldInfo.push_back(std::move(specialTypeInfo)); } else { ObjectModel::Enum::EnumerationLabel enumerationLabel = { name, *(unsigned int const*)constValue }; if (maxNameLen < enumerationLabel.EnumerationName.length()) { maxNameLen = enumerationLabel.EnumerationName.length(); } PopulateAttributes(*it, enumerationLabel.Attributes); enumerationLabel.IsPublic = IsFdPublic(attrs); enumerationLabel.HasDefault = (IsFdHasDefault(attrs) != 0); enumerationLabel.IsStatic = (IsFdStatic(attrs) != 0); enumerationLabel.IsLiteral = (IsFdLiteral(attrs) != 0); e->EnumerationLabels.push_back(std::move(enumerationLabel)); } } e->MaxElementNameLen = maxNameLen; } virtual void Visit(const shared_ptr<Struct>& s) { if (s->Category & ObjectModel::TypeCategory::WinRtGeneric) { return; } PopulateAttributes(s->Token, s->Attributes); PopulateFields(s->Token, s->Fields); } virtual void Visit(const shared_ptr<Delegate>& d) { if (d->Category & ObjectModel::TypeCategory::WinRtGeneric) { return; } PopulateAttributes(d->Token, d->Attributes); // EmitCustomAttributes(d.Token, false); PopulateMembers(d->Token, d->Members); } bool HasAttribute(mdToken token, const wchar_t* attributeName) { const void* attributeValue = nullptr; ULONG attributeLen = 0; _converter->Scope()->GetCustomAttributeByName(token, attributeName, &attributeValue, &attributeLen); if (attributeLen != 0) { return true; } return false; } void PopulateAttributes(mdToken token, multimap<const wstring, shared_ptr<Attribute>>& attributes) { if (!IsNilToken(token)) { wchar_t name[MaxTypeNameLen]; name[0] = 0; CMetadataAttributeEnumerator enumAttribs(_converter->Scope(), token, 0); for (auto it = enumAttribs.begin(); it != enumAttribs.end(); ++it) { auto attribute = make_shared<Attribute>(L"", mdTokenNil, nullptr, _converter->FileName()); if (_converter->GetCustomAttributeInformation(*it, attribute)) { attributes.insert(std::move(make_pair(attribute->Name, attribute))); } } } } void PopulateInterfaceImplInfo(mdToken tdef, vector<InterfaceImplInfo>& interfaceImplInfo) { CMetadataInterfaceImplEnumerator iiEnum(_converter->Scope(), tdef); for (auto it = iiEnum.begin(); it != iiEnum.end(); ++it) { mdToken implementsToken; _converter->Scope()->GetInterfaceImplProps(*it, nullptr, &implementsToken); shared_ptr<Symbol> symbol; NameFromToken(implementsToken, false, &symbol); InterfaceImplInfo interfaceImpl = { symbol }; PopulateAttributes(*it, interfaceImpl.Attributes); interfaceImplInfo.push_back(std::move(interfaceImpl)); } } void PopulateMembers(mdToken tdef, map<mdToken, shared_ptr<MemberInfo>>& members) { CMetadataMethodEnumerator enumMethods(_converter->Scope(), tdef); for (auto it = enumMethods.begin(); it != enumMethods.end(); ++it) { wchar_t name[MaxTypeNameLen]; name[0] = 0; ULONG nameLen = 0; DWORD attrs = 0; PCCOR_SIGNATURE sig; ULONG sigLen; _converter->Scope()->GetMemberProps( *it, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, &sig, &sigLen, nullptr, nullptr, nullptr, nullptr, nullptr); auto memberInfo = make_shared<MemberInfo>(); memberInfo->Name = name; PopulateAttributes(*it, memberInfo->Attributes); memberInfo->IsPublic = IsMdPublic(attrs); memberInfo->IsStatic = (IsMdStatic(attrs) != 0); memberInfo->IsProtected = (IsMdFamily(attrs) != 0); memberInfo->IsCtor = IsMdInstanceInitializerW(attrs, name); memberInfo->IsHideBySig = (IsMdHideBySig(attrs) != 0); memberInfo->IsSpecialName = (IsMdSpecialName(attrs) != 0); memberInfo->IsRtSpecialName = (IsMdRTSpecialName(attrs) != 0); if (HasAttribute(*it, L"Windows.Foundation.Metadata.OverloadAttribute")) { memberInfo->HasOverload = true; } if (HasAttribute(*it, L"Windows.Foundation.Metadata.DefaultOverloadAttribute")) { memberInfo->HasDefaultOverload = true; } DecodeEncodeMethodSigs(*it, sig, sigLen, *memberInfo); members.insert(std::move(std::make_pair(*it, std::move(memberInfo)))); } } void PopulateFields(mdToken tdef, vector<FieldInfo>& fields) { CMetadataFieldEnumerator enumFields(_converter->Scope(), tdef); for (auto it = enumFields.begin(); it != enumFields.end(); ++it) { wchar_t name[MaxTypeNameLen]; name[0] = 0; ULONG nameLen = 0; DWORD attrs = 0; PCCOR_SIGNATURE sig; ULONG sigLen; UVCP_CONSTANT constValue; ULONG constValueLen; PCCOR_SIGNATURE marshalSig; ULONG marshalSigLen = 0; _converter->Scope() ->GetFieldProps(*it, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, &sig, &sigLen, nullptr, &constValue, &constValueLen); ObjectModel::FieldInfo fieldInfo; fieldInfo.ElementName = name; fieldInfo.IsPublic = IsFdPublic(attrs); fieldInfo.HasFieldMarshalTableRow = _converter->Scope()->GetFieldMarshal(*it, &marshalSig, &marshalSigLen); PopulateAttributes(*it, fieldInfo.Attributes); DecodeEncodeFieldSigs(sig, sigLen, fieldInfo); if (!IsFdSpecialName(attrs)) { // Add to Fields fields.push_back(std::move(fieldInfo)); } } } void GetEvents(mdToken token, vector<shared_ptr<EventInfo>>& info) { CMetadataEventEnumerator eventEnum(_converter->Scope(), token); for (auto it = eventEnum.begin(); it != eventEnum.end(); ++it) { mdMethodDef eventAdd = mdTokenNil; mdMethodDef eventRemove = mdTokenNil; wchar_t name[MaxTypeNameLen]; name[0] = 0; ULONG nameLen = 0; _converter->Scope()->GetEventProps( *it, nullptr, name, MaxTypeNameLen, &nameLen, nullptr, nullptr, &eventAdd, &eventRemove, nullptr, nullptr, 0, nullptr); { auto event = make_shared<EventInfo>(); event->Name = name; if (eventAdd != mdTokenNil) { event->Adder.Token = eventAdd; } if (eventRemove != mdTokenNil) { event->Remover.Token = eventRemove; } info.push_back(std::move(event)); } } } void GetProperties(mdToken token, vector<shared_ptr<PropertyInfo>>& info) { CMetadataPropertyEnumerator propertyEnum(_converter->Scope(), token); for (auto it = propertyEnum.begin(); it != propertyEnum.end(); ++it) { mdMethodDef propertyGet = mdTokenNil; mdMethodDef propertySet = mdTokenNil; mdMethodDef other[128]; ULONG otherCount = 0; wchar_t name[MaxTypeNameLen]; name[0] = 0; ULONG nameLen = 0; _converter->Scope()->GetPropertyProps(*it, nullptr, name, MaxTypeNameLen, &nameLen, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &propertySet, &propertyGet, other, 128, &otherCount); { auto property(std::make_shared<PropertyInfo>()); property->Name = name; if (propertyGet != mdTokenNil) { property->Getter.Token = propertyGet; } if (propertySet != mdTokenNil) { property->Setter.Token = propertySet; } info.push_back(std::move(property)); } } } void HandleEventMethods(vector<shared_ptr<EventInfo>>& info, map<mdToken, shared_ptr<MemberInfo>>& members) { for (auto it : info) { auto adderMember = members.find(it->Adder.Token); if (adderMember != members.end()) { it->Adder.Info = adderMember->second; } auto removerMember = members.find(it->Remover.Token); if (removerMember != members.end()) { it->Remover.Info = removerMember->second; } } } void HandlePropertyMethods(vector<shared_ptr<PropertyInfo>>& info, map<mdToken, shared_ptr<MemberInfo>>& members) { for (auto it : info) { auto getterMember = members.find(it->Getter.Token); if (getterMember != members.end()) { it->Getter.Info = getterMember->second; } auto setterMember = members.find(it->Setter.Token); if (setterMember != members.end()) { it->Setter.Info = setterMember->second; } } } virtual void Visit(const shared_ptr<Interface>& iface) { if (iface->Category & ObjectModel::TypeCategory::WinRtGeneric) { return; } GetEvents(iface->Token, iface->Events); GetProperties(iface->Token, iface->Properties); PopulateAttributes(iface->Token, iface->Attributes); // EmitCustomAttributes(iface.Token, false); iface->IsExclusiveTo = HasAttribute(iface->Token, L"Windows.Foundation.Metadata.ExclusiveToAttribute"); PopulateInterfaceImplInfo(iface->Token, iface->InterfaceImplements); PopulateMembers(iface->Token, iface->Members); HandleEventMethods(iface->Events, iface->Members); HandlePropertyMethods(iface->Properties, iface->Members); } virtual void Visit(const shared_ptr<RuntimeClass>& r) { if (r->Category & ObjectModel::TypeCategory::WinRtGeneric) { return; } PopulateAttributes(r->Token, r->Attributes); GetEvents(r->Token, r->Events); GetProperties(r->Token, r->Properties); // EmitCustomAttributes(r.Token, false); PopulateInterfaceImplInfo(r->Token, r->InterfaceImplements); if (HasAttribute(r->Token, L"Windows.Foundation.Metadata.ActivatableAttribute")) { r->IsActivatable = true; } if (HasAttribute(r->Token, L"Windows.Foundation.Metadata.ComposableAttribute")) { r->IsComposable = true; } PopulateMembers(r->Token, r->Members); HandleEventMethods(r->Events, r->Members); HandlePropertyMethods(r->Properties, r->Members); CMetadataMethodImplEnumerator enumMethodImpl(_converter->Scope(), r->Token); for (auto it = enumMethodImpl.begin(); it != enumMethodImpl.end(); ++it) { mdToken tkMethodBody = (*it).first; // The method implementation in the implementation class. mdToken tkMethodDecl = (*it).second; // The method declaration in this class. // If this member is the source of the methodimpl table row, hook up its // implementation type. if (r->Members[tkMethodBody] != nullptr) { mdToken tkMemberClass = mdTokenNil; wchar_t rgchMemberName[MaxTypeNameLen]; ULONG nameLen = 0; PCCOR_SIGNATURE sig = nullptr; ULONG sigLen = 0; if (TypeFromToken(tkMethodDecl) == mdtMemberRef) { _converter->Scope()->GetMemberRefProps( tkMethodDecl, &tkMemberClass, rgchMemberName, ARRAYSIZE(rgchMemberName), &nameLen, &sig, &sigLen); } else if (TypeFromToken(tkMethodDecl) == mdtMethodDef) { _converter->Scope()->GetMemberProps(tkMethodDecl, &tkMemberClass, rgchMemberName, ARRAYSIZE(rgchMemberName), &nameLen, nullptr, &sig, &sigLen, nullptr, nullptr, nullptr, nullptr, nullptr); } // // Ok, we now have the class which contains the implementation. The // next step is to figure out which member in that class implements // this method. // auto memberInfoRef = make_shared<MemberInfo>(); memberInfoRef->Name = rgchMemberName; // Remember the method name on the destination type. DecodeEncodeMethodSigs(mdTokenNil, sig, sigLen, *memberInfoRef); // Remember the name of the type which implements the method. NameFromToken(tkMemberClass, false, &r->Members[tkMethodBody]->MethodImplType); r->Members[tkMethodBody]->MethodImpl = std::move(memberInfoRef); } } } virtual void Visit(const shared_ptr<AttributeDef>& attrDef) { if (attrDef->Category & ObjectModel::TypeCategory::WinRtGeneric) { return; } PopulateAttributes(attrDef->Token, attrDef->Attributes); PopulateMembers(attrDef->Token, attrDef->Members); PopulateFields(attrDef->Token, attrDef->Fields); attrDef->IsPublic = IsTdPublic(attrDef->RawType->attrs); } virtual void Visit(const shared_ptr<Array>&) { } virtual void Visit(const shared_ptr<Generic>& /*generic*/) { } virtual void Visit(const shared_ptr<BasicType>&) { } }; // Generate a generic specialization name for the generic type implType given the typespec // description contained in typeSpec. The typeSpec allows us to find the actual types which // correspond to the generic types listed in the implType. wstring GenerateGenericSpecializationName(const shared_ptr<ObjectModel::Generic>& implType, const shared_ptr<ObjectModel::Generic>& typeSpec) { wstringstream ssTypeName; ssTypeName << implType->Type->Name << L"<"; for (auto it = implType->Parameters.begin(); it != implType->Parameters.end(); it++) { if ((*it)->Category == ObjectModel::WinRtGenericParam) { shared_ptr<ObjectModel::GenericParam> param = static_pointer_cast<ObjectModel::GenericParam>((*it)); ssTypeName << typeSpec->Parameters[param->ParamIndex]->Name; } else { ssTypeName << (*it)->Name; } // If we're not done, add in a comma. if (it + 1 != implType->Parameters.end()) { ssTypeName << L","; } } ssTypeName << L">"; return ssTypeName.str(); } // Returns true if the types are equal, false if they are not. // // Note that when comparing typespecs, the left type is always the method type and the // right type is always the methodimpl type (and thus may be a generic). // // When comparing two types, the first thing you want to do is to check for null (void) types. // After that, two types are equal iff their names are equal. It's that simple. There are // two special cases that need to be considered. // // The first is when you're comparing a type and a generic. In that case, if you have a // generic specialization available for the type on the left, calculate the name of the // generic substituting the generic params for the corresponding types in the typespec. // // The second case happens when you compare a type with a generic parameter. In that case, if // you have a generic specialization, simply use the type from the generic specialization // instead. // // Note that we won't have to recurse on generics - that's because even if an entry in the // typespec is a generic, it's a specific generic specialization and you can use the name of // that specialization in the replacement. // bool CompareTypes(const shared_ptr<ObjectModel::Symbol>& left, const shared_ptr<ObjectModel::Symbol>& right, const shared_ptr<ObjectModel::Generic>& typeSpec) { // Check for null types - if both left and right are the same pointer (or if both are null // (void)), it's a match. if (left == right) { return true; } // If either is null, they don't match (we know that they're not both null. if (left == nullptr || right == nullptr) { return false; } // Pull out the left and right names. wstring leftTypeName(left->Name); wstring rightTypeName(right->Name); // If the implementation type is a generic, find the corresponding parameter in the // typespec specification (in the genericImpl) if (typeSpec != nullptr) { if (right->Category == ObjectModel::WinRtGeneric) { rightTypeName = GenerateGenericSpecializationName(static_pointer_cast<ObjectModel::Generic>(right), typeSpec); } if (right->Category == ObjectModel::WinRtGenericParam) { rightTypeName = typeSpec->Parameters[static_pointer_cast<ObjectModel::GenericParam>(right)->ParamIndex]->Name; } } return (leftTypeName == rightTypeName); } } // namespace ObjectModel MetaDataConvert::MetaDataConvert(_In_ wstring filename, map<wstring, shared_ptr<ObjectModel::Symbol>>& fqnMap) : _fileName(filename), _fqnMap(fqnMap), _scope(new CMetadataScope(filename)) { } HRESULT MetaDataConvert::ConvertMetaData(const MetaDataConvert::NamespaceDomain& nsDom) { HRESULT hr = S_OK; if (!_scope->CreateScope(CMetadataScope::ScopeType::ReadOnly)) { return E_FAIL; } // Determine the version of the winmd file wchar_t szVersionString[128]; DWORD cchVersionString; _scope->GetVersionString(szVersionString, ARRAYSIZE(szVersionString), &cchVersionString); _scope->DetermineMetadataFormatVersion(szVersionString); // Collect unique namespaces in the WinMD EnumerateTypeDefs(&MetaDataConvert::CollectNamespaces); // Remove wayward namespaces if (nsDom.incNs.size()) { auto oldNamespaces = _namespaces; for (auto it : oldNamespaces) { bool remove = true; for (auto ns : nsDom.incNs) { if (it.first.substr(0, ns.length()) == ns) { remove = false; break; } } if (remove) { _namespaces.erase(it.first); } } } if (nsDom.rejectNs.size()) { auto oldNamespaces = _namespaces; for (auto ns : nsDom.rejectNs) { for (auto it : oldNamespaces) { if (it.first.substr(0, ns.length()) == ns) { _namespaces.erase(it.first); } } } } for (auto it = _namespaces.begin(); it != _namespaces.end(); it++) { // Decode Metadata for types in namespace { ObjectModel::DecodeMetadata decodeVisitor(this, it->first); it->second->Visit(&decodeVisitor); } } // Remove wayward types for (auto type : nsDom.rejectTypes) { _fqnMap.erase(type); } auto oldTypes = _fqnMap; if (nsDom.incTypes.size()) { for (auto type : oldTypes) { if (nsDom.incTypes.find(type.first) == nsDom.incTypes.end()) { _fqnMap.erase(type.first); } } } return hr; } void MetaDataConvert::VisitNamespaces(ObjectModel::Visitor* visitor) { for (auto it = _namespaces.begin(); it != _namespaces.end(); it++) { it->second->Visit(visitor); } } namespace ObjectModel { ULONG DecodeMetadata::DecodeEncodeSig(PCCOR_SIGNATURE signature, ULONG signatureLength, mdParamDef parameterToken, bool returnParameter, shared_ptr<ObjectModel::Symbol>* sym) { if (sym == nullptr) { DebugBreak(); } CorElementType elementType = static_cast<CorElementType>(signature[0]); ULONG bytesUsed = 1; bool isOutParam = false; // If we have a param token, check to see if it's null. if (parameterToken != mdTokenNil) { ULONG attrs = 0; _converter->Scope()->GetParamProps(parameterToken, nullptr, nullptr, nullptr, 0, nullptr, &attrs, nullptr, nullptr, nullptr); if (IsPdOut(attrs)) { isOutParam = true; } } switch (elementType) { case ELEMENT_TYPE_VOID: { if (returnParameter) { *sym = nullptr; break; } } case ELEMENT_TYPE_BOOLEAN: case ELEMENT_TYPE_CHAR: case ELEMENT_TYPE_I1: case ELEMENT_TYPE_U1: case ELEMENT_TYPE_I2: case ELEMENT_TYPE_U2: case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R4: case ELEMENT_TYPE_R8: { shared_ptr<ObjectModel::Symbol> symbol( new ObjectModel::BasicType(IntrinsicTypeMap[elementType], _converter->FileName(), TypeCategory::WinRtFundamental)); symbol->TypeKind = ElementTypeKind::Value; *sym = (std::move(symbol)); } break; case ELEMENT_TYPE_STRING: { shared_ptr<ObjectModel::Symbol> symbol( new ObjectModel::BasicType(IntrinsicTypeMap[elementType], _converter->FileName(), TypeCategory::WinRtFundamental)); symbol->TypeKind = ElementTypeKind::String; *sym = (std::move(symbol)); } break; case ELEMENT_TYPE_OBJECT: { *sym = std::move(shared_ptr<ObjectModel::BasicType>(new ObjectModel::BasicType(L"System.Object", _converter->FileName()))); } break; case ELEMENT_TYPE_ARRAY: { shared_ptr<ObjectModel::Array> arrayType(new ObjectModel::Array(L"", mdTokenNil, _converter->FileName())); if (returnParameter || isOutParam) { arrayType->ArrayCategory = ObjectModel::Array::ArrayCategory::FillArray; } else { arrayType->ArrayCategory = ObjectModel::Array::ArrayCategory::InArray; } // Decode the type bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, returnParameter, &arrayType->Type); // Decode the rank ULONG rank; bytesUsed += CorSigUncompressData(signature + bytesUsed, &rank); // Decode all the dimension sizes ULONG numSizes; bytesUsed += CorSigUncompressData(signature + bytesUsed, &numSizes); for (ULONG i = 0; i < numSizes; i++) { ULONG size; bytesUsed += CorSigUncompressData(signature + bytesUsed, &size); } // Decode all the dimension lower bounds ULONG numLoBounds; bytesUsed += CorSigUncompressData(signature + bytesUsed, &numLoBounds); for (ULONG i = 0; i < numLoBounds; i++) { int loBound; bytesUsed += CorSigUncompressSignedInt(signature + bytesUsed, &loBound); } // Invalidate the type. The info parsed above will be discarded; we just needed to go through the motions to get the correct // bytesUsed. shared_ptr<ObjectModel::BasicType> tmpSym( new ObjectModel::BasicType(L"ELEMENT_TYPE_ARRAY", _converter->FileName(), ObjectModel::TypeCategory::InvalidType)); *sym = std::move(tmpSym); } break; case ELEMENT_TYPE_SZARRAY: { shared_ptr<ObjectModel::Array> arrayType(new ObjectModel::Array(L"", mdTokenNil, _converter->FileName())); if (returnParameter || isOutParam) { arrayType->ArrayCategory = ObjectModel::Array::ArrayCategory::FillArray; } else { arrayType->ArrayCategory = ObjectModel::Array::ArrayCategory::InArray; } bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, returnParameter, &arrayType->Type); *sym = std::move(arrayType); } break; case ELEMENT_TYPE_VALUETYPE: case ELEMENT_TYPE_CLASS: { mdToken token; ULONG bytesUsedTemp = CorSigUncompressToken(signature + bytesUsed, &token); bytesUsed += bytesUsedTemp; NameFromToken(token, true, sym); if (elementType == ELEMENT_TYPE_VALUETYPE) { (*sym)->TypeKind = ElementTypeKind::Value; } else { (*sym)->TypeKind = ElementTypeKind::Class; } } break; case ELEMENT_TYPE_CMOD_REQD: case ELEMENT_TYPE_CMOD_OPT: { // Custom Modifiers // Example of format: ELEMENT_TYPE_CUSTOMMOD_OPT TYPEREF1 ELEMENT_TYPE_CUSTOMMOD_OPT TYPEREF2 ELEMENT_TYPE_VALUE_TYPE (or other // like ELEMENT_TYPE_CLASS) // A custom modifier is associated with a Type (the last one in the format). // In some cases there might be something in the middle (last MOD_OPT and Type) which is processed when hitting the type (eg, // ELEMENT_TYPE_PINNED). // Upon hitting ELEMENT_TYPE_CMOD_OPT, process them all, process the Type and return the Type with all the custom modifiers // ECMA II.23.2.10 Param // There can be multiple Custom Modifiers, for example in parameters multimap<const wstring, shared_ptr<CustomModifier>> customModifiers; CorElementType currentElementType = elementType; do { mdToken token = mdTokenNil; shared_ptr<CustomModifier> customModifierSymbol(make_shared<CustomModifier>((currentElementType == ELEMENT_TYPE_CMOD_OPT) ? CustomModifierKind::Optional : CustomModifierKind::Required, _converter->FileName())); bytesUsed += CorSigUncompressToken(signature + bytesUsed, &token); NameFromToken(token, true, &customModifierSymbol->Type); customModifiers.emplace(std::move(make_pair(customModifierSymbol->Type->Name, customModifierSymbol))); currentElementType = static_cast<CorElementType>((bytesUsed + signature)[0]); } while ((currentElementType == ELEMENT_TYPE_CMOD_OPT) || (currentElementType == ELEMENT_TYPE_CMOD_REQD)); bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, returnParameter, sym); (*sym)->CustomModifiers = std::move(customModifiers); break; } case ELEMENT_TYPE_I: case ELEMENT_TYPE_U: { shared_ptr<ObjectModel::Symbol> symbol( new ObjectModel::BasicType(IntrinsicTypeMap[ELEMENT_TYPE_STRING + 2 + (elementType - ELEMENT_TYPE_I)], _converter->FileName(), ObjectModel::TypeCategory::InvalidType)); *sym = (std::move(symbol)); } break; case ELEMENT_TYPE_END: case ELEMENT_TYPE_SENTINEL: { shared_ptr<ObjectModel::BasicType> tmpSym( new ObjectModel::BasicType(L"End/Sentinel", _converter->FileName(), ObjectModel::TypeCategory::InvalidType)); *sym = std::move(tmpSym); } break; case ELEMENT_TYPE_VAR: case ELEMENT_TYPE_MVAR: { wchar_t buf[128]; ULONG val; bytesUsed += CorSigUncompressData(signature + bytesUsed, &val); _ultow_s(val, buf, 10); shared_ptr<ObjectModel::Symbol> symbol(new ObjectModel::GenericParam(buf, val, _converter->FileName())); *sym = (std::move(symbol)); } break; case ELEMENT_TYPE_GENERICINST: { // Parse the generic instance. Also calculate the name of the generic instance, // this will later be used to compare type names. wstringstream strGenericName; shared_ptr<ObjectModel::Generic> genericSym(new ObjectModel::Generic(_converter->FileName())); bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, &genericSym->Type); strGenericName << genericSym->Type->Name << L"<"; ULONG argcnt = static_cast<ULONG>(signature[bytesUsed]); bytesUsed++; for (ULONG i = 0; i < argcnt; i++) { shared_ptr<ObjectModel::Symbol> genericArgument; bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, &genericArgument); strGenericName << genericArgument->Name; genericSym->Parameters.push_back(std::move(genericArgument)); if (i + 1 < argcnt) { strGenericName << L","; } } strGenericName << L">"; genericSym->Name = std::move(strGenericName.str()); *sym = std::move(genericSym); } break; case ELEMENT_TYPE_PTR: { bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, sym); (*sym)->PointerKind = ElementPointerKind::Native; } break; case ELEMENT_TYPE_BYREF: { bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, sym); if ((*sym)->Category == TypeCategory::WinRtArray) { reinterpret_cast<Array*>((*sym).get())->ArrayCategory = Array::ArrayCategory::ReceiveArray; } (*sym)->PointerKind = ElementPointerKind::ByRef; } break; case ELEMENT_TYPE_INTERNAL: case ELEMENT_TYPE_PINNED: { bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, sym); } break; case ELEMENT_TYPE_FNPTR: { bytesUsed += GetMethodSigSize(signature + bytesUsed); shared_ptr<ObjectModel::BasicType> tmpSym( new ObjectModel::BasicType(L"FunctionPointer", _converter->FileName(), ObjectModel::TypeCategory::InvalidType)); *sym = std::move(tmpSym); } break; default: { // we have no idea what we saw here, so gracefully mark it as such shared_ptr<ObjectModel::BasicType> tmpSym( new ObjectModel::BasicType(L"UnknownType", _converter->FileName(), ObjectModel::TypeCategory::InvalidType)); *sym = std::move(tmpSym); } break; } return bytesUsed; } ULONG DecodeMetadata::DecodeEncodeFieldSigs(PCCOR_SIGNATURE signature, ULONG signatureLength, ObjectModel::FieldInfo& elementInfo) { ULONG bytesUsed = 1; bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, &elementInfo.ElementType); return bytesUsed; } void DecodeMetadata::DecodeParamAttrs(ULONG attrs, ObjectModel::ParameterInfo& paramInfo) { paramInfo.IsOutParam = (IsPdOut(attrs) != 0); paramInfo.IsInParam = (IsPdIn(attrs) != 0); paramInfo.IsOptional = (IsPdOptional(attrs) != 0); paramInfo.HasDefault = (IsPdHasDefault(attrs) != 0); } // Determines the length of a method's signature // This is useful for skipping over a method signature in the case of function pointers // // Arguments: // signature: the signature object to use to determine the length of the sig // // Returns: // the length of the method signature ULONG DecodeMetadata::GetMethodSigSize(PCCOR_SIGNATURE signature) { ULONG bytesUsed = 1; ULONG paramCount = 0; shared_ptr<ObjectModel::Symbol> spDummy(nullptr); bytesUsed += CorSigUncompressData(signature + bytesUsed, &paramCount); bytesUsed += DecodeEncodeSig(signature + bytesUsed, 0, mdTokenNil, false, &spDummy); for (unsigned int n = 0; n < paramCount; n++) { bytesUsed += DecodeEncodeSig(signature + bytesUsed, 0, mdTokenNil, false, &spDummy); } return bytesUsed; } ULONG DecodeMetadata::DecodeEncodeMethodSigs(mdMethodDef methodToken, PCCOR_SIGNATURE signature, ULONG signatureLength, ObjectModel::MemberInfo& memberInfo) { ULONG bytesUsed = 1; // BYTE callingConvention = signature[0]; ULONG paramCount = 0; ULONG bytesUsedTemp = CorSigUncompressData(signature + bytesUsed, &paramCount); bytesUsed += bytesUsedTemp; mdParamDef paramToken = mdTokenNil; if (!IsNilToken(methodToken)) { _converter->Scope()->GetParamForMethodIndex(methodToken, 0, &paramToken); } // Return Type if (!IsNilToken(paramToken)) { wchar_t name[MaxTypeNameLen]; name[0] = 0; ULONG nameLen = 0; PCCOR_SIGNATURE marshalSig; ULONG marshalSigLen = 0; ULONG attrs = 0; _converter->Scope()->GetParamProps(paramToken, nullptr, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, nullptr, nullptr, nullptr); memberInfo.ReturnParameter.Name = name; memberInfo.ReturnParameter.HasFieldMarshalTableRow = _converter->Scope()->GetFieldMarshal(paramToken, &marshalSig, &marshalSigLen); DecodeParamAttrs(attrs, memberInfo.ReturnParameter); } memberInfo.ReturnParameter.IsOutParam = true; bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, paramToken, true, &memberInfo.ReturnParameter.Type); memberInfo.ReturnParameter.IsVoid = (memberInfo.ReturnParameter.Type == nullptr); // Resize the parameters vector so we don't reallocate on every parameter. memberInfo.Parameters.reserve(paramCount); // Parameters for (unsigned int n = 0; n < paramCount; n++) { wchar_t name[MaxTypeNameLen]; name[0] = 0; ULONG nameLen = 0; ULONG attrs = 0; bool hasParamTableRow = false; if (!IsNilToken(methodToken)) { _converter->Scope()->GetParamForMethodIndex(methodToken, n + 1, &paramToken); if (!IsNilToken(paramToken)) { _converter->Scope() ->GetParamProps(paramToken, nullptr, nullptr, name, MaxTypeNameLen, &nameLen, &attrs, nullptr, nullptr, nullptr); hasParamTableRow = true; } } ParameterInfo parameterInfo(name); parameterInfo.HasParamTableRow = hasParamTableRow; if (!IsNilToken(paramToken)) { PCCOR_SIGNATURE marshalSig; ULONG marshalSigLen = 0; PopulateAttributes(paramToken, parameterInfo.Attributes); parameterInfo.HasFieldMarshalTableRow = _converter->Scope()->GetFieldMarshal(paramToken, &marshalSig, &marshalSigLen); } DecodeParamAttrs(attrs, parameterInfo); bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, paramToken, false, &parameterInfo.Type); parameterInfo.IsVoid = false; // If this is an in parameter, account for it. // There's one strange exception to the "in parameter" rule: For the purposes of // overload detection, an out parameter which matches the FillArray pattern will also // count as an "in" parameter. if (IsPdIn(attrs) || (IsPdOut(attrs) && parameterInfo.Type != nullptr && (parameterInfo.Type->Category == WinRtArray) && (static_pointer_cast<ObjectModel::Array>(parameterInfo.Type)->ArrayCategory == ObjectModel::Array::FillArray))) { memberInfo.InParamCount += 1; } else if (IsPdOut(attrs)) { memberInfo.OutParamCount += 1; } memberInfo.Parameters.push_back(std::move(parameterInfo)); } return bytesUsed; } ULONG DecodeMetadata::DecodeEncodeTypeSpecSigs(PCCOR_SIGNATURE signature, ULONG signatureLength, shared_ptr<ObjectModel::Symbol>* sym) { ULONG bytesUsed = 0; bytesUsed += DecodeEncodeSig(signature + bytesUsed, signatureLength, mdTokenNil, false, sym); return bytesUsed; } void DecodeMetadata::NameFromToken(mdToken token, bool nameForParameter, shared_ptr<ObjectModel::Symbol>* sym) { if (TypeFromToken(token) == mdtTypeSpec) { PCCOR_SIGNATURE sig; ULONG sigLen; _converter->Scope()->GetTypeSpecFromToken(token, &sig, &sigLen); DecodeEncodeTypeSpecSigs(sig, sigLen, sym); return; } _converter->NameFromToken(token, nameForParameter, sym); } } // namespace ObjectModel void MetaDataConvert::NameFromToken(mdToken token, bool nameForParameter, shared_ptr<ObjectModel::Symbol>* sym) { if (sym == nullptr) { DebugBreak(); } if (IsNilToken(token)) { return; } if (TypeFromToken(token) == mdtTypeDef) { shared_ptr<ObjectModel::RawType> type; GetTypeInformation(token, type); // This should always succeed because it's dealing with a typedef (and thus is within the winmd file). *sym = std::move(shared_ptr<ObjectModel::Symbol>(new ObjectModel::UnresolvedSymbol(type->typeName, token, type, _fileName))); if (!nameForParameter && (type->typeCategory & ObjectModel::TypeCategory::WinRtGeneric)) { shared_ptr<ObjectModel::Generic> typeGeneric(new ObjectModel::Generic(_fileName)); typeGeneric->Type = std::move(*sym); *sym = std::move(typeGeneric); } return; } else if (TypeFromToken(token) == mdtTypeRef) { shared_ptr<ObjectModel::RawType> type; // If we couldn't figure out the type information, it's probably because the type was an // external typeref. if (!GetTypeInformation(token, type)) { mdToken resolutionScope; wchar_t name[MaxTypeNameLen]; name[0] = 0; ULONG nameLen = 0; Scope()->GetTypeRefProps(token, &resolutionScope, name, MaxTypeNameLen, &nameLen); type = shared_ptr<ObjectModel::RawType>(new ObjectModel::RawType(token, name, 0, L"", ObjectModel::TypeCategory::UnresolvedType)); } if (type->typeName.compare(L"System.Guid") == 0) { *sym = std::move(shared_ptr<ObjectModel::Symbol>( new ObjectModel::BasicType(L"GUID", _fileName, ObjectModel::TypeCategory::WinRtFundamental))); return; } *sym = std::move(shared_ptr<ObjectModel::Symbol>(new ObjectModel::UnresolvedSymbol(type->typeName, token, type, _fileName))); if (!nameForParameter && type->typeCategory & ObjectModel::TypeCategory::WinRtGeneric) { shared_ptr<ObjectModel::Generic> typeGeneric(new ObjectModel::Generic(_fileName)); typeGeneric->Type = std::move(*sym); *sym = std::move(typeGeneric); } return; } return; } // Returns false if it fails to extract valid data from the CA signature, true otherwise. bool MetaDataConvert::GetValueFromCustomAttributeSig(CustomAttributeParser& CA, ULONG elemType, ObjectModel::CustomAttributeParamInfo& parameter) { UINT8 u1 = 0; UINT16 u2 = 0; UINT32 u4 = 0; UINT64 u8 = 0; unsigned __int64 uI64; bool boolVal; double dblVal; bool ret = true; switch (elemType) { case ELEMENT_TYPE_I1: case ELEMENT_TYPE_U1: CA.GetU1(&u1); parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType], _fileName, ObjectModel::TypeCategory::WinRtFundamental); parameter.SignedIntValue = u1; parameter.ElementType = elemType; break; case ELEMENT_TYPE_I2: case ELEMENT_TYPE_U2: CA.GetU2(&u2); parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType], _fileName, ObjectModel::TypeCategory::WinRtFundamental); parameter.SignedIntValue = u2; parameter.ElementType = elemType; break; case ELEMENT_TYPE_BOOLEAN: CA.GetBool(&boolVal); parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType], _fileName, ObjectModel::TypeCategory::WinRtFundamental); parameter.SignedIntValue = boolVal; parameter.ElementType = elemType; break; case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: CA.GetU4(&u4); parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType], _fileName, ObjectModel::TypeCategory::WinRtFundamental); parameter.SignedIntValue = u4; parameter.ElementType = elemType; break; case SERIALIZATION_TYPE_ENUM: CA.GetU4(&u4); parameter.Type = std::make_shared<ObjectModel::BasicType>(L"", _fileName, ObjectModel::TypeCategory::UnresolvedType); parameter.SignedIntValue = u4; parameter.ElementType = elemType; break; case SERIALIZATION_TYPE_TYPE: { wstring strVal = CA.GetWString(); mdToken token = mdTokenNil; shared_ptr<ObjectModel::Symbol> tempParam; if (Scope()->FindTypeDefByName(strVal.c_str(), mdTokenNil, &token) && !IsNilToken(token)) { NameFromToken(token, false, &tempParam); } else { tempParam.reset(new ObjectModel::BasicType(strVal, _fileName)); } parameter.Type = std::make_shared<ObjectModel::BasicType>(L"System.Type", _fileName, ObjectModel::TypeCategory::UnresolvedType); parameter.StringValue = std::move(tempParam->Name); parameter.ElementType = elemType; } break; case ELEMENT_TYPE_STRING: { wstring strVal = CA.GetWString(); parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType], _fileName, ObjectModel::TypeCategory::WinRtFundamental); parameter.StringValue = std::move(strVal); parameter.ElementType = elemType; } break; case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: CA.GetU8(&u8); uI64 = u8; parameter.SignedIntValue = uI64; parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType], _fileName, ObjectModel::TypeCategory::WinRtFundamental); parameter.ElementType = elemType; break; case ELEMENT_TYPE_R4: dblVal = CA.GetR4(); parameter.DoubleValue = dblVal; parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType], _fileName, ObjectModel::TypeCategory::WinRtFundamental); parameter.ElementType = elemType; break; case ELEMENT_TYPE_R8: dblVal = CA.GetR8(); parameter.DoubleValue = dblVal; parameter.Type = std::make_shared<ObjectModel::BasicType>(IntrinsicTypeMap[elemType], _fileName, ObjectModel::TypeCategory::WinRtFundamental); parameter.ElementType = elemType; break; default: ret = false; break; } return ret; } typedef LPCSTR LPCUTF8; bool MetaDataConvert::GetCustomAttributeInformation(mdCustomAttribute token, shared_ptr<ObjectModel::Attribute> attribute) { const BYTE* pValue; // The custom value. ULONG cbValue; // Length of the custom value. mdToken tkObj; // Attributed object. mdToken tkType; // Type of the custom attribute. mdToken tk; // For name lookup. LPCUTF8 pMethName = 0; // Name of custom attribute ctor, if any. PCCOR_SIGNATURE pSig = 0; // Signature of ctor. ULONG cbSig; // Size of the signature. WCHAR rcName[MAX_CLASS_NAME]; // Name of the type. Scope()->GetCustomAttributeProps( // S_OK or error. token, // The attribute. &tkObj, // The attributed object &tkType, // The attributes type. (const void**)&pValue, // Put pointer to data here. &cbValue); // Put size here. // Get the name of the memberref or methoddef. tk = tkType; rcName[0] = L'\0'; // Get the member name, and the parent token. switch (TypeFromToken(tk)) { case mdtMemberRef: Scope()->GetNameFromToken(tk, &pMethName); Scope()->GetMemberRefProps(tk, &tk, 0, 0, 0, &pSig, &cbSig); break; case mdtMethodDef: Scope()->GetNameFromToken(tk, &pMethName); Scope()->GetMethodProps(tk, &tk, 0, 0, 0, 0, &pSig, &cbSig, 0, 0); break; } // switch // Get the type name. switch (TypeFromToken(tk)) { case mdtTypeDef: Scope()->GetTypeDefProps(tk, rcName, MAX_CLASS_NAME, 0, 0, 0); break; case mdtTypeRef: Scope()->GetTypeRefProps(tk, 0, rcName, MAX_CLASS_NAME, 0); break; } // switch attribute->Name = rcName; if (pSig) { // Interpret the signature. //<TODO> all sig elements </TODO> PCCOR_SIGNATURE ps = pSig; ULONG cb; ULONG ulData; ULONG cParams; CustomAttributeParser CA(pValue, cbValue); CA.ValidateProlog(); // Get the calling convention. cb = CorSigUncompressData(ps, &ulData); ps += cb; // Get the count of params. cb = CorSigUncompressData(ps, &cParams); ps += cb; // Get the return value. cb = CorSigUncompressData(ps, &ulData); ps += cb; if (ulData == ELEMENT_TYPE_VOID) { try { // For each fixed param... for (ULONG i = 0; i < cParams; ++i) { // Get the next param type. cb = CorSigUncompressData(ps, &ulData); ps += cb; wchar_t enumName[MaxTypeNameLen]; ULONG chName = 0; if (ulData == ELEMENT_TYPE_VALUETYPE) { // The only value type that we accept are enums. Decompress the TypeDefOrRefOrSpecEncoded from // the sig. mdToken typeToken; cb = CorSigUncompressToken(ps, &typeToken); memset(enumName, 0, MaxTypeNameLen * sizeof(wchar_t)); // retrieve the name of the enum if (TypeFromToken(typeToken) == mdtTypeRef) { _scope->GetTypeRefProps(typeToken, nullptr, enumName, MaxTypeNameLen, &chName); } else { _scope->GetTypeDefProps(typeToken, enumName, MaxTypeNameLen, &chName, nullptr, nullptr); } ps += cb; ulData = SERIALIZATION_TYPE_ENUM; } else if (ulData == ELEMENT_TYPE_CLASS) { // The only class type that we accept is System.Type. Decompress the TypeDefOrRefOrSpecEncoded // from the sig. // Possible TODO: verify that the decompressed token corresponds to the System.Type typeref. mdToken typeToken; cb = CorSigUncompressToken(ps, &typeToken); ps += cb; ulData = SERIALIZATION_TYPE_TYPE; } ObjectModel::CustomAttributeParamInfo parameter; parameter.Type = std::make_shared<ObjectModel::BasicType>(L"", _fileName, ObjectModel::TypeCategory::UnresolvedType); if (GetValueFromCustomAttributeSig(CA, ulData, parameter)) { if (chName > 0) { parameter.Type->Name = enumName; } attribute->FixedParameters.push_back(std::move(parameter)); } else { // Failed to get the value. Invalidate the attribute. attribute->Category = ObjectModel::TypeCategory::InvalidType; } } // Now that we've parsed out all of the fixed arguments, we parse the named arguments. UINT16 numNamed; CA.GetU2(&numNamed); for (ULONG i = 0; i < numNamed; i++) { // This must be 0x53, indicating a field. ECMA 335 also allows it to be 0x54 to indicate a property, but there // are no legal scenarios for this in winmd files. (ECMA 335 Partition II 23.3) UINT8 fieldMarker; CA.GetU1(&fieldMarker); if (fieldMarker == 0x53) { UINT8 fieldType; CA.GetU1(&fieldType); ObjectModel::CustomAttributeParamInfo parameter; parameter.Type = std::make_shared<ObjectModel::BasicType>(L"", _fileName, ObjectModel::TypeCategory::UnresolvedType); wstring enumName = L""; // An Enum parameter has the name of the Enum as part of the field type. if (fieldType == SERIALIZATION_TYPE_ENUM) { enumName = CA.GetWString(); } wstring fieldName = CA.GetWString(); if (GetValueFromCustomAttributeSig(CA, fieldType, parameter)) { if (!enumName.empty()) { parameter.Type->Name = std::move(enumName); } if (attribute->NamedParameters.count(fieldName) == 0) { attribute->NamedParameters.insert(std::move(std::make_pair(fieldName, parameter))); } else { // Multiple parameters with the same name. Invalidate the attribute. attribute->Category = ObjectModel::TypeCategory::InvalidType; } } else { // Failed to get the value. Invalidate the attribute. attribute->Category = ObjectModel::TypeCategory::InvalidType; } } else { // Malformed blob. Invalidate the attribute. attribute->Category = ObjectModel::TypeCategory::InvalidType; } } // After parsing the fixed and named parameters, we should have consumed the entire custom attribute blob. Confirm. if (CA.BytesLeft() != 0) { // Malformed blob. Invalidate the attribute. attribute->Category = ObjectModel::TypeCategory::InvalidType; } } catch (HRESULT) { // Caught error. Invalidate the attribute. attribute->Category = ObjectModel::TypeCategory::InvalidType; } } } return true; } MultiFileObjectModel::MultiFileObjectModel(vector<wstring> filenames) { for (auto file = filenames.begin(); file != filenames.end(); ++file) { _perFileModels[*file] = shared_ptr<MetaDataConvert>(new MetaDataConvert(*file, _fqnMap)); } for (auto pfModel = _perFileModels.begin(); pfModel != _perFileModels.end(); ++pfModel) { pfModel->second->ConvertMetaData(); } } void MultiFileObjectModel::VisitNamespaces(ObjectModel::Visitor* visitor) { for (auto pfModel = _perFileModels.begin(); pfModel != _perFileModels.end(); ++pfModel) { pfModel->second->VisitNamespaces(visitor); } }
59,826
16,495
// Copyright (C) 2018-2021 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #pragma once #include "openvino/op/op.hpp" #include "openvino/op/util/attr_types.hpp" namespace ov { namespace op { namespace util { /// \brief Base class for color conversion operation from NV12 to RGB/BGR format. /// Input: /// - Operation expects input shape in NHWC layout. /// - Input NV12 image can be represented in a two ways: /// a) Single plane: NV12 height dimension is 1.5x bigger than image height. 'C' dimension shall be 1 /// b) Two separate planes: Y and UV. In this case /// b1) Y plane has height same as image height. 'C' dimension equals to 1 /// b2) UV plane has dimensions: 'H' = image_h / 2; 'W' = image_w / 2; 'C' = 2. /// - Supported element types: u8 or any supported floating-point type. /// Output: /// - Output node will have NHWC layout and shape HxW same as image spatial dimensions. /// - Number of output channels 'C' will be 3 /// /// \details Conversion of each pixel from NV12 (YUV) to RGB space is represented by following formulas: /// R = 1.164 * (Y - 16) + 1.596 * (V - 128) /// G = 1.164 * (Y - 16) - 0.813 * (V - 128) - 0.391 * (U - 128) /// B = 1.164 * (Y - 16) + 2.018 * (U - 128) /// Then R, G, B values are clipped to range (0, 255) /// class OPENVINO_API ConvertColorNV12Base : public Op { public: /// \brief Exact conversion format details /// Currently supports conversion from NV12 to RGB or BGR, in future can be extended with NV21_to_RGBA/BGRA, etc enum class ColorConversion : int { NV12_TO_RGB = 0, NV12_TO_BGR = 1 }; protected: ConvertColorNV12Base() = default; /// \brief Constructs a conversion operation from input image in NV12 format /// As per NV12 format definition, node height dimension shall be 1.5 times bigger than image height /// so that image (w=640, h=480) is represented by NHWC shape {N,720,640,1} (height*1.5 x width) /// /// \param arg Node that produces the input tensor. Input tensor represents image in NV12 format (YUV). /// \param format Conversion format. explicit ConvertColorNV12Base(const Output<Node>& arg, ColorConversion format); /// \brief Constructs a conversion operation from 2-plane input image in NV12 format /// In general case Y channel of image can be separated from UV channel which means that operation needs two nodes /// for Y and UV planes respectively. Y plane has one channel, and UV has 2 channels, both expect 'NHWC' layout /// /// \param arg_y Node that produces the input tensor for Y plane (NHWC layout). Shall have WxH dimensions /// equal to image dimensions. 'C' dimension equals to 1. /// /// \param arg_uv Node that produces the input tensor for UV plane (NHWC layout). 'H' is half of image height, /// 'W' is half of image width, 'C' dimension equals to 2. Channel 0 represents 'U', channel 1 represents 'V' /// channel /// /// \param format Conversion format. ConvertColorNV12Base(const Output<Node>& arg_y, const Output<Node>& arg_uv, ColorConversion format); public: OPENVINO_OP("ConvertColorNV12Base", "util"); void validate_and_infer_types() override; bool visit_attributes(AttributeVisitor& visitor) override; bool evaluate(const HostTensorVector& outputs, const HostTensorVector& inputs) const override; bool has_evaluate() const override; protected: bool is_type_supported(const ov::element::Type& type) const; ColorConversion m_format = ColorConversion::NV12_TO_RGB; }; } // namespace util } // namespace op } // namespace ov
3,729
1,215
#include "BFLuaRuntimeRegistry.h" #include <utility> namespace BlackFox { BFLuaRuntimeRegistry::BFLuaRuntimeRegistry() { registerComponent<Components::BFLuaRuntimeComponent>(); } unsigned int BFLuaRuntimeRegistry::identifier() { static auto next = runtimeComponentId; return next++; } unsigned int BFLuaRuntimeRegistry::registerRuntimeComponent(const std::string& componentName, const std::string& scriptPath, sol::state* state) { BF_PRINT("Register runtime component {} ({})", componentName, scriptPath); auto id = identifier(); m_runtimeComponentLuaScripts[componentName] = std::make_tuple(id, scriptPath); return id; } sol::object BFLuaRuntimeRegistry::setComponent(const entt::entity entity, const ComponentId typeId, sol::state* state) { auto it = std::find_if(m_runtimeComponentLuaScripts.begin(), m_runtimeComponentLuaScripts.end(), [&](const auto& entry) -> bool { return std::get<ComponentId>(entry.second) == typeId; }); const auto componentScript = getComponentScript(typeId); return invoke<funcMap::funcTypeSet, sol::object, &funcMap::set, sol::state*, const std::string*>( entity, typeId, state, componentScript); } void BFLuaRuntimeRegistry::unsetComponent(const entt::entity entity, const ComponentId typeId) { invoke<funcMap::funcTypeUnset, void, &funcMap::unset>(entity, typeId); } bool BFLuaRuntimeRegistry::hasComponent(const entt::entity entity, const ComponentId typeId) { return invoke<funcMap::funcTypeHas, bool, &funcMap::has>(entity, typeId); } sol::object BFLuaRuntimeRegistry::getComponent(const entt::entity entity, const ComponentId typeId, sol::state* state) { return invoke<funcMap::funcTypeGet, sol::object, &funcMap::get, sol::state*>(entity, typeId, state); } void BFLuaRuntimeRegistry::setEntityManager(EntityManager em) { m_entityManager = std::move(em); } bool BFLuaRuntimeRegistry::isNativeComponent(ComponentId component) const { const auto it = std::find_if(m_runtimeComponentLuaScripts.cbegin(), m_runtimeComponentLuaScripts.cend(), [&](const auto& entry) { return std::get<ComponentId>(entry.second) == component; }); return it == m_runtimeComponentLuaScripts.cend(); } const std::string* BFLuaRuntimeRegistry::getComponentScript(ComponentId component) const { const auto it = std::find_if(m_runtimeComponentLuaScripts.cbegin(), m_runtimeComponentLuaScripts.cend(), [&](const auto& entry) { return std::get<ComponentId>(entry.second) == component; }); return (it != m_runtimeComponentLuaScripts.cend() ? &std::get<std::string>(it->second) : nullptr); } std::tuple<entt::runtime_view, std::vector<ComponentId>, std::vector<ComponentId>> BFLuaRuntimeRegistry::getView(const std::vector<ComponentId>& components) const { std::vector<ComponentId> engineComponents; std::vector<ComponentId> runtimeComponents; for (const auto& type : components) { if (isNativeComponent(type)) { engineComponents.push_back(type); } else { if (runtimeComponents.empty()) { engineComponents.push_back(entt::type_info<Components::BFLuaRuntimeComponent>::id()); } runtimeComponents.push_back(type); } } return std::make_tuple(m_entityManager->runtime_view(engineComponents.begin(), engineComponents.end()), engineComponents, runtimeComponents); } std::vector<sol::object> BFLuaRuntimeRegistry::getComponents( sol::state* state, const entt::entity& entity, const std::vector<ComponentId>& components) { std::vector<sol::object> v; for (const auto& component : components) { v.push_back(getComponent(entity, component, state)); } return v; } }
3,657
1,252
/* * PathNetwork.cpp * * Created on: Dec 15, 2015 * Author: jcassidy */ #include "PathNetwork.hpp" #include "OSMDatabase.hpp" #include <boost/container/flat_map.hpp> using namespace std; const char* OSMWayFilterRoads::includeHighwayTagValueStrings_[] = { "residential", "primary", "primary_link", "secondary", "secondary_link", "tertiary", "tertiary_link", "motorway", "motorway_link", "service", "trunk", "living_street", "unclassified", "road", nullptr }; PathNetwork buildNetwork(const OSMDatabase& db, const OSMEntityFilter<OSMWay>& wayFilter) { PathNetwork G; float defaultMax = 50.0f; struct NodeWithRefCount { PathNetwork::vertex_descriptor graphVertexDescriptor = -1U; unsigned nodeVectorIndex = -1U; unsigned refcount = 0; }; std::unordered_map<unsigned long long, NodeWithRefCount> nodesByOSMID; unsigned kiHighway = db.wayTags().getIndexForKeyString("highway"); if (kiHighway == -1U) std::cerr << "ERROR in buildNetwork(db,wf): failed to find tag key 'highway'" << std::endl; const std::vector<std::pair<std::string,float>> defaultMaxSpeedByHighwayString { std::make_pair("motorway",105.0f), std::make_pair("trunk",90.0f), std::make_pair("primary",90.0f), std::make_pair("secondary",80.0f), std::make_pair("tertiary",80.0f), std::make_pair("unclassified",50.0f), std::make_pair("residential",50.0f), std::make_pair("living_street",40.0f), }; // fetch tag numbers for the highway strings boost::container::flat_map<unsigned,float> defaultMaxSpeedByHighwayTagValue; for(const auto p : defaultMaxSpeedByHighwayString) { unsigned viString = db.wayTags().getIndexForValueString(p.first); if (viString != -1U) { const auto res = defaultMaxSpeedByHighwayTagValue.insert(std::make_pair(viString,p.second)); if (!res.second) std::cerr << "ERROR in buildNetwork(db,wf): duplicate tag value '" << p.first << "' ID=" << viString << std::endl; } } // create OSM ID -> vector index mapping for all nodes std::cout << "Computing index map" << std::endl; for (unsigned i = 0; i < db.nodes().size(); ++i) nodesByOSMID[db.nodes()[i].id()].nodeVectorIndex = i; // traverse the listed ways, marking node reference counts std::cout << "Computing reference counts" << std::endl; for (const OSMWay& w : db.ways() | boost::adaptors::filtered(std::cref(wayFilter))) for (const unsigned long long nd : w.ndrefs()) { auto it = nodesByOSMID.find(nd); if (it == nodesByOSMID.end()) std::cerr << "WARNING: Dangling reference to node " << nd << " in way " << w.id() << std::endl; else it->second.refcount++; } // calculate and print reference-count (# way refs for each node) histogram for fun std::vector<unsigned> refhist; std::cout << "Computing reference-count frequency histogram" << std::endl; for (const auto ni : nodesByOSMID | boost::adaptors::map_values) { if (ni.refcount >= refhist.size()) refhist.resize(ni.refcount + 1, 0); refhist[ni.refcount]++; } for (unsigned i = 0; i < refhist.size(); ++i) if (refhist[i] > 0) std::cout << " " << std::setw(3) << i << " refs: " << refhist[i] << " nodes" << std::endl; // iterate over ways, creating edges in the intersection graph with associated curvepoints) size_t nCurvePoints = 0; unsigned k_maxspeed = db.wayTags().getIndexForKeyString("maxspeed"); enum OneWayType { Bidir, Forward, Backward, Reversible, Unknown }; unsigned k_oneway = db.wayTags().getIndexForKeyString("oneway"); unsigned v_oneway_yes = db.wayTags().getIndexForValueString("yes"); unsigned v_oneway_one = db.wayTags().getIndexForValueString("1"); unsigned v_oneway_minus_one = db.wayTags().getIndexForValueString("-1"); unsigned v_oneway_reversible = db.wayTags().getIndexForValueString("reversible"); unsigned v_oneway_no = db.wayTags().getIndexForValueString("no"); unsigned nOnewayForward = 0, nOnewayBackward = 0, nOnewayReversible = 0, nBidir = 0, nUnknown = 0; unsigned nWays = 0; boost::container::flat_map<unsigned,float> speedValues; for (const auto& w : db.ways() | boost::adaptors::filtered(std::cref(wayFilter))) { ++nWays; PathNetwork::vertex_descriptor segmentStartVertex = -1ULL, segmentEndVertex = -1ULL; vector<LatLon> curvePoints; // max speed is per way; mark as NaN by default (change NaNs to other value later) float speed = std::numeric_limits<float>::quiet_NaN(); unsigned v; if ((v = w.getValueForKey(k_maxspeed)) != -1U) // has maxspeed tag { boost::container::flat_map<unsigned, float>::iterator it; bool inserted; tie(it, inserted) = speedValues.insert(make_pair(v, std::numeric_limits<float>::quiet_NaN())); if (inserted) // need to map this string value to a number { float spd; string str = db.wayTags().getValue(v); stringstream ss(str); ss >> spd; if (ss.fail()) { ss.clear(); cout << "truncating '" << str << "' to substring '"; str = str.substr(str.find_first_of(':') + 1); cout << str << "'" << endl; ss.str(str); ss >> spd; } if (ss.fail()) std::cout << "Failed to convert value for maxspeed='" << str << "'" << endl; else if (!ss.eof()) { string rem; ss >> rem; if (rem == "kph") it->second = spd; else if (rem == "mph") it->second = spd * 1.609f; else { std::cout << "Warning: trailing characters in maxspeed='" << str << "'" << endl; std::cout << " remaining: '" << rem << "'" << endl; } } else it->second = spd; if (!isnan(it->second)) std::cout << "Added new speed '" << str << "' = " << it->second << endl; else std::cout << "Failed to convert speed '" << str << "'" << endl; } speed = it->second; } else // no maxspeed -> default based on road type { unsigned viHighwayValue = w.getValueForKey(kiHighway); if (viHighwayValue == -1U) std::cerr << "ERROR in buildNetwork(db,wf): missing highway tag!" << std::endl; else { const auto it = defaultMaxSpeedByHighwayTagValue.find(viHighwayValue); if (it != defaultMaxSpeedByHighwayTagValue.end()) speed = it->second; } } // assume bidirectional if not specified OneWayType oneway = Unknown; if (k_oneway == -1U) { oneway = Bidir; ++nBidir; } else { unsigned v_oneway = w.getValueForKey(k_oneway); if (v_oneway == -1U || v_oneway == v_oneway_no) { oneway = Bidir; ++nBidir; } else if (v_oneway == v_oneway_one) { oneway = Forward; ++nOnewayForward; } else if (v_oneway == v_oneway_yes) { oneway = Forward; ++nOnewayForward; } else if (v_oneway == v_oneway_minus_one) { oneway = Backward; ++nOnewayBackward; } else if (v_oneway == v_oneway_reversible) { oneway = Reversible; ++nOnewayReversible; } else { cout << "Unrecognized tag oneway='" << db.wayTags().getValue(v_oneway); ++nUnknown; } } // hamilton_canada and newyork: k=oneway v=-1 | 1 | yes | no | yes;-1 | reversible for (unsigned i = 0; i < w.ndrefs().size(); ++i) { const auto currNodeIt = nodesByOSMID.find(w.ndrefs()[i]); LatLon prevCurvePoint; if (currNodeIt == nodesByOSMID.end()) // dangling node reference: discard { cout << "WARNING: Dangling node with OSM ID " << w.ndrefs()[i] << " on way with OSM ID " << w.id() << endl; segmentEndVertex = -1U; continue; } else if (currNodeIt->second.refcount == 1) // referenced by only 1 way -> curve point { LatLon ll = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords(); curvePoints.push_back(ll); } else if (currNodeIt->second.refcount > 1 || i == 0 || i == w.ndrefs().size() - 1) // referenced by >1 way or first/last node ref in a way -> node is an intersection { segmentEndVertex = currNodeIt->second.graphVertexDescriptor; // if vertex hasn't been added yet, add now if (segmentEndVertex == -1U) { currNodeIt->second.graphVertexDescriptor = segmentEndVertex = add_vertex(G); G[segmentEndVertex].latlon = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords(); G[segmentEndVertex].osmid = currNodeIt->first; } // arriving at an intersection node via a way if (segmentStartVertex != -1ULL) { PathNetwork::edge_descriptor e; bool inserted; assert(segmentStartVertex < num_vertices(G)); assert(segmentEndVertex < num_vertices(G)); std::tie(e, inserted) = add_edge(segmentStartVertex, segmentEndVertex, G); assert(inserted && "Duplicate edge"); G[e].wayOSMID = w.id(); if (oneway == Forward || oneway == Backward) { // goes towards end vertex; if greater then goes towards greater // flip it bool towardsGreater = (segmentEndVertex > segmentStartVertex) ^ (oneway == Backward); G[e].oneWay = towardsGreater ? EdgeProperties::ToGreaterVertexNumber : EdgeProperties::ToLesserVertexNumber; } else G[e].oneWay = EdgeProperties::Bidir; G[e].maxspeed = speed; nCurvePoints += curvePoints.size(); G[e].curvePoints = std::move(curvePoints); } segmentStartVertex = segmentEndVertex; } prevCurvePoint = db.nodes().at(currNodeIt->second.nodeVectorIndex).coords(); } } std::cout << "PathNetwork created with " << num_vertices(G) << " vertices and " << num_edges(G) << " edges, with " << nCurvePoints << " curve points" << std::endl; std::cout << " Used " << nWays << "/" << db.ways().size() << " ways" << endl; std::cout << " One-way streets: " << (nOnewayForward + nOnewayBackward) << "/" << nWays << " (" << nOnewayReversible << " reversible and " << nUnknown << " unknown)" << std::endl; assert(nOnewayForward + nOnewayBackward + nOnewayReversible + nBidir + nUnknown == nWays); // create/print edge-degree histogram std::cout << "Vertex degree histogram:" << std::endl; std::vector<unsigned> dhist; for (auto v : boost::make_iterator_range(vertices(G))) { unsigned d = out_degree(v, G); if (d >= dhist.size()) dhist.resize(d + 1, 0); dhist[d]++; } unsigned Ndefault = 0; for (auto e : boost::make_iterator_range(edges(G))) { if (isnan(G[e].maxspeed)) { ++Ndefault; G[e].maxspeed = defaultMax; } } cout << "Assigned " << Ndefault << "/" << num_edges(G) << " street segments to default max speed for lack of information" << endl; for (unsigned i = 0; i < dhist.size(); ++i) if (dhist[i] > 0) std::cout << " " << std::setw(3) << i << " refs: " << dhist[i] << " nodes" << std::endl; return G; } class StreetEdgeVisitor { public: StreetEdgeVisitor(PathNetwork* G) : m_G(G) { } std::vector<std::string> assign() { m_streets.clear(); m_streets.push_back("<unknown>"); for (const auto e : edges(*m_G)) if ((*m_G)[e].streetVectorIndex == 0) startWithEdge(e); return std::move(m_streets); } // pick up the street name from the specified edge, add it to the vertex, and expand the source/target vertices void startWithEdge(PathNetwork::edge_descriptor e); // inspect all out-edges of the vertex, assigning and recursively expanding any which match the way ID or street name void expandVertex(PathNetwork::vertex_descriptor v, OSMID wayID); void osmDatabase(OSMDatabase* p) { m_osmDatabase = p; m_keyIndexName = p->wayTags().getIndexForKeyString("name"); m_keyIndexNameEn = p->wayTags().getIndexForKeyString("name:en"); } private: const std::string streetNameForWay(OSMID osmid) { const OSMWay& w = m_osmDatabase->wayFromID(osmid); unsigned valTag = -1U; if ((valTag = w.getValueForKey(m_keyIndexNameEn)) == -1U) valTag = w.getValueForKey(m_keyIndexName); if (valTag == -1U) return std::string(); else return m_osmDatabase->wayTags().getValue(valTag); } static const std::string np; PathNetwork* m_G = nullptr; // the path network OSMDatabase* m_osmDatabase = nullptr; // OSM database with source data unsigned m_keyIndexName = -1U, m_keyIndexNameEn = -1U; // cached values for key-value tables std::vector<std::string> m_streets; // street name vector being built unsigned m_currStreetVectorIndex = 0; // index of current street }; const std::string StreetEdgeVisitor::np = {"<name-not-present>"}; void StreetEdgeVisitor::startWithEdge(PathNetwork::edge_descriptor e) { // grab OSM ID of this way, look up its name OSMID wID = (*m_G)[e].wayOSMID; std::string streetName = streetNameForWay(wID); if (!streetName.empty()) { // insert the street name (*m_G)[e].streetVectorIndex = m_currStreetVectorIndex = m_streets.size(); m_streets.push_back(streetName); // expand the vertices at both ends expandVertex(source(e, *m_G), wID); expandVertex(target(e, *m_G), wID); } } /** Recursively expand the specified vertex, along out-edges which have way OSMID == currWayID, or have the same street name */ void StreetEdgeVisitor::expandVertex(PathNetwork::vertex_descriptor v, OSMID currWayID) { for (const auto e : out_edges(v, *m_G)) // for all out-edges of this vertex { if ((*m_G)[e].streetVectorIndex != 0) // skip if already assigned (prevents infinite recursion back to origin) continue; OSMID wID = (*m_G)[e].wayOSMID; assert(wID != 0 && wID != -1U); if (wID == currWayID) // (connected,same way -> same name) -> same street (*m_G)[e].streetVectorIndex = m_currStreetVectorIndex; else if (streetNameForWay(wID) == m_streets.back()) // (connected,same name) -> same street (*m_G)[e].streetVectorIndex = m_currStreetVectorIndex; else // different way, different name -> done expanding continue; // this is the fall-through case for the if/elseif above (terminates if reaches a different street) expandVertex(target(e, *m_G), wID); } } std::vector<std::string> assignStreets(OSMDatabase* db, PathNetwork& G) { StreetEdgeVisitor sev(&G); sev.osmDatabase(db); // blank out existing street names for (const auto e : edges(G)) G[e].streetVectorIndex = 0; return sev.assign(); }
16,233
5,097
#include "pandar_pointcloud/decoder/pandar64_decoder.hpp" #include "pandar_pointcloud/decoder/pandar64.hpp" namespace { static inline double deg2rad(double degrees) { return degrees * M_PI / 180.0; } } namespace pandar_pointcloud { namespace pandar64 { Pandar64Decoder::Pandar64Decoder(Calibration& calibration, float scan_phase, double dual_return_distance_threshold, ReturnMode return_mode) { firing_offset_ = { 23.18, 21.876, 20.572, 19.268, 17.964, 16.66, 11.444, 46.796, 7.532, 36.956, 50.732, 54.668, 40.892, 44.828,31.052, 34.988, 48.764, 52.7, 38.924, 42.86, 29.084, 33.02, 46.796, 25.148, 36.956, 50.732, 27.116, 40.892, 44.828, 31.052, 34.988, 48.764, 25.148, 38.924, 42.86, 29.084, 33.02, 52.7, 6.228, 54.668, 15.356, 27.116, 10.14, 23.18, 4.924, 21.876, 14.052, 17.964, 8.836, 19.268, 3.62, 20.572, 12.748, 16.66, 7.532, 11.444, 6.228, 15.356, 10.14, 4.924, 3.62, 14.052, 8.836, 12.748 }; for (int block = 0; block < BLOCK_NUM; ++block) { block_offset_single_[block] = 55.56f * (BLOCK_NUM - block - 1) + 28.58f; block_offset_dual_[block] = 55.56f * ((BLOCK_NUM - block - 1) / 2) + 28.58f; } // TODO: add calibration data validation // if(calibration.elev_angle_map.size() != num_lasers_){ // // calibration data is not valid! // } for (size_t laser = 0; laser < UNIT_NUM; ++laser) { elev_angle_[laser] = calibration.elev_angle_map[laser]; azimuth_offset_[laser] = calibration.azimuth_offset_map[laser]; } scan_phase_ = static_cast<uint16_t>(scan_phase * 100.0f); return_mode_ = return_mode; dual_return_distance_threshold_ = dual_return_distance_threshold; last_phase_ = 0; has_scanned_ = false; scan_pc_.reset(new pcl::PointCloud<PointXYZIRADT>); overflow_pc_.reset(new pcl::PointCloud<PointXYZIRADT>); } bool Pandar64Decoder::hasScanned() { return has_scanned_; } PointcloudXYZIRADT Pandar64Decoder::getPointcloud() { return scan_pc_; } void Pandar64Decoder::unpack(const pandar_msgs::PandarPacket& raw_packet) { if (!parsePacket(raw_packet)) { return; } if (has_scanned_) { scan_pc_ = overflow_pc_; overflow_pc_.reset(new pcl::PointCloud<PointXYZIRADT>); has_scanned_ = false; } bool dual_return = (packet_.return_mode == DUAL_RETURN); auto step = dual_return ? 2 : 1; if (!dual_return) { if ((packet_.return_mode == STRONGEST_RETURN && return_mode_ != ReturnMode::STRONGEST) || (packet_.return_mode == LAST_RETURN && return_mode_ != ReturnMode::LAST)) { ROS_WARN ("Sensor return mode configuration does not match requested return mode"); } } for (int block_id = 0; block_id < BLOCK_NUM; block_id += step) { auto block_pc = dual_return ? convert_dual(block_id) : convert(block_id); int current_phase = (static_cast<int>(packet_.blocks[block_id].azimuth) - scan_phase_ + 36000) % 36000; if (current_phase > last_phase_ && !has_scanned_) { *scan_pc_ += *block_pc; } else { *overflow_pc_ += *block_pc; has_scanned_ = true; } last_phase_ = current_phase; } } PointXYZIRADT Pandar64Decoder::build_point(int block_id, int unit_id, uint8_t return_type) { const auto& block = packet_.blocks[block_id]; const auto& unit = block.units[unit_id]; auto unix_second = static_cast<double>(timegm(&packet_.t)); bool dual_return = (packet_.return_mode == DUAL_RETURN); PointXYZIRADT point{}; double xyDistance = unit.distance * cosf(deg2rad(elev_angle_[unit_id])); point.x = static_cast<float>( xyDistance * sinf(deg2rad(azimuth_offset_[unit_id] + (static_cast<double>(block.azimuth)) / 100.0))); point.y = static_cast<float>( xyDistance * cosf(deg2rad(azimuth_offset_[unit_id] + (static_cast<double>(block.azimuth)) / 100.0))); point.z = static_cast<float>(unit.distance * sinf(deg2rad(elev_angle_[unit_id]))); point.intensity = unit.intensity; point.distance = static_cast<float>(unit.distance); point.ring = unit_id; point.azimuth = static_cast<float>(block.azimuth) + round(azimuth_offset_[unit_id] * 100.0f); point.return_type = return_type; point.time_stamp = unix_second + (static_cast<double>(packet_.usec)) / 1000000.0; point.time_stamp += dual_return ? (static_cast<double>(block_offset_dual_[block_id] + firing_offset_[unit_id]) / 1000000.0f) : (static_cast<double>(block_offset_single_[block_id] + firing_offset_[unit_id]) / 1000000.0f); return point; } PointcloudXYZIRADT Pandar64Decoder::convert(const int block_id) { PointcloudXYZIRADT block_pc(new pcl::PointCloud<PointXYZIRADT>); const auto& block = packet_.blocks[block_id]; for (size_t unit_id = 0; unit_id < UNIT_NUM; ++unit_id) { PointXYZIRADT point{}; const auto& unit = block.units[unit_id]; // skip invalid points if (unit.distance <= 0.1 || unit.distance > 200.0) { continue; } block_pc->points.emplace_back(build_point(block_id, unit_id, (packet_.return_mode == STRONGEST_RETURN) ? ReturnType::SINGLE_STRONGEST : ReturnType::SINGLE_LAST)); } return block_pc; } PointcloudXYZIRADT Pandar64Decoder::convert_dual(const int block_id) { // Under the Dual Return mode, the ranging data from each firing is stored in two adjacent blocks: // · The even number block is the first return // · The odd number block is the last return // · The Azimuth changes every two blocks // · Important note: Hesai datasheet block numbering starts from 0, not 1, so odd/even are reversed here PointcloudXYZIRADT block_pc(new pcl::PointCloud<PointXYZIRADT>); int even_block_id = block_id; int odd_block_id = block_id + 1; const auto& even_block = packet_.blocks[even_block_id]; const auto& odd_block = packet_.blocks[odd_block_id]; for (size_t unit_id = 0; unit_id < UNIT_NUM; ++unit_id) { const auto& even_unit = even_block.units[unit_id]; const auto& odd_unit = odd_block.units[unit_id]; bool even_usable = !(even_unit.distance <= 0.1 || even_unit.distance > 200.0); bool odd_usable = !(odd_unit.distance <= 0.1 || odd_unit.distance > 200.0); if (return_mode_ == ReturnMode::STRONGEST && even_usable) { // First return is in even block block_pc->points.emplace_back(build_point(even_block_id, unit_id, ReturnType::SINGLE_STRONGEST)); } else if (return_mode_ == ReturnMode::LAST && even_usable) { // Last return is in odd block block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::SINGLE_LAST)); } else if (return_mode_ == ReturnMode::DUAL) { // If the two returns are too close, only return the last one if ((abs(even_unit.distance - odd_unit.distance) < dual_return_distance_threshold_) && odd_usable) { block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::DUAL_ONLY)); } else { if (even_usable) { block_pc->points.emplace_back(build_point(even_block_id, unit_id, ReturnType::DUAL_FIRST)); } if (odd_usable) { block_pc->points.emplace_back(build_point(odd_block_id, unit_id, ReturnType::DUAL_LAST)); } } } } return block_pc; } bool Pandar64Decoder::parsePacket(const pandar_msgs::PandarPacket& raw_packet) { if (raw_packet.size != PACKET_SIZE && raw_packet.size != PACKET_WITHOUT_UDPSEQ_SIZE) { return false; } const uint8_t* buf = &raw_packet.data[0]; size_t index = 0; // Parse 12 Bytes Header packet_.header.sob = (buf[index] & 0xff) << 8| ((buf[index+1] & 0xff)); packet_.header.chLaserNumber = buf[index+2] & 0xff; packet_.header.chBlockNumber = buf[index+3] & 0xff; packet_.header.chReturnType = buf[index+4] & 0xff; packet_.header.chDisUnit = buf[index+5] & 0xff; index += HEAD_SIZE; if (packet_.header.sob != 0xEEFF) { // Error Start of Packet! return false; } for (size_t block = 0; block < packet_.header.chBlockNumber; block++) { packet_.blocks[block].azimuth = (buf[index] & 0xff) | ((buf[index + 1] & 0xff) << 8); index += BLOCK_HEADER_AZIMUTH; for (int unit = 0; unit < packet_.header.chLaserNumber; unit++) { unsigned int unRange = (buf[index]& 0xff) | ((buf[index + 1]& 0xff) << 8); packet_.blocks[block].units[unit].distance = (static_cast<double>(unRange * packet_.header.chDisUnit)) / 1000.; packet_.blocks[block].units[unit].intensity = (buf[index+2]& 0xff); index += UNIT_SIZE; }//end fot laser }//end for block index += RESERVED_SIZE; // skip reserved bytes index += ENGINE_VELOCITY; packet_.usec = (buf[index] & 0xff)| (buf[index+1] & 0xff) << 8 | ((buf[index+2] & 0xff) << 16) | ((buf[index+3] & 0xff) << 24); index += TIMESTAMP_SIZE; packet_.return_mode = buf[index] & 0xff; index += RETURN_SIZE; index += FACTORY_SIZE; packet_.t.tm_year = (buf[index + 0] & 0xff) + 100; // in case of time error if (packet_.t.tm_year >= 200) { packet_.t.tm_year -= 100; } packet_.t.tm_mon = (buf[index + 1] & 0xff) - 1; packet_.t.tm_mday = buf[index + 2] & 0xff; packet_.t.tm_hour = buf[index + 3] & 0xff; packet_.t.tm_min = buf[index + 4] & 0xff; packet_.t.tm_sec = buf[index + 5] & 0xff; packet_.t.tm_isdst = 0; index += UTC_SIZE; return true; }//parsePacket }//pandar64 }//pandar_pointcloud
10,076
4,025