text
string
size
int64
token_count
int64
#include "PathTree.h" #include <sstream> #include "StringUtil.h" namespace ze::assetdatabase { void PathTree::add(const std::filesystem::path& path) { ZE_CHECK(path.is_relative()); /** Check if path already exists */ if (has_path(path)) return; /** Insert the path in the map if it is a directory */ if (!path.has_extension()) paths.insert({ path, PathDirectory() }); /** Now scan each part to build a tree */ std::vector<std::string> tokens = stringutil::split(path.string(), std::filesystem::path::preferred_separator); /** Insert at root */ if (tokens.size() == 1) { paths[""].childs.insert(path); } else { std::filesystem::path final_path; std::filesystem::path parent = ""; for (size_t i = 0; i < tokens.size() - 1; ++i) { const auto& token = tokens[i]; final_path = final_path / token; if (paths[parent].childs.find(token) == paths[parent].childs.end()) { paths[parent / token].parent = parent; paths[parent].childs.insert(token); } /** Insert file */ if (i == tokens.size() - 2) { paths[parent / token].childs.insert(tokens[tokens.size() - 1]); } parent /= token; } } } std::vector<std::filesystem::path> PathTree::get_childs(const std::filesystem::path& path, const bool& include_files) { std::vector<std::filesystem::path> childs; if (paths.find(path) == paths.end()) return childs; childs.reserve(paths[path].childs.size()); for (const auto& child : paths[path].childs) { if (!include_files && child.has_extension()) continue; childs.emplace_back(child); } return childs; } bool PathTree::has_path(const std::filesystem::path& path) const { if (path.has_filename()) { /** Check to the parent of the file */ auto parent_it = paths.find(path.parent_path()); if (parent_it != paths.end()) { return parent_it->second.childs.find(path.filename()) != parent_it->second.childs.end(); } return false; } else { return paths.find(path) != paths.end(); } } }
1,990
785
#include <iostream> long Factorial(int no); long nCr(int n, int r); int main() { int n, r; std::cout << "Enter a value for n "; std::cin >> n; std::cout << "Enter a value for r "; std::cin >> r; std::cout << "nCr = "; std::cout << nCr(n, r); std::cout << std::endl; return 0; } long Factorial(int no) { long sum; int i; sum = 1; for (i = no; i >= 1; i--) { sum = i * sum; } return sum; } long nCr(int n, int r) { long ncr; ncr = Factorial(n) / (Factorial(r) * Factorial((n-r))); return ncr; }
520
249
/* file: adaboost_predict_dense_default_batch_fpt_dispatcher.cpp */ /******************************************************************************* * Copyright 2014-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. *******************************************************************************/ /* //++ // Implementation of Ada Boost prediction algorithm container -- // a class that contains Fast Ada Boost kernels for supported architectures. //-- */ #include "algorithms/boosting/adaboost_predict.h" #include "src/algorithms/adaboost/adaboost_predict_batch_container.h" namespace daal { namespace algorithms { __DAAL_INSTANTIATE_DISPATCH_CONTAINER(adaboost::prediction::BatchContainer, batch, DAAL_FPTYPE, adaboost::prediction::defaultDense) __DAAL_INSTANTIATE_DISPATCH_CONTAINER(adaboost::prediction::BatchContainer, batch, DAAL_FPTYPE, adaboost::prediction::sammeR) namespace adaboost { namespace prediction { namespace interface2 { template <> Batch<DAAL_FPTYPE, adaboost::prediction::defaultDense>::Batch(size_t nClasses) { _par = new ParameterType(nClasses); parameter().nClasses = nClasses; initialize(); } using BatchTypeDefault = Batch<DAAL_FPTYPE, adaboost::prediction::defaultDense>; template <> Batch<DAAL_FPTYPE, adaboost::prediction::defaultDense>::Batch(const BatchTypeDefault & other) : classifier::prediction::Batch(other), input(other.input) { _par = new ParameterType(other.parameter()); initialize(); } template <> Batch<DAAL_FPTYPE, adaboost::prediction::sammeR>::Batch(size_t nClasses) { _par = new ParameterType(nClasses); parameter().nClasses = nClasses; initialize(); } using BatchTypeSammeR = Batch<DAAL_FPTYPE, adaboost::prediction::sammeR>; template <> Batch<DAAL_FPTYPE, adaboost::prediction::sammeR>::Batch(const BatchTypeSammeR & other) : classifier::prediction::Batch(other), input(other.input) { _par = new ParameterType(other.parameter()); initialize(); } } // namespace interface2 } // namespace prediction } // namespace adaboost } // namespace algorithms } // namespace daal
2,620
811
#include <memory> #include <src/recordbuf.hpp> #include <gtest/gtest.h> namespace blackhole { inline namespace v1 { namespace { TEST(recordbuf_t, FromRecordMessage) { std::unique_ptr<recordbuf_t> result; { const string_view message("GET"); const attribute_pack pack; const record_t record(0, message, pack); result.reset(new recordbuf_t(record)); } EXPECT_EQ(string_view("GET"), result->into_view().message()); } TEST(owned, FromRecordFormattedMessage) { std::unique_ptr<recordbuf_t> result; { const string_view message("GET: {}"); const attribute_pack pack; record_t record(0, message, pack); record.activate("GET: 42"); result.reset(new recordbuf_t(record)); } EXPECT_EQ(string_view("GET: 42"), result->into_view().formatted()); } TEST(owned, FromRecordSeverity) { std::unique_ptr<recordbuf_t> result; { const string_view message(""); const attribute_pack pack; const record_t record(42, message, pack); result.reset(new recordbuf_t(record)); } EXPECT_EQ(42, result->into_view().severity()); } TEST(owned, FromRecordTimestamp) { std::unique_ptr<recordbuf_t> result; record_t::clock_type::time_point min = {}; record_t::clock_type::time_point max = {}; { const string_view message(""); const attribute_pack pack; min = record_t::clock_type::now(); record_t record(0, message, pack); record.activate(); max = record_t::clock_type::now(); result.reset(new recordbuf_t(record)); } EXPECT_TRUE(min <= result->into_view().timestamp()); EXPECT_TRUE(max >= result->into_view().timestamp()); } TEST(owned, FromRecordThreadId) { std::unique_ptr<recordbuf_t> result; { const string_view message(""); const attribute_pack pack; const record_t record(0, message, pack); result.reset(new recordbuf_t(record)); } EXPECT_EQ(::pthread_self(), result->into_view().tid()); } TEST(owned, FromRecordAttributes) { std::unique_ptr<recordbuf_t> result; { const string_view message(""); const attribute_list attributes{{"key#1", "value#1"}}; const attribute_pack pack{attributes}; const record_t record(0, message, pack); result.reset(new recordbuf_t(record)); } const attribute_list attributes{{"key#1", "value#1"}}; ASSERT_EQ(1, result->into_view().attributes().size()); EXPECT_EQ(attributes, result->into_view().attributes().at(0).get()); } TEST(owned, MoveConstructor) { std::unique_ptr<recordbuf_t> result; { const string_view message("GET"); const attribute_list attributes{{"key#1", "value#1"}}; const attribute_pack pack{attributes}; const record_t record(42, message, pack); recordbuf_t own(record); result.reset(new recordbuf_t(std::move(own))); } EXPECT_EQ(string_view("GET"), result->into_view().message()); EXPECT_EQ(42, result->into_view().severity()); const attribute_list attributes{{"key#1", "value#1"}}; ASSERT_EQ(1, result->into_view().attributes().size()); EXPECT_EQ(attributes, result->into_view().attributes().at(0).get()); } TEST(owned, MoveAssignment) { std::unique_ptr<recordbuf_t> result; { const string_view message("GET"); const attribute_list attributes{{"key#1", "value#1"}}; const attribute_pack pack{attributes}; const record_t record(42, message, pack); result.reset(new recordbuf_t(record)); } { const string_view message("POST"); const attribute_list attributes{{"key#2", "value#2"}}; const attribute_pack pack{attributes}; const record_t record(10, message, pack); recordbuf_t own(record); *result = std::move(own); } EXPECT_EQ(string_view("POST"), result->into_view().message()); EXPECT_EQ(10, result->into_view().severity()); const attribute_list attributes{{"key#2", "value#2"}}; ASSERT_EQ(1, result->into_view().attributes().size()); EXPECT_EQ(attributes, result->into_view().attributes().at(0).get()); } TEST(owned, MoveAssignmentWithDifferentSizes) { std::unique_ptr<recordbuf_t> result; { const string_view message("GET"); const attribute_list attributes{{"key#1", "value#1"}}; const attribute_pack pack{attributes}; const record_t record(42, message, pack); result.reset(new recordbuf_t(record)); } { const string_view message("POST"); const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}}; const attribute_pack pack{attributes}; const record_t record(10, message, pack); recordbuf_t own(record); *result = std::move(own); } EXPECT_EQ(string_view("POST"), result->into_view().message()); EXPECT_EQ(10, result->into_view().severity()); const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}}; ASSERT_EQ(1, result->into_view().attributes().size()); EXPECT_EQ(attributes, result->into_view().attributes().at(0).get()); } TEST(recordbuf_t, DefaultMove) { recordbuf_t recordbuf; const string_view message("POST"); const attribute_list attributes{{"key#2", "value#2"}, {"key#3", "value#3"}}; const attribute_pack pack{attributes}; const record_t record(10, message, pack); recordbuf = recordbuf_t(record); recordbuf_t destroyer; destroyer = std::move(recordbuf); } } // namespace } // namespace v1 } // namespace blackhole
5,655
1,842
#include "../../include/core/Allocator.h" using namespace PhysicsEngine; Allocator::Allocator() { } Allocator::~Allocator(){};
128
47
#ifndef TOTEM_HPP #define TOTEM_HPP #include "gameobject.hpp" class Totem : public GameObject { public: Totem(btVector3 origin, btDiscreteDynamicsWorld *dyn_world); virtual bool collide(btManifoldPoint &cp, const btCollisionObjectWrapper *obj1, int id1, int index1); virtual void update(float dt); GameObject *carried; private: btDiscreteDynamicsWorld *dyn_world; btCollisionShape *ghost_shape; btPairCachingGhostObject *ghost; }; #endif
495
176
#include "RTTStar.hpp" #include <algorithm> #include <map> #include <memory> #include <numeric> #include <utility> /** * Constructs the RRT Star class. * * @param cost_map The cost_map to perform path finding on. * @param epsilon The maximum distance the new point can be away from the * nearest point. * @param radius The radius to select nearby points from. */ RTTStar::RTTStar(std::unique_ptr<CostMap2D> cost_map, double_t epsilon, double_t radius) noexcept : cost_map(std::move(cost_map)), eps(epsilon), radius(radius) { this->gen = std::mt19937(std::random_device()()); } /** * Constructs an initial path between two points. * * @param start The starting point of the path. * @param goal The goal point of the path. * @return The first path constructed between the start && goal. */ std::vector<Point2D> RTTStar::initial_path(const Point2D &start, const Point2D &goal) { this->reset(); this->start_point = start; this->end_point = goal; this->costs.insert(std::make_pair(start, 0.0)); std::tie(this->x_sample_space, this->y_sample_space) = this->cost_map->sample_space(std::vector{start, goal}); while (!this->costs.contains(goal) && !this->relations.contains(goal)) { this->iterate(); } return this->path(); } /** * Iterates on the current path in order to refine it. * * @param time The amount of time in milliseconds to refine the path for. * @return Returns the refined path. */ std::vector<Point2D> RTTStar::refine_path(size_t time) { const auto end_time = std::chrono::system_clock::now() + std::chrono::milliseconds(time); // Run the function for approximately the specified amount of time while (std::chrono::system_clock::now() < end_time) { this->iterate(); } return this->path(); } /** * Iterates on the current path in order to refine it. */ void RTTStar::iterate() { // Return if the start || end points were not set if (!this->start_point.has_value() || !this->end_point.has_value()) { return; } // Get a new random point const Point2D x = std::make_tuple(x_sample_space(this->gen), y_sample_space(this->gen)); // Check if the random point is valid || has already been selected if (this->cost_map->get(x) == std::nullopt && !costs.contains(x)) { // Get the point nearest to the new point const Point2D x_nearest = this->nearest(x); // Adjust the distance of the new point const Point2D x_new = this->steer(x_nearest, x); // If the new point does not intersect with an obstacle if (this->obstacle_free(x_nearest, x_new)) { // Set the points cost && parent this->costs.insert(std::make_pair( x_new, costs.at(x_nearest) + this->distance(x_new, x_nearest))); this->relations.insert(std::make_pair(x_new, x_nearest)); // Update the neighbors of the new point with the new point if the cost is // lower const auto x_near = this->near(x_new); std::for_each( x_near.begin(), x_near.end(), [&x_new, this](const auto &p) { const auto c = this->costs.at(x_new) + this->distance(p, x_new); if (c < this->costs.at(p) && this->obstacle_free(p, x_new)) { this->costs.at(p) = c; this->relations.at(p) = x_new; } }); } } } /** * Resets the class so that it can be re-run on an updated map. */ void RTTStar::reset() { this->costs.clear(); this->relations.clear(); this->start_point = std::nullopt; this->end_point = std::nullopt; } /** * Returns the current path * * @return Return the current optimal path || an empty path if a path does not * exist. */ std::vector<Point2D> RTTStar::path() { // Check if there if the start && goal have not been set if (!this->start_point.has_value() || !this->end_point.has_value()) { return std::vector<Point2D>{}; } // Construct the path std::vector<Point2D> p{this->end_point.value()}; while (true) { p.emplace_back(this->relations.at(p.back())); // Check if the point was found if (p.back() == start_point.value()) { return p; } // If a point is double counted a valid path does not exist. if (p.back() == p.at(p.size() - 2)) { return std::vector<Point2D>{}; } } } /** * Returns the nearest point to a point. * * @param x The point to find a point near. * @return The nearest point to a point. */ Point2D RTTStar::nearest(const Point2D &x) { const auto it = std::min_element(this->costs.begin(), this->costs.end(), [&x, this](const auto &a, const auto &b) { return this->distance(a.first, x) < this->distance(b.first, x) && a.first != x; }); return it->first; } /** * Limits the maximum step size of a move. * * @param x_nearest The anchor point which you can only move a certain distance * away from. * @param x The ideal move position. * @return The new point to move to. */ Point2D RTTStar::steer(const Point2D &x_nearest, const Point2D &x) { const auto dist = this->distance(x_nearest, x); if (dist >= this->eps) { return std::make_tuple( std::get<0>(x_nearest) + std::floor((static_cast<double_t>(std::get<0>(x) - std::get<0>(x_nearest)) * this->eps) / dist), std::get<1>(x_nearest) + std::floor((static_cast<double_t>(std::get<1>(x) - std::get<1>(x_nearest)) * this->eps) / dist)); } else { return x; } } /** * Checks if the line * * @param x_nearest The nearest point to x_new * @param x_new The point that will be moved to. * @return The */ bool RTTStar::obstacle_free(const Point2D &x_nearest, const Point2D &x_new) { const auto traversed = traversed_points(x_nearest, x_new); // Check that none of the points are in the cost map return std::all_of( traversed.begin(), traversed.end(), [this](const auto &pt) { return !this->cost_map->contains(pt); }); } /** * Returns the points that fall on a line. * * @param x_nearest A point on the line. * @param x_new The associated cost_map data type. * @return The points that fall on the line. */ std::vector<Point2D> RTTStar::traversed_points(const Point2D &x_nearest, const Point2D &x_new) { std::vector<Point2D> intersections; // The change const auto delta_x = std::get<0>(x_new) - std::get<0>(x_nearest); const auto delta_y = std::get<1>(x_new) - std::get<1>(x_nearest); // If the line is not vertical if (delta_x != 0) { // Get the sign of the slope && slope const double_t sign = (delta_y * delta_x > 0) ? 1 : ((delta_y * delta_x < 0) ? -1 : 0); const double_t delta_error = std::abs(static_cast<double_t>(delta_y) / static_cast<double_t>(delta_x)); // Get the x indices to traverse std::vector<int64_t> indices(std::abs(delta_x) + 1); std::iota(indices.begin(), indices.end(), std::min(std::get<0>(x_new), std::get<0>(x_nearest))); intersections.reserve(indices.size()); // Get the y value associated with the smallest x value int64_t y = std::min(std::get<0>(x_new), std::get<0>(x_nearest)) == std::get<0>(x_new) ? std::get<1>(x_new) : std::get<1>(x_nearest); double_t error = 0.0; // Collect all of the points intersecting on the line std::for_each( indices.begin(), indices.end(), [&error, &y, &sign, &delta_error, &intersections](const auto &x) { intersections.emplace_back(std::make_tuple(x, y)); error += delta_error; while (error >= 0.5) { y += sign; error -= 1.0; intersections.emplace_back(std::make_tuple(x, y)); } }); } else { // Get the y indices to traverse std::vector<int64_t> indices(std::abs(delta_y) + 1); std::iota(indices.begin(), indices.end(), std::min(std::get<1>(x_new), std::get<1>(x_nearest))); intersections.reserve(indices.size()); // Get the x value const int64_t x = std::get<0>(x_new); // Collect all of the points on the line std::transform(indices.begin(), indices.end(), std::back_inserter(intersections), [&x](const auto &y) { return std::make_tuple(x, y); }); } return intersections; } /** * Returns the euclidean distance between two points. * * @param first_point A point to get the distance between. * @param second_point A point to get the distance between. * @return The distance between the two points. */ inline double_t RTTStar::distance(const Point2D &first_point, const Point2D &second_point) { return std::sqrt(static_cast<double_t>( std::pow(std::get<0>(first_point) - std::get<0>(second_point), 2) + std::pow(std::get<1>(first_point) - std::get<1>(second_point), 2))); } /** * Returns the points nearby a point. * * @param point The points to find nearby points for. * @return The nearby points. */ std::vector<Point2D> RTTStar::near(const Point2D &point) { std::vector<Point2D> near; std::for_each(this->costs.begin(), this->costs.end(), [&](const auto &p) { if (this->distance(p.first, point) < this->radius && p.first != point) { near.emplace_back(p.first); } }); return near; }
9,762
3,235
/**************************************************************************** **This file is part of the Motorcar 3D windowing framework ** ** **Copyright (C) 2014 Forrest Reiling ** ** ** You may use this file under the terms of the BSD license as follows: ** ** "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. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** ****************************************************************************/ #include <scenegraph/input/singlebonetracker.h> using namespace motorcar; SingleBoneTracker::SingleBoneTracker(Bone *trackedBone, glm::mat4 boneTrackTransform, Skeleton *skeleton, PhysicalNode *parent, const glm::mat4 &transform) :BoneSensor(skeleton, parent, transform) ,m_trackedBone(trackedBone) ,m_boneTrackTransform(boneTrackTransform) { } glm::mat4 SingleBoneTracker::trackerParentSpaceToBoneParentSpaceTransform() { //define tracker parent space in bone space glm::mat4 workingTransform = trackedBone()->inverseWorldTransform() * this->parentNode()->worldTransform(); //apply inverse bone track transform in the bone space //this makes sure that the bone's orientation is taken into account when applying translation workingTransform = glm::inverse(boneTrackTransform()) * workingTransform; //bring into bone parent space workingTransform = trackedBone()->transform() * workingTransform; return workingTransform; } void SingleBoneTracker::setTransformFromTrackedBone() { this->setTransform(this->parentNode()->inverseWorldTransform() * trackedBone()->worldTransform() * boneTrackTransform()); } void SingleBoneTracker::setPosition(const glm::vec3 &position) { glm::vec4 parentSpaceBonePos = trackerParentSpaceToBoneParentSpaceTransform() * glm::vec4(position, 1); trackedBone()->setPosition(glm::vec3(parentSpaceBonePos)); setTransformFromTrackedBone(); } void SingleBoneTracker::setOrientation(const glm::mat3 &orientation) { glm::mat4 orientation4X4 = glm::mat4(orientation); glm::mat4 boneOrientation4X4 = trackerParentSpaceToBoneParentSpaceTransform() * orientation4X4 ; trackedBone()->setOrientation(glm::mat3(boneOrientation4X4)); setTransformFromTrackedBone(); } Bone *SingleBoneTracker::trackedBone() const { return m_trackedBone; } void SingleBoneTracker::setTrackedBone(Bone *trackedBone) { m_trackedBone = trackedBone; } glm::mat4 SingleBoneTracker::boneTrackTransform() const { return m_boneTrackTransform; } void SingleBoneTracker::setBoneTrackTransform(const glm::mat4 &boneTrackTransform) { m_boneTrackTransform = boneTrackTransform; }
3,840
1,243
#include <iostream> using namespace std; int main() { int t,i,j,k; int sum; char a,b; cin >>t; while(t--) { sum=0; cin>>i>>a>>j>>b>>k; if(a=='+') sum = i+j; else sum = i-j; if(b=='+') sum = sum + k; else sum=sum-k; cout <<sum<<endl; } return 0; }
383
150
/* * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "interactive_markers/tools.h" #include <tf/LinearMath/Quaternion.h> #include <tf/LinearMath/Matrix3x3.h> #include <math.h> #include <assert.h> #include <set> #include <sstream> namespace interactive_markers { void autoComplete( visualization_msgs::InteractiveMarker &msg, bool enable_autocomplete_transparency ) { // this is a 'delete' message. no need for action. if ( msg.controls.empty() ) { return; } // default size if ( msg.scale == 0 ) { msg.scale = 1; } // correct empty orientation, normalize if ( msg.pose.orientation.w == 0 && msg.pose.orientation.x == 0 && msg.pose.orientation.y == 0 && msg.pose.orientation.z == 0 ) { msg.pose.orientation.w = 1; } //normalize quaternion tf::Quaternion int_marker_orientation( msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z, msg.pose.orientation.w ); int_marker_orientation.normalize(); msg.pose.orientation.x = int_marker_orientation.x(); msg.pose.orientation.y = int_marker_orientation.y(); msg.pose.orientation.z = int_marker_orientation.z(); msg.pose.orientation.w = int_marker_orientation.w(); // complete the controls for ( unsigned c=0; c<msg.controls.size(); c++ ) { autoComplete( msg, msg.controls[c], enable_autocomplete_transparency); } uniqueifyControlNames( msg ); } void uniqueifyControlNames( visualization_msgs::InteractiveMarker& msg ) { int uniqueification_number = 0; std::set<std::string> names; for( unsigned c = 0; c < msg.controls.size(); c++ ) { std::string name = msg.controls[c].name; while( names.find( name ) != names.end() ) { std::stringstream ss; ss << name << "_u" << uniqueification_number++; name = ss.str(); } msg.controls[c].name = name; names.insert( name ); } } void autoComplete( const visualization_msgs::InteractiveMarker &msg, visualization_msgs::InteractiveMarkerControl &control, bool enable_autocomplete_transparency) { // correct empty orientation if ( control.orientation.w == 0 && control.orientation.x == 0 && control.orientation.y == 0 && control.orientation.z == 0 ) { control.orientation.w = 1; } // add default control handles if there are none if ( control.markers.empty() ) { switch ( control.interaction_mode ) { case visualization_msgs::InteractiveMarkerControl::NONE: break; case visualization_msgs::InteractiveMarkerControl::MOVE_AXIS: control.markers.reserve(2); makeArrow( msg, control, 1.0 ); makeArrow( msg, control, -1.0 ); break; case visualization_msgs::InteractiveMarkerControl::MOVE_PLANE: case visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS: case visualization_msgs::InteractiveMarkerControl::MOVE_ROTATE: makeDisc( msg, control ); break; case visualization_msgs::InteractiveMarkerControl::BUTTON: break; case visualization_msgs::InteractiveMarkerControl::MENU: makeViewFacingButton( msg, control, control.description ); break; default: break; } } // get interactive marker pose for later tf::Quaternion int_marker_orientation( msg.pose.orientation.x, msg.pose.orientation.y, msg.pose.orientation.z, msg.pose.orientation.w ); tf::Vector3 int_marker_position( msg.pose.position.x, msg.pose.position.y, msg.pose.position.z ); // fill in missing pose information into the markers for ( unsigned m=0; m<control.markers.size(); m++ ) { visualization_msgs::Marker &marker = control.markers[m]; if ( marker.scale.x == 0 ) { marker.scale.x = 1; } if ( marker.scale.y == 0 ) { marker.scale.y = 1; } if ( marker.scale.z == 0 ) { marker.scale.z = 1; } marker.ns = msg.name; // correct empty orientation if ( marker.pose.orientation.w == 0 && marker.pose.orientation.x == 0 && marker.pose.orientation.y == 0 && marker.pose.orientation.z == 0 ) { marker.pose.orientation.w = 1; } //normalize orientation tf::Quaternion marker_orientation( marker.pose.orientation.x, marker.pose.orientation.y, marker.pose.orientation.z, marker.pose.orientation.w ); marker_orientation.normalize(); marker.pose.orientation.x = marker_orientation.x(); marker.pose.orientation.y = marker_orientation.y(); marker.pose.orientation.z = marker_orientation.z(); marker.pose.orientation.w = marker_orientation.w(); static volatile unsigned id = 0; marker.id = id++; marker.ns = msg.name; // If transparency is disabled, set alpha to 1.0 for all semi-transparent markers if ( !enable_autocomplete_transparency && marker.color.a > 0.0 ) { marker.color.a = 1.0; } } } void makeArrow( const visualization_msgs::InteractiveMarker &msg, visualization_msgs::InteractiveMarkerControl &control, float pos ) { visualization_msgs::Marker marker; // rely on the auto-completion for the correct orientation marker.pose.orientation = control.orientation; marker.type = visualization_msgs::Marker::ARROW; marker.scale.x = msg.scale * 0.15; // aleeper: changed from 0.3 due to Rviz fix marker.scale.y = msg.scale * 0.25; // aleeper: changed from 0.5 due to Rviz fix marker.scale.z = msg.scale * 0.2; assignDefaultColor(marker, control.orientation); float dist = fabs(pos); float dir = pos > 0 ? 1 : -1; float inner = 0.5 * dist; float outer = inner + 0.4; marker.points.resize(2); marker.points[0].x = dir * msg.scale * inner; marker.points[1].x = dir * msg.scale * outer; control.markers.push_back( marker ); } void makeDisc( const visualization_msgs::InteractiveMarker &msg, visualization_msgs::InteractiveMarkerControl &control, float width ) { visualization_msgs::Marker marker; // rely on the auto-completion for the correct orientation marker.pose.orientation = control.orientation; marker.type = visualization_msgs::Marker::TRIANGLE_LIST; marker.scale.x = msg.scale; marker.scale.y = msg.scale; marker.scale.z = msg.scale; assignDefaultColor(marker, control.orientation); // compute points on a circle in the y-z plane int steps = 36; std::vector<geometry_msgs::Point> circle1, circle2; circle1.reserve(steps); circle2.reserve(steps); geometry_msgs::Point v1,v2; for ( int i=0; i<steps; i++ ) { float a = float(i)/float(steps) * M_PI * 2.0; v1.y = 0.5 * cos(a); v1.z = 0.5 * sin(a); v2.y = (1+width) * v1.y; v2.z = (1+width) * v1.z; circle1.push_back( v1 ); circle2.push_back( v2 ); } marker.points.resize(6*steps); std_msgs::ColorRGBA color; color.r=color.g=color.b=color.a=1; switch ( control.interaction_mode ) { case visualization_msgs::InteractiveMarkerControl::ROTATE_AXIS: { marker.colors.resize(2*steps); std_msgs::ColorRGBA base_color = marker.color; for ( int i=0; i<steps; i++ ) { int i1 = i; int i2 = (i+1) % steps; int i3 = (i+2) % steps; int p = i*6; int c = i*2; marker.points[p+0] = circle1[i1]; marker.points[p+1] = circle2[i2]; marker.points[p+2] = circle1[i2]; marker.points[p+3] = circle1[i2]; marker.points[p+4] = circle2[i2]; marker.points[p+5] = circle2[i3]; float t = 0.6 + 0.4 * (i%2); color.r = base_color.r * t; color.g = base_color.g * t; color.b = base_color.b * t; marker.colors[c] = color; marker.colors[c+1] = color; } break; } case visualization_msgs::InteractiveMarkerControl::MOVE_ROTATE: { marker.colors.resize(2*steps); std_msgs::ColorRGBA base_color = marker.color; for ( int i=0; i<steps-1; i+=2 ) { int i1 = i; int i2 = (i+1) % steps; int i3 = (i+2) % steps; int p = i * 6; int c = i * 2; marker.points[p+0] = circle1[i1]; marker.points[p+1] = circle2[i2]; marker.points[p+2] = circle1[i2]; marker.points[p+3] = circle1[i2]; marker.points[p+4] = circle2[i2]; marker.points[p+5] = circle1[i3]; color.r = base_color.r * 0.6; color.g = base_color.g * 0.6; color.b = base_color.b * 0.6; marker.colors[c] = color; marker.colors[c+1] = color; p += 6; c += 2; marker.points[p+0] = circle2[i1]; marker.points[p+1] = circle2[i2]; marker.points[p+2] = circle1[i1]; marker.points[p+3] = circle2[i2]; marker.points[p+4] = circle2[i3]; marker.points[p+5] = circle1[i3]; marker.colors[c] = base_color; marker.colors[c+1] = base_color; } break; } default: for ( int i=0; i<steps; i++ ) { int i1 = i; int i2 = (i+1) % steps; int p = i*6; marker.points[p+0] = circle1[i1]; marker.points[p+1] = circle2[i1]; marker.points[p+2] = circle1[i2]; marker.points[p+3] = circle2[i1]; marker.points[p+4] = circle2[i2]; marker.points[p+5] = circle1[i2]; } break; } control.markers.push_back(marker); } void makeViewFacingButton( const visualization_msgs::InteractiveMarker &msg, visualization_msgs::InteractiveMarkerControl &control, std::string text ) { control.orientation_mode = visualization_msgs::InteractiveMarkerControl::VIEW_FACING; control.independent_marker_orientation = false; visualization_msgs::Marker marker; float base_scale = 0.25 * msg.scale; float base_z = 1.2 * msg.scale; marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING; marker.scale.x = base_scale; marker.scale.y = base_scale; marker.scale.z = base_scale; marker.color.r = 1.0; marker.color.g = 1.0; marker.color.b = 1.0; marker.color.a = 1.0; marker.pose.position.x = base_scale * -0.1; marker.pose.position.z = base_z + base_scale * -0.1; marker.text = text; control.markers.push_back( marker ); } void assignDefaultColor(visualization_msgs::Marker &marker, const geometry_msgs::Quaternion &quat ) { geometry_msgs::Vector3 v; tf::Quaternion bt_quat( quat.x, quat.y, quat.z, quat.w ); tf::Vector3 bt_x_axis = tf::Matrix3x3(bt_quat) * tf::Vector3(1,0,0); float x,y,z; x = fabs(bt_x_axis.x()); y = fabs(bt_x_axis.y()); z = fabs(bt_x_axis.z()); float max_xy = x>y ? x : y; float max_yz = y>z ? y : z; float max_xyz = max_xy > max_yz ? max_xy : max_yz; marker.color.r = x / max_xyz; marker.color.g = y / max_xyz; marker.color.b = z / max_xyz; marker.color.a = 0.5; } visualization_msgs::InteractiveMarkerControl makeTitle( const visualization_msgs::InteractiveMarker &msg ) { visualization_msgs::Marker marker; marker.type = visualization_msgs::Marker::TEXT_VIEW_FACING; marker.scale.x = msg.scale * 0.15; marker.scale.y = msg.scale * 0.15; marker.scale.z = msg.scale * 0.15; marker.color.r = 1.0; marker.color.g = 1.0; marker.color.b = 1.0; marker.color.a = 1.0; marker.pose.position.z = msg.scale * 1.4; marker.text = msg.description; visualization_msgs::InteractiveMarkerControl control; control.interaction_mode = visualization_msgs::InteractiveMarkerControl::NONE; control.orientation_mode = visualization_msgs::InteractiveMarkerControl::VIEW_FACING; control.always_visible = true; control.markers.push_back( marker ); autoComplete( msg, control ); return control; } }
13,125
4,760
#include <sys/file.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <iostream> #include "ecal_process_stub.h" int main(int argc, char** argv) { if (argc <= 1) { std::cout << "This program is part of eCAL and should not be launched manually." << std::endl; return EXIT_FAILURE; } else if ((argc == 2) && (std::string(argv[1]) == "--version")) { // POSIX wants us to provide some output when launching with --version. We also use this to determine the correctnis of this application from other applications. std::cout << ECAL_PROCESS_STUB_VERSION_STRING << std::endl; return EXIT_SUCCESS; } else if (argc > 3) { char* fifo_name = argv[1]; char* lockfile_name = argv[2]; int process_args_start = 3; // Create and lock the lockfile. The lockfile will automaticall be // closed (and unlocked) when the execvp was successfull or the // process exits. // We have to do this BEFORE writing the FIFO, because after we have // written the PID to the FIFO, the main process will also attempt // to lock the lockfile. int lockfile_fd = open(lockfile_name, O_RDWR | O_CREAT | O_CLOEXEC, 0666); if (lockfile_fd) { if (flock(lockfile_fd, LOCK_EX) == -1) std::cerr << "Error locking lockfile \"" << lockfile_name << "\": " << strerror(errno) << std::endl; } else { std::cerr << "Error creating lockfile \"" << lockfile_name << "\": " << strerror(errno) << std::endl; } // Open FIFO and send the PID to the eCAL. The other process will wait until // we send the PID, here. It is important to know that although we have a // valid PID, we cannot know whether the execvp will be successfull, yet. // This is were the lockfile becomes important, as it will implicitely be // unlocked when execvp is successfull. pid_t process_id = getpid(); int fifo_fd = open(fifo_name, O_WRONLY); if (fifo_fd >= 0) { if(write(fifo_fd, &process_id, sizeof(process_id)) <= 0) { std::cerr << "Error writing to FIFO \"" << fifo_name << "\": " << strerror(errno) << std::endl; } close(fifo_fd); } else { std::cerr << "Error opening FIFO \"" << fifo_name << "\": " << strerror(errno) << std::endl; } // Now call execvp, which will replace this process by the new one, if // successfull. In that case, the lockfill will automatically be closed and // unlocked. const char** c_argv = new const char*[argc - process_args_start + 1]; for (int i = 0; i < argc - process_args_start; i++) { c_argv[i] = argv[i + process_args_start]; } c_argv[argc - process_args_start] = nullptr; execvp(c_argv[0], (char**)c_argv); // ERROR! >> If we have ever reached this code, execvp has not succeeded. // Now we have to tell the external main process via the lockfile. We simply // write our errno to that file and then exit. This will release the lock // and let the main process read the errno. std::cerr << "Error executing process " << c_argv[0] << ": " << strerror(errno); int errno_int = errno; size_t written_bytes = write(lockfile_fd, &errno_int, sizeof(errno_int)); if(written_bytes == 0) { std::cerr << "Error writing errno to file \"" << lockfile_name << "\": " << strerror(errno); } delete c_argv; return EXIT_FAILURE; } else { return EXIT_FAILURE; } }
3,492
1,198
#include "pch.h" #include "BoundingBox.h" BoundingBox::BoundingBox(glm::vec3 min, glm::vec3 max) { m_Params[0] = min; m_Params[1] = max; m_Centre = (min + max) * 0.5f; //Split(0); } BoundingBox::~BoundingBox() { } void BoundingBox::Split(int level) { //if (level == MAX_DEPTH) return; glm::vec3 min; glm::vec3 max; //if (m_Triangles.size() > MAX_TRIANGLES_PER_BOX) //{ float epsilon = 1e-1; BoundingBox* temp[NUMBER_OF_CHILDREN]; //Make children temp[0]= new BoundingBox(this->m_Params[0] - epsilon, this->m_Centre + epsilon); min = glm::vec3(this->m_Centre.x - epsilon, this->m_Params[0].y - epsilon, this->m_Params[0].z - epsilon); max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Centre.y + epsilon, this->m_Centre.z + epsilon); temp[1] = new BoundingBox(min, max); min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Centre.y - epsilon, this->m_Params[0].z - epsilon); max = glm::vec3(this->m_Centre.x + epsilon, this->m_Params[1].y + epsilon, this->m_Centre.z + epsilon); temp[2] = new BoundingBox(min, max); min = glm::vec3(this->m_Centre.x - epsilon, this->m_Centre.y - epsilon, this->m_Params[0].z - epsilon); max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Params[1].y + epsilon, this->m_Centre.z + epsilon); temp[3] = new BoundingBox(min, max); min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Params[0].y - epsilon, this->m_Centre.z- epsilon); max = glm::vec3(this->m_Centre.x + epsilon, this->m_Centre.y + epsilon, this->m_Params[1].z + epsilon); temp[4] = new BoundingBox(min, max); min = glm::vec3(this->m_Centre.x - epsilon, this->m_Params[0].y - epsilon, this->m_Centre.z - epsilon); max = glm::vec3(this->m_Params[1].x + epsilon, this->m_Centre.y + epsilon, this->m_Params[1].z + epsilon); temp[5] = new BoundingBox(min, max); min = glm::vec3(this->m_Params[0].x - epsilon, this->m_Centre.y - epsilon, this->m_Centre.z - epsilon); max = glm::vec3(this->m_Centre.x + epsilon, this->m_Params[1].y + epsilon, this->m_Params[1].z + epsilon); temp[6] = new BoundingBox(min, max); temp[7] = new BoundingBox(this->m_Centre - epsilon, this->m_Params[1] + epsilon); //if (level < MAX_DEPTH) { for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { for (int j = 0; j < m_Triangles.size(); j++) { temp[i]->Add(m_Triangles[j]); //Try and add this triangle -> push_back(t) if (j == m_Triangles.size() - 1) { if (temp[i]->m_Triangles.size() <= 0) { delete temp[i]; break; } if (temp[i]->m_Triangles.size() > MAX_TRIANGLES_PER_BOX) { temp[i]->Split(0); temp[i]->m_Triangles.clear(); children.push_back(temp[i]); break; } children.push_back(temp[i]); } } } //m_Triangles.clear(); /*for (int i = 0; i < NUMBER_OF_CHILDREN; i++) { if() }*/ /* for (int i = 0; i < children.size(); i++) { if (this->children[i]->m_Triangles.size() > 0) { this->children[i]->Split(level + 1); } }*/ //} //} //else //{ //// if (m_Triangles.size() == 0) delete this; // WARN("Triangles On leaf: {0}", m_Triangles.size()); // isLeaf = true; //} } bool BoundingBox::Intersect(Ray & ray) { float txmin, txmax, tymin, tymax, tzmin, tzmax; txmin = (m_Params[ray.sign[0]].x - ray.Origin.x) * ray.Inv_Direction.x; txmax = (m_Params[1 - ray.sign[0]].x - ray.Origin.x) * ray.Inv_Direction.x; tymin = (m_Params[ray.sign[1]].y - ray.Origin.y) * ray.Inv_Direction.y; tymax = (m_Params[1 - ray.sign[1]].y - ray.Origin.y) * ray.Inv_Direction.y; if (txmin > txmax) swap(txmin, txmax); if (tymin > tymax) swap(tymin, tymax); if ((txmin > tymax) || (tymin > txmax)) return false; if (tymin > txmin) txmin = tymin; if (tymax < txmax) txmax = tymax; tzmin = (m_Params[ray.sign[2]].z - ray.Origin.z) * ray.Inv_Direction.z; tzmax = (m_Params[1 - ray.sign[2]].z - ray.Origin.z) * ray.Inv_Direction.z; if (tzmin > tzmax) swap(tzmin, tzmax); if ((txmin > tzmax) || (tzmin > txmax)) return false; if (tzmin > txmin) txmin = tzmin; if (tzmax < txmax) txmax = tzmax; bool intersect = false; if (children.size() > 0) { for (int i = 0; i < children.size(); i++) { this->children[i]->Intersect(ray); } } else { for (int i = 0; i < m_Triangles.size(); i++) { if (m_Triangles[i]->Intersect(ray)) { intersect = true; } } } return intersect; } void BoundingBox::swap(float& first, float& second) { float temp; temp = first; first = second; second = temp; } void BoundingBox::Add(Triangle * t) { if (IsVertexInside(t->A()) || IsVertexInside(t->B()) || IsVertexInside(t->C())) { m_Triangles.push_back(t); } } bool BoundingBox::IsVertexInside(const glm::vec3& vert) { if (vert.x >= m_Params[0].x && vert.y >= m_Params[0].y && vert.z >= m_Params[0].z && vert.x <= m_Params[1].x && vert.y <= m_Params[1].y && vert.z <= m_Params[1].z ) { return true; } return false; }
4,978
2,400
#include <algorithm> #include <cassert> #include <iostream> #include <sstream> #include <string.h> #include <stdio.h> #include "Buffer.h" #include "Device.h" #include "Event.h" #include "Kernel.h" #include "Platform.h" #include "Program.h" #include "Queue.h" #include "SystemConfiguration.h" #include "bench_support.h" //----------------------------------------------------------------------------- constexpr int SIZE = 512; std::vector<size_t> globalWorkSize = { SIZE }; std::vector<size_t> localWorkSize = { 128 }; const std::string kernelFileName = "mv.cl"; std::string kernelName = ""; //----------------------------------------------------------------------------- void initialization(int argNumber, char **arguments); void hostMemoryAlloc(); void deviceMemoryAlloc(); void setKernelArguments(); void enqueWriteCommands(Queue &queue); void enqueReadCommands(Queue &queue); void run(Queue &queue); void freeMemory(); void setNDRangeSizes(); void verify(); //----------------------------------------------------------------------------- // Runtime components. Platform *platform; Kernel *kernel; // Host data. std::vector<float> inputMatrixHost; std::vector<float> inputVectorHost; std::vector<float> outputVectorHost; // Device data. Buffer *inputMatrix = nullptr; Buffer *inputVector = nullptr; Buffer *outputVector = nullptr; cl_int *width = nullptr; cl_int *height = nullptr; // Device. int PLATFORM_ID = 0; int DEVICE_ID = 0; //----------------------------------------------------------------------------- int main(int argNumber, char **arguments) { initialization(argNumber, arguments); getPlatformDevice(&PLATFORM_ID, &DEVICE_ID); platform = new Platform(PLATFORM_ID); Context *context = platform->getContext(); Device device = platform->getDevice(DEVICE_ID); setNDRangeSizes(); std::cout << "Device name: " << device.getName() << "\n"; hostMemoryAlloc(); deviceMemoryAlloc(); std::string kernelFile = KERNEL_DIR + kernelFileName; Program program(context, kernelFile); Queue queue(*context, device, Queue::EnableProfiling); enqueWriteCommands(queue); if (!program.build(device)) { std::cout << "Error building the program: \n"; std::cout << program.getBuildLog(device) << "\n"; return 1; } kernel = program.createKernel(kernelName.c_str()); setKernelArguments(); run(queue); enqueReadCommands(queue); verify(); freeMemory(); return 0; } //----------------------------------------------------------------------------- void initialization(int argNumber, char **arguments) { assert(globalWorkSize.size() == localWorkSize.size() && "Mismatching local and global work sizes"); if (argNumber != 2) { std::cerr << "Must specify kernel name\n"; exit(1); } kernelName = std::string(arguments[1]); } //----------------------------------------------------------------------------- void setNDRangeSizes() { std::vector<size_t> newGlobalWorkSize(globalWorkSize.size(), 0); std::vector<size_t> newLocalWorkSize(localWorkSize.size(), 0); getNewSizes(globalWorkSize.data(), localWorkSize.data(), newGlobalWorkSize.data(), newLocalWorkSize.data(), kernelName.c_str(), globalWorkSize.size()); globalWorkSize.clear(); localWorkSize.clear(); std::copy(newGlobalWorkSize.begin(), newGlobalWorkSize.end(), std::back_inserter(globalWorkSize)); std::copy(newLocalWorkSize.begin(), newLocalWorkSize.end(), std::back_inserter(localWorkSize)); } //----------------------------------------------------------------------------- void freeMemory() { delete kernel; delete platform; delete width; delete height; } //----------------------------------------------------------------------------- void hostMemoryAlloc() { width = new cl_int(globalWorkSize[0]); height = new cl_int(globalWorkSize[0]); std::random_device randomDevice; std::mt19937_64 gen(randomDevice()); std::uniform_real_distribution<float> distribution; inputVectorHost.assign(*width, 0.f); inputMatrixHost.assign(*width * (*height), 0.f); outputVectorHost.assign(*height, 0.f); std::generate_n(inputVectorHost.begin(), *width, [&] { return (distribution(gen)); }); std::generate_n(inputMatrixHost.begin(), *width * (*height), [&] { return (distribution(gen)); }); } //----------------------------------------------------------------------------- void deviceMemoryAlloc() { inputVector = new Buffer(*(platform->getContext()), Buffer::ReadOnly, inputVectorHost.size() * sizeof(float), nullptr); inputMatrix = new Buffer(*(platform->getContext()), Buffer::ReadOnly, inputMatrixHost.size() * sizeof(float), nullptr); outputVector = new Buffer(*(platform->getContext()), Buffer::WriteOnly, outputVectorHost.size() * sizeof(float), nullptr); } //----------------------------------------------------------------------------- void enqueWriteCommands(Queue &queue) { queue.writeBuffer(*inputVector, inputVectorHost.size() * sizeof(float), (void *)inputVectorHost.data()); queue.writeBuffer(*inputMatrix, inputMatrixHost.size() * sizeof(float), (void *)inputMatrixHost.data()); queue.finish(); } //----------------------------------------------------------------------------- void enqueReadCommands(Queue &queue) { queue.readBuffer(*outputVector, outputVectorHost.size() * sizeof(float), (void *)outputVectorHost.data()); queue.finish(); } //----------------------------------------------------------------------------- void setKernelArguments() { kernel->setArgument(0, *inputMatrix); kernel->setArgument(1, *inputVector); kernel->setArgument(2, sizeof(cl_uint), (void *)width); kernel->setArgument(3, sizeof(cl_uint), (void *)height); kernel->setArgument(4, *outputVector); if(kernelName == "MatVecMulCoalesced0") { kernel->setArgument(5, localWorkSize[0] * sizeof(float), nullptr); } } //----------------------------------------------------------------------------- void run(Queue &queue) { queue.run(*kernel, globalWorkSize.size(), 0, globalWorkSize.data(), localWorkSize.data()); queue.finish(); } //----------------------------------------------------------------------------- void verify() { for (int row = 0; row < 32; ++row) { float result = 0.0f; for (int column = 0; column < *width; ++column) { result += inputMatrixHost[row * (*width) + column] * inputVectorHost[column]; } std::cout << outputVectorHost[row] << " " << result << "\n"; // if (abs(outputVectorHost[row] - result) >= 0.001f) { // std::cout << "Error\n"; // exit(1); // } } }
6,763
1,945
#include <negli/NeuralGliderGame.hpp> #include <negli/ConsolePrint.hpp> using namespace negli; int main() { NeuralGliderGame game = NeuralGliderGame(20, 20, 5, 5); negli::printGame(game); return 0; }
216
91
#include <iostream> #include "util.hpp" #include "tsp.hpp" #include "nearest_neighbor.hpp" #include "nearest_insertion.hpp" #include "farthest_insertion.hpp" #include "double_mst.hpp" #include "greedy.hpp" #include "quick_boruvka.hpp" #include "two_opt.hpp" // main routine int main(int argc, char **argv){ if(argc<2){ std::cerr << "Error: need input filename." << std::endl; return 1; } // input { std::string s(argv[1]); s = "in/" + s + ".in"; TSP::input(s); } // nearest neighbor { Util::resettime(); Util::timestamp("Nearest Neighbor"); TSP::Tour tour_nn = TSP::NearestNeighbor::calc(); Util::timestamp("End"); std::string s(argv[1]); s = "out/" + s + "_nn.out"; TSP::output(tour_nn,s); tour_nn.clear(); } // nearest insertion { Util::resettime(); Util::timestamp("Nearest Insertion"); TSP::Tour tour_ni = TSP::NearestInsertion::calc(); Util::timestamp("End"); std::string s(argv[1]); s = "out/" + s + "_ni.out"; TSP::output(tour_ni,s); tour_ni.clear(); } // farthest insertion { Util::resettime(); Util::timestamp("Farthest Insertion"); TSP::Tour tour_fi = TSP::FarthestInsertion::calc(); Util::timestamp("End"); std::string s(argv[1]); s = "out/" + s + "_fi.out"; TSP::output(tour_fi,s); tour_fi.clear(); } // double mst { Util::resettime(); Util::timestamp("Double Minimum Spanning Tree"); TSP::Tour tour_dmst = TSP::DoubleMST::calc(); Util::timestamp("End"); std::string s(argv[1]); s = "out/" + s + "_dmst.out"; TSP::output(tour_dmst,s); tour_dmst.clear(); } // greedy { Util::resettime(); Util::timestamp("Greedy"); TSP::Tour tour_gr = TSP::Greedy::calc(); Util::timestamp("End"); std::string s(argv[1]); s = "out/" + s + "_gr.out"; TSP::output(tour_gr,s); tour_gr.clear(); } // quick boruvka { Util::resettime(); Util::timestamp("Quick Boruvka"); TSP::Tour tour_qb = TSP::QuickBoruvka::calc(); Util::timestamp("End"); std::string s(argv[1]); s = "out/" + s + "_qb.out"; TSP::output(tour_qb,s); tour_qb.clear(); } // nearest neighbor & 2-opt { Util::resettime(); Util::timestamp("Nearest Neighbor & 2-opt"); TSP::Tour tour_nn_2opt = TSP::NearestNeighbor::calc(); Util::timestamp("End(NN)"); TSP::TwoOpt::improve(tour_nn_2opt); Util::timestamp("End(2-opt)"); std::string s(argv[1]); s = "out/" + s + "_nn_2opt.out"; TSP::output(tour_nn_2opt,s); tour_nn_2opt.clear(); } // nearest insertion & 2-opt { Util::resettime(); Util::timestamp("Nearest Insertion & 2-opt"); TSP::Tour tour_ni_2opt = TSP::NearestInsertion::calc(); Util::timestamp("End(NI)"); TSP::TwoOpt::improve(tour_ni_2opt); Util::timestamp("End(2-opt)"); std::string s(argv[1]); s = "out/" + s + "_ni_2opt.out"; TSP::output(tour_ni_2opt,s); tour_ni_2opt.clear(); } // farthest insertion & 2-opt { Util::resettime(); Util::timestamp("Farthest Insertion & 2-opt"); TSP::Tour tour_fi_2opt = TSP::FarthestInsertion::calc(); Util::timestamp("End(FI)"); TSP::TwoOpt::improve(tour_fi_2opt); Util::timestamp("End(2-opt)"); std::string s(argv[1]); s = "out/" + s + "_fi_2opt.out"; TSP::output(tour_fi_2opt,s); tour_fi_2opt.clear(); } // double mst & 2-opt { Util::resettime(); Util::timestamp("Double Minimum Spanning Tree & 2-opt"); TSP::Tour tour_dmst_2opt = TSP::DoubleMST::calc(); Util::timestamp("End(DMST)"); TSP::TwoOpt::improve(tour_dmst_2opt); Util::timestamp("End(2-opt)"); std::string s(argv[1]); s = "out/" + s + "_dmst_2opt.out"; TSP::output(tour_dmst_2opt,s); tour_dmst_2opt.clear(); } // greedy & 2-opt { Util::resettime(); Util::timestamp("Greedy & 2-opt"); TSP::Tour tour_gr_2opt = TSP::Greedy::calc(); Util::timestamp("End(GR)"); TSP::TwoOpt::improve(tour_gr_2opt); Util::timestamp("End(2-opt)"); std::string s(argv[1]); s = "out/" + s + "_gr_2opt.out"; TSP::output(tour_gr_2opt,s); tour_gr_2opt.clear(); } // quick boruvka & 2-opt { Util::resettime(); Util::timestamp("Quick Boruvka & 2-opt"); TSP::Tour tour_qb_2opt = TSP::QuickBoruvka::calc(); Util::timestamp("End(QB)"); TSP::TwoOpt::improve(tour_qb_2opt); Util::timestamp("End(2-opt)"); std::string s(argv[1]); s = "out/" + s + "_qb_2opt.out"; TSP::output(tour_qb_2opt,s); tour_qb_2opt.clear(); } TSP::halt(); return 0; }
4,611
1,914
/* ** EPITECH PROJECT, 2021 ** rtype ** File description: ** Created by seb, */ #pragma once namespace ecs {namespace component { struct Drawable { Drawable() { this->layer = 0; this->visible = false; } Drawable(unsigned int layer, bool visible) { this->layer = layer; this->visible = visible; } unsigned int layer; bool visible; }; }}
370
149
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: qtang@openailab.com */ #include "test_op.h" int create_test_clip_node(graph_t graph, const char* input_name, const char* node_name, int data_type, int layout, int n, int c, int h, int w) { (void)layout; (void)n; (void)c; (void)h; (void)w; /* create the test node */ struct node* test_node = (struct node*)create_graph_node(graph, node_name, "Clip"); tensor_t input_tensor = get_graph_tensor(graph, input_name); if (NULL == input_tensor) { fprintf(stderr, "create test node failed.\n"); return -1; } /* input tensors of test node */ set_node_input_tensor(test_node, 0, input_tensor); /* output tensors of test node */ tensor_t output_tensor = create_graph_tensor(graph, node_name, data_type); set_node_output_tensor(test_node, 0, output_tensor, TENSOR_TYPE_VAR); return 0; } float input_fp32[5] = {-3.0f, 3.0f, 8.0f, 1.0f, -2.0f}; float reference_out[5] = {0.0f, 3.0f, 6.0f, 1.0f, 0.0f}; int main(int argc, char* argv[]) { int n = 1, c = 1, h = 5, w = 1; const char* test_node_name = "clip"; int data_type = TENGINE_DT_FP32; int layout = TENGINE_LAYOUT_NCHW; // init int ret = test_graph_init(); if (0 != ret) fprintf(stderr, "Tengine init failed.\n"); // create graph_t graph = create_tensorrt_test_graph(test_node_name, data_type, layout, n, c, h, w, &create_test_clip_node); if (NULL == graph) return -1; set_log_level(LOG_INFO); dump_graph(graph); // set quantize params struct tensor* input_tensor = (struct tensor*)get_graph_input_tensor(graph, 0, 0); struct tensor* output_tensor = (struct tensor*)get_graph_output_tensor(graph, 0, 0); // set input data set_tensor_buffer(input_tensor, input_fp32, 5 * 4); // graph run ret = test_graph_run(graph); if (0 != ret) { fprintf(stderr, "Run graph error. ERRNO: %d.\n", ret); test_graph_release(graph); return -1; } // get output and dequant float* output_data = (float*)output_tensor->data; int output_size = output_tensor->elem_num; // check the result ret = 0; for (int i = 0; i < output_size; i++) { if (fabsf(output_data[i] - reference_out[i]) > 0.1) { fprintf(stderr, "index:%d, a:%f, b:%f\n", i, output_data[i], reference_out[i]); ret = -1; } } if (ret == 0) fprintf(stderr, "test pass.\n"); else fprintf(stderr, "test failed.\n"); // exit test_graph_release(graph); return ret; }
3,442
1,235
//No of islands (only 4 neighbours) //Time: O(M*N) //Space: O(M*N) #include <bits/stdc++.h> using namespace std; bool isInside(int n, int m, int i, int j) { if(i<0||j<0||i>n-1||j>m-1) return false; return true; } void dfs(vector<vector<char>>&grid, vector<vector<bool>>&vis, int n, int m, int i, int j) { vis[i][j]=true; int dx[] = { 0, -1, 0, 1 }; int dy[] = { -1, 0, 1, 0 }; for(int k=0;k<4;k++) { int x=dx[k]+i; int y=dy[k]+j; if(isInside(n,m,x,y) && !vis[x][y] && grid[x][y]=='X') dfs(grid,vis,n,m,x,y); } return; } int solve(vector<vector<char>>& grid) { int n=grid.size(); int m=grid[0].size(); int ans=0; vector<vector<bool>>vis(n,vector<bool>(m,false)); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { if(!vis[i][j] && grid[i][j]=='X') { dfs(grid,vis,n,m,i,j); ans++; } } } return ans; } int main() { int n,m; cin>>n>>m; vector<vector<char>>grid(n,vector<char>(m)); for(int i=0;i<n;i++) { for(int j=0;j<m;j++) { cin>>grid[i][j]; } } int ans = solve(grid); cout<<ans; }
1,368
588
#if !defined ADBASE_LOGGING_HPP_ # error "Not allow include this header." #endif #ifndef ADBASE_UTILITY_ASYNCLOGGING_HPP_ #define ADBASE_UTILITY_ASYNCLOGGING_HPP_ #include <thread> #include <condition_variable> #include <vector> namespace adbase { /** * @addtogroup logging adbase::Logging */ /*@{*/ class AsyncLogging { public: AsyncLogging(const std::string& basename, size_t rollSize, int flushInterval = 3); AsyncLogging(const AsyncLogging&) = delete; void operator=(const AsyncLogging&) = delete; ~AsyncLogging() { if (_running) { stop(); } } void append(const char* logline, int len); void start(); void stop() { _running = false; _cond.notify_one(); } static void deleteThread(std::thread *t); private: void threadFunc(void *data); typedef adbase::detail::FixedBuffer<adbase::detail::kLargeBuffer> Buffer; typedef std::unique_ptr<Buffer> BufferPtr; typedef std::vector<BufferPtr> BufferVector; const int _flushInterval; bool _running; std::string _basename; size_t _rollSize; mutable std::mutex _mut; std::condition_variable _cond; BufferPtr _currentBuffer; BufferPtr _nextBuffer; BufferVector _buffers; typedef std::unique_ptr<std::thread, decltype(&AsyncLogging::deleteThread)> ThreadPtr; typedef std::vector<ThreadPtr> ThreadPool; ThreadPool _threads; }; /*@}*/ } #endif
1,353
512
/* The MIT License (MIT) Copyright (c) 2021 Lancaster University. 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 "MicroBit.h" #include "Tests.h" extern MicroBit uBit; MicroBitUARTService *uart; // we use events abd the 'connected' variable to keep track of the status of the Bluetooth connection void onConnected(MicroBitEvent) { uBit.display.print("C"); } void onDisconnected(MicroBitEvent) { uBit.display.print("D"); } void onDelim(MicroBitEvent) { ManagedString r = uart->readUntil("\r\n"); uart->send(r); } void ble_test() { // Configuration Tips // // An example codal.json is provided in the root directory: codal.ble.json // Rename codal.ble.json to codal.json to use this BLE sample // // codal.json contains various Bluetooth related properties some of which are explained here: // // "SOFTDEVICE_PRESENT": 1 Determines whether the build contains softdevice // "DEVICE_BLE": 1 Determines whether BLE is enabled // "MICROBIT_BLE_ENABLED" : 1 Determines whether BLE is enabled // "MICROBIT_BLE_PAIRING_MODE": 1 Determines whether Pairing Mode is enabled // "MICROBIT_BLE_DFU_SERVICE": 1 Determines whether the Nordic DFU Service is enabled // "MICROBIT_BLE_DEVICE_INFORMATION_SERVICE": 1 Determines whether the DIS is enabled // "MICROBIT_BLE_EVENT_SERVICE" : 1, Determines whether the Event Service is enabled // "MICROBIT_BLE_PARTIAL_FLASHING" : 0 Determines whether Partial Flashing is enabled (Needs MakeCode/Python) // "MICROBIT_BLE_SECURITY_LEVEL": "SECURITY_MODE_ENCRYPTION_WITH_MITM" Determines security mode // // Options for MICROBIT_BLE_SECURITY_LEVEL are: // SECURITY_MODE_ENCRYPTION_WITH_MITM, enables pairing with a passcode // SECURITY_MODE_ENCRYPTION_NO_MITM, enables pairing without a passcode // SECURITY_MODE_ENCRYPTION_OPEN_LINK, pairing is no required // // A cunning code to indicate during start-up the particular Bluetooth configuration in the build // // SERVICE CODES // A: Accelerometer Service // B: Button Service // D: Device Information Service // E: Event Service // F: DFU Service // I: IO Pin Service // L: LED Service // M: Magnetometer Service // T: Temperature Service // U: UART Service // // P: PASSKEY // J: Just Works // N: No Pairing Required // Services/Pairing Config/Power Level uBit.display.scroll("BLE ABDILMTU/P"); uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_CONNECTED, onConnected); uBit.messageBus.listen(MICROBIT_ID_BLE, MICROBIT_BLE_EVT_DISCONNECTED, onDisconnected); uBit.messageBus.listen(MICROBIT_ID_BLE_UART, MICROBIT_UART_S_EVT_DELIM_MATCH, onDelim); new MicroBitAccelerometerService(*uBit.ble, uBit.accelerometer); new MicroBitButtonService(*uBit.ble); new MicroBitIOPinService(*uBit.ble, uBit.io); new MicroBitLEDService(*uBit.ble, uBit.display); new MicroBitMagnetometerService(*uBit.ble, uBit.compass); new MicroBitTemperatureService(*uBit.ble, uBit.thermometer); uart = new MicroBitUARTService(*uBit.ble, 32, 32); uart->eventOn("\r\n"); // If main exits, there may still be other fibers running or registered event handlers etc. // Simply release this fiber, which will mean we enter the scheduler. Worse case, we then // sit in the idle task forever, in a power efficient sleep. release_fiber(); }
4,485
1,532
/* * Copyright 2021 Marzocchi Alessandro * All rights reserved. Distributed under the terms of the MIT license. */ #include "port.h" using namespace HFMidi; Port::Port() { } void Port::sendEvent(const QByteArray &data) { sendData(data); } bool Port::sendData(const QByteArray &data) { Q_UNUSED(data); return false; } void Port::receivedData(const QByteArray &data) { // qDebug()<<data.toHex(); emit midiEvent(data); }
438
167
class Solution { public: int rob(vector<int>& nums) { int n = nums.size() ; if(n==1) return nums[0] ; if(n==2) return max(nums[0],nums[1]) ; int dp1[n-1] ; dp1[0] = nums[0] ; dp1[1] = max(nums[0],nums[1]) ; for(int i=2;i<n-1;i++) { dp1[i] = max(dp1[i-1],nums[i]+dp1[i-2]); } int dp2[n-1] ; dp2[0] = nums[1] ; dp2[1] = max(nums[2],nums[1]) ; for(int i=2;i<n-1;i++) { dp2[i] = max(dp2[i-1],nums[i+1]+dp2[i-2]); } return max(dp1[n-2],dp2[n-2]) ; } };
660
309
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: proto/gRPCCommunication/GrpcStepInput.proto #include "proto/gRPCCommunication/GrpcStepInput.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> namespace gRPCCommunication { class GrpcStepInputDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<GrpcStepInput> _instance; } _GrpcStepInput_default_instance_; } // namespace gRPCCommunication static void InitDefaultsscc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::gRPCCommunication::_GrpcStepInput_default_instance_; new (ptr) ::gRPCCommunication::GrpcStepInput(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::gRPCCommunication::GrpcStepInput::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsscc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto}, {}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::gRPCCommunication::GrpcStepInput, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::gRPCCommunication::GrpcStepInput, actions_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::gRPCCommunication::GrpcStepInput)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::gRPCCommunication::_GrpcStepInput_default_instance_), }; const char descriptor_table_protodef_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto[] = "\n+proto/gRPCCommunication/GrpcStepInput." "proto\022\021gRPCCommunication\" \n\rGrpcStepInpu" "t\022\017\n\007actions\030\001 \003(\002b\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_deps[1] = { }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_sccs[1] = { &scc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_once; static bool descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_initialized = false; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = { &descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_initialized, descriptor_table_protodef_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto, "proto/gRPCCommunication/GrpcStepInput.proto", 106, &descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_once, descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_sccs, descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto_deps, 1, 0, schemas, file_default_instances, TableStruct_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto::offsets, file_level_metadata_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto, 1, file_level_enum_descriptors_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto, file_level_service_descriptors_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto), true); namespace gRPCCommunication { // =================================================================== void GrpcStepInput::InitAsDefaultInstance() { } class GrpcStepInput::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int GrpcStepInput::kActionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 GrpcStepInput::GrpcStepInput() : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:gRPCCommunication.GrpcStepInput) } GrpcStepInput::GrpcStepInput(const GrpcStepInput& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr), actions_(from.actions_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:gRPCCommunication.GrpcStepInput) } void GrpcStepInput::SharedCtor() { } GrpcStepInput::~GrpcStepInput() { // @@protoc_insertion_point(destructor:gRPCCommunication.GrpcStepInput) SharedDtor(); } void GrpcStepInput::SharedDtor() { } void GrpcStepInput::SetCachedSize(int size) const { _cached_size_.Set(size); } const GrpcStepInput& GrpcStepInput::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_GrpcStepInput_proto_2fgRPCCommunication_2fGrpcStepInput_2eproto.base); return *internal_default_instance(); } void GrpcStepInput::Clear() { // @@protoc_insertion_point(message_clear_start:gRPCCommunication.GrpcStepInput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; actions_.Clear(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* GrpcStepInput::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // repeated float actions = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ::PROTOBUF_NAMESPACE_ID::internal::PackedFloatParser(mutable_actions(), ptr, ctx); CHK_(ptr); } else if (static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 13) { add_actions(::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<float>(ptr)); ptr += sizeof(float); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool GrpcStepInput::MergePartialFromCodedStream( ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:gRPCCommunication.GrpcStepInput) for (;;) { ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated float actions = 1; case 1: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (10 & 0xFF)) { DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPackedPrimitive< float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT>( input, this->mutable_actions()))); } else if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (13 & 0xFF)) { DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< float, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_FLOAT>( 1, 10u, input, this->mutable_actions()))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:gRPCCommunication.GrpcStepInput) return true; failure: // @@protoc_insertion_point(parse_failure:gRPCCommunication.GrpcStepInput) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void GrpcStepInput::SerializeWithCachedSizes( ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:gRPCCommunication.GrpcStepInput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated float actions = 1; if (this->actions_size() > 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTag(1, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_actions_cached_byte_size_.load( std::memory_order_relaxed)); ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteFloatArray( this->actions().data(), this->actions_size(), output); } if (_internal_metadata_.have_unknown_fields()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:gRPCCommunication.GrpcStepInput) } ::PROTOBUF_NAMESPACE_ID::uint8* GrpcStepInput::InternalSerializeWithCachedSizesToArray( ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:gRPCCommunication.GrpcStepInput) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated float actions = 1; if (this->actions_size() > 0) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteTagToArray( 1, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream::WriteVarint32ToArray( _actions_cached_byte_size_.load(std::memory_order_relaxed), target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: WriteFloatNoTagToArray(this->actions_, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:gRPCCommunication.GrpcStepInput) return target; } size_t GrpcStepInput::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:gRPCCommunication.GrpcStepInput) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated float actions = 1; { unsigned int count = static_cast<unsigned int>(this->actions_size()); size_t data_size = 4UL * count; if (data_size > 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( static_cast<::PROTOBUF_NAMESPACE_ID::int32>(data_size)); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(data_size); _actions_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void GrpcStepInput::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:gRPCCommunication.GrpcStepInput) GOOGLE_DCHECK_NE(&from, this); const GrpcStepInput* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<GrpcStepInput>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:gRPCCommunication.GrpcStepInput) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:gRPCCommunication.GrpcStepInput) MergeFrom(*source); } } void GrpcStepInput::MergeFrom(const GrpcStepInput& from) { // @@protoc_insertion_point(class_specific_merge_from_start:gRPCCommunication.GrpcStepInput) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; actions_.MergeFrom(from.actions_); } void GrpcStepInput::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:gRPCCommunication.GrpcStepInput) if (&from == this) return; Clear(); MergeFrom(from); } void GrpcStepInput::CopyFrom(const GrpcStepInput& from) { // @@protoc_insertion_point(class_specific_copy_from_start:gRPCCommunication.GrpcStepInput) if (&from == this) return; Clear(); MergeFrom(from); } bool GrpcStepInput::IsInitialized() const { return true; } void GrpcStepInput::Swap(GrpcStepInput* other) { if (other == this) return; InternalSwap(other); } void GrpcStepInput::InternalSwap(GrpcStepInput* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); actions_.InternalSwap(&other->actions_); } ::PROTOBUF_NAMESPACE_ID::Metadata GrpcStepInput::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace gRPCCommunication PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::gRPCCommunication::GrpcStepInput* Arena::CreateMaybeMessage< ::gRPCCommunication::GrpcStepInput >(Arena* arena) { return Arena::CreateInternal< ::gRPCCommunication::GrpcStepInput >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
15,475
5,766
// Copyright 2021 The WebNN-native 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 "ops/Pad.h" #include "Utils.h" namespace node::op { Napi::Value Pad::Build(const Napi::CallbackInfo& info, wnn::GraphBuilder builder) { // Operand pad(Operand input, Operand padding, optional PadOptions options = {}); WEBNN_NODE_ASSERT(info.Length() == 2 || info.Length() == 3, "The number of arguments is invalid."); std::vector<napi_value> args; wnn::Operand input; WEBNN_NODE_ASSERT(GetOperand(info[0], input, args), "The input parameter is invalid."); wnn::Operand padding; WEBNN_NODE_ASSERT(GetOperand(info[1], padding, args), "The padding parameter is invalid."); // dictionary PadOptions { // PaddingMode mode; // float value = false; // }; wnn::PadOptions options; if (info.Length() == 3 && !info[2].IsUndefined()) { WEBNN_NODE_ASSERT(info[2].IsObject(), "The options must be an object."); Napi::Object jsOptions = info[2].As<Napi::Object>(); if (HasOptionMember(jsOptions, "mode")) { WEBNN_NODE_ASSERT(GetPaddingMode(jsOptions.Get("mode"), options.mode), "The mode parameter is invalid."); } if (HasOptionMember(jsOptions, "value")) { WEBNN_NODE_ASSERT(GetValue(jsOptions.Get("value"), options.value), "The value parameter is invalid."); } } Napi::Object object = Operand::constructor.New(args); Operand* operand = Napi::ObjectWrap<Operand>::Unwrap(object); operand->SetImpl(builder.Pad(input, padding, &options)); return object; } } // namespace node::op
2,338
682
#include "ControlWindow.h" void CreateControlWindow(WinDat& wd){ wd._handle = CreateWindowEx(0, wd._className, NULL, wd._style, wd._x, wd._y, wd._w, wd._h, wd._parent, 0, NULL, NULL); HTREEITEM hRoot; TV_INSERTSTRUCT tvins; tvins = { 0 }; tvins.hInsertAfter = TVI_ROOT; tvins.item.mask = TVIF_TEXT; tvins.item.pszText = L"Root"; tvins.item.cchTextMax = 10; hRoot = TreeView_InsertItem(wd._handle, &tvins); //tvins.hInsertAfter = TVI_LAST; //tvins.item.pszText = "Child"; //hChild = TreeView_InsertItem(hSidePanel, &tvins); ListViewAddItem(wd._handle, hRoot, L"test"); ListViewAddItem(wd._handle, hRoot, L"cat"); ListViewAddItem(wd._handle, ListViewAddItem(wd._handle, hRoot, L"murder"), L"more"); tvins.hInsertAfter = TVI_ROOT; tvins.item.mask = TVIF_TEXT; tvins.item.pszText = L"Root2"; tvins.item.cchTextMax = 10; hRoot = TreeView_InsertItem(wd._handle, &tvins); } HTREEITEM ListViewAddItem(HWND hWnd, HTREEITEM hItem, LPWSTR lpstr) { TVINSERTSTRUCT insert; insert = { 0 }; insert.hParent = hItem; insert.hInsertAfter = TVI_LAST; insert.item.mask = TVIF_TEXT; insert.item.pszText = lpstr; insert.item.cchTextMax = 10; //HTREEITEM test = TVM_INSERTITEM(0, &insert); return TreeView_InsertItem(hWnd, &insert); }
1,259
553
extern "C" { #include "vl/generic.h" #include "vl/stringop.h" #include "vl/pgm.h" #include "vl/dsift.h" #include "vl/sift.h" #include "vl/getopt_long.h" } #include <errno.h> #include <cstdlib> #include <cstdio> #include <cassert> #include <iostream> #include <sstream> #include <cmath> #include <string> #include <cstdio> #include <cstring> #include <cstdarg> #include "vldsift.hpp" using namespace std; enum { DEBUG = 0, INFO, WARN, ERROR, FATAL, SIGNAL }; // log levels int loglevel = INFO; #define verify(_x) \ do { \ if (!(_x)) { \ LOG(FATAL, "Assertion failure in %s line %d of %s: %s\n", \ __FUNCTION__, __LINE__, __FILE__, #_x); \ } \ } while (0) void LOG(int level, const char *fmt, ...) { static const char *level_str[] = { "DEBUG", "INFO", "WARN", "ERROR", "FATAL", "SIGNAL" }; assert(loglevel >= DEBUG); assert(loglevel <= SIGNAL); if (level >= loglevel) { va_list args; fprintf(stderr, "[%s] ", level_str[level]); if (level == ERROR) { fprintf(stderr, "(errno: %s) ", strerror(errno)); } va_start(args, fmt); vfprintf(stderr, fmt, args); va_end(args); } if (level == FATAL) { exit(1); } } char* input_path = NULL; int verbose = 0; int step_size = 10; int cur_scale = 0; int flag_ascii = 1; void printUsageAndExit() { cerr << "vldsift [options] input_file" << endl << "-s stepsize , default 10" << endl << "-b output binary ( default ascii )" << endl << "-l current scale ( default 0, image is assumed to have been reduced by 2^l. position is for the original image)" << endl << "stdout: vldsift format" << endl; exit(1); } bool parseArgs(int argc, char** argv) { //get rid of program name argc--; argv++; while(argc > 0) { if(!strcmp(*argv, "-s")){ argc--; argv++; if(argc == 0) { fprintf(stderr, "must specify -s\n"); return false; } else { step_size = atoi(*argv); } } if(!strcmp(*argv, "-l")){ argc--; argv++; if(argc == 0) { fprintf(stderr, "must specify -s\n"); return false; } else { cur_scale = atoi(*argv); } } else if(!strcmp(*argv, "-b")){ flag_ascii=0; }else { input_path = *argv; } argc--; argv++; } if( input_path == NULL ) { return false; } return true; } int main(int argc, char** argv ) { if( !parseArgs(argc, argv) ) { printUsageAndExit(); } vl_uint8 *data = 0 ; vl_sift_pix *fdata = 0 ; int err; VlPgmImage pim ; FILE* in; /* open input file */ if( !strcmp(input_path, "-" )) { in = stdin; } else { in = fopen (input_path, "rb") ; } if (!in) { LOG(FATAL, "cannot open file %s\n", input_path); } /* ............................................................... * Read data * ............................................................ */ /* read PGM header */ err = vl_pgm_extract_head (in, &pim) ; if (err) { switch (vl_err_no) { case VL_ERR_PGM_IO : /* snprintf(err_msg, sizeof(err_msg), "Cannot read from '%s'.", name) ; */ err = VL_ERR_IO ; break ; case VL_ERR_PGM_INV_HEAD : /* snprintf(err_msg, sizeof(err_msg), */ LOG(FATAL, "'%s' contains a malformed PGM header.", input_path); err = VL_ERR_IO ; } } if (verbose) fprintf (stderr, "sift: image is %d by %d pixels\n", pim. width, pim. height) ; /* allocate buffer */ data = (vl_uint8*)malloc(vl_pgm_get_npixels (&pim) * vl_pgm_get_bpp (&pim) * sizeof (vl_uint8) ) ; fdata = (float*)malloc(vl_pgm_get_npixels (&pim) * vl_pgm_get_bpp (&pim) * sizeof (float)) ; if (!data || !fdata) { err = VL_ERR_ALLOC ; /* snprintf(err_msg, sizeof(err_msg), "Could not allocate enough memory.") ; */ LOG(FATAL, "Could not allocate enough memory.") ; } /* read PGM body */ err = vl_pgm_extract_data (in, &pim, data) ; if (err) { /* snprintf(err_msg, sizeof(err_msg), "PGM body malformed.") ; */ err = VL_ERR_IO ; LOG(FATAL,"PGM body malformed."); } /* convert data type */ for (int q = 0 ; q < pim.width * pim.height ; ++q) fdata [q] = data [q] ; VlDsiftFilter* df = vl_dsift_new(pim.width, pim.height); vl_dsift_set_steps(df, step_size, step_size); vl_dsift_process(df, fdata); int num_keypoints = vl_dsift_get_keypoint_num(df); const VlDsiftKeypoint* points = vl_dsift_get_keypoints(df); const float* descriptors = vl_dsift_get_descriptors(df); int dim = vl_dsift_get_descriptor_size(df); Points_vldsift mypoints; verify(VLDSIFT_DIM==dim); for( int i = 0 ;i< num_keypoints; i++ ) { const VlDsiftKeypoint& p = points[i]; mypoints.vecs.push_back(Point_vldsift()); Point_vldsift& q = mypoints.vecs.back(); q.x = p.x / (float)pim.width; q.y = p.y / (float)pim.height; q.scale = cur_scale; q.norm = p.norm; for( int k = 0; k < dim; k++ ) { q.desc[k] = descriptors[i*dim+k]; } } if( flag_ascii ) { cout << mypoints.toASCII() << endl; } else { string s = mypoints.toBinary(); cout.write((char*)s.data(),s.length()); } vl_dsift_delete(df); return 0; }
5,339
2,217
/* BME280Spi.cpp This code records data from the BME280Spi sensor and provides an API. This file is part of the Arduino BME280Spi library. Copyright (C) 2016 Tyler Glenn This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Written: Dec 18 2016. - Happy Holidays! Last Updated: Oct 07 2017. This header must be included in any derived code or copies of the code. Based on the data sheet provided by Bosch for the BME280Spi environmental sensor, calibration code based on algorithms providedBosch, some unit conversations courtesy of www.endmemo.com, altitude equation courtesy of NOAA, and dew point equation courtesy of Brian McNoldy at http://andrew.rsmas.miami.edu. */ #include "Arduino.h" #include "BME280Spi.h" #include <SPI.h> /****************************************************************/ BME280Spi::BME280Spi ( const Settings& settings ) :BME280(settings), csPin(settings.spiCsPin) { } /****************************************************************/ bool BME280Spi::Initialize() { pinMode(csPin, OUTPUT); digitalWrite(csPin, HIGH); return BME280::Initialize(); } /****************************************************************/ bool BME280Spi::ReadRegister ( uint8_t addr, uint8_t data[], uint8_t len ) { SPI.beginTransaction(SPISettings(500000,MSBFIRST,SPI_MODE0)); // bme280 uses the msb to select read and write // combine the addr with the read/write bit uint8_t readAddr = addr | BME280_SPI_READ; //select the device digitalWrite(csPin, LOW); // transfer the addr SPI.transfer(readAddr); // read the data for(int i = 0; i < len; ++i) { // transfer 0x00 to get the data data[i] = SPI.transfer(0); } // de-select the device digitalWrite(csPin, HIGH); SPI.endTransaction(); return true; } /****************************************************************/ bool BME280Spi::WriteRegister ( uint8_t addr, uint8_t data ) { SPI.beginTransaction(SPISettings(500000,MSBFIRST,SPI_MODE0)); // bme280 uses the msb to select read and write // combine the addr with the read/write bit uint8_t writeAddr = addr & ~0x80; // select the device digitalWrite(csPin, LOW); // transfer the addr and then the data to spi device SPI.transfer(writeAddr); SPI.transfer(data); // de-select the device digitalWrite(csPin, HIGH); SPI.endTransaction(); return true; }
2,977
1,032
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ // MITK #include "mitkUSDeviceReaderWriterConstants.h" #include "mitkUSDeviceWriterXML.h" #include <mitkIGTMimeTypes.h> #include <mitkLocaleSwitch.h> #include <mitkUSDevice.h> // Third Party #include <tinyxml.h> #include <itksys/SystemTools.hxx> #include <fstream> #include <iostream> mitk::USDeviceWriterXML::USDeviceWriterXML() : AbstractFileWriter(USDevice::GetStaticNameOfClass(), mitk::IGTMimeTypes::USDEVICEINFORMATIONXML_MIMETYPE(), "MITK USDevice Writer (XML)"), m_Filename("") { RegisterService(); } mitk::USDeviceWriterXML::USDeviceWriterXML(const mitk::USDeviceWriterXML& other) : AbstractFileWriter(other) { } mitk::USDeviceWriterXML::~USDeviceWriterXML() { } mitk::USDeviceWriterXML* mitk::USDeviceWriterXML::Clone() const { return new USDeviceWriterXML(*this); } void mitk::USDeviceWriterXML::Write() { if (m_Filename == "") { MITK_WARN << "Cannot write to file - empty filename!"; return; } } void mitk::USDeviceWriterXML::SetFilename(std::string filename) { m_Filename = filename; } bool mitk::USDeviceWriterXML::WriteUltrasoundVideoDeviceConfiguration(mitk::USDeviceReaderXML::USVideoDeviceConfigData & config) { TiXmlDocument document; TiXmlDeclaration* xmlDeclaration = new TiXmlDeclaration("1.0", "", ""); document.LinkEndChild(xmlDeclaration); //Create the xml information of the ULTRASOUNDDEVICE-Tag: TiXmlElement *ultrasoundDeviceTag = new TiXmlElement(TAG_ULTRASOUNDDEVICE); this->CreateXmlInformationOfUltrasoundDeviceTag(document, ultrasoundDeviceTag, config); //Create the xml information of the GENERALSETTINGS-Tag: TiXmlElement *generalSettingsTag = new TiXmlElement(TAG_GENERALSETTINGS); this->CreateXmlInformationOfGeneralSettingsTag(ultrasoundDeviceTag, generalSettingsTag, config); //Create the xml information of the PROBES-Tag: this->CreateXmlInformationOfProbesTag(ultrasoundDeviceTag, config); return document.SaveFile(m_Filename); } void mitk::USDeviceWriterXML::CreateXmlInformationOfUltrasoundDeviceTag( TiXmlDocument &document, TiXmlElement * ultrasoundDeviceTag, mitk::USDeviceReaderXML::USVideoDeviceConfigData &config) { ultrasoundDeviceTag->SetAttribute(ATTR_FILEVERS, config.fileversion); ultrasoundDeviceTag->SetAttribute(ATTR_TYPE, config.deviceType); ultrasoundDeviceTag->SetAttribute(ATTR_NAME, config.deviceName); ultrasoundDeviceTag->SetAttribute(ATTR_MANUFACTURER, config.manufacturer); ultrasoundDeviceTag->SetAttribute(ATTR_MODEL, config.model); ultrasoundDeviceTag->SetAttribute(ATTR_COMMENT, config.comment); ultrasoundDeviceTag->SetAttribute(ATTR_IMAGESTREAMS, config.numberOfImageStreams); document.LinkEndChild(ultrasoundDeviceTag); } void mitk::USDeviceWriterXML::CreateXmlInformationOfGeneralSettingsTag(TiXmlElement *parentTag, TiXmlElement *generalSettingsTag, mitk::USDeviceReaderXML::USVideoDeviceConfigData & config) { std::string value = config.useGreyscale ? "true" : "false"; generalSettingsTag->SetAttribute(ATTR_GREYSCALE, value); value = config.useResolutionOverride ? "true" : "false"; generalSettingsTag->SetAttribute(ATTR_RESOLUTIONOVERRIDE, value); generalSettingsTag->SetAttribute(ATTR_RESOLUTIONWIDTH, config.resolutionWidth); generalSettingsTag->SetAttribute(ATTR_RESOLUTIONHEIGHT, config.resolutionHeight); generalSettingsTag->SetAttribute(ATTR_SOURCEID, config.sourceID); generalSettingsTag->SetAttribute(ATTR_FILEPATH, config.filepathVideoSource); generalSettingsTag->SetAttribute(ATTR_OPENCVPORT, config.opencvPort); parentTag->LinkEndChild(generalSettingsTag); } void mitk::USDeviceWriterXML::CreateXmlInformationOfProbesTag(TiXmlElement * parentTag, mitk::USDeviceReaderXML::USVideoDeviceConfigData & config) { if (config.probes.size() != 0) { TiXmlElement *probesTag = new TiXmlElement(TAG_PROBES); parentTag->LinkEndChild(probesTag); for (size_t index = 0; index < config.probes.size(); ++index) { TiXmlElement *probeTag = new TiXmlElement(TAG_PROBE); probesTag->LinkEndChild(probeTag); mitk::USProbe::Pointer probe = config.probes.at(index); probeTag->SetAttribute(ATTR_NAME, probe->GetName()); std::map<int, mitk::Vector3D> depthsAndSpacing = probe->GetDepthsAndSpacing(); if (depthsAndSpacing.size() != 0) { TiXmlElement *depthsTag = new TiXmlElement(TAG_DEPTHS); probeTag->LinkEndChild(depthsTag); for (std::map<int, mitk::Vector3D>::iterator it = depthsAndSpacing.begin(); it != depthsAndSpacing.end(); it++) { TiXmlElement *depthTag = new TiXmlElement(TAG_DEPTH); depthTag->SetAttribute(ATTR_DEPTH, it->first); depthsTag->LinkEndChild(depthTag); TiXmlElement *spacingTag = new TiXmlElement(TAG_SPACING); spacingTag->SetDoubleAttribute(ATTR_X, it->second[0], 6); spacingTag->SetDoubleAttribute(ATTR_Y, it->second[1], 6); depthTag->LinkEndChild(spacingTag); } TiXmlElement *croppingTag = new TiXmlElement(TAG_CROPPING); probeTag->LinkEndChild(croppingTag); croppingTag->SetAttribute(ATTR_TOP, probe->GetProbeCropping().top); croppingTag->SetAttribute(ATTR_BOTTOM, probe->GetProbeCropping().bottom); croppingTag->SetAttribute(ATTR_LEFT, probe->GetProbeCropping().left); croppingTag->SetAttribute(ATTR_RIGHT, probe->GetProbeCropping().right); } } } }
5,885
1,917
/******************************************************************************* * @file oled.cpp * @brief File containing all OLED functions. *******************************************************************************/ #ifndef oled_cpp // Start of precompiler check to avoid dupicate inclusion of this code block. #define oled_cpp // Precompiler macro used for precompiler check. #include <main.h> // Header file for all libraries needed by this program. /** * @brief Hardware Interrupt Service Routine for Button A on OLED display. * ==========================================================================*/ void IRAM_ATTR ButtonA_ISR() { buttonA_flag = true; } // ButtonA_ISR() /** * @brief Hardware Interrupt Service Routine for Button B on OLED display. * ==========================================================================*/ void IRAM_ATTR ButtonB_ISR() { buttonB_flag = true; } // ButtonB_ISR() /** * @brief Hardware Interrupt Service Routine for Button C on OLED display. * ==========================================================================*/ void IRAM_ATTR ButtonC_ISR() { buttonC_flag = true; } // ButtonC_ISR() /** * @brief Places a text message centrered vertically and horizontally. * * @param msg A text message to be displayed. * @param fontSize Multiplier of base text size (6px X 8px). Usually 1-3. * @param fontColour SH110X_WHITE is the usual choice here. * ==========================================================================*/ void placeTextVHcentre(String msg, uint8_t fontSize, uint16_t fontColour) { display.setTextSize(fontSize); display.setTextColor(fontColour); uint8_t x = (oledX - (textBaseX * fontSize * msg.length())) / 2; uint8_t y = (oledY - (textBaseY * fontSize)) / 2; display.setCursor(x, y); display.print(msg); } // placeTextVHcentre /** * @brief Places a text message centrered horizontally. * * @param msg A text message to be displayed. * @param fontSize Multiplier of base text size (6px X 8px). Usually 1-3. * @param fontColour SH110X_WHITE is the usual choice here. * ==========================================================================*/ void placeTextHcentre(String msg, uint8_t fontSize, uint16_t fontColour) { display.setTextSize(fontSize); display.setTextColor(fontColour); uint8_t x = (oledX - (textBaseX * fontSize * msg.length())) / 2; display.setCursor(x, display.getCursorY()); display.println(msg); } // placeTextHcentre() /** * @brief Rotate the display. * @details Does not rotate the current screen content but will affect all * new content sent t the OLED. Note that the the setRotation() function * orients the content displayed on the OLED screen using a 1 byte parameter * which has does the following: * 0 sets the orietation so that the top is where the buttons are. * 1 rotates the top of the display 90 degrees clockwise from position 0. * 2 rotates the top of the display 180 degrees clockwise from position 0. * 3 rotates the top of the display 270 degrees clockwise from position 0. * @param newOrientation which of the 4 valid orientations to use. * ==========================================================================*/ void rotateDisplay(int8_t newOrientation) { switch(newOrientation) { case 0: Log.verboseln("<rotateDisplay> OLED top is now where the buttons are."); oledOrientation = newOrientation; display.setRotation(oledOrientation); // Orient screen content. break; case 1: Log.verboseln("<rotateDisplay> OLED top is now 90 degrees clockwise from where the buttons are."); oledOrientation = newOrientation; display.setRotation(oledOrientation); // Orient screen content. break; case 2: Log.verboseln("<rotateDisplay> OLED top is now 180 degrees clockwise from where the buttons are."); oledOrientation = newOrientation; display.setRotation(oledOrientation); // Orient screen content. break; case 3: Log.verboseln("<rotateDisplay> OLED top is now 270 degrees clockwise from where the buttons are."); oledOrientation = newOrientation; display.setRotation(oledOrientation); // Orient screen content. break; default: Log.errorln("<rotateDisplay> Invalid OLED orientation request of %d. Only values 0-3 are allowed.", newOrientation); break; } // switch } // rotateDisplay() /** * @brief Display the splash screen. * @details Clear the OLED display, set the orientation then display the * splash screen. Note that the the setRotation() function orients the content * displayed on the OLED screen using a 1 byte parameter which has does the * following: * 0 sets the orietation so that the top is where the buttons are. * 1 rotates the top of the display 90 degrees clockwise from position 0. * 2 rotates the top of the display 180 degrees clockwise from position 0. * 3 rotates the top of the display 270 degrees clockwise from position 0. * @param msg Text message to add as tag line to splash screen. * ==========================================================================*/ void displaySplashScreen(String msg) { if(oledConnected == false) { Log.warningln("<displaySplashScreen> OLED missing. Message suppressed."); return; } // if int8_t headingSize = 3; int8_t subMsgSize = 1; display.clearDisplay(); // Clear the buffer. if(msg == "") // No sub heading message { placeTextVHcentre("HEXBOT", headingSize, SH110X_WHITE); } // if else { placeTextVHcentre("HEXBOT", headingSize, SH110X_WHITE); placeTextHcentre(msg, subMsgSize, SH110X_WHITE); } // else delay(10); // Wait for buffer. yield(); // Periodic yield call to avoid watchdog reset. display.display(); // Actually display all of the above } // displaySplashScreen() /** * @brief Display what the legs are doing. * ==========================================================================*/ void displayStatusScreen() { if(oledConnected == false) { Log.warningln("<displayStatusScreen> OLED missing. Message suppressed."); return; } // if display.clearDisplay(); display.setCursor(0, 0); placeTextHcentre("Robot Status", 1, SH110X_WHITE); display.print("\nWifi: "); // Wifi status. if(networkConnected == true) { display.println("OK"); } // if else { display.println("ERR"); } // else // MQTT broker connection status. display.print("MQTT: "); if(mqttBrokerConnected == true) { display.println("OK"); } // if else { display.println("ERR"); } // else // Mobility status (if leg servo controllers are detected on I2C). display.print("Legs: "); if(mobilityStatus == true) { display.println("OK"); } // if else { display.println("ERR"); } // else // Current robot goal. display.print("Goal: "); display.println(legDirExpl[legDirIndex]); delay(10); yield(); display.display(); // actually display all of the above } // displayStatusScreen() /** * @brief Check to see if any of the OLED buttons have been pressed. * ==========================================================================*/ void checkOledButtons() { if(buttonA_flag == true) { buttonA_flag = false; display.clearDisplay(); display.setCursor(0, 0); placeTextHcentre("Configuration", 1, SH110X_WHITE); display.print("\nRobot: "); display.println(WiFi.localIP()); display.print("Broker: "); display.println(getMqttBrokerIP()); delay(10); yield(); display.display(); // actually display all of the above } // if if(buttonB_flag == true) { buttonB_flag = false; displayStatusScreen(); } // if if(buttonC_flag == true) { buttonC_flag = false; displaySplashScreen(""); } // if } // loop() /** * @brief Initiaize OLED display. * ==========================================================================*/ void initOled() { if(oledConnected == false) { Log.warningln("<initOled> OLED missing. Skipping initialization."); return; } // if Log.verboseln("<initOled> 128x64 OLED FeatherWing setup."); display.begin(0x3C, true); // Address 0x3C default Log.verboseln("<initOled> OLED begun."); pinMode(G_BUTTON_A, INPUT_PULLUP); // Make button A pin input with weak pullup. pinMode(G_BUTTON_B, INPUT_PULLUP); // Make button B pin input with weak pullup. pinMode(G_BUTTON_C, INPUT_PULLUP); // Make button C pin input with weak pullup. attachInterrupt(G_BUTTON_A, ButtonA_ISR, RISING); // Assign ISR for button A. attachInterrupt(G_BUTTON_B, ButtonB_ISR, RISING); // Assign ISR for button B. attachInterrupt(G_BUTTON_C, ButtonC_ISR, RISING); // Assign ISR for button C. rotateDisplay(oledOrientation); // Orient OLED text. displaySplashScreen(""); } // setup() #endif // End of precompiler protected code block
9,122
2,737
#include<stdio.h> #include <vector> using namespace std; #include <algorithm> // std::random_shuffle #include <iostream> #include <random> void swap(int* a, int* b) { // return a int temp = *a; *a = *b; *b = temp; } int partition(std::vector<int> a, int low, int high) { int i = low + 1, j = high; bool iStop = false, jStop = false; while(true) { if (iStop == false && a[low] > a[i]) i++; else iStop = true; if (jStop == false && a[j] > a[low]) j--; else jStop = true; if (iStop && jStop) { cout << "\ni: " << i << "\n"; cout << "\nj: " << j << "\n"; cout << "Time to Change\n"; swap(&a[i], &a[j]); for(int i=0; i<a.size(); ++i) cout << a[i] << ' '; break; } } return 10; } void sort(std::vector<int> arrayToBeSorted, int low, int high) { if (high <= low) return; int j = partition(arrayToBeSorted, low, high); cout << "\npartitionJ: " << j << "\n"; } void sort(std::vector<int> arrayToBeSorted) { std::random_device randomDevice; std::mt19937 generator(randomDevice()); shuffle(arrayToBeSorted.begin(), arrayToBeSorted.end(), generator); for(int i=0; i<arrayToBeSorted.size(); ++i) cout << arrayToBeSorted[i] << ' '; sort(arrayToBeSorted, 0, arrayToBeSorted.size() - 1); } int main() { printf("Test\n"); size_t size = 10; std::vector<int> array(size); for(int i=0; i<size; ++i) { array[i] = i; } sort(array); int a = 10; int b = 5; swap(&a, &b); }
1,623
623
#include "timemory/mpl/math.hpp" #include "timemory/mpl/stl.hpp" #include <timemory/components.hpp> #include <timemory/components/base.hpp> #include <timemory/mpl/types.hpp> // for overload resolution, e.g. foo.store(normalize_tag{}, size_t) struct normalization {}; namespace tim { namespace component { template <typename T> struct normalized; } } // namespace tim namespace tim { namespace trait { // set the derivation types template <typename T> struct derivation_types<component::normalized<T>> { using type = type_list<type_list<T>>; }; // template <typename T> struct statistics<component::normalized<T>> { using type = typename statistics<T>::type; }; // template <typename T> struct is_available<component::normalized<T>> { using type = typename is_available<T>::type; static constexpr auto value = is_available<T>::value; }; // template <typename T> struct base_has_accum<component::normalized<T>> : false_type {}; // template <typename T> struct echo_enabled<component::normalized<T>> : false_type {}; } // namespace trait } // namespace tim namespace tim { namespace component { template <typename T> struct normalized : public base<normalized<T>, T> { using value_type = T; using base_type = base<normalized<T>, value_type>; using base_type::get_value; static std::string label(); static std::string description(); static auto unit(); static auto display_unit(); static const std::ios::fmtflags format_flags = std::ios_base::scientific | std::ios_base::dec | std::ios_base::showpoint; void store(normalization&&, size_t _sz); auto get() const; auto get_display() const; bool derive(T* comp); private: size_t data_size = 1; }; template <typename T> std::string normalized<T>::label() { return TIMEMORY_JOIN("_", "normalized", T::label()); } template <typename T> std::string normalized<T>::description() { return TIMEMORY_JOIN(" ", T::description(), "normalized to data size"); } template <typename T> auto normalized<T>::unit() { return T::unit(); } template <typename T> auto normalized<T>::display_unit() { return T::display_unit(); } template <typename T> void normalized<T>::store(normalization&&, size_t _sz) { data_size = _sz; } template <typename T> auto normalized<T>::get() const { // below might not be valid for more complex components return get_value().get() / data_size; // this will be valid for more complex components // auto _v = get_value().get(); // using compute_type = math::compute<decay_t<decltype(_v)>>; // compute_type::divide(_v, data_size); // return _v; } template <typename T> auto normalized<T>::get_display() const { auto _v = get_value(); // below might not be valid for more complex components _v /= data_size; // this will be valid for more complex components // using compute_type = math::compute<T>; // compute_type::divide(_v, data_size); return _v.get_display(); } template <typename T> bool normalized<T>::derive(T* comp) { if(comp) base_type::value = *comp; return (comp != nullptr); } } // namespace component } // namespace tim
3,222
1,055
/********************************************************************** Audacity: A Digital Audio Editor @file PlugFrame.cpp @author Vitaly Sverchinsky @brief Part of Audacity VST3 module **********************************************************************/ #include "PlugFrame.h" using namespace internal::x11; IMPLEMENT_REFCOUNT(PlugFrame) Steinberg::tresult PlugFrame::queryInterface (const ::Steinberg::TUID _iid, void** obj) { QUERY_INTERFACE (_iid, obj, Steinberg::FUnknown::iid, Steinberg::IPlugFrame); QUERY_INTERFACE (_iid, obj, Steinberg::IPlugFrame::iid, Steinberg::IPlugFrame); //As VST3 documentation states, IPlugFrame also has to provide //reference to the Steinberg::Linux::IRunLoop implementation. if (mRunLoop && Steinberg::FUnknownPrivate::iidEqual (_iid, Steinberg::Linux::IRunLoop::iid)) { mRunLoop->addRef(); *obj = static_cast<Steinberg::Linux::IRunLoop*>(mRunLoop.get()); return ::Steinberg::kResultOk; } *obj = nullptr; return ::Steinberg::kNoInterface; } PlugFrame::PlugFrame(Steinberg::Linux::IRunLoop* runLoop, wxWindow* window) : mWindow(window), mRunLoop(runLoop) { FUNKNOWN_CTOR; } PlugFrame::~PlugFrame() { FUNKNOWN_DTOR; } Steinberg::tresult PlugFrame::resizeView(Steinberg::IPlugView* view, Steinberg::ViewRect* newSize) { const auto fixedSize = view->canResize() == Steinberg::kResultFalse; if(UpdateSize({newSize->getWidth(), newSize->getHeight()}, fixedSize)) return Steinberg::kResultTrue; return Steinberg::kResultFalse; } bool PlugFrame::UpdateSize(const wxSize& newSize, bool fixed) { if(auto window = mWindow.get()) { //Wrapper (x11::SocketWindow) geometry needs to be updated too auto wrapper = window->GetChildren()[0]; if(fixed) { //Update min/max if plugin window has fixed size //but for some reason resize was requested window->SetMinSize(newSize); window->SetMaxSize(newSize); wrapper->SetMinSize(newSize); wrapper->SetMaxSize(newSize); } window->SetSize(newSize); wrapper->SetSize(newSize); return true; } return false; }
2,181
710
#include "menu.h" #include "Course.h" #include "Courses.h" /// <summary> /// Print menu options to stdout /// </summary> /// <param name=""></param> void printMenu(void) { cout << "Menu:" << endl; cout << " 1. Load Data Structure." << endl; cout << " 2. Print Course List." << endl; cout << " 3. Print Course." << endl; cout << " 9. Exit" << endl << endl; cout << "What would you like to do? "; } /// <summary> /// Call various functions based on the user's choice. /// </summary> /// <param name="choice"></param> /// <param name="courses"></param> void handleChoice(int choice, Courses& courses) { switch (choice) { case 1: // load file { string filename; auto state = cin.exceptions(); // setup exception handling for stdin cin.exceptions(std::istream::failbit | state); cout << "Please enter the name of the data file to load." << endl; cin.ignore(); // if already loaded discard previous and start another if (courses.getSize() > 0) { courses.clear(); } try { getline(cin, filename); // get user input of filename courses.loadFromCSV(filename); } catch (exception ex) { cout << ex.what() << endl; // display what happened to console } cin.exceptions(state); // restore previous exception settings } break; case 2: // print all courses with id and title in alphanumeric order cout << "Here is a sample schedule:" << endl << endl; courses.printAll(); break; case 3: // print one course and its prerequisites { string courseId; cout << "What course do you want to know about? "; cin >> courseId; courses.printCourse(courseId); } break; case 9: // exit program cout << "Thank you for using the course planner!" << endl; break; default: // invalid choice cout << choice << "is not a valid option." << endl << endl; break; } } void commandLoop(void) { int choice = 0; Courses courses; // declaring here allocates the memory for the lifetime of the loop cout << "Welcome to the course planner." << endl; while (choice != 9) { // while not exit command cout << endl; printMenu(); cin >> choice; // wait for user input handleChoice(choice, courses); } }
2,515
703
#include "PanelAbout.h" #include "Application.h" #include "ModuleGui.h" #include "Imgui/imgui.h" #include "mmgr/mmgr.h" PanelAbout::PanelAbout(char * name) : Panel(name) { } PanelAbout::~PanelAbout() { } bool PanelAbout::Draw() { ImGuiWindowFlags settingsFlags = 0; settingsFlags = ImGuiWindowFlags_NoFocusOnAppearing; if (ImGui::Begin(name, &enabled, settingsFlags)) { // --- Introduction --- ImGui::Separator(); ImGui::Text("SAD 3D"); ImGui::SameLine(); ImGui::Text("Version 2.0"); ImGui::SameLine(); if (ImGui::Button("GitHub")) { App->gui->RequestBrowser("https://github.com/t3m1X/SAD-3D"); } ImGui::Text("A fork of Central 3D"); ImGui::Text("By: "); ImGui::SameLine(); if (ImGui::Button("Sergi Parra")) { App->gui->RequestBrowser("https://github.com/t3m1X"); } ImGui::Text("Central 3D by:"); ImGui::SameLine(); if (ImGui::Button("Aitor Simona")) { App->gui->RequestBrowser("https://github.com/AitorSimona"); } ImGui::Spacing(); ImGui::Separator(); ImGui::Spacing(); // --- License --- ImGui::TextWrapped("MIT License"); ImGui::TextWrapped("Copyright(c) 2019 Aitor Simona Bouzas"); ImGui::TextWrapped("Copyright (c) 2021 Sergi Parra Ramirez"); ImGui::TextWrapped("Copyright for portions of SAD 3D are held by Aitor Simona Bouzas, 2019 as part of project CENTRAL 3D (Version 2.0)."); ImGui::TextWrapped("All other copyright for project SAD 3D are held by Sergi Parra Ramirez, 2021."); ImGui::TextWrapped(""); ImGui::TextWrapped("Permission is hereby granted, free of charge, to any person obtaining a copyof 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 : "); ImGui::TextWrapped("The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software."); ImGui::TextWrapped("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."); } ImGui::End(); return true; }
2,607
961
#include <PCH.h> #include <EditorFramework/EngineProcess/EngineProcessDocumentContext.h> #include <EditorFramework/EngineProcess/EngineProcessMessages.h> #include <EditorFramework/IPC/SyncObject.h> #include <EditorFramework/EngineProcess/EngineProcessMessages.h> #include <EditorFramework/EngineProcess/EngineProcessViewContext.h> #include <Foundation/Reflection/ReflectionUtils.h> #include <Foundation/Serialization/ReflectionSerializer.h> #include <Foundation/Logging/Log.h> #include <Gizmos/GizmoHandle.h> #include <RendererCore/RenderContext/RenderContext.h> EZ_BEGIN_DYNAMIC_REFLECTED_TYPE(ezEngineProcessDocumentContext, ezReflectedClass, 1, ezRTTINoAllocator); EZ_END_DYNAMIC_REFLECTED_TYPE(); ezHashTable<ezUuid, ezEngineProcessDocumentContext*> ezEngineProcessDocumentContext::s_DocumentContexts; ezEngineProcessDocumentContext* ezEngineProcessDocumentContext::GetDocumentContext(ezUuid guid) { ezEngineProcessDocumentContext* pResult = nullptr; s_DocumentContexts.TryGetValue(guid, pResult); return pResult; } void ezEngineProcessDocumentContext::AddDocumentContext(ezUuid guid, ezEngineProcessDocumentContext* pContext, ezProcessCommunication* pIPC) { EZ_ASSERT_DEV(!s_DocumentContexts.Contains(guid), "Cannot add a view with an index that already exists"); s_DocumentContexts[guid] = pContext; pContext->Initialize(guid, pIPC); } void ezEngineProcessDocumentContext::DestroyDocumentContext(ezUuid guid) { ezEngineProcessDocumentContext* pContext = nullptr; if (s_DocumentContexts.Remove(guid, &pContext)) { pContext->Deinitialize(); pContext->GetDynamicRTTI()->GetAllocator()->Deallocate(pContext); } } ezEngineProcessDocumentContext::ezEngineProcessDocumentContext() { m_pWorld = nullptr; m_uiNextComponentPickingID = 1; } ezEngineProcessDocumentContext::~ezEngineProcessDocumentContext() { EZ_ASSERT_DEV(m_pWorld == nullptr, "World has not been deleted! Call 'ezEngineProcessDocumentContext::DestroyDocumentContext'"); } void ezEngineProcessDocumentContext::Deinitialize() { ClearViewContexts(); OnDeinitialize(); CleanUpContextSyncObjects(); EZ_DEFAULT_DELETE(m_pWorld); } void ezEngineProcessDocumentContext::SendProcessMessage(ezProcessMessage* pMsg, bool bSuperHighPriority /*= false*/) { m_pIPC->SendMessage(pMsg, bSuperHighPriority); } void ezEngineProcessDocumentContext::HandleMessage(const ezEditorEngineDocumentMsg* pMsg) { EZ_LOCK(m_pWorld->GetWriteMarker()); if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezEntityMsgToEngine>()) { const ezEntityMsgToEngine* pMsg2 = static_cast<const ezEntityMsgToEngine*>(pMsg); HandlerEntityMsg(pMsg2); } else if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezEditorEngineSyncObjectMsg>()) { const ezEditorEngineSyncObjectMsg* pMsg2 = static_cast<const ezEditorEngineSyncObjectMsg*>(pMsg); ProcessEditorEngineSyncObjectMsg(*pMsg2); } else if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezObjectTagMsgToEngine>()) { const ezObjectTagMsgToEngine* pMsg2 = static_cast<const ezObjectTagMsgToEngine*>(pMsg); ezGameObjectHandle hObject = m_GameObjectMap.GetHandle(pMsg2->m_ObjectGuid); ezTag tag; ezTagRegistry::GetGlobalRegistry().RegisterTag(pMsg2->m_sTag, &tag); ezGameObject* pObject; if (m_pWorld->TryGetObject(hObject, pObject)) { if (pMsg2->m_bSetTag) pObject->GetTags().Set(tag); else pObject->GetTags().Clear(tag); } } if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezEditorEngineViewMsg>()) { if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezViewRedrawMsgToEngine>()) { UpdateSyncObjects(); } const ezEditorEngineViewMsg* pViewMsg = static_cast<const ezEditorEngineViewMsg*>(pMsg); EZ_ASSERT_DEV(pViewMsg->m_uiViewID < 0xFFFFFFFF, "Invalid view ID in '%s'", pMsg->GetDynamicRTTI()->GetTypeName()); if (pViewMsg->m_uiViewID >= m_ViewContexts.GetCount()) m_ViewContexts.SetCount(pViewMsg->m_uiViewID + 1); if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezViewDestroyedMsgToEngine>()) { if (m_ViewContexts[pViewMsg->m_uiViewID] != nullptr) { DestroyViewContext(m_ViewContexts[pViewMsg->m_uiViewID]); m_ViewContexts[pViewMsg->m_uiViewID] = nullptr; ezLog::Info("Destroyed View %i", pViewMsg->m_uiViewID); } } else { if (m_ViewContexts[pViewMsg->m_uiViewID] == nullptr) m_ViewContexts[pViewMsg->m_uiViewID] = CreateViewContext(); m_ViewContexts[pViewMsg->m_uiViewID]->HandleViewMessage(pViewMsg); } return; } else if (pMsg->GetDynamicRTTI()->IsDerivedFrom<ezViewHighlightMsgToEngine>()) { const ezViewHighlightMsgToEngine* pMsg2 = static_cast<const ezViewHighlightMsgToEngine*>(pMsg); ezUInt32 uiPickingID = m_OtherPickingMap.GetHandle(pMsg2->m_HighlightObject); ezRenderContext::GetDefaultInstance()->SetMaterialParameter("PickingHighlightID", (ezInt32)uiPickingID); } } void ezEngineProcessDocumentContext::Initialize(const ezUuid& DocumentGuid, ezProcessCommunication* pIPC) { m_DocumentGuid = DocumentGuid; m_pIPC = pIPC; m_pWorld = EZ_DEFAULT_NEW(ezWorld, ezConversionUtils::ToString(m_DocumentGuid)); OnInitialize(); } void ezEngineProcessDocumentContext::AddSyncObject(ezEditorEngineSyncObject* pSync) { m_SyncObjects[pSync->GetGuid()] = pSync; } void ezEngineProcessDocumentContext::RemoveSyncObject(ezEditorEngineSyncObject* pSync) { m_SyncObjects.Remove(pSync->GetGuid()); } ezEditorEngineSyncObject* ezEngineProcessDocumentContext::FindSyncObject(const ezUuid& guid) { auto it = m_SyncObjects.Find(guid); if (it.IsValid()) return it.Value(); return nullptr; } void ezEngineProcessDocumentContext::ClearViewContexts() { for (auto* pContext : m_ViewContexts) { DestroyViewContext(pContext); } m_ViewContexts.Clear(); } void ezEngineProcessDocumentContext::CleanUpContextSyncObjects() { while (!m_SyncObjects.IsEmpty()) { auto it = m_SyncObjects.GetIterator(); it.Value()->GetDynamicRTTI()->GetAllocator()->Deallocate(it.Value()); } } void ezEngineProcessDocumentContext::ProcessEditorEngineSyncObjectMsg(const ezEditorEngineSyncObjectMsg& msg) { auto it = m_SyncObjects.Find(msg.m_ObjectGuid); if (msg.m_sObjectType.IsEmpty()) { // object has been deleted! if (it.IsValid()) { it.Value()->GetDynamicRTTI()->GetAllocator()->Deallocate(it.Value()); } return; } const ezRTTI* pRtti = ezRTTI::FindTypeByName(msg.m_sObjectType); ezEditorEngineSyncObject* pSyncObject = nullptr; bool bSetOwner = false; if (pRtti == nullptr) { ezLog::Error("Cannot sync object of type unknown '%s' to engine process", msg.m_sObjectType.GetData()); return; } if (!it.IsValid()) { // object does not yet exist EZ_ASSERT_DEV(pRtti->GetAllocator() != nullptr, "Sync object of type '%s' does not have a default allocator", msg.m_sObjectType.GetData()); void* pObject = pRtti->GetAllocator()->Allocate(); pSyncObject = static_cast<ezEditorEngineSyncObject*>(pObject); bSetOwner = true; } else { pSyncObject = it.Value(); } ezMemoryStreamStorage storage; ezMemoryStreamWriter writer(&storage); ezMemoryStreamReader reader(&storage); writer.WriteBytes(msg.m_sObjectData.GetData(), msg.m_sObjectData.GetElementCount()); ezReflectionSerializer::ReadObjectPropertiesFromJSON(reader, *pRtti, pSyncObject); if (bSetOwner) pSyncObject->SetOwner(this); pSyncObject->SetModified(true); } void ezEngineProcessDocumentContext::HandlerGameObjectMsg(const ezEntityMsgToEngine* pMsg, ezRTTI* pRtti) { switch (pMsg->m_iMsgType) { case ezEntityMsgToEngine::ObjectAdded: { ezGameObjectDesc d; d.m_sName.Assign(ezConversionUtils::ToString(pMsg->m_ObjectGuid).GetData()); if (pMsg->m_NewParentGuid.IsValid()) d.m_hParent = m_GameObjectMap.GetHandle(pMsg->m_NewParentGuid); ezGameObjectHandle hObject = m_pWorld->CreateObject(d); m_GameObjectMap.RegisterObject(pMsg->m_ObjectGuid, hObject); ezGameObject* pObject; if (m_pWorld->TryGetObject(hObject, pObject)) { UpdateProperties(pMsg, pObject, ezGetStaticRTTI<ezGameObject>()); } } break; case ezEntityMsgToEngine::ObjectMoved: { ezRTTI* pRtti = ezRTTI::FindTypeByName(pMsg->m_sObjectType); if (pRtti == nullptr) { ezLog::Error("Cannot create object of type '%s', RTTI is unknown", pMsg->m_sObjectType.GetData()); break; } ezGameObjectHandle hObject = m_GameObjectMap.GetHandle(pMsg->m_ObjectGuid); ezGameObjectHandle hNewParent; if (pMsg->m_NewParentGuid.IsValid()) hNewParent = m_GameObjectMap.GetHandle(pMsg->m_NewParentGuid); ezGameObject* pObject = nullptr; if (m_pWorld->TryGetObject(hObject, pObject)) { pObject->SetParent(hNewParent); } else ezLog::Error("Couldn't access game object object %s in world %p", ezConversionUtils::ToString(pMsg->m_ObjectGuid).GetData(), m_pWorld); } break; case ezEntityMsgToEngine::ObjectRemoved: { m_pWorld->DeleteObject(m_GameObjectMap.GetHandle(pMsg->m_ObjectGuid)); m_GameObjectMap.UnregisterObject(pMsg->m_ObjectGuid); } break; case ezEntityMsgToEngine::PropertyChanged: { ezGameObjectHandle hObject = m_GameObjectMap.GetHandle(pMsg->m_ObjectGuid); ezGameObject* pObject; if (m_pWorld->TryGetObject(hObject, pObject)) { UpdateProperties(pMsg, pObject, ezGetStaticRTTI<ezGameObject>()); //pObject->UpdateGlobalTransform(); } } break; } } void ezEngineProcessDocumentContext::HandleComponentMsg(const ezEntityMsgToEngine* pMsg, ezRTTI* pRtti) { ezComponentManagerBase* pMan = m_pWorld->GetComponentManager(pRtti); if (pMan == nullptr) { ezLog::Error("Component of type '%s' cannot be created, no component manager is registered", pRtti->GetTypeName()); return; } switch (pMsg->m_iMsgType) { case ezEntityMsgToEngine::ObjectAdded: { ezComponentHandle hComponent = pMan->CreateComponent(); ezGameObjectHandle hParent = m_GameObjectMap.GetHandle(pMsg->m_NewParentGuid); ezGameObject* pParent; if (!m_pWorld->TryGetObject(hParent, pParent)) break; ezComponent* pComponent; if (pMan->TryGetComponent(hComponent, pComponent)) { m_ComponentMap.RegisterObject(pMsg->m_ObjectGuid, hComponent); UpdateProperties(pMsg, pComponent, pComponent->GetDynamicRTTI()); pComponent->m_uiEditorPickingID = m_uiNextComponentPickingID++; m_ComponentPickingMap.RegisterObject(pMsg->m_ObjectGuid, pComponent->m_uiEditorPickingID); } else { ezLog::Error("Component of type '%s' cannot be found after creation", pRtti->GetTypeName()); } pParent->AddComponent(hComponent); } break; case ezEntityMsgToEngine::ObjectMoved: { ezGameObjectHandle hParent = m_GameObjectMap.GetHandle(pMsg->m_NewParentGuid); ezGameObject* pParent; if (!m_pWorld->TryGetObject(hParent, pParent)) break; ezComponentHandle hComponent = m_ComponentMap.GetHandle(pMsg->m_ObjectGuid); ezComponent* pComponent; if (pMan->TryGetComponent(hComponent, pComponent)) { if (pComponent->GetOwner()) pComponent->GetOwner()->RemoveComponent(pComponent); } pParent->AddComponent(hComponent); } break; case ezEntityMsgToEngine::ObjectRemoved: { ezComponentHandle hComponent = m_ComponentMap.GetHandle(pMsg->m_ObjectGuid); m_ComponentMap.UnregisterObject(pMsg->m_ObjectGuid); m_ComponentPickingMap.UnregisterObject(pMsg->m_ObjectGuid); pMan->DeleteComponent(hComponent); } break; case ezEntityMsgToEngine::PropertyChanged: { ezComponentHandle hComponent = m_ComponentMap.GetHandle(pMsg->m_ObjectGuid); ezComponent* pComponent; if (pMan->TryGetComponent(hComponent, pComponent)) { UpdateProperties(pMsg, pComponent, pComponent->GetDynamicRTTI()); } else { ezLog::Error("Component of type '%s' cannot be found", pRtti->GetTypeName()); } } break; } } void ezEngineProcessDocumentContext::HandlerEntityMsg(const ezEntityMsgToEngine* pMsg) { ezRTTI* pRtti = ezRTTI::FindTypeByName(pMsg->m_sObjectType); if (pRtti == nullptr) { ezLog::Error("Cannot create object of type '%s', RTTI is unknown", pMsg->m_sObjectType.GetData()); return; } if (pRtti == ezGetStaticRTTI<ezGameObject>()) { HandlerGameObjectMsg(pMsg, pRtti); } if (pRtti->IsDerivedFrom<ezComponent>()) { HandleComponentMsg(pMsg, pRtti); } } void ezEngineProcessDocumentContext::UpdateSyncObjects() { for (auto* pSyncObject : m_SyncObjects) { if (pSyncObject->GetModified() && pSyncObject->GetDynamicRTTI()->IsDerivedFrom<ezGizmoHandle>()) { // reset the modified state to make sure the object isn't updated unless a new sync messages comes in pSyncObject->SetModified(false); ezGizmoHandle* pGizmoHandle = static_cast<ezGizmoHandle*>(pSyncObject); EZ_LOCK(m_pWorld->GetWriteMarker()); if (pGizmoHandle->SetupForEngine(m_pWorld, m_uiNextComponentPickingID)) { m_OtherPickingMap.RegisterObject(pGizmoHandle->GetGuid(), m_uiNextComponentPickingID); ++m_uiNextComponentPickingID; } pGizmoHandle->UpdateForEngine(m_pWorld); } } } void ezEngineProcessDocumentContext::UpdateProperties(const ezEntityMsgToEngine* pMsg, void* pObject, const ezRTTI* pRtti) { ezMemoryStreamStorage storage; ezMemoryStreamWriter writer(&storage); ezMemoryStreamReader reader(&storage); writer.WriteBytes(pMsg->m_sObjectData.GetData(), pMsg->m_sObjectData.GetElementCount()); ezReflectionSerializer::ReadObjectPropertiesFromJSON(reader, *pRtti, pObject); }
13,944
4,718
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "tmp112.h" #include <lib/fake_ddk/fake_ddk.h> #include <lib/mock-i2c/mock-i2c.h> #include <zxtest/zxtest.h> namespace { bool FloatNear(float a, float b) { return std::abs(a - b) < 0.001f; } } // namespace namespace temperature { using TemperatureClient = fidl::WireSyncClient<fuchsia_hardware_temperature::Device>; class Tmp112DeviceTest : public zxtest::Test { public: Tmp112DeviceTest() {} void SetUp() override { dev_ = std::make_unique<Tmp112Device>(fake_ddk::kFakeParent, ddk::I2cChannel(mock_i2c_.GetProto())); const auto message_op = [](void* ctx, fidl_incoming_msg_t* msg, fidl_txn_t* txn) -> zx_status_t { return static_cast<Tmp112Device*>(ctx)->DdkMessage(msg, txn); }; ASSERT_OK(messenger_.SetMessageOp(dev_.get(), message_op)); } protected: mock_i2c::MockI2c mock_i2c_; std::unique_ptr<Tmp112Device> dev_; fake_ddk::FidlMessenger messenger_; }; TEST_F(Tmp112DeviceTest, Init) { uint8_t initial_config_val[2] = {kConfigConvertResolutionSet12Bit, 0}; mock_i2c_.ExpectWrite({kConfigReg}).ExpectReadStop({0x0, 0x0}); mock_i2c_.ExpectWriteStop({kConfigReg, initial_config_val[0], initial_config_val[1]}); dev_->Init(); mock_i2c_.VerifyAndClear(); } TEST_F(Tmp112DeviceTest, GetTemperatureCelsius) { mock_i2c_.ExpectWrite({kTemperatureReg}).ExpectReadStop({0x34, 0x12}); TemperatureClient client(std::move(messenger_.local())); auto result = client.GetTemperatureCelsius(); EXPECT_OK(result->status); EXPECT_TRUE(FloatNear(result->temp, dev_->RegToTemperatureCelsius(0x1234))); mock_i2c_.VerifyAndClear(); } TEST_F(Tmp112DeviceTest, RegToTemperature) { EXPECT_TRUE(FloatNear(dev_->RegToTemperatureCelsius(0x1234), 52.0625)); } } // namespace temperature
1,987
811
// NOLINT(namespace-quic) // // This file is part of the QUICHE platform implementation, and is not to be // consumed or referenced directly by other Envoy code. It serves purely as a // porting layer for QUICHE. #include "platform/epoll_platform_impl/quic_epoll_clock.h" namespace quic { QuicEpollClock::QuicEpollClock(epoll_server::SimpleEpollServer* epoll_server) : epoll_server_(epoll_server), largest_time_(QuicTime::Zero()) {} QuicTime QuicEpollClock::ApproximateNow() const { return CreateTimeFromMicroseconds(epoll_server_->ApproximateNowInUsec()); } QuicTime QuicEpollClock::Now() const { QuicTime now = CreateTimeFromMicroseconds(epoll_server_->NowInUsec()); if (now <= largest_time_) { // Time not increasing, return |largest_time_|. return largest_time_; } largest_time_ = now; return largest_time_; } QuicWallTime QuicEpollClock::WallNow() const { return QuicWallTime::FromUNIXMicroseconds(epoll_server_->ApproximateNowInUsec()); } QuicTime QuicEpollClock::ConvertWallTimeToQuicTime(const QuicWallTime& walltime) const { return QuicTime::Zero() + QuicTime::Delta::FromMicroseconds(walltime.ToUNIXMicroseconds()); } } // namespace quic
1,186
426
/* * Copywrite 2014-2015 Krzysztof Stasik. All rights reserved. */ #include "monitor_plugin.h" #include "base/io/base_file.h" #include "common/json/json_writer.h" #include "link/plugin_log.h" #include "base/core/time_utils.h" #include "base/core/assert.h" #include <unistd.h> namespace Link { static const streamsize kProcBufferSize = 1024; struct CPUSample { u32 timestamp; // sample time. u32 user; // normal processes executing in user mode. u32 nice; // niced processes executing in user mode. u32 system; // processes executing in krenel mode. u32 idle; // twiddling thumbs. u32 iowait; // waiting for I/O to complete. u32 irq; // servicing interrupts. u32 softirq; // servicing softirqs. void InitMax() { timestamp = (u32)-1; user = (u32)-1; nice = (u32)-1; system = (u32)-1; idle = (u32)-1; iowait = (u32)-1; irq = (u32)-1; softirq = (u32)-1; } void GetMax(const CPUSample &a) { if(a.timestamp > timestamp) timestamp = a.timestamp; if(a.user > user) user = a.user; if(a.nice > nice) nice = a.nice; if(a.system > system) system = a.system; if(a.idle > idle) idle = a.idle; if(a.iowait > iowait) iowait = a.iowait; if(a.irq > irq) irq = a.irq; if(a.softirq > softirq) softirq = a.softirq; } void GetMin(const CPUSample &a) { if(a.timestamp < timestamp) timestamp = a.timestamp; if(a.user < user) user = a.user; if(a.nice < nice) nice = a.nice; if(a.system < system) system = a.system; if(a.idle < idle) idle = a.idle; if(a.iowait < iowait) iowait = a.iowait; if(a.irq < irq) irq = a.irq; if(a.softirq < softirq) softirq = a.softirq; } CPUSample &operator+=(const CPUSample &rhs) { timestamp += rhs.timestamp; user += rhs.user; nice += rhs.nice; system += rhs.system; idle += rhs.idle; iowait += rhs.iowait; irq += rhs.irq; softirq += rhs.softirq; return *this; } }; struct ProcessSample { u32 timestamp; u32 user; u32 system; }; float ToPercent(u32 stat, u32 time, u32 hz) { float dt_sec = static_cast<float>(time) * 0.001f; float denom = dt_sec * static_cast<float>(hz); if(denom == 0.f) { return 0.f; } return static_cast<float>(stat) / denom; } struct ProcessPercent { float user; float system; void Calculate(const ProcessSample &delta, u32 hz) { user = ToPercent(delta.user, delta.timestamp, hz); system = ToPercent(delta.system, delta.timestamp, hz); } }; template <> inline void JsonWriter::AppendValue(const ProcessPercent &info) { JsonWriter writer(m_destination); writer.Write("user", info.user); writer.Write("system", info.system); writer.Finalize(); } struct ProcessHistory { u32 num_samples; u32 current_sample; ProcessSample *data; ProcessHistory() : num_samples(0), current_sample(0), data(nullptr) {} ~ProcessHistory() { delete[] data; } void Resize(u32 _num_samples) { BASE_ASSERT(_num_samples > 0); num_samples = _num_samples; current_sample = 0; delete[] data; data = new ProcessSample[num_samples]; } ProcessSample *GetNextSample() { BASE_ASSERT(current_sample < num_samples, "sample out of range"); ProcessSample *res = &data[current_sample]; current_sample = (++current_sample) % num_samples; return res; } void LastSampleStats(u32 tick_per_sec, ProcessPercent *out) { ProcessSample diff; Diff(data[(current_sample - 1) % num_samples], data[(current_sample - 2) % num_samples], &diff); out->Calculate(diff, tick_per_sec); } void Diff(const ProcessSample &a, const ProcessSample &b, ProcessSample *res) { res->user = a.user - b.user; res->system = a.system - b.system; } }; struct CPUPercent { float user; float nice; float system; float idle; float iowait; float irq; float softirq; void InitMax() { user = 1.f; nice = 1.f; system = 1.f; idle = 1.f; iowait = 1.f; irq = 1.f; softirq = 1.f; } void GetMin(const CPUPercent &d) { if(d.user < user) user = d.user; if(d.nice < nice) nice = d.nice; if(d.system < system) system = d.system; if(d.idle < idle) idle = d.idle; if(d.iowait < iowait) iowait = d.iowait; if(d.irq < irq) irq = d.irq; if(d.softirq < softirq) softirq = d.softirq; } void GetMax(const CPUPercent &d) { if(d.user > user) user = d.user; if(d.nice > nice) nice = d.nice; if(d.system > system) system = d.system; if(d.idle > idle) idle = d.idle; if(d.iowait > iowait) iowait = d.iowait; if(d.irq > irq) irq = d.irq; if(d.softirq > softirq) softirq = d.softirq; } void Calculate(const CPUSample &delta, u32 hz) { user = ToPercent(delta.user, delta.timestamp, hz); nice = ToPercent(delta.nice, delta.timestamp, hz); system = ToPercent(delta.system, delta.timestamp, hz); idle = ToPercent(delta.idle, delta.timestamp, hz); iowait = ToPercent(delta.iowait, delta.timestamp, hz); irq = ToPercent(delta.irq, delta.timestamp, hz); softirq = ToPercent(delta.softirq, delta.timestamp, hz); } }; template <> inline void JsonWriter::AppendValue(const CPUPercent &info) { JsonWriter writer(m_destination); writer.Write("user", info.user); writer.Write("nice", info.nice); writer.Write("system", info.system); writer.Write("idle", info.idle); writer.Write("iowait", info.iowait); writer.Write("irq", info.irq); writer.Write("softirq", info.softirq); writer.Finalize(); } struct CPUHistory { u32 num_samples; u32 current_sample; struct CPUSample *data; struct CPUPercent min, max, avg; CPUHistory() : num_samples(0), current_sample(0), data(0) {} ~CPUHistory() { delete[] data; } void Resize(u32 _num_samples) { BASE_ASSERT(_num_samples > 0); num_samples = _num_samples; current_sample = 0; delete[] data; data = new CPUSample[num_samples]; } CPUSample *GetNextSample() { BASE_ASSERT(current_sample < num_samples, "sample out of range"); CPUSample *res = &data[current_sample]; current_sample = (++current_sample) % num_samples; return res; } void LastSampleStats(u32 tick_per_sec, CPUPercent *out) { CPUSample diff; Diff(data[(current_sample - 1) % num_samples], data[(current_sample - 2) % num_samples], &diff); out->Calculate(diff, tick_per_sec); } void Calculate(u32 tick_per_sec) { CPUSample sum = {}, diff; min.InitMax(); for(u32 i = 0; i < num_samples; ++i) { Diff(data[(i - 1) % num_samples], data[(i - 2) % num_samples], &diff); sum += diff; CPUPercent tmp; tmp.Calculate(diff, tick_per_sec); min.GetMin(tmp); max.GetMax(tmp); } avg.Calculate(sum, tick_per_sec); } void Diff(const CPUSample &a, const CPUSample &b, CPUSample *res) { res->timestamp = a.timestamp - b.timestamp; res->user = a.user - b.user; res->nice = a.nice - b.nice; res->system = a.system - b.system; res->idle = a.idle - b.idle; res->iowait = a.iowait - b.iowait; res->irq = a.irq - b.irq; res->softirq = a.softirq - b.softirq; } }; template <> inline void JsonWriter::AppendValue(const CPUSample &info) { JsonWriter writer(m_destination); writer.Write("timestamp", info.timestamp); writer.Write("user", info.user); writer.Write("nice", info.nice); writer.Write("system", info.system); writer.Write("idle", info.idle); writer.Write("iowait", info.iowait); writer.Write("irq", info.irq); writer.Write("softirq", info.softirq); writer.Finalize(); } char *GoToNextValue(char *cur) { // skip current value. while(*cur != ' ' && *cur != '\t') { ++cur; } // skip whitespaces. while(*cur == ' ' || *cur == '\t') { ++cur; } return cur; } char *GoToNextLine(char *cur) { while(*cur != '\n' && *cur != 0) { ++cur; } if(*cur == '\n') { ++cur; } return cur; } bool ReadCPUStatus(char *&pointer, struct CPUSample *stats, u32 timestamp) { // field definition: http://man7.org/linux/man-pages/man5/proc.5.html if(pointer[0] != 'c' || pointer[1] != 'p' || pointer[2] != 'u') { return false; } stats->timestamp = timestamp; pointer = GoToNextValue(pointer); Base::String::FromString(pointer, stats->user); pointer = GoToNextValue(pointer); Base::String::FromString(pointer, stats->nice); pointer = GoToNextValue(pointer); Base::String::FromString(pointer, stats->system); pointer = GoToNextValue(pointer); Base::String::FromString(pointer, stats->idle); pointer = GoToNextValue(pointer); Base::String::FromString(pointer, stats->iowait); pointer = GoToNextValue(pointer); Base::String::FromString(pointer, stats->irq); pointer = GoToNextValue(pointer); Base::String::FromString(pointer, stats->softirq); pointer = GoToNextLine(pointer); return true; } bool ReadCPUStats(struct CPUHistory *total, struct CPUHistory **cpu, int num_cpu) { Base::FileHandle file = Base::Open("/proc/stat", Base::OM_Read); if(file == -1) { PLUGIN_ERROR("failed opeining proc stat"); return false; } char buffer[kProcBufferSize]; size_t nbytes = Base::Read(file, buffer, kProcBufferSize); if(nbytes == static_cast<size_t>(-1)) { PLUGIN_ERROR("problem reading proc stat"); return false; } u32 timestamp = Base::Time::GetTimeMs(); char *pointer = buffer; if(!ReadCPUStatus(pointer, total->GetNextSample(), timestamp)) { PLUGIN_ERROR("problem reading cpu stats"); Base::Close(file); return false; } for(int i = 0; i < num_cpu; ++i) { if(!pointer || !ReadCPUStatus(pointer, cpu[i]->GetNextSample(), timestamp)) { PLUGIN_ERROR("problem reading %d cpu stats", i); Base::Close(file); return false; } } Base::Close(file); return true; } bool ReadProcessStats(struct ProcessHistory *hist) { Base::FileHandle file = Base::Open("/proc/self/stat", Base::OM_Read); char buffer[kProcBufferSize]; size_t nbytes = Base::Read(file, buffer, kProcBufferSize); if(nbytes == static_cast<size_t>(-1)) { PLUGIN_ERROR("problem reading proc stat"); return false; } char *pointer = buffer; for(int i = 0; i < 13; ++i) { pointer = GoToNextValue(pointer); } ProcessSample *sample = hist->GetNextSample(); Base::String::FromString(pointer, sample->user); pointer = GoToNextValue(pointer); Base::String::FromString(pointer, sample->system); Base::Close(file); return true; } struct CPUStatsCmd::PIMPL { u32 m_num_cpu; // number of processors u32 m_ticks_per_sec; // clock speed. ProcessHistory m_process; // process stat data. CPUHistory m_total; // all cpu stat data. CPUHistory *m_cpu; // stat data per cpu. u32 m_last_read_time; // last time stats were read. bool m_error; // true if there was a processing error PIMPL(u32 sample_count) : m_error(false) { m_num_cpu = sysconf(_SC_NPROCESSORS_ONLN); m_ticks_per_sec = sysconf(_SC_CLK_TCK); m_cpu = new CPUHistory[m_num_cpu]; m_total.Resize(sample_count); for(u32 i = 0; i < m_num_cpu; ++i) { m_cpu[i].Resize(sample_count); } m_process.Resize(sample_count); // init stats. ReadStats(); } ~PIMPL() { delete[] m_cpu; } void ReadStats() { ReadCPUStats(&m_total, &m_cpu, m_num_cpu); ReadProcessStats(&m_process); m_last_read_time = Base::Time::GetTimeMs(); } void Recalculate() { m_total.Calculate(m_ticks_per_sec); for(u32 i = 0; i < m_num_cpu; ++i) { m_cpu[i].Calculate(m_ticks_per_sec); } } }; CPUStatsCmd::CPUStatsCmd() { u32 sample_count = 10; m_pimpl = new PIMPL(sample_count); } CPUStatsCmd::~CPUStatsCmd() { delete m_pimpl; } void CPUStatsCmd::Sample() {} bool CPUStatsCmd::OnCommand(const std::string &query_string, const std::string &post_data, std::string *response_data) { u32 prev_read_time = m_pimpl->m_last_read_time; m_pimpl->ReadStats(); m_pimpl->Recalculate(); CPUPercent total; m_pimpl->m_total.LastSampleStats(m_pimpl->m_ticks_per_sec, &total); ProcessPercent process; m_pimpl->m_process.LastSampleStats(m_pimpl->m_ticks_per_sec, &process); JsonWriter writer(*response_data); writer.Write("platform", "linux"); writer.Write("error", m_pimpl->m_error); writer.Write("cpu_num", m_pimpl->m_num_cpu); writer.Write("ticks_per_sec", m_pimpl->m_ticks_per_sec); writer.Write("timestamp", m_pimpl->m_last_read_time); writer.Write("timeslice", m_pimpl->m_last_read_time - prev_read_time); writer.Write("total", total); writer.Write("process", process); writer.Finalize(); return true; } } // namespace Link
12,922
4,922
#include "template.hpp" int main() { int64_t a, b, k, l; cin >> a >> b >> k >> l; cout << min(k % l * a + k / l * b, k / l * b + b) << endl; }
150
73
#include "../external_dependencies/cmts/include/cmts.h" #include "algorithm_thread.h" #include "graphics/vulkan_state.h" #include "windows-specific/framework.h" #include "windows-specific/Resource.h" #include <atomic> #include <chrono> #define MAX_LOADSTRING 100 HINSTANCE hinstance; HWND hwnd; static HACCEL accel; std::atomic<bool> should_continue_global = true; std::atomic<bool> should_continue_sort; TCHAR window_title_buffer[4096]; extern LRESULT CALLBACK window_callbacks(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam); extern int init_vulkan(); extern void draw_main_array(); namespace cmts_checks { const int count = 65536; alignas(64) std::atomic_int counter_a; alignas(64) std::atomic_int counter_b; static void count_test_task_a(void* unused) { counter_a.fetch_add(1, std::memory_order_relaxed); } static void count_test_task_b(void* unused) { counter_b.fetch_add(1, std::memory_order_relaxed); } static void count_test() { cmts_init_options_t options = {}; options.task_stack_size = cmts_default_task_stack_size(); options.max_tasks = count; options.thread_count = cmts_processor_count(); auto code = cmts_lib_init(&options); assert(code == CMTS_OK); code = cmts_dispatch([](void* unused) { cmts_counter_t ca, cb; cmts_counter_init(&ca, count); cmts_counter_init(&cb, count); cmts_dispatch_options_t options = {}; options.flags = CMTS_DISPATCH_FLAGS_FORCE; options.sync_type = CMTS_SYNC_TYPE_COUNTER; options.sync_object = &ca; for (int i = 0; i != count; ++i) cmts_dispatch(count_test_task_a, &options); options.sync_object = &cb; for (int i = 0; i != count; ++i) cmts_dispatch(count_test_task_b, &options); cmts_counter_await(&ca); cmts_counter_await(&cb); cmts_lib_exit_signal(); }, nullptr); assert(code == CMTS_OK); code = cmts_lib_exit_await(nullptr); assert(code == CMTS_OK); } static void run() { count_test(); } } int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); //cmts_checks::run(); constexpr TCHAR class_name[] = TEXT("AVKClassName"); WNDCLASSEXW wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = window_callbacks; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ARRAYVK)); wcex.hCursor = LoadCursor(nullptr, IDC_ARROW); wcex.hbrBackground = CreateSolidBrush(0); wcex.lpszMenuName = MAKEINTRESOURCEW(IDC_MAIN_MENU); wcex.lpszClassName = class_name; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); constexpr auto base_counter = __COUNTER__; if (RegisterClassEx(&wcex) == INVALID_ATOM) return -(__COUNTER__ - base_counter); hinstance = hInstance; constexpr TCHAR title[] = TEXT("AVK - Sorting Algorithm Visualizer"); hwnd = CreateWindow( class_name, title, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr); if (hwnd == nullptr) return -(__COUNTER__ - base_counter); ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); accel = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_MAIN_MENU)); const int res = init_vulkan(); if (res < 0) return (1 << 30) | res; algorithm_thread::launch(); using namespace std::chrono; auto last = high_resolution_clock::now(); auto delay = std::chrono::milliseconds(1); main_array::set_compare_delay(delay); main_array::set_read_delay(delay); main_array::set_write_delay(delay); main_array::resize(1 << 8); constexpr TCHAR title_format[] = TEXT("AVK - Sorting Algorithm Visualizer - [ %u elements ]"); #ifdef UNICODE wsprintf(window_title_buffer, title_format, main_array::size()); SetWindowText(hwnd, window_title_buffer); #else sprintf(window_title_buffer, title_format, main_array::size()); SetWindowTextA(hwnd, window_title_buffer); #endif main_array::for_each([&](item& e, uint32_t position) { e.value = position; e.original_position = position; e.color = item_color::white(); }); constexpr auto framerrate = duration<long double>(1.0 / 60.0); auto last_draw = high_resolution_clock::now(); MSG msg = {}; while (should_continue_global.load(std::memory_order_acquire)) { while (PeekMessage(&msg, hwnd, 0, 0, PM_REMOVE)) { if (!TranslateAccelerator(msg.hwnd, accel, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } const auto now = high_resolution_clock::now(); if (now - last_draw > framerrate) { draw_main_array(); last_draw = now; } } algorithm_thread::terminate(); return (int)msg.message; }
5,380
1,926
#pragma once #include <PP/declval.hpp> #include <PP/get_type.hpp> #include <PP/macros/simple_concept.hpp> #include <PP/value_t.hpp> #include <PP/tuple/count.hpp> #include <PP/tuple/element.hpp> #include <PP/tuple/get.hpp> #include <PP/tuple/value_sequence_for.hpp> namespace PP::detail { template <typename T, auto I> concept tuple_access = requires { ::PP::declval_impl<T>()[::PP::value<I>]; ::PP::tuple::element(::PP::value<I>, ::PP::declval_impl<T>()); }; template <typename T, auto... I> concept tuple_accesses = (tuple_access<T, I> && ...); template <auto... I> constexpr auto is_tuple_helper(concepts::type auto&& t, value_sequence<I...>) noexcept { return tuple_accesses<PP_GT(t), I...>; } } namespace PP::concepts { template <typename T> concept tuple = requires { ::PP::tuple::count_value_t(::PP::declval_impl<T>()); } &&PP::detail::is_tuple_helper(PP::type<T>, tuple::type_value_sequence_for(PP::type<T>)); }
999
369
// Copyright (c) 2020 The Orbit 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 <gmock/gmock.h> #include <gtest/gtest.h> #include "FakeProducerSideService/FakeProducerSideService.h" #include "VulkanLayerProducerImpl.h" namespace orbit_vulkan_layer { namespace { class MockCaptureStatusListener : public VulkanLayerProducer::CaptureStatusListener { public: MOCK_METHOD(void, OnCaptureStart, (orbit_grpc_protos::CaptureOptions), (override)); MOCK_METHOD(void, OnCaptureStop, (), (override)); MOCK_METHOD(void, OnCaptureFinished, (), (override)); }; class VulkanLayerProducerImplTest : public ::testing::Test { protected: void SetUp() override { fake_service_.emplace(); grpc::ServerBuilder builder; builder.RegisterService(&fake_service_.value()); fake_server_ = builder.BuildAndStart(); ASSERT_NE(fake_server_, nullptr); std::shared_ptr<grpc::Channel> channel = fake_server_->InProcessChannel(grpc::ChannelArguments{}); producer_.emplace(); producer_->SetCaptureStatusListener(&mock_listener_); producer_->BringUp(channel); // Leave some time for the ReceiveCommandsAndSendEvents RPC to actually happen. std::this_thread::sleep_for(std::chrono::milliseconds(50)); } void TearDown() override { // Leave some time for all pending communication to finish. std::this_thread::sleep_for(std::chrono::milliseconds(50)); producer_->TakeDown(); producer_->SetCaptureStatusListener(nullptr); producer_.reset(); fake_service_->FinishAndDisallowRpc(); fake_server_->Shutdown(); fake_server_->Wait(); fake_service_.reset(); fake_server_.reset(); } std::optional<orbit_fake_producer_side_service::FakeProducerSideService> fake_service_; std::unique_ptr<grpc::Server> fake_server_; std::optional<VulkanLayerProducerImpl> producer_; MockCaptureStatusListener mock_listener_; static const std::string kInternedString1; static const uint64_t kExpectedInternedString1Key; static const std::string kInternedString2; static const uint64_t kExpectedInternedString2Key; static const std::string kInternedString3; static const uint64_t kExpectedInternedString3Key; }; const std::string VulkanLayerProducerImplTest::kInternedString1 = "a"; const uint64_t VulkanLayerProducerImplTest::kExpectedInternedString1Key = std::hash<std::string>{}(kInternedString1); const std::string VulkanLayerProducerImplTest::kInternedString2 = "b"; const uint64_t VulkanLayerProducerImplTest::kExpectedInternedString2Key = std::hash<std::string>{}(kInternedString2); const std::string VulkanLayerProducerImplTest::kInternedString3 = "c"; const uint64_t VulkanLayerProducerImplTest::kExpectedInternedString3Key = std::hash<std::string>{}(kInternedString3); constexpr std::chrono::milliseconds kWaitMessagesSentDuration{25}; const orbit_grpc_protos::CaptureOptions kFakeCaptureOptions = [] { orbit_grpc_protos::CaptureOptions capture_options; capture_options.set_pid(42); capture_options.set_samples_per_second(1234.0); return capture_options; }(); MATCHER_P(CaptureOptionsEq, that, "") { const orbit_grpc_protos::CaptureOptions& a = arg; const orbit_grpc_protos::CaptureOptions& b = that; return a.SerializeAsString() == b.SerializeAsString(); } TEST_F(VulkanLayerProducerImplTest, IsCapturingAndListener) { EXPECT_FALSE(producer_->IsCapturing()); EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_TRUE(producer_->IsCapturing()); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_FALSE(producer_->IsCapturing()); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); fake_service_->SendCaptureFinishedCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_FALSE(producer_->IsCapturing()); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_TRUE(producer_->IsCapturing()); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_FALSE(producer_->IsCapturing()); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); fake_service_->SendCaptureFinishedCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_FALSE(producer_->IsCapturing()); } TEST_F(VulkanLayerProducerImplTest, WorksWithNoListener) { EXPECT_CALL(mock_listener_, OnCaptureStart).Times(0); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(0); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(0); producer_->SetCaptureStatusListener(nullptr); EXPECT_FALSE(producer_->IsCapturing()); fake_service_->SendStartCaptureCommand(orbit_grpc_protos::CaptureOptions{}); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_TRUE(producer_->IsCapturing()); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_FALSE(producer_->IsCapturing()); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); fake_service_->SendCaptureFinishedCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_FALSE(producer_->IsCapturing()); } TEST_F(VulkanLayerProducerImplTest, EnqueueCaptureEvent) { EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); EXPECT_FALSE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent())); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); int32_t capture_events_received_count = 0; ON_CALL(*fake_service_, OnCaptureEventsReceived) .WillByDefault([&capture_events_received_count]( const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) { capture_events_received_count += events.size(); }); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(::testing::Between(1, 3)); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); EXPECT_TRUE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent())); EXPECT_TRUE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent())); EXPECT_TRUE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent())); std::this_thread::sleep_for(kWaitMessagesSentDuration); EXPECT_EQ(capture_events_received_count, 3); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); EXPECT_FALSE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent())); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendCaptureFinishedCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); EXPECT_FALSE(producer_->EnqueueCaptureEvent(orbit_grpc_protos::ProducerCaptureEvent())); } static void ExpectInternedStrings( const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& actual_events, const std::vector<std::pair<std::string, uint64_t>>& expected_interns) { ASSERT_EQ(actual_events.size(), expected_interns.size()); for (size_t i = 0; i < actual_events.size(); ++i) { ASSERT_EQ(actual_events[i].event_case(), orbit_grpc_protos::ProducerCaptureEvent::kInternedString); EXPECT_EQ(actual_events[i].interned_string().intern(), expected_interns[i].first); EXPECT_EQ(actual_events[i].interned_string().key(), expected_interns[i].second); } } TEST_F(VulkanLayerProducerImplTest, InternStringIfNecessaryAndGetKey) { EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); std::vector<orbit_grpc_protos::ProducerCaptureEvent> events_received; EXPECT_CALL(*fake_service_, OnCaptureEventsReceived) .Times(::testing::Between(1, 2)) .WillRepeatedly( [&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) { events_received.insert(events_received.end(), events.begin(), events.end()); }); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); uint64_t actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key}, {kInternedString2, kExpectedInternedString2Key}}); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); // These should not be sent to the service. actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString3); EXPECT_EQ(actual_key, kExpectedInternedString3Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendCaptureFinishedCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); // These should not be sent to the service. actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString3); EXPECT_EQ(actual_key, kExpectedInternedString3Key); } TEST_F(VulkanLayerProducerImplTest, DontSendInternTwice) { EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); std::vector<orbit_grpc_protos::ProducerCaptureEvent> events_received; EXPECT_CALL(*fake_service_, OnCaptureEventsReceived) .Times(1) .WillRepeatedly( [&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) { events_received.insert(events_received.end(), events.begin(), events.end()); }); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); uint64_t actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key}}); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendCaptureFinishedCommand(); } TEST_F(VulkanLayerProducerImplTest, ReInternInNewCapture) { EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); std::vector<orbit_grpc_protos::ProducerCaptureEvent> events_received; EXPECT_CALL(*fake_service_, OnCaptureEventsReceived) .Times(::testing::Between(1, 2)) .WillRepeatedly( [&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) { events_received.insert(events_received.end(), events.begin(), events.end()); }); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); uint64_t actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key}, {kInternedString2, kExpectedInternedString2Key}}); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendCaptureFinishedCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); events_received.clear(); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived) .Times(::testing::Between(1, 2)) .WillRepeatedly( [&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) { events_received.insert(events_received.end(), events.begin(), events.end()); }); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key}, {kInternedString2, kExpectedInternedString2Key}}); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendCaptureFinishedCommand(); } TEST_F(VulkanLayerProducerImplTest, InternOnlyWhenCapturing) { EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); // These should not be sent to the service. uint64_t actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendCaptureFinishedCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); // These should not be sent to the service. actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStart(CaptureOptionsEq(kFakeCaptureOptions))).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendStartCaptureCommand(kFakeCaptureOptions); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); std::vector<orbit_grpc_protos::ProducerCaptureEvent> events_received; EXPECT_CALL(*fake_service_, OnCaptureEventsReceived) .Times(::testing::Between(1, 2)) .WillRepeatedly( [&events_received](const std::vector<orbit_grpc_protos::ProducerCaptureEvent>& events) { events_received.insert(events_received.end(), events.begin(), events.end()); }); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString1); EXPECT_EQ(actual_key, kExpectedInternedString1Key); actual_key = producer_->InternStringIfNecessaryAndGetKey(kInternedString2); EXPECT_EQ(actual_key, kExpectedInternedString2Key); std::this_thread::sleep_for(kWaitMessagesSentDuration); ExpectInternedStrings(events_received, {{kInternedString1, kExpectedInternedString1Key}, {kInternedString2, kExpectedInternedString2Key}}); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureStop).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(1); fake_service_->SendStopCaptureCommand(); std::this_thread::sleep_for(kWaitMessagesSentDuration); ::testing::Mock::VerifyAndClearExpectations(&mock_listener_); ::testing::Mock::VerifyAndClearExpectations(&*fake_service_); EXPECT_CALL(mock_listener_, OnCaptureFinished).Times(1); EXPECT_CALL(*fake_service_, OnCaptureEventsReceived).Times(0); EXPECT_CALL(*fake_service_, OnAllEventsSentReceived).Times(0); fake_service_->SendCaptureFinishedCommand(); } } // namespace } // namespace orbit_vulkan_layer
24,837
8,640
/******************************************************************************* Copyright (c) 2020, Fabio Muratore, Honda Research Institute Europe GmbH, and Technical University of Darmstadt. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Fabio Muratore, Honda Research Institute Europe GmbH, or Technical University of Darmstadt, 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 FABIO MURATORE, HONDA RESEARCH INSTITUTE EUROPE GMBH, OR TECHNICAL UNIVERSITY OF DARMSTADT 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 "RcsSimEnv.h" #include "config/PropertySourceDict.h" #include "config/PropertySourceXml.h" #include "control/ControlPolicy.h" #include "physics/vortex_log.h" #include "util/BoxSpace.h" #include "util/type_casters.h" #include "util/pybind_dict_utils.h" #include <pybind11/stl.h> namespace py = pybind11; #include <Rcs_resourcePath.h> #include <Rcs_macros.h> #include <Rcs_MatNd.h> #include <Rcs_Vec3d.h> #include <PhysicsFactory.h> #include <SegFaultHandler.h> #include <Rcs_typedef.h> RCS_INSTALL_ERRORHANDLERS /* Could be done in the future void define_gui_classes(py::module& m); */ PYBIND11_MODULE(_rcsenv, m) { // define exceptions py::register_exception<Rcs::JointLimitException>(m, "JointLimitException"); // Define BoxSpace as class. It's not providing a constructor here, it's just meant to be passed to python for information py::class_<Rcs::BoxSpace>(m, "BoxSpace") .def_property_readonly("min", &Rcs::BoxSpace::getMin, py::return_value_policy::reference_internal) .def_property_readonly("max", &Rcs::BoxSpace::getMax, py::return_value_policy::reference_internal) .def_property_readonly("names", []( const Rcs::BoxSpace& thiz) -> py::object { auto& names = thiz.getNames(); if (names.empty()) { return py::none(); } return py::cast(names); }); // Define simulator base class py::class_<Rcs::RcsSimEnv>(m, "RcsSimEnv") .def(py::init([](py::kwargs kwargs) { // Get properties from xml or python Rcs::PropertySource* config; std::string configFileName; if (try_get(kwargs, "experimentConfigFile", configFileName)) { config = new Rcs::PropertySourceXml(configFileName.c_str()); } else { config = new Rcs::PropertySourceDict(kwargs); } // Create config object, takes ownership of property source return new Rcs::RcsSimEnv(config); }) ) .def("step", &Rcs::RcsSimEnv::step, py::arg("action"), py::arg("disturbance") = py::none(), py::call_guard<py::gil_scoped_release>()) .def("reset", [](Rcs::RcsSimEnv& self, py::object domainParam, const MatNd* initState) { Rcs::PropertySource* domainParamSource = Rcs::PropertySource::empty(); if (!domainParam.is_none()) { domainParamSource = new Rcs::PropertySourceDict(domainParam); } MatNd* result = self.reset(domainParamSource, initState); if (!domainParam.is_none()) { delete domainParamSource; } return result; }, py::arg("domainParam").none(true) = py::none(), py::arg("initState").none(true) = py::none() ) .def("render", &Rcs::RcsSimEnv::render, py::arg("mode") = "human", py::arg("close") = false) .def("toggleVideoRecording", &Rcs::RcsSimEnv::toggleVideoRecording) .def("setTransitionNoiseBuffer", &Rcs::RcsSimEnv::setTransitionNoiseBuffer) .def("saveConfigXML", [](Rcs::RcsSimEnv& self, const char* fileName) { self.getConfig()->properties->saveXML(fileName, "Experiment"); }) .def("getBodyPosition", [](Rcs::RcsSimEnv& self, const char* bodyName, const char* refBodyName, const char* refFrameName) { const RcsBody* body = RcsGraph_getBodyByName(self.getConfig()->graph, bodyName); RCHECK(body); const RcsBody* refBody = RcsGraph_getBodyByName(self.getConfig()->graph, refBodyName); const RcsBody* refFrame = RcsGraph_getBodyByName(self.getConfig()->graph, refFrameName); double I_r[3]; // Effector-fixed reference point in world coordinates Vec3d_copy(I_r, body->A_BI->org); // Transform to reference frame: ref_r = A_ref-I * (I_r - I_r_refBdy) if (refBody != NULL) { Vec3d_subSelf(I_r, refBody->A_BI->org); // I_r -= I_r_refBdy // refBody and refFrame, but they differ: refFrame_r = A_refFrame-I*I_r if ((refFrame != NULL) && (refFrame != refBody)) { Vec3d_rotateSelf(I_r, refFrame->A_BI->rot); } // refBody and refFrame are the same: refFrame_r = A_refBody-I*I_r else { Vec3d_rotateSelf(I_r, refBody->A_BI->rot); } } // No refBody, but refFrame: Rotate into refFrame coordinates else { // Rotate into refFrame if it exists if (refFrame != NULL) { Vec3d_rotateSelf(I_r, refFrame->A_BI->rot); } } MatNd* pos = NULL; pos = MatNd_create(3, 1); for (unsigned int i = 0; i < 3; i++) { MatNd_set(pos, i, 0, I_r[i]); } return pos; }, py::arg("bodyName"), py::arg("refFrameName"), py::arg("refBodyName") ) .def("getBodyExtents", [](Rcs::RcsSimEnv& self, const char* bodyName, const int shapeIdx) { const RcsBody* body = RcsGraph_getBodyByName(self.getConfig()->graph, bodyName); RCHECK(body); MatNd* extents = NULL; extents = MatNd_create(3, 1); for (unsigned int i = 0; i < 3; i++) { MatNd_set(extents, i, 0, body->shape[shapeIdx]->extents[i]); } return extents; }, py::arg("bodyName"), py::arg("shapeIdx") ) // Properties .def_property_readonly("observationSpace", &Rcs::RcsSimEnv::observationSpace) .def_property_readonly("actionSpace", &Rcs::RcsSimEnv::actionSpace) .def_property_readonly("initStateSpace", &Rcs::RcsSimEnv::initStateSpace) .def_property_readonly("domainParam", [](Rcs::RcsSimEnv& self) { // Expose the domain parameters to the Python side py::dict result; Rcs::PropertySourceDict psink(result); self.getPhysicsManager()->getValues(&psink); return result; }) .def_property_readonly("internalStateDim", &Rcs::RcsSimEnv::getInternalStateDim) .def_property_readonly("dt", [](Rcs::RcsSimEnv& self) { return self.getConfig()->dt; }) .def_property_readonly("lastAction", &Rcs::RcsSimEnv::getCurrentAction, py::return_value_policy::copy) .def_property_readonly("lastObservation", &Rcs::RcsSimEnv::getCurrentObservation, py::return_value_policy::copy); // Define ControlPolicy for tests py::class_<Rcs::ControlPolicy> controlPolicy(m, "ControlPolicy"); controlPolicy.def(py::init<Rcs::ControlPolicy* (*)(const char*, const char*)>(&Rcs::ControlPolicy::create)); controlPolicy.def("__call__", [](Rcs::ControlPolicy& self, const MatNd* input, unsigned int output_size) { MatNd* output = MatNd_create(output_size, 1); self.computeAction(output, input); return output; }); controlPolicy.def("reset", &Rcs::ControlPolicy::reset); controlPolicy.def_property_readonly_static("types", [](py::handle /* self */) { return Rcs::ControlPolicy::getTypeNames(); }); // Expose the ControlPolicy classes to the Python side // py::class_<Rcs::ActionModelIKPolicy>(m, "ActionModelIKPolicy", controlPolicy) // .def(py::init(&Rcs::loadMLPPolicyFromXml)); /* Could be done in the future #ifdef GUI_AVAILABLE // Define gui stuff if available define_gui_classes(m); #endif */ m.def("saveExperimentParams", [](py::dict& config, const char* filename){ std::unique_ptr<Rcs::PropertySource> ps(new Rcs::PropertySourceDict(config)); ps->saveXML(filename, "Experiment"); }, py::arg("config"), py::arg("filename")); // Sets the rcs log level m.def("setLogLevel", [](int level) { RcsLogLevel = level; }); // Adds a directory to the resource path m.def("addResourcePath", [](const char* path) { return Rcs_addResourcePath(path); }); // Check if physics engine is available (can't list, unfortunately) m.def("supportsPhysicsEngine", &Rcs::PhysicsFactory::hasEngine); // Control vortex log level, setting it to warnings only by default (this avoids log spam) Rcs::setVortexLogLevel("warn"); // Allow changing it if desired m.def("setVortexLogLevel", &Rcs::setVortexLogLevel); }
10,856
3,280
#include <iostream> #include <cmath> #define EPSILON 1e-10 bool is_same(double __x, double __y) { if(std::abs(__x - __y) < EPSILON) { std::cout << std::fixed << "IN Function __x\t\t" << __x << "\n"; std::cout << std::fixed << "IN Function __y\t\t" << __y << "\n"; std::cout << std::fixed << "std::abs(__x - __y)\t" << std::abs(__x - __y) << "\n"; return true; } else { return false; } } double distance(double x1, double y1, double x2, double y2) { return std::sqrt(std::pow((x2 - x1), 2) + std::pow((y2 - y1), 2)); } int main() { std::cout.precision(17); // maximum precision : https://stackoverflow.com/a/554134/7105963 std::cout << std::fixed << "dist (0, 0) ~ (3, 4)\t" << distance(0, 0, 3, 4) << "\n"; std::cout << std::fixed << "EPSILON(small)\t\t" << EPSILON << "\n"; std::cout << std::fixed << "distance + EPSILON\t" << (distance(0, 0, 3, 4) + EPSILON) << "\n"; std::cout << std::fixed << "distance - EPSILON\t" << (distance(0, 0, 3, 4) - EPSILON) << "\n"; // std::cout << is_same(distance(0, 0, 3, 4), (distance(0, 0, 3, 4) + __DBL_EPSILON__)) << "\n"; std::cout << is_same(distance(0, 0, 3, 4), (distance(0, 0, 3, 4) + EPSILON)) << "\n"; std::cout << std::fixed << "5.0 + EPSILON\t\t" << (5.0 + EPSILON) << "\n"; std::cout << std::fixed << "5.0 - EPSILON\t\t" << (5.0 - EPSILON) << "\n"; std::cout << std::fixed << "5.0 - EPSILON\t\t" << (5.0 - EPSILON) << "\n"; }
1,485
661
// DDCPP/standard/bits/DD_ReferenceCounter.hpp #ifndef DD_REFERENCE_COUNTER_HPP_INCLUDED_ # define DD_REFERENCE_COUNTER_HPP_INCLUDED_ 1 # include "DD_global_definitions.hpp" DD_DETAIL_BEGIN_ struct ReferenceCounter { public: DD_ALIAS(ThisType, ReferenceCounter); public: DD_ALIAS(LengthType, ::DD::LengthType); public: Pair<LengthType> m_reference_count_; public: Pair<LengthType> const& get_reference_count() const DD_NOEXCEPT { return m_reference_count_; } public: LengthType get_strong_reference_count() const DD_NOEXCEPT { return get_reference_count().first; } public: LengthType get_weak_reference_count() const DD_NOEXCEPT { return get_reference_count().second; } public: ValidityType is_unique_strong_reference() const DD_NOEXCEPT { return get_strong_reference_count() == LengthType(1); } public: ValidityType is_unique_weak_reference() const DD_NOEXCEPT { return get_weak_reference_count() == LengthType(1); } public: ValidityType has_strong_reference() const DD_NOEXCEPT { return get_strong_reference_count(); } public: ValidityType has_weak_reference() const DD_NOEXCEPT { return get_weak_reference_count(); } public: ValidityType is_expired() const DD_NOEXCEPT { return !has_strong_reference(); } public: ProcessType strongly_referred() DD_NOEXCEPT { ++m_reference_count_.first; } public: ProcessType weakly_referred() DD_NOEXCEPT { ++m_reference_count_.second; } public: ProcessType strongly_released() DD_NOEXCEPT { --m_reference_count_.first; } public: ProcessType weakly_released() DD_NOEXCEPT { --m_reference_count_.second; } }; DD_DETAIL_END_ DD_BEGIN_ using detail_::ReferenceCounter; DD_END_ #endif
1,731
714
// RUN: %clang_cc1 %s -std=c++14 -triple=spir -emit-llvm -o - | FileCheck %s // RUN: %clang_cc1 %s -std=c++17 -triple=spir -emit-llvm -o - | FileCheck %s struct MyType { MyType(int i) : i(i) {} int i; }; //CHECK: call void @_ZN6MyTypeC1Ei(%struct.MyType* addrspacecast (%struct.MyType addrspace(10)* @m to %struct.MyType*), i32 123) MyType __attribute__((address_space(10))) m = 123;
389
182
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { long long n,r; cin>>n; cin>>r; long long arr1[n],arr2[n]; for(long long i=0;i<n;i++) { cin>>arr1[i]; } for(long long i=0;i<n;i++) { cin>>arr2[i]; } long long tension=arr2[0]; long long temp=0; long long res=arr2[0]; if(n==1) { cout<<arr2[0]<<endl; } else { for(long long i=1;i<n;i++) { temp=arr1[i]-arr1[i-1]; tension=tension-(temp*r); if(tension<0) { tension=0; } //cout<<tension+arr2[i]-rest<<endl; //tension = tension +arr2[i-1]-rest; tension = arr2[i] + tension; res=max(res,tension); } cout<<res<<endl; } } }
992
364
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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 "utils/lockp.std.h" #include <gtest/gtest.h> using namespace dsn; using namespace dsn::tools; TEST(tools_common, std_lock_provider) { std_lock_provider *lock = new std_lock_provider(nullptr); lock->lock(); EXPECT_TRUE(lock->try_lock()); lock->unlock(); lock->unlock(); std_lock_nr_provider *nr_lock = new std_lock_nr_provider(nullptr); nr_lock->lock(); EXPECT_FALSE(nr_lock->try_lock()); nr_lock->unlock(); std_rwlock_nr_provider *rwlock = new std_rwlock_nr_provider(nullptr); rwlock->lock_read(); rwlock->unlock_read(); rwlock->lock_write(); rwlock->unlock_write(); std_semaphore_provider *sema = new std_semaphore_provider(0, nullptr); std::thread t([](std_semaphore_provider *s) { s->wait(1000000); }, sema); sema->signal(1); t.join(); delete lock; delete nr_lock; delete rwlock; delete sema; }
2,111
739
#include "AST/UnaryOperator.hpp" #include "visitor/AstNodeVisitor.hpp" UnaryOperatorNode::UnaryOperatorNode(const uint32_t line, const uint32_t col, Operator op, ExpressionNode *p_operand) : ExpressionNode{line, col}, op(op), operand(p_operand) {} const char *UnaryOperatorNode::getOpCString() const { return kOpString[static_cast<size_t>(op)]; } void UnaryOperatorNode::accept(AstNodeVisitor &p_visitor) { p_visitor.visit(*this); } void UnaryOperatorNode::visitChildNodes(AstNodeVisitor &p_visitor) { operand->accept(p_visitor); } const Operator& UnaryOperatorNode::getOperator() const { return op; }
664
229
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <lib/sys/cpp/testing/component_context_provider.h> #include <zircon/syscalls.h> #include "garnet/lib/ui/gfx/tests/vk_session_test.h" #include "gtest/gtest.h" #include "lib/ui/gfx/util/time.h" #include "lib/ui/scenic/cpp/commands.h" #include "src/ui/lib/escher/test/gtest_vulkan.h" namespace scenic_impl { namespace gfx { namespace test { class CompositorTest : public SessionTest { public: CompositorTest() {} void TearDown() override { SessionTest::TearDown(); view_linker_.reset(); resource_linker_.reset(); time_stamper_.reset(); scene_graph_.reset(); } SessionContext CreateSessionContext() override { SessionContext session_context = SessionTest::CreateSessionContext(); FXL_DCHECK(!scene_graph_); FXL_DCHECK(!time_stamper_); FXL_DCHECK(!resource_linker_); FXL_DCHECK(!view_linker_); // Generate scene graph. scene_graph_ = std::make_unique<SceneGraph>(); // Generate other parameters needed for session context. sys::testing::ComponentContextProvider context_provider_; app_context_ = context_provider_.TakeContext(); time_stamper_ = std::make_unique<EventTimestamper>(app_context_.get()); resource_linker_ = std::make_unique<ResourceLinker>(); view_linker_ = std::make_unique<ViewLinker>(); // Apply to the session context; session_context.event_timestamper = time_stamper_.get(); session_context.view_linker = view_linker_.get(); session_context.resource_linker = resource_linker_.get(); // Finally apply scene graph weak pointer. session_context.scene_graph = scene_graph_->GetWeakPtr(); // Return session return session_context; } private: std::unique_ptr<SceneGraph> scene_graph_; // This is saved because it needs to live longer than the EventTimestamper std::unique_ptr<sys::ComponentContext> app_context_; std::unique_ptr<EventTimestamper> time_stamper_; std::unique_ptr<ViewLinker> view_linker_; std::unique_ptr<ResourceLinker> resource_linker_; }; TEST_F(CompositorTest, Validation) { const int CompositorId = 15; std::array<float, 3> preoffsets = {0, 0, 0}; std::array<float, 9> matrix = {0.3, 0.6, 0.1, 0.3, 0.6, 0.1, 0.3, 0.6, 0.1}; std::array<float, 3> postoffsets = {0, 0, 0}; ASSERT_TRUE(Apply(scenic::NewCreateDisplayCompositorCmd(CompositorId))); ASSERT_TRUE(Apply( scenic::NewSetDisplayColorConversionCmdHACK(CompositorId, preoffsets, matrix, postoffsets))); Display* display = display_manager()->default_display(); ASSERT_TRUE(display != nullptr); const ColorTransform& transform = display->color_transform(); ASSERT_TRUE(transform.preoffsets == preoffsets); ASSERT_TRUE(transform.matrix == matrix); ASSERT_TRUE(transform.postoffsets == postoffsets); } } // namespace test } // namespace gfx } // namespace scenic_impl
3,001
1,050
// // Created by fy on 2019-01-29. // #ifndef FORCEIO_CONTRACT_RELAY_TOKEN_HPP #define FORCEIO_CONTRACT_RELAY_TOKEN_HPP #pragma once #include <eosiolib/eosio.hpp> #include "force.relay/force.relay.hpp" #include "sys.match/sys.match.hpp" namespace relay { using namespace eosio; using std::string; struct sys_bridge_addmort { name trade_name; account_name trade_maker; uint64_t type; void parse(const string memo); }; struct sys_bridge_exchange { name trade_name; account_name trade_maker; account_name recv; uint64_t type; void parse(const string memo); }; enum class trade_type:uint64_t { match=1, bridge_addmortgage, bridge_exchange, trade_type_count }; #ifdef BEFORE_ONLINE_TEST static constexpr uint32_t UPDATE_CYCLE = 126; #else static constexpr uint32_t UPDATE_CYCLE = 315; #endif static constexpr uint64_t OTHER_COIN_WEIGHT = 500; #define COIN_REWARD_RECORD_SIZE 360 class token : public eosio::contract { public: using contract::contract; token( account_name self ) : contract(self) {} struct action { account_name from; account_name to; asset quantity; std::string memo; EOSLIB_SERIALIZE(action, (from)(to)(quantity)(memo)) }; /// @abi action void on( name chain, const checksum256 block_id, const force::relay::action& act ); /// @abi action void create( account_name issuer, name chain, account_name side_account, action_name side_action, asset maximum_supply ); /// @abi action void issue( name chain, account_name to, asset quantity, string memo ); /// @abi action void destroy( name chain, account_name from, asset quantity, string memo ); /// @abi action void transfer( account_name from, account_name to, name chain, asset quantity, string memo ); inline asset get_supply( name chain, symbol_name sym )const; /// @abi action void trade( account_name from, account_name to, name chain, asset quantity, trade_type type, string memo); /// @abi action void addreward(name chain,asset supply,int32_t reward_now); /// @abi action void rewardmine(asset quantity); /// @abi action void claim(name chain,asset quantity,account_name receiver); /// @abi action void settlemine(account_name system_account); /// @abi action void activemine(account_name system_account); private: inline static uint128_t get_account_idx(const name& chain, const asset& a) { return (uint128_t(uint64_t(chain)) << 64) + uint128_t(a.symbol.name()); } struct account { uint64_t id; asset balance; name chain; int128_t mineage = 0; // asset.amount * block height uint32_t mineage_update_height = 0; asset reward = asset(0); uint64_t primary_key() const { return id; } uint128_t get_index_i128() const { return get_account_idx(chain, balance); } }; struct account_next_id { uint64_t id; account_name account; uint64_t primary_key() const { return account; } }; struct reward_mine_info { int128_t total_mineage = 0; asset reward_pool = asset(0); int32_t reward_block_num = 0; uint64_t primary_key() const { return reward_block_num; } }; struct currency_stats { asset supply; asset max_supply; account_name issuer; name chain; account_name side_account; action_name side_action; int128_t total_mineage = 0; // asset.amount * block height uint32_t total_mineage_update_height = 0; uint64_t reward_scope; int32_t reward_size = 0; // vector<reward_mine_info> reward_mine; uint64_t primary_key() const { return supply.symbol.name(); } }; struct reward_currency { uint64_t id; name chain; asset supply; bool reward_now = true; //记录是否是立刻进行挖矿的代币 uint64_t primary_key() const { return id; } uint128_t get_index_i128() const { return get_account_idx(chain, supply); } }; typedef multi_index<N(accounts), account, indexed_by< N(bychain), const_mem_fun<account, uint128_t, &account::get_index_i128 >>> accounts; typedef multi_index<N(stat), currency_stats> stats; typedef multi_index<N(accountid), account_next_id> account_next_ids ; typedef multi_index<N(reward), reward_currency, indexed_by< N(bychain), const_mem_fun<reward_currency, uint128_t, &reward_currency::get_index_i128 >>> rewards; typedef multi_index<N(minereward), reward_mine_info> reward_mine ; void sub_balance( account_name owner, name chain, asset value ); void add_balance( account_name owner, name chain, asset value, account_name ram_payer ); void settle_user(account_name owner, name chain, asset value); public: struct transfer_args { account_name from; account_name to; name chain; asset quantity; string memo; }; }; asset token::get_supply( name chain, symbol_name sym )const { stats statstable( _self, chain ); const auto& st = statstable.get( sym ); return st.supply; } }; #endif //FORCEIO_CONTRACT_RELAY_TOKEN_HPP
5,560
1,863
/* FileName: superblock.hpp * Author: Hover * E-Mail: hover@hust.edu.cn * GitHub: HoverWings * Description: superblock */ #ifndef _SUPERBLOCK_H_ #define _SUPERBLOCK_H_ #include "inode.hpp" #include <fstream> #include <list> #include <map> #include <string> #include <vector> #include <cstring> #include "macro.h" #include "assert.h" #include "myfs.hpp" #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> class myFS; class SuperBlock { private: bool inode_bitmap[INODE_NUM]; bool block_bitmap[BLOCK_NUM]; public: // uint node_num; // now inode num // uint direct_blocks; // uint blocks_num; // uint block_size; int q; class myFS* myfs; SuperBlock(); bool write_back_to_disk(); bool read_from_disk(); // template<class Archive> // void serialize(Archive & ar, const unsigned int version) // { // ar& inode_bitmap; // ar& block_bitmap; // } }; #endif
1,161
401
#include <iostream> template <bool value> int reversed_binary_value() { return value; } template <bool a, bool b, bool... d> int reversed_binary_value() { return (reversed_binary_value<b, d...>() << 1) + a; }
215
81
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: AllContentModel.hpp 568078 2007-08-21 11:43:25Z amassari $ */ #if !defined(ALLCONTENTMODEL_HPP) #define ALLCONTENTMODEL_HPP #include <xercesc/framework/XMLContentModel.hpp> #include <xercesc/util/ValueVectorOf.hpp> #include <xercesc/validators/common/ContentLeafNameTypeVector.hpp> XERCES_CPP_NAMESPACE_BEGIN class ContentSpecNode; // // AllContentModel is a derivative of the abstract content model base // class that handles the special case of <all> feature in schema. If a model // is <all>, all non-optional children must appear // // So, all we have to do is to keep an array of the possible children and // validate by just looking up each child being validated by looking it up // in the list, and make sure all non-optional children appear. // class AllContentModel : public XMLContentModel { public : // ----------------------------------------------------------------------- // Constructors and Destructor // ----------------------------------------------------------------------- AllContentModel ( ContentSpecNode* const parentContentSpec , const bool isMixed , MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager ); ~AllContentModel(); // ----------------------------------------------------------------------- // Implementation of the ContentModel virtual interface // ----------------------------------------------------------------------- virtual int validateContent ( QName** const children , const unsigned int childCount , const unsigned int emptyNamespaceId ) const; virtual int validateContentSpecial ( QName** const children , const unsigned int childCount , const unsigned int emptyNamespaceId , GrammarResolver* const pGrammarResolver , XMLStringPool* const pStringPool ) const; virtual ContentLeafNameTypeVector* getContentLeafNameTypeVector() const ; virtual unsigned int getNextState(const unsigned int currentState, const unsigned int elementIndex) const; virtual void checkUniqueParticleAttribution ( SchemaGrammar* const pGrammar , GrammarResolver* const pGrammarResolver , XMLStringPool* const pStringPool , XMLValidator* const pValidator , unsigned int* const pContentSpecOrgURI , const XMLCh* pComplexTypeName = 0 ) ; private : // ----------------------------------------------------------------------- // Private helper methods // ----------------------------------------------------------------------- void buildChildList ( ContentSpecNode* const curNode , ValueVectorOf<QName*>& toFill , ValueVectorOf<bool>& toType ); // ----------------------------------------------------------------------- // Unimplemented constructors and operators // ----------------------------------------------------------------------- AllContentModel(); AllContentModel(const AllContentModel&); AllContentModel& operator=(const AllContentModel&); // ----------------------------------------------------------------------- // Private data members // // fCount // The count of possible children in the fChildren member. // // fChildren // The list of possible children that we have to accept. This array // is allocated as large as needed in the constructor. // // fChildOptional // The corresponding list of optional state of each child in fChildren // True if the child is optional (i.e. minOccurs = 0). // // fNumRequired // The number of required children in <all> (i.e. minOccurs = 1) // // fIsMixed // AllContentModel with mixed PCDATA. // ----------------------------------------------------------------------- MemoryManager* fMemoryManager; unsigned int fCount; QName** fChildren; bool* fChildOptional; unsigned int fNumRequired; bool fIsMixed; bool fHasOptionalContent; }; inline ContentLeafNameTypeVector* AllContentModel::getContentLeafNameTypeVector() const { return 0; } inline unsigned int AllContentModel::getNextState(const unsigned int, const unsigned int) const { return XMLContentModel::gInvalidTrans; } XERCES_CPP_NAMESPACE_END #endif
5,393
1,366
#include <nan.h> #include <ghostscript/gserrors.h> #include <ghostscript/iapi.h> using namespace std; using namespace Nan; using namespace v8; class ghostscript : public AsyncWorker { public: ghostscript(Callback *callback, vector<string> args) : AsyncWorker(callback), args(args) {} // Executes in worker thread void Execute() { if (args.size() == 0) { gscode = 1; return; } void *minst; unsigned int gsargc = (unsigned int) args.size() + 1; char *gsargv[gsargc]; gsargv[0] = (char *) "gs"; for (int unsigned i = 0; i < args.size(); i++) { char *argsToChar = new char[args[i].length() + 1]; strcpy(argsToChar, args[i].c_str()); gsargv[i + 1] = argsToChar; } gscode = gsapi_new_instance(&minst, NULL); if (gscode < 0) return; gsapi_set_stdio(minst, gsdll_stdin, gsdll_stdout, gsdll_stderr); gscode = gsapi_set_arg_encoding(minst, GS_ARG_ENCODING_UTF8); if (gscode == 0) gscode = gsapi_init_with_args(minst, gsargc, gsargv); gscode1 = gsapi_exit(minst); if ((gscode == 0) || (gscode == gs_error_Quit)) gscode = gscode1; gsapi_delete_instance(minst); } // Executes in event loop void HandleOKCallback() { if (gscode == gs_okay) { Local<Value> argv[] = {Nan::Null()}; callback->Call(1, argv); } else { Local<Integer> codeError = Nan::New(gscode); Local<Value> argv[] = {codeError}; callback->Call(1, argv); } } private: vector<string> args; int gscode = 0; int gscode1; static int gsdll_stdin(void *instance, char *buf, int len) { int ch; int count = 0; while (count < len) { ch = fgetc(stdin); if (ch == EOF) return 0; *buf++ = (char) ch; count++; if (ch == '\n') break; } return count; } static int gsdll_stdout(void *instance, const char *str, int len) { return len; } static int gsdll_stderr(void *instance, const char *str, int len) { return len; } }; NAN_METHOD(exec) { if (info.Length() < 2) { return Nan::ThrowError("Wrong number of arguments"); } Local<Array> input = Local<Array>::Cast(info[0]); vector<string> args; if (input->IsArray()) { for (int unsigned i = 0; i < input->Length(); i++) { Nan::Utf8String val(Nan::Get(input, i).ToLocalChecked()); std::string str(*val); args.push_back(str); } } Callback *callback = new Callback(info[1].As<Function>()); AsyncQueueWorker(new ghostscript(callback, args)); } NAN_MODULE_INIT(Init) { Nan::Set(target, New<String>("exec").ToLocalChecked(), GetFunction(New<FunctionTemplate>(exec)).ToLocalChecked()); } NODE_MODULE(ghostscriptjs, Init)
2,991
1,037
#include "demoloop.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtx/rotate_vector.hpp> #include "graphics/shader.h" using namespace std; using namespace demoloop; const uint32_t CYCLE_LENGTH = 10; const static std::string shaderCode = R"===( uniform mediump float cycle_ratio; #define DEMOLOOP_M_PI 3.1459 #ifdef VERTEX vec4 position(mat4 transform_proj, mat4 model, vec4 vertpos) { return transform_proj * model * vertpos; } #endif #ifdef PIXEL highp vec3 mod289(highp vec3 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } highp vec2 mod289(highp vec2 x) { return x - floor(x * (1.0 / 289.0)) * 289.0; } highp vec3 permute(highp vec3 x) { return mod289(((x*34.0)+1.0)*x); } float snoise( vec2 v) { const highp vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0 0.366025403784439, // 0.5*(sqrt(3.0)-1.0) -0.577350269189626, // -1.0 + 2.0 * C.x 0.024390243902439); // 1.0 / 41.0 // First corner highp vec2 i = floor(v + dot(v, C.yy) ); highp vec2 x0 = v - i + dot(i, C.xx); // Other corners highp vec2 i1; //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0 //i1.y = 1.0 - i1.x; i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0); // x0 = x0 - 0.0 + 0.0 * C.xx ; // x1 = x0 - i1 + 1.0 * C.xx ; // x2 = x0 - 1.0 + 2.0 * C.xx ; highp vec4 x12 = x0.xyxy + C.xxzz; x12.xy -= i1; // Permutations i = mod289(i); // Avoid truncation effects in permutation highp vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 )) + i.x + vec3(0.0, i1.x, 1.0 )); highp vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0); m = m*m ; m = m*m ; // Gradients: 41 points uniformly over a line, mapped onto a diamond. // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287) highp vec3 x = 2.0 * fract(p * C.www) - 1.0; highp vec3 h = abs(x) - 0.5; highp vec3 ox = floor(x + 0.5); highp vec3 a0 = x - ox; // Normalise gradients implicitly by scaling m // Approximation of: m *= inversesqrt( a0*a0 + h*h ); m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h ); // Compute final noise value at P highp vec3 g; g.x = a0.x * x0.x + h.x * x0.y; g.yz = a0.yz * x12.xz + h.yz * x12.yw; return 130.0 * dot(m, g); } float snoise(float x, float y) { return snoise(vec2(x, y)); } float noise(float x, float y, float a, float b) { return snoise(x * a / 256.0, y * b / 256.0); } vec3 mix(float a, vec3 v1, vec3 v2) { return v1 * (1.0 - a) + v2 * a; } float smoothStep(float w, float a, float b) { if (w>=b) return 1.0; if (w<=a) return 0.0; float d = b-a; return (w-a)/d; } vec3 colsca(vec3 c, float s) { return c * s; } vec3 eye(float x, float y, float b) { float rx = 2.0*(x-0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y; float ry = 2.0*(y-0.5); float a = atan(ry, rx); float e = rx*rx + ry*ry; float r = sqrt(e); vec3 fue = vec3(1.0, 1.0, 1.0); vec3 den = vec3(0.3, 0.7, 0.4 + e); // veins // float ven = noise(24 * x, 24 * y, 128, 128); // ven = smoothStep(ven, -0.2, 0.0) - smoothStep(ven, 0.0, 0.2); // ven += x + pow(x, 6) * 10; // fue.r += 0.04 - 0.00*ven; // fue.g += 0.04 - 0.05*ven; // fue.b += 0.04 - 0.05*ven; // circular pattern float noiseOffset = pow(sin(cycle_ratio * DEMOLOOP_M_PI), 2.0) * 1.0; float no = 0.8 + 0.2 * noise(4.0*r + noiseOffset, 32.0*a/DEMOLOOP_M_PI + noiseOffset, 256.0, 256.0); den = colsca(den, no); // iris float irisSize = 0.025 - (1.0 - pow(sin((cycle_ratio) * DEMOLOOP_M_PI), 3.0)) * 0.02; float f2 = smoothStep(e, irisSize, irisSize + 0.01); den = colsca(den, f2); vec3 mixed = mix(smoothStep(e, 0.35, 0.36), den, fue); // ring float ri = smoothStep(e, 0.31, 0.35) - smoothStep(e, 0.35, 0.36); ri = 1.0 - 0.35 * ri; mixed = colsca(mixed, ri); // reflection // float r3 = sqrt(r*r*r); // float re = noise(2.0+4.0*r3*cos(a), 4.0*r3*sin(a), 128.0, 128.0); // re = 0.4 * smoothStep(re, 0.1, 0.5); // mixed += re * (1.0 - mixed); // eye contours mixed=colsca(mixed,0.8+0.15*smoothStep(-b,0.0,0.2)); mixed=colsca(mixed,0.8+0.2*smoothStep(-b,0.0,0.05)); return mixed; } vec3 skin(float x, float y, float b) { float rx = 2.0*(x - 0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y; float ry = 2.0*(y - 0.5); vec3 skinColor = vec3(0.75, 0.69, 0.6); // float cel = 0.95 + 0.05 * noise(64.0*x, 64.0*y, 256.0, 256.0); // skinColor = colsca(skinColor, cel); // skinColor.r += 0.03 * rx; // skinColor.g += 0.03 * ry; // skinColor = colsca(skinColor, y * 0.1 + 0.9); // float bri = noise(128.0 * x, 128.0 * y, 256.0, 256.0); // bri = 0.2 + 0.8 * smoothStep(bri, 0.0, 0.3); // skinColor = mix(bri*0.08*y, skinColor, vec3(1, 1, 1)); // float san = 0.50*noise(16.0*x,16.0*y,256.0,256.0); // san+= 0.25*noise(32.0*x,32.0*y,256.0,256.0); // skinColor.g*=1-0.1*san; // float osc = 0.500*noise(16.0*x,16.0*y,256.0,256.0); // osc+= 0.250*noise(24.0*x,24.0*y,256.0,256.0); // osc+= 0.125*noise(48.0*x,48.0*y,256.0,256.0); // skinColor=colsca(skinColor,0.9+0.1*osc); // skinColor.r+=0.08*x; // skinColor.g+=0.01; // float pecas = noise(32.0*x,32.0*y,256.0,256.0); // pecas=smoothStep(pecas,0.80,0.8001); // skinColor *= 1.0 - 0.16*pecas; float g = smoothStep(1.0 - b, 0.2, 0.7); g -= smoothStep(1.0 - b, 0.8, 1.0) * 3.0; skinColor += g * 0.1; // skinColor = mix(0.14, skinColor, vec3(1.0, 1.0, 1.0)); // skinColor *= 1.23; // skinColor += 0.21; skinColor=colsca(skinColor,(1.0-(b*0.5))); return skinColor; } vec4 effect(vec4 color, Image texture, vec2 tc, vec2 screen_coords) { float t = cycle_ratio; float r = 0.0, g = 0.0, b = 0.0; float x = tc.x; float y = tc.y; float rx = 2.0*(x - 0.5)*demoloop_ScreenSize.x/demoloop_ScreenSize.y; float ry = 2.0*(y - 0.5); // float h = 3.0*sqrt(x*x*x)*(1.0-x); float h = (2.0*(1.0 - pow(sin(cycle_ratio * DEMOLOOP_M_PI), 5.0)) + 1.0)*sqrt(x*x*x)*(1.0-x); float e = abs(ry) - h; float f = smoothStep( e, 0.0, 0.01 ); float eyeX = x + cos(cycle_ratio * DEMOLOOP_M_PI * 2.0) * 0.1 - 0.1; // y += sin(cycle_ratio * DEMOLOOP_M_PI * 2) * 0.1; vec3 skinColor = skin(x, y, e); vec3 eyeColor = eye(eyeX, y, e); return vec4(mix(f, eyeColor, skinColor), 1.0); } #endif )==="; class Loop050 : public Demoloop { public: Loop050() : Demoloop(CYCLE_LENGTH, 150, 150, 150), shader({shaderCode, shaderCode}) { } void Update() { const float cycle_ratio = getCycleRatio(); shader.attach(); shader.sendFloat("cycle_ratio", 1, &cycle_ratio, 1); renderTexture(gl.getDefaultTexture(), 0, 0, width, height); shader.detach(); } private: Shader shader; }; int main(int, char**){ Loop050 test; test.Run(); return 0; }
6,813
3,671
#pragma once #include "biboumi.h" #ifdef BOTAN_FOUND #include <botan/credentials_manager.h> #include <botan/certstor.h> #include <botan/tls_client.h> class TCPSocketHandler; /** * If the given cert isn’t valid, based on the given hostname * and fingerprint, then throws the exception if it’s non-empty. * * Must be called after the standard (from Botan) way of * checking the certificate, if we want to also accept certificates based * on a trusted fingerprint. */ void check_tls_certificate(const std::vector<Botan::X509_Certificate>& certs, const std::string& hostname, const std::string& trusted_fingerprint, const std::exception_ptr& exc); class BasicCredentialsManager: public Botan::Credentials_Manager { public: BasicCredentialsManager(const TCPSocketHandler* const socket_handler); BasicCredentialsManager(BasicCredentialsManager&&) = delete; BasicCredentialsManager(const BasicCredentialsManager&) = delete; BasicCredentialsManager& operator=(const BasicCredentialsManager&) = delete; BasicCredentialsManager& operator=(BasicCredentialsManager&&) = delete; std::vector<Botan::Certificate_Store*> trusted_certificate_authorities(const std::string& type, const std::string& context) override final; void set_trusted_fingerprint(const std::string& fingerprint); const std::string& get_trusted_fingerprint() const; private: const TCPSocketHandler* const socket_handler; static bool try_to_open_one_ca_bundle(const std::vector<std::string>& paths); static void load_certs(); static Botan::Certificate_Store_In_Memory certificate_store; static bool certs_loaded; std::string trusted_fingerprint; }; #endif //BOTAN_FOUND
1,797
509
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: diplomacy_tensorflow/core/profiler/tfprof_options.proto #include "diplomacy_tensorflow/core/profiler/tfprof_options.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // This is a temporary google only hack #ifdef GOOGLE_PROTOBUF_ENFORCE_UNIQUENESS #include "third_party/protobuf/version.h" #endif // @@protoc_insertion_point(includes) namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto { extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto_CheckerOption; extern PROTOBUF_INTERNAL_EXPORT_protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto_CheckersEntry_DoNotUse; } // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto namespace diplomacy { namespace tensorflow { namespace tfprof { class OptionsProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<OptionsProto> _instance; } _OptionsProto_default_instance_; class AdvisorOptionsProto_CheckersEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AdvisorOptionsProto_CheckersEntry_DoNotUse> _instance; } _AdvisorOptionsProto_CheckersEntry_DoNotUse_default_instance_; class AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> _instance; } _AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse_default_instance_; class AdvisorOptionsProto_CheckerOptionDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AdvisorOptionsProto_CheckerOption> _instance; } _AdvisorOptionsProto_CheckerOption_default_instance_; class AdvisorOptionsProtoDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<AdvisorOptionsProto> _instance; } _AdvisorOptionsProto_default_instance_; } // namespace tfprof } // namespace tensorflow } // namespace diplomacy namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto { static void InitDefaultsOptionsProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_OptionsProto_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::OptionsProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::tfprof::OptionsProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_OptionsProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsOptionsProto}, {}}; static void InitDefaultsAdvisorOptionsProto_CheckersEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckersEntry_DoNotUse_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse(); } ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto_CheckersEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsAdvisorOptionsProto_CheckersEntry_DoNotUse}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckerOption.base,}}; static void InitDefaultsAdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse(); } ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsAdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse}, {}}; static void InitDefaultsAdvisorOptionsProto_CheckerOption() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckerOption_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto_CheckerOption = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsAdvisorOptionsProto_CheckerOption}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse.base,}}; static void InitDefaultsAdvisorOptionsProto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_default_instance_; new (ptr) ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_AdvisorOptionsProto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsAdvisorOptionsProto}, { &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckersEntry_DoNotUse.base,}}; void InitDefaults() { ::google::protobuf::internal::InitSCC(&scc_info_OptionsProto.base); ::google::protobuf::internal::InitSCC(&scc_info_AdvisorOptionsProto_CheckersEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse.base); ::google::protobuf::internal::InitSCC(&scc_info_AdvisorOptionsProto_CheckerOption.base); ::google::protobuf::internal::InitSCC(&scc_info_AdvisorOptionsProto.base); } ::google::protobuf::Metadata file_level_metadata[5]; const ::google::protobuf::uint32 TableStruct::offsets[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, max_depth_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_bytes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_peak_bytes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_residual_bytes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_output_bytes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_micros_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_accelerator_micros_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_cpu_micros_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_params_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_float_ops_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, min_occurrence_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, step_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, order_by_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, account_type_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, start_name_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, trim_name_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, show_name_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, hide_name_regexes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, account_displayed_op_only_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, select_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, output_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::OptionsProto, dump_to_file_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse, value_), 0, 1, GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, _has_bits_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, key_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption, options_), ~0u, // no _has_bits_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto, checkers_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::diplomacy::tensorflow::tfprof::OptionsProto)}, { 27, 34, sizeof(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse)}, { 36, 43, sizeof(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse)}, { 45, -1, sizeof(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption)}, { 51, -1, sizeof(::diplomacy::tensorflow::tfprof::AdvisorOptionsProto)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_OptionsProto_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckersEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_CheckerOption_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::diplomacy::tensorflow::tfprof::_AdvisorOptionsProto_default_instance_), }; void protobuf_AssignDescriptors() { AddDescriptors(); AssignDescriptors( "diplomacy_tensorflow/core/profiler/tfprof_options.proto", schemas, file_default_instances, TableStruct::offsets, file_level_metadata, NULL, NULL); } void protobuf_AssignDescriptorsOnce() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, protobuf_AssignDescriptors); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_PROTOBUF_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::internal::RegisterAllTypes(file_level_metadata, 5); } void AddDescriptorsImpl() { InitDefaults(); static const char descriptor[] GOOGLE_PROTOBUF_ATTRIBUTE_SECTION_VARIABLE(protodesc_cold) = { "\n7diplomacy_tensorflow/core/profiler/tfp" "rof_options.proto\022\033diplomacy.tensorflow." "tfprof\"\225\004\n\014OptionsProto\022\021\n\tmax_depth\030\001 \001" "(\003\022\021\n\tmin_bytes\030\002 \001(\003\022\026\n\016min_peak_bytes\030" "\023 \001(\003\022\032\n\022min_residual_bytes\030\024 \001(\003\022\030\n\020min" "_output_bytes\030\025 \001(\003\022\022\n\nmin_micros\030\003 \001(\003\022" "\036\n\026min_accelerator_micros\030\026 \001(\003\022\026\n\016min_c" "pu_micros\030\027 \001(\003\022\022\n\nmin_params\030\004 \001(\003\022\025\n\rm" "in_float_ops\030\005 \001(\003\022\026\n\016min_occurrence\030\021 \001" "(\003\022\014\n\004step\030\022 \001(\003\022\020\n\010order_by\030\007 \001(\t\022\034\n\024ac" "count_type_regexes\030\010 \003(\t\022\032\n\022start_name_r" "egexes\030\t \003(\t\022\031\n\021trim_name_regexes\030\n \003(\t\022" "\031\n\021show_name_regexes\030\013 \003(\t\022\031\n\021hide_name_" "regexes\030\014 \003(\t\022!\n\031account_displayed_op_on" "ly\030\r \001(\010\022\016\n\006select\030\016 \003(\t\022\016\n\006output\030\017 \001(\t" "\022\024\n\014dump_to_file\030\020 \001(\t\"\370\002\n\023AdvisorOption" "sProto\022P\n\010checkers\030\001 \003(\0132>.diplomacy.ten" "sorflow.tfprof.AdvisorOptionsProto.Check" "ersEntry\032o\n\rCheckersEntry\022\013\n\003key\030\001 \001(\t\022M" "\n\005value\030\002 \001(\0132>.diplomacy.tensorflow.tfp" "rof.AdvisorOptionsProto.CheckerOption:\0028" "\001\032\235\001\n\rCheckerOption\022\\\n\007options\030\001 \003(\0132K.d" "iplomacy.tensorflow.tfprof.AdvisorOption" "sProto.CheckerOption.OptionsEntry\032.\n\014Opt" "ionsEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028" "\001b\006proto3" }; ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( descriptor, 1009); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "diplomacy_tensorflow/core/profiler/tfprof_options.proto", &protobuf_RegisterTypes); } void AddDescriptors() { static ::google::protobuf::internal::once_flag once; ::google::protobuf::internal::call_once(once, AddDescriptorsImpl); } // Force AddDescriptors() to be called at dynamic initialization time. struct StaticDescriptorInitializer { StaticDescriptorInitializer() { AddDescriptors(); } } static_descriptor_initializer; } // namespace protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto namespace diplomacy { namespace tensorflow { namespace tfprof { // =================================================================== void OptionsProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int OptionsProto::kMaxDepthFieldNumber; const int OptionsProto::kMinBytesFieldNumber; const int OptionsProto::kMinPeakBytesFieldNumber; const int OptionsProto::kMinResidualBytesFieldNumber; const int OptionsProto::kMinOutputBytesFieldNumber; const int OptionsProto::kMinMicrosFieldNumber; const int OptionsProto::kMinAcceleratorMicrosFieldNumber; const int OptionsProto::kMinCpuMicrosFieldNumber; const int OptionsProto::kMinParamsFieldNumber; const int OptionsProto::kMinFloatOpsFieldNumber; const int OptionsProto::kMinOccurrenceFieldNumber; const int OptionsProto::kStepFieldNumber; const int OptionsProto::kOrderByFieldNumber; const int OptionsProto::kAccountTypeRegexesFieldNumber; const int OptionsProto::kStartNameRegexesFieldNumber; const int OptionsProto::kTrimNameRegexesFieldNumber; const int OptionsProto::kShowNameRegexesFieldNumber; const int OptionsProto::kHideNameRegexesFieldNumber; const int OptionsProto::kAccountDisplayedOpOnlyFieldNumber; const int OptionsProto::kSelectFieldNumber; const int OptionsProto::kOutputFieldNumber; const int OptionsProto::kDumpToFileFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 OptionsProto::OptionsProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_OptionsProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.tfprof.OptionsProto) } OptionsProto::OptionsProto(const OptionsProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL), account_type_regexes_(from.account_type_regexes_), start_name_regexes_(from.start_name_regexes_), trim_name_regexes_(from.trim_name_regexes_), show_name_regexes_(from.show_name_regexes_), hide_name_regexes_(from.hide_name_regexes_), select_(from.select_) { _internal_metadata_.MergeFrom(from._internal_metadata_); order_by_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.order_by().size() > 0) { order_by_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.order_by_); } output_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.output().size() > 0) { output_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.output_); } dump_to_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.dump_to_file().size() > 0) { dump_to_file_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.dump_to_file_); } ::memcpy(&max_depth_, &from.max_depth_, static_cast<size_t>(reinterpret_cast<char*>(&account_displayed_op_only_) - reinterpret_cast<char*>(&max_depth_)) + sizeof(account_displayed_op_only_)); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.tfprof.OptionsProto) } void OptionsProto::SharedCtor() { order_by_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); output_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dump_to_file_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&max_depth_, 0, static_cast<size_t>( reinterpret_cast<char*>(&account_displayed_op_only_) - reinterpret_cast<char*>(&max_depth_)) + sizeof(account_displayed_op_only_)); } OptionsProto::~OptionsProto() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.tfprof.OptionsProto) SharedDtor(); } void OptionsProto::SharedDtor() { order_by_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); output_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dump_to_file_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void OptionsProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* OptionsProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const OptionsProto& OptionsProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_OptionsProto.base); return *internal_default_instance(); } void OptionsProto::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.tfprof.OptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; account_type_regexes_.Clear(); start_name_regexes_.Clear(); trim_name_regexes_.Clear(); show_name_regexes_.Clear(); hide_name_regexes_.Clear(); select_.Clear(); order_by_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); output_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dump_to_file_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); ::memset(&max_depth_, 0, static_cast<size_t>( reinterpret_cast<char*>(&account_displayed_op_only_) - reinterpret_cast<char*>(&max_depth_)) + sizeof(account_displayed_op_only_)); _internal_metadata_.Clear(); } bool OptionsProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.tfprof.OptionsProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(16383u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int64 max_depth = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(8u /* 8 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &max_depth_))); } else { goto handle_unusual; } break; } // int64 min_bytes = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(16u /* 16 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_bytes_))); } else { goto handle_unusual; } break; } // int64 min_micros = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(24u /* 24 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_micros_))); } else { goto handle_unusual; } break; } // int64 min_params = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(32u /* 32 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_params_))); } else { goto handle_unusual; } break; } // int64 min_float_ops = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(40u /* 40 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_float_ops_))); } else { goto handle_unusual; } break; } // string order_by = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(58u /* 58 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_order_by())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->order_by().data(), static_cast<int>(this->order_by().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.order_by")); } else { goto handle_unusual; } break; } // repeated string account_type_regexes = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(66u /* 66 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_account_type_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->account_type_regexes(this->account_type_regexes_size() - 1).data(), static_cast<int>(this->account_type_regexes(this->account_type_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.account_type_regexes")); } else { goto handle_unusual; } break; } // repeated string start_name_regexes = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(74u /* 74 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_start_name_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->start_name_regexes(this->start_name_regexes_size() - 1).data(), static_cast<int>(this->start_name_regexes(this->start_name_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.start_name_regexes")); } else { goto handle_unusual; } break; } // repeated string trim_name_regexes = 10; case 10: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(82u /* 82 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_trim_name_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->trim_name_regexes(this->trim_name_regexes_size() - 1).data(), static_cast<int>(this->trim_name_regexes(this->trim_name_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.trim_name_regexes")); } else { goto handle_unusual; } break; } // repeated string show_name_regexes = 11; case 11: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(90u /* 90 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_show_name_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->show_name_regexes(this->show_name_regexes_size() - 1).data(), static_cast<int>(this->show_name_regexes(this->show_name_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.show_name_regexes")); } else { goto handle_unusual; } break; } // repeated string hide_name_regexes = 12; case 12: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(98u /* 98 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_hide_name_regexes())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->hide_name_regexes(this->hide_name_regexes_size() - 1).data(), static_cast<int>(this->hide_name_regexes(this->hide_name_regexes_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.hide_name_regexes")); } else { goto handle_unusual; } break; } // bool account_displayed_op_only = 13; case 13: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(104u /* 104 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &account_displayed_op_only_))); } else { goto handle_unusual; } break; } // repeated string select = 14; case 14: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(114u /* 114 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_select())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->select(this->select_size() - 1).data(), static_cast<int>(this->select(this->select_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.select")); } else { goto handle_unusual; } break; } // string output = 15; case 15: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(122u /* 122 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_output())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->output().data(), static_cast<int>(this->output().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.output")); } else { goto handle_unusual; } break; } // string dump_to_file = 16; case 16: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(130u /* 130 & 0xFF */)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_dump_to_file())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dump_to_file().data(), static_cast<int>(this->dump_to_file().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.OptionsProto.dump_to_file")); } else { goto handle_unusual; } break; } // int64 min_occurrence = 17; case 17: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(136u /* 136 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_occurrence_))); } else { goto handle_unusual; } break; } // int64 step = 18; case 18: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(144u /* 144 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &step_))); } else { goto handle_unusual; } break; } // int64 min_peak_bytes = 19; case 19: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(152u /* 152 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_peak_bytes_))); } else { goto handle_unusual; } break; } // int64 min_residual_bytes = 20; case 20: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(160u /* 160 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_residual_bytes_))); } else { goto handle_unusual; } break; } // int64 min_output_bytes = 21; case 21: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(168u /* 168 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_output_bytes_))); } else { goto handle_unusual; } break; } // int64 min_accelerator_micros = 22; case 22: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(176u /* 176 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_accelerator_micros_))); } else { goto handle_unusual; } break; } // int64 min_cpu_micros = 23; case 23: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(184u /* 184 & 0xFF */)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &min_cpu_micros_))); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.tfprof.OptionsProto) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.tfprof.OptionsProto) return false; #undef DO_ } void OptionsProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.tfprof.OptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 max_depth = 1; if (this->max_depth() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->max_depth(), output); } // int64 min_bytes = 2; if (this->min_bytes() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->min_bytes(), output); } // int64 min_micros = 3; if (this->min_micros() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(3, this->min_micros(), output); } // int64 min_params = 4; if (this->min_params() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->min_params(), output); } // int64 min_float_ops = 5; if (this->min_float_ops() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(5, this->min_float_ops(), output); } // string order_by = 7; if (this->order_by().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->order_by().data(), static_cast<int>(this->order_by().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.order_by"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 7, this->order_by(), output); } // repeated string account_type_regexes = 8; for (int i = 0, n = this->account_type_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->account_type_regexes(i).data(), static_cast<int>(this->account_type_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.account_type_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 8, this->account_type_regexes(i), output); } // repeated string start_name_regexes = 9; for (int i = 0, n = this->start_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->start_name_regexes(i).data(), static_cast<int>(this->start_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.start_name_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 9, this->start_name_regexes(i), output); } // repeated string trim_name_regexes = 10; for (int i = 0, n = this->trim_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->trim_name_regexes(i).data(), static_cast<int>(this->trim_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.trim_name_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 10, this->trim_name_regexes(i), output); } // repeated string show_name_regexes = 11; for (int i = 0, n = this->show_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->show_name_regexes(i).data(), static_cast<int>(this->show_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.show_name_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 11, this->show_name_regexes(i), output); } // repeated string hide_name_regexes = 12; for (int i = 0, n = this->hide_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->hide_name_regexes(i).data(), static_cast<int>(this->hide_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.hide_name_regexes"); ::google::protobuf::internal::WireFormatLite::WriteString( 12, this->hide_name_regexes(i), output); } // bool account_displayed_op_only = 13; if (this->account_displayed_op_only() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(13, this->account_displayed_op_only(), output); } // repeated string select = 14; for (int i = 0, n = this->select_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->select(i).data(), static_cast<int>(this->select(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.select"); ::google::protobuf::internal::WireFormatLite::WriteString( 14, this->select(i), output); } // string output = 15; if (this->output().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->output().data(), static_cast<int>(this->output().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.output"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 15, this->output(), output); } // string dump_to_file = 16; if (this->dump_to_file().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dump_to_file().data(), static_cast<int>(this->dump_to_file().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.dump_to_file"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 16, this->dump_to_file(), output); } // int64 min_occurrence = 17; if (this->min_occurrence() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(17, this->min_occurrence(), output); } // int64 step = 18; if (this->step() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(18, this->step(), output); } // int64 min_peak_bytes = 19; if (this->min_peak_bytes() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(19, this->min_peak_bytes(), output); } // int64 min_residual_bytes = 20; if (this->min_residual_bytes() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(20, this->min_residual_bytes(), output); } // int64 min_output_bytes = 21; if (this->min_output_bytes() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(21, this->min_output_bytes(), output); } // int64 min_accelerator_micros = 22; if (this->min_accelerator_micros() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(22, this->min_accelerator_micros(), output); } // int64 min_cpu_micros = 23; if (this->min_cpu_micros() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(23, this->min_cpu_micros(), output); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.tfprof.OptionsProto) } ::google::protobuf::uint8* OptionsProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.tfprof.OptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int64 max_depth = 1; if (this->max_depth() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->max_depth(), target); } // int64 min_bytes = 2; if (this->min_bytes() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->min_bytes(), target); } // int64 min_micros = 3; if (this->min_micros() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(3, this->min_micros(), target); } // int64 min_params = 4; if (this->min_params() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->min_params(), target); } // int64 min_float_ops = 5; if (this->min_float_ops() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(5, this->min_float_ops(), target); } // string order_by = 7; if (this->order_by().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->order_by().data(), static_cast<int>(this->order_by().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.order_by"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 7, this->order_by(), target); } // repeated string account_type_regexes = 8; for (int i = 0, n = this->account_type_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->account_type_regexes(i).data(), static_cast<int>(this->account_type_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.account_type_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(8, this->account_type_regexes(i), target); } // repeated string start_name_regexes = 9; for (int i = 0, n = this->start_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->start_name_regexes(i).data(), static_cast<int>(this->start_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.start_name_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(9, this->start_name_regexes(i), target); } // repeated string trim_name_regexes = 10; for (int i = 0, n = this->trim_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->trim_name_regexes(i).data(), static_cast<int>(this->trim_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.trim_name_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(10, this->trim_name_regexes(i), target); } // repeated string show_name_regexes = 11; for (int i = 0, n = this->show_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->show_name_regexes(i).data(), static_cast<int>(this->show_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.show_name_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(11, this->show_name_regexes(i), target); } // repeated string hide_name_regexes = 12; for (int i = 0, n = this->hide_name_regexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->hide_name_regexes(i).data(), static_cast<int>(this->hide_name_regexes(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.hide_name_regexes"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(12, this->hide_name_regexes(i), target); } // bool account_displayed_op_only = 13; if (this->account_displayed_op_only() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(13, this->account_displayed_op_only(), target); } // repeated string select = 14; for (int i = 0, n = this->select_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->select(i).data(), static_cast<int>(this->select(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.select"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(14, this->select(i), target); } // string output = 15; if (this->output().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->output().data(), static_cast<int>(this->output().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.output"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 15, this->output(), target); } // string dump_to_file = 16; if (this->dump_to_file().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dump_to_file().data(), static_cast<int>(this->dump_to_file().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.OptionsProto.dump_to_file"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 16, this->dump_to_file(), target); } // int64 min_occurrence = 17; if (this->min_occurrence() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(17, this->min_occurrence(), target); } // int64 step = 18; if (this->step() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(18, this->step(), target); } // int64 min_peak_bytes = 19; if (this->min_peak_bytes() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(19, this->min_peak_bytes(), target); } // int64 min_residual_bytes = 20; if (this->min_residual_bytes() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(20, this->min_residual_bytes(), target); } // int64 min_output_bytes = 21; if (this->min_output_bytes() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(21, this->min_output_bytes(), target); } // int64 min_accelerator_micros = 22; if (this->min_accelerator_micros() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(22, this->min_accelerator_micros(), target); } // int64 min_cpu_micros = 23; if (this->min_cpu_micros() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(23, this->min_cpu_micros(), target); } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.tfprof.OptionsProto) return target; } size_t OptionsProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.tfprof.OptionsProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // repeated string account_type_regexes = 8; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->account_type_regexes_size()); for (int i = 0, n = this->account_type_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->account_type_regexes(i)); } // repeated string start_name_regexes = 9; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->start_name_regexes_size()); for (int i = 0, n = this->start_name_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->start_name_regexes(i)); } // repeated string trim_name_regexes = 10; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->trim_name_regexes_size()); for (int i = 0, n = this->trim_name_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->trim_name_regexes(i)); } // repeated string show_name_regexes = 11; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->show_name_regexes_size()); for (int i = 0, n = this->show_name_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->show_name_regexes(i)); } // repeated string hide_name_regexes = 12; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->hide_name_regexes_size()); for (int i = 0, n = this->hide_name_regexes_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->hide_name_regexes(i)); } // repeated string select = 14; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->select_size()); for (int i = 0, n = this->select_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->select(i)); } // string order_by = 7; if (this->order_by().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->order_by()); } // string output = 15; if (this->output().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->output()); } // string dump_to_file = 16; if (this->dump_to_file().size() > 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::StringSize( this->dump_to_file()); } // int64 max_depth = 1; if (this->max_depth() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->max_depth()); } // int64 min_bytes = 2; if (this->min_bytes() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_bytes()); } // int64 min_micros = 3; if (this->min_micros() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_micros()); } // int64 min_params = 4; if (this->min_params() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_params()); } // int64 min_float_ops = 5; if (this->min_float_ops() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_float_ops()); } // int64 min_occurrence = 17; if (this->min_occurrence() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_occurrence()); } // int64 step = 18; if (this->step() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->step()); } // int64 min_peak_bytes = 19; if (this->min_peak_bytes() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_peak_bytes()); } // int64 min_residual_bytes = 20; if (this->min_residual_bytes() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_residual_bytes()); } // int64 min_output_bytes = 21; if (this->min_output_bytes() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_output_bytes()); } // int64 min_accelerator_micros = 22; if (this->min_accelerator_micros() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_accelerator_micros()); } // int64 min_cpu_micros = 23; if (this->min_cpu_micros() != 0) { total_size += 2 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->min_cpu_micros()); } // bool account_displayed_op_only = 13; if (this->account_displayed_op_only() != 0) { total_size += 1 + 1; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void OptionsProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.tfprof.OptionsProto) GOOGLE_DCHECK_NE(&from, this); const OptionsProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const OptionsProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.tfprof.OptionsProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.tfprof.OptionsProto) MergeFrom(*source); } } void OptionsProto::MergeFrom(const OptionsProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.tfprof.OptionsProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; account_type_regexes_.MergeFrom(from.account_type_regexes_); start_name_regexes_.MergeFrom(from.start_name_regexes_); trim_name_regexes_.MergeFrom(from.trim_name_regexes_); show_name_regexes_.MergeFrom(from.show_name_regexes_); hide_name_regexes_.MergeFrom(from.hide_name_regexes_); select_.MergeFrom(from.select_); if (from.order_by().size() > 0) { order_by_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.order_by_); } if (from.output().size() > 0) { output_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.output_); } if (from.dump_to_file().size() > 0) { dump_to_file_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.dump_to_file_); } if (from.max_depth() != 0) { set_max_depth(from.max_depth()); } if (from.min_bytes() != 0) { set_min_bytes(from.min_bytes()); } if (from.min_micros() != 0) { set_min_micros(from.min_micros()); } if (from.min_params() != 0) { set_min_params(from.min_params()); } if (from.min_float_ops() != 0) { set_min_float_ops(from.min_float_ops()); } if (from.min_occurrence() != 0) { set_min_occurrence(from.min_occurrence()); } if (from.step() != 0) { set_step(from.step()); } if (from.min_peak_bytes() != 0) { set_min_peak_bytes(from.min_peak_bytes()); } if (from.min_residual_bytes() != 0) { set_min_residual_bytes(from.min_residual_bytes()); } if (from.min_output_bytes() != 0) { set_min_output_bytes(from.min_output_bytes()); } if (from.min_accelerator_micros() != 0) { set_min_accelerator_micros(from.min_accelerator_micros()); } if (from.min_cpu_micros() != 0) { set_min_cpu_micros(from.min_cpu_micros()); } if (from.account_displayed_op_only() != 0) { set_account_displayed_op_only(from.account_displayed_op_only()); } } void OptionsProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.tfprof.OptionsProto) if (&from == this) return; Clear(); MergeFrom(from); } void OptionsProto::CopyFrom(const OptionsProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.tfprof.OptionsProto) if (&from == this) return; Clear(); MergeFrom(from); } bool OptionsProto::IsInitialized() const { return true; } void OptionsProto::Swap(OptionsProto* other) { if (other == this) return; InternalSwap(other); } void OptionsProto::InternalSwap(OptionsProto* other) { using std::swap; account_type_regexes_.InternalSwap(CastToBase(&other->account_type_regexes_)); start_name_regexes_.InternalSwap(CastToBase(&other->start_name_regexes_)); trim_name_regexes_.InternalSwap(CastToBase(&other->trim_name_regexes_)); show_name_regexes_.InternalSwap(CastToBase(&other->show_name_regexes_)); hide_name_regexes_.InternalSwap(CastToBase(&other->hide_name_regexes_)); select_.InternalSwap(CastToBase(&other->select_)); order_by_.Swap(&other->order_by_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); output_.Swap(&other->output_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); dump_to_file_.Swap(&other->dump_to_file_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(max_depth_, other->max_depth_); swap(min_bytes_, other->min_bytes_); swap(min_micros_, other->min_micros_); swap(min_params_, other->min_params_); swap(min_float_ops_, other->min_float_ops_); swap(min_occurrence_, other->min_occurrence_); swap(step_, other->step_); swap(min_peak_bytes_, other->min_peak_bytes_); swap(min_residual_bytes_, other->min_residual_bytes_); swap(min_output_bytes_, other->min_output_bytes_); swap(min_accelerator_micros_, other->min_accelerator_micros_); swap(min_cpu_micros_, other->min_cpu_micros_); swap(account_displayed_op_only_, other->account_displayed_op_only_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata OptionsProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== AdvisorOptionsProto_CheckersEntry_DoNotUse::AdvisorOptionsProto_CheckersEntry_DoNotUse() {} AdvisorOptionsProto_CheckersEntry_DoNotUse::AdvisorOptionsProto_CheckersEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void AdvisorOptionsProto_CheckersEntry_DoNotUse::MergeFrom(const AdvisorOptionsProto_CheckersEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata AdvisorOptionsProto_CheckersEntry_DoNotUse::GetMetadata() const { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[1]; } void AdvisorOptionsProto_CheckersEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse() {} AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::MergeFrom(const AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::GetMetadata() const { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[2]; } void AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } // =================================================================== void AdvisorOptionsProto_CheckerOption::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int AdvisorOptionsProto_CheckerOption::kOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 AdvisorOptionsProto_CheckerOption::AdvisorOptionsProto_CheckerOption() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckerOption.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) } AdvisorOptionsProto_CheckerOption::AdvisorOptionsProto_CheckerOption(const AdvisorOptionsProto_CheckerOption& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); options_.MergeFrom(from.options_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) } void AdvisorOptionsProto_CheckerOption::SharedCtor() { } AdvisorOptionsProto_CheckerOption::~AdvisorOptionsProto_CheckerOption() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) SharedDtor(); } void AdvisorOptionsProto_CheckerOption::SharedDtor() { } void AdvisorOptionsProto_CheckerOption::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* AdvisorOptionsProto_CheckerOption::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const AdvisorOptionsProto_CheckerOption& AdvisorOptionsProto_CheckerOption::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto_CheckerOption.base); return *internal_default_instance(); } void AdvisorOptionsProto_CheckerOption::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; options_.Clear(); _internal_metadata_.Clear(); } bool AdvisorOptionsProto_CheckerOption::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // map<string, string> options = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 >, ::google::protobuf::Map< ::std::string, ::std::string > > parser(&options_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), static_cast<int>(parser.value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.value")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) return false; #undef DO_ } void AdvisorOptionsProto_CheckerOption::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, string> options = 1; if (!this->options().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.value"); } }; if (output->IsSerializationDeterministic() && this->options().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->options().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(options_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it) { entry.reset(options_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) } ::google::protobuf::uint8* AdvisorOptionsProto_CheckerOption::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, string> options = 1; if (!this->options().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption.OptionsEntry.value"); } }; if (deterministic && this->options().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->options().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(options_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it) { entry.reset(options_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) return target; } size_t AdvisorOptionsProto_CheckerOption::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<string, string> options = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->options_size()); { ::std::unique_ptr<AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->options().begin(); it != this->options().end(); ++it) { entry.reset(options_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void AdvisorOptionsProto_CheckerOption::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) GOOGLE_DCHECK_NE(&from, this); const AdvisorOptionsProto_CheckerOption* source = ::google::protobuf::internal::DynamicCastToGenerated<const AdvisorOptionsProto_CheckerOption>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) MergeFrom(*source); } } void AdvisorOptionsProto_CheckerOption::MergeFrom(const AdvisorOptionsProto_CheckerOption& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; options_.MergeFrom(from.options_); } void AdvisorOptionsProto_CheckerOption::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) if (&from == this) return; Clear(); MergeFrom(from); } void AdvisorOptionsProto_CheckerOption::CopyFrom(const AdvisorOptionsProto_CheckerOption& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption) if (&from == this) return; Clear(); MergeFrom(from); } bool AdvisorOptionsProto_CheckerOption::IsInitialized() const { return true; } void AdvisorOptionsProto_CheckerOption::Swap(AdvisorOptionsProto_CheckerOption* other) { if (other == this) return; InternalSwap(other); } void AdvisorOptionsProto_CheckerOption::InternalSwap(AdvisorOptionsProto_CheckerOption* other) { using std::swap; options_.Swap(&other->options_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata AdvisorOptionsProto_CheckerOption::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages]; } // =================================================================== void AdvisorOptionsProto::InitAsDefaultInstance() { } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int AdvisorOptionsProto::kCheckersFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 AdvisorOptionsProto::AdvisorOptionsProto() : ::google::protobuf::Message(), _internal_metadata_(NULL) { ::google::protobuf::internal::InitSCC( &protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto.base); SharedCtor(); // @@protoc_insertion_point(constructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) } AdvisorOptionsProto::AdvisorOptionsProto(const AdvisorOptionsProto& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { _internal_metadata_.MergeFrom(from._internal_metadata_); checkers_.MergeFrom(from.checkers_); // @@protoc_insertion_point(copy_constructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) } void AdvisorOptionsProto::SharedCtor() { } AdvisorOptionsProto::~AdvisorOptionsProto() { // @@protoc_insertion_point(destructor:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) SharedDtor(); } void AdvisorOptionsProto::SharedDtor() { } void AdvisorOptionsProto::SetCachedSize(int size) const { _cached_size_.Set(size); } const ::google::protobuf::Descriptor* AdvisorOptionsProto::descriptor() { ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages].descriptor; } const AdvisorOptionsProto& AdvisorOptionsProto::default_instance() { ::google::protobuf::internal::InitSCC(&protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::scc_info_AdvisorOptionsProto.base); return *internal_default_instance(); } void AdvisorOptionsProto::Clear() { // @@protoc_insertion_point(message_clear_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; checkers_.Clear(); _internal_metadata_.Clear(); } bool AdvisorOptionsProto::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // map<string, .diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption> checkers = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == static_cast< ::google::protobuf::uint8>(10u /* 10 & 0xFF */)) { AdvisorOptionsProto_CheckersEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< AdvisorOptionsProto_CheckersEntry_DoNotUse, ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_MESSAGE, 0 >, ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption > > parser(&checkers_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckersEntry.key")); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) return true; failure: // @@protoc_insertion_point(parse_failure:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) return false; #undef DO_ } void AdvisorOptionsProto::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption> checkers = 1; if (!this->checkers().empty()) { typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckersEntry.key"); } }; if (output->IsSerializationDeterministic() && this->checkers().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->checkers().size()]); typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(checkers_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it) { entry.reset(checkers_.NewEntryWrapper( it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *entry, output); Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), output); } // @@protoc_insertion_point(serialize_end:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) } ::google::protobuf::uint8* AdvisorOptionsProto::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // map<string, .diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption> checkers = 1; if (!this->checkers().empty()) { typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckersEntry.key"); } }; if (deterministic && this->checkers().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->checkers().size()]); typedef ::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it, ++n) { items[static_cast<ptrdiff_t>(n)] = SortItem(&*it); } ::std::sort(&items[0], &items[static_cast<ptrdiff_t>(n)], Less()); ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(checkers_.NewEntryWrapper( items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; Utf8Check::Check(items[static_cast<ptrdiff_t>(i)]); } } else { ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it) { entry.reset(checkers_.NewEntryWrapper( it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *entry, deterministic, target); ; Utf8Check::Check(&*it); } } } if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance()), target); } // @@protoc_insertion_point(serialize_to_array_end:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) return target; } size_t AdvisorOptionsProto::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) size_t total_size = 0; if ((_internal_metadata_.have_unknown_fields() && ::google::protobuf::internal::GetProto3PreserveUnknownsDefault())) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( (::google::protobuf::internal::GetProto3PreserveUnknownsDefault() ? _internal_metadata_.unknown_fields() : _internal_metadata_.default_instance())); } // map<string, .diplomacy.tensorflow.tfprof.AdvisorOptionsProto.CheckerOption> checkers = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->checkers_size()); { ::std::unique_ptr<AdvisorOptionsProto_CheckersEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >::const_iterator it = this->checkers().begin(); it != this->checkers().end(); ++it) { entry.reset(checkers_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void AdvisorOptionsProto::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) GOOGLE_DCHECK_NE(&from, this); const AdvisorOptionsProto* source = ::google::protobuf::internal::DynamicCastToGenerated<const AdvisorOptionsProto>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) MergeFrom(*source); } } void AdvisorOptionsProto::MergeFrom(const AdvisorOptionsProto& from) { // @@protoc_insertion_point(class_specific_merge_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; checkers_.MergeFrom(from.checkers_); } void AdvisorOptionsProto::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) if (&from == this) return; Clear(); MergeFrom(from); } void AdvisorOptionsProto::CopyFrom(const AdvisorOptionsProto& from) { // @@protoc_insertion_point(class_specific_copy_from_start:diplomacy.tensorflow.tfprof.AdvisorOptionsProto) if (&from == this) return; Clear(); MergeFrom(from); } bool AdvisorOptionsProto::IsInitialized() const { return true; } void AdvisorOptionsProto::Swap(AdvisorOptionsProto* other) { if (other == this) return; InternalSwap(other); } void AdvisorOptionsProto::InternalSwap(AdvisorOptionsProto* other) { using std::swap; checkers_.Swap(&other->checkers_); _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata AdvisorOptionsProto::GetMetadata() const { protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::protobuf_AssignDescriptorsOnce(); return ::protobuf_diplomacy_5ftensorflow_2fcore_2fprofiler_2ftfprof_5foptions_2eproto::file_level_metadata[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace tfprof } // namespace tensorflow } // namespace diplomacy namespace google { namespace protobuf { template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::OptionsProto* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::OptionsProto >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::OptionsProto >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckersEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption_OptionsEntry_DoNotUse >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto_CheckerOption >(arena); } template<> GOOGLE_PROTOBUF_ATTRIBUTE_NOINLINE ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto* Arena::CreateMaybeMessage< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto >(Arena* arena) { return Arena::CreateInternal< ::diplomacy::tensorflow::tfprof::AdvisorOptionsProto >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope)
98,005
34,443
/* mbed Microcontroller Library * Copyright (c) 2006-2019 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "drivers/PwmOut.h" #if DEVICE_PWMOUT #include "platform/mbed_critical.h" #include "platform/mbed_power_mgmt.h" #include "platform/mbed_assert.h" namespace mbed { PwmOut::PwmOut(PinName pin) : _pin(pin), _deep_sleep_locked(false), _initialized(false), _duty_cycle(0) { PwmOut::init(); } PwmOut::PwmOut(const PinMap &pinmap) : _deep_sleep_locked(false) { core_util_critical_section_enter(); pwmout_init_direct(&_pwm, &pinmap); core_util_critical_section_exit(); } PwmOut::~PwmOut() { PwmOut::deinit(); } void PwmOut::write(float value) { core_util_critical_section_enter(); pwmout_write(&_pwm, value); core_util_critical_section_exit(); } float PwmOut::read() { core_util_critical_section_enter(); float val = pwmout_read(&_pwm); core_util_critical_section_exit(); return val; } void PwmOut::period(float seconds) { core_util_critical_section_enter(); pwmout_period(&_pwm, seconds); core_util_critical_section_exit(); } void PwmOut::period_ms(int ms) { core_util_critical_section_enter(); pwmout_period_ms(&_pwm, ms); core_util_critical_section_exit(); } void PwmOut::period_us(int us) { core_util_critical_section_enter(); pwmout_period_us(&_pwm, us); core_util_critical_section_exit(); } void PwmOut::pulsewidth(float seconds) { core_util_critical_section_enter(); pwmout_pulsewidth(&_pwm, seconds); core_util_critical_section_exit(); } void PwmOut::pulsewidth_ms(int ms) { core_util_critical_section_enter(); pwmout_pulsewidth_ms(&_pwm, ms); core_util_critical_section_exit(); } void PwmOut::pulsewidth_us(int us) { core_util_critical_section_enter(); pwmout_pulsewidth_us(&_pwm, us); core_util_critical_section_exit(); } void PwmOut::suspend() { core_util_critical_section_enter(); if (_initialized) { _duty_cycle = PwmOut::read(); PwmOut::deinit(); } core_util_critical_section_exit(); } void PwmOut::resume() { core_util_critical_section_enter(); if (!_initialized) { PwmOut::init(); PwmOut::write(_duty_cycle); } core_util_critical_section_exit(); } void PwmOut::lock_deep_sleep() { if (_deep_sleep_locked == false) { sleep_manager_lock_deep_sleep(); _deep_sleep_locked = true; } } void PwmOut::unlock_deep_sleep() { if (_deep_sleep_locked == true) { sleep_manager_unlock_deep_sleep(); _deep_sleep_locked = false; } } void PwmOut::init() { core_util_critical_section_enter(); if (!_initialized) { pwmout_init(&_pwm, _pin); lock_deep_sleep(); _initialized = true; } core_util_critical_section_exit(); } void PwmOut::deinit() { core_util_critical_section_enter(); if (_initialized) { pwmout_free(&_pwm); unlock_deep_sleep(); _initialized = false; } core_util_critical_section_exit(); } } // namespace mbed #endif // #if DEVICE_PWMOUT
3,845
1,467
/* * ASCLITE * Author: Jerome Ajot, Jon Fiscus, Nicolas Radde, Chris Laprun * * This software was developed at the National Institute of Standards and Technology by * employees of the Federal Government in the course of their official duties. Pursuant * to title 17 Section 105 of the United States Code this software is not subject to * copyright protection and is in the public domain. ASCLITE is an experimental system. * NIST assumes no responsibility whatsoever for its use by other parties, and makes no * guarantees, expressed or implied, about its quality, reliability, or any other * characteristic. We would appreciate acknowledgement if the software is used. * * THIS SOFTWARE IS PROVIDED "AS IS." With regard to this software, NIST MAKES NO EXPRESS * OR IMPLIED WARRANTY AS TO ANY MATTER WHATSOEVER, INCLUDING MERCHANTABILITY, * OR FITNESS FOR A PARTICULAR PURPOSE. */ #include "alignment_test.h" #include "graphalignedsegment.h" #include "alignedspeech.h" AlignmentTest::AlignmentTest() { bench = new StdBenchmark(); } AlignmentTest::~AlignmentTest() { //delete bench; } void AlignmentTest::TestAll() { cout << "Testing insertions..." << endl; TestInsertions(); cout << "OK!" << endl; cout << "Testing deletions..." << endl; TestDeletions(); cout << "OK!" << endl; } void AlignmentTest::TestInsertions() { Alignment* ali; SegmentsGroup* sg; std::size_t testIndex = 2; // simple insertion, one segment ali = GetAlignmentFor(testIndex, &sg); Segment* ref = sg->GetReference(0)[0]; Segment* hyp = sg->GetHypothesis(0)[0]; vector< Token* > refs = ref->ToTopologicalOrderedStruct(); vector< Token* > hyps = hyp->ToTopologicalOrderedStruct(); cout << "Single Insertion tests:" << endl; cout << "\tCheck speech and segment..."; cout.flush(); Speech* refSpeech = ref->GetParentSpeech(); AlignedSpeech* asp = ali->GetOrCreateAlignedSpeechFor(refSpeech, false); assert(refSpeech == asp->GetReferenceSpeech()); AlignedSegment* asg = asp->GetOrCreateAlignedSegmentFor(ref, false); assert(ref == asg->GetReferenceSegment()); assert(asg->GetTokenAlignmentCount() == 3); cout << " OK." << endl; cout << "\tCheck tokens..."; cout.flush(); TokenAlignment* ta = asg->GetTokenAlignmentAt(0); assert(ta->GetReferenceToken() == refs[0]); assert(ta->GetTokenFor("hyp") == hyps[0]); ta = asg->GetTokenAlignmentAt(1); assert(ta->GetReferenceToken() == NULL); assert(ta->GetTokenFor("hyp") == hyps[1]); ta = asg->GetTokenAlignmentAt(2); assert(ta->GetReferenceToken() == refs[1]); assert(ta->GetTokenFor("hyp") == hyps[2]); cout << " OK." << endl; testIndex = 4; // only insertion, one segment ali = GetAlignmentFor(testIndex, &sg); ref = sg->GetReference(0)[0]; hyp = sg->GetHypothesis(0)[0]; refs = ref->ToTopologicalOrderedStruct(); hyps = hyp->ToTopologicalOrderedStruct(); cout << "Only Insertion tests:" << endl; cout << "\tCheck speech and segment..."; cout.flush(); refSpeech = ref->GetParentSpeech(); asp = ali->GetOrCreateAlignedSpeechFor(refSpeech, false); assert(refSpeech == asp->GetReferenceSpeech()); asg = asp->GetOrCreateAlignedSegmentFor(ref, false); assert(ref == asg->GetReferenceSegment()); assert(asg->GetTokenAlignmentCount() == 3); cout << " OK." << endl; cout << "\tCheck tokens..."; cout.flush(); ta = asg->GetTokenAlignmentAt(0); assert(ta->GetReferenceToken() == NULL); assert(ta->GetTokenFor("hyp") == hyps[0]); ta = asg->GetTokenAlignmentAt(1); assert(ta->GetReferenceToken() == NULL); assert(ta->GetTokenFor("hyp") == hyps[1]); ta = asg->GetTokenAlignmentAt(2); assert(ta->GetReferenceToken() == NULL); assert(ta->GetTokenFor("hyp") == hyps[2]); cout << " OK." << endl; delete ali; delete sg; } void AlignmentTest::TestDeletions() { Alignment* ali; SegmentsGroup* sg; std::size_t testIndex = 3; // simple deletion, one segment ali = GetAlignmentFor(testIndex, &sg); Segment* ref = sg->GetReference(0)[0]; Segment* hyp = sg->GetHypothesis(0)[0]; vector< Token* > refs = ref->ToTopologicalOrderedStruct(); vector< Token* > hyps = hyp->ToTopologicalOrderedStruct(); cout << "Single Deletion tests:" << endl; cout << "\tCheck speech and segment..."; cout.flush(); Speech* refSpeech = ref->GetParentSpeech(); AlignedSpeech* asp = ali->GetOrCreateAlignedSpeechFor(refSpeech, false); assert(refSpeech == asp->GetReferenceSpeech()); AlignedSegment* asg = asp->GetOrCreateAlignedSegmentFor(ref, false); assert(ref == asg->GetReferenceSegment()); assert(asg->GetTokenAlignmentCount() == 3); cout << " OK." << endl; cout << "\tCheck tokens..."; cout.flush(); TokenAlignment* ta = asg->GetTokenAlignmentAt(0); assert(ta->GetReferenceToken() == refs[0]); assert(ta->GetTokenFor("hyp") == hyps[0]); ta = asg->GetTokenAlignmentAt(1); assert(ta->GetReferenceToken() == refs[1]); assert(ta->GetTokenFor("hyp") == NULL); ta = asg->GetTokenAlignmentAt(2); assert(ta->GetReferenceToken() == refs[2]); assert(ta->GetTokenFor("hyp") == hyps[1]); cout << " OK." << endl; testIndex = 5; // only deletions, one segment ali = GetAlignmentFor(testIndex, &sg); ref = sg->GetReference(0)[0]; hyp = sg->GetHypothesis(0)[0]; refs = ref->ToTopologicalOrderedStruct(); hyps = hyp->ToTopologicalOrderedStruct(); cout << "Only Deletions tests:" << endl; cout << "\tCheck speech and segment..."; cout.flush(); refSpeech = ref->GetParentSpeech(); asp = ali->GetOrCreateAlignedSpeechFor(refSpeech, false); assert(refSpeech == asp->GetReferenceSpeech()); asg = asp->GetOrCreateAlignedSegmentFor(ref, false); assert(ref == asg->GetReferenceSegment()); assert(asg->GetTokenAlignmentCount() == 3); cout << " OK." << endl; cout << "\tCheck tokens..."; cout.flush(); ta = asg->GetTokenAlignmentAt(0); assert(ta->GetReferenceToken() == refs[0]); assert(ta->GetTokenFor("hyp") == NULL); ta = asg->GetTokenAlignmentAt(1); assert(ta->GetReferenceToken() == refs[1]); assert(ta->GetTokenFor("hyp") == NULL); ta = asg->GetTokenAlignmentAt(2); assert(ta->GetReferenceToken() == refs[2]); assert(ta->GetTokenFor("hyp") == NULL); cout << " OK." << endl; delete ali; delete sg; } Alignment* AlignmentTest::GetAlignmentFor(std::size_t testIndex, SegmentsGroup** sg) { Alignment* ali = NULL; GraphAlignedSegment* gas = bench->GetResult(testIndex); *sg = bench->GetTest(testIndex); ali = new Alignment(); ali->AddSystem("", "hyp"); ali->AddGraphAlignedSegment(gas, "hyp", *sg); return ali; }
6,457
2,303
/** * @file RTEC_Initializer.cpp * * $Id: RTEC_Initializer.cpp 91675 2010-09-08 19:09:19Z johnnyw $ * * @author Carlos O'Ryan <coryan@uci.edu> */ #include "RTEC_Initializer.h" #include "RTCORBA_Setup.h" #include "orbsvcs/Event/EC_Event_Channel.h" #include "orbsvcs/Event/EC_Default_Factory.h" #include "orbsvcs/Event/EC_RTCORBA_Factory.h" #include "ace/Dynamic_Service.h" TAO_EC_Event_Channel * RTEC_Initializer::create (PortableServer::POA_ptr consumer_poa, PortableServer::POA_ptr supplier_poa, RTCORBA_Setup * rtcorba_setup) { TAO_EC_Event_Channel_Attributes attr (consumer_poa, supplier_poa); if (rtcorba_setup == 0) { return new TAO_EC_Event_Channel (attr); } TAO_EC_Factory *body = ACE_Dynamic_Service<TAO_EC_Factory>::instance ("EC_Factory"); auto_ptr<TAO_EC_Factory> factory ( new TAO_EC_RTCORBA_Factory (body, rtcorba_setup->lanes ())); TAO_EC_Event_Channel *ec = new TAO_EC_Event_Channel (attr, factory.get (), 1); factory.release (); return ec; }
1,140
455
// // kern_policy.hpp // Lilu // // Copyright © 2016-2017 vit9696. All rights reserved. // #ifndef kern_policy_hpp #define kern_policy_hpp #include <Headers/kern_config.hpp> #include <sys/types.h> #include <sys/proc.h> #include <Library/security/mac_framework.h> #include <Library/security/mac_policy.h> #include <Headers/kern_util.hpp> class Policy { /** * TrustedBSD Policy handle */ mac_policy_handle_t policyHandle {0}; /** * TrustedBSD policy configuration */ mac_policy_conf policyConf; public: /** * May be used at TrustedBSD policy initialisation * * @param conf policy configuration */ static void dummyPolicyInitBSD(mac_policy_conf *conf) { DBGLOG("policy", "init bsd"); } /** * Compile-time policy constructor * * @param name policy name literal * @param descr policy description literal * @param ops policy functions */ constexpr Policy(const char *name, const char *descr, struct mac_policy_ops *ops) : policyConf{ .mpc_name = name, .mpc_fullname = descr, .mpc_labelnames = nullptr, .mpc_labelname_count = 0, .mpc_ops = ops, // Our policies are loaded very early and are static. We cannot unload them. .mpc_loadtime_flags = 0 /*MPC_LOADTIME_FLAG_UNLOADOK*/, .mpc_field_off = nullptr, .mpc_runtime_flags = 0 } { } /** * Registers TrustedBSD policy * * @return true on success */ EXPORT bool registerPolicy(); /** * Unregisters TrustedBSD policy if allowed * * @return true on success */ EXPORT bool unregisterPolicy(); }; #endif /* kern_policy_hpp */
1,583
621
#include <iostream> using namespace std; int main(int argc, char *argv[]) { char vowels [] {'a', 'e','i', 'w', 'r'}; cout << "The first vowels is " << vowels[0] << endl; cout << "The last vowels is " << vowels[4] << endl; double hi_temps [] {90.1, 89.7, 77.5, 81.6}; cout << "The first high temperature is " << hi_temps[0] << endl; hi_temps[0] = 100.7; for (int i=0; i<=3; i++) cout << hi_temps[i] << endl; int test_score [] {}; cout << "Input 5 test scores: " << endl; cin >> test_score[0]; cin >> test_score[1]; cin >> test_score[2]; cin >> test_score[3]; cin >> test_score[4]; cout << "First score at index 0 is " << test_score[0] << endl; cout << "Second score at index 1 is " << test_score[1] << endl; cout << "Third score at index 2 is " << test_score[2] << endl; cout << "Fourth score at index 3 is " << test_score[3] << endl; cout << "Fifth score at index 4 is " << test_score[4] << endl; cout << test_score << endl; return 0; }
1,066
414
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <limits> #include "base/debug/trace_event.h" #include "cc/base/region.h" #include "cc/debug/benchmark_instrumentation.h" #include "cc/debug/debug_colors.h" #include "cc/resources/picture_pile_impl.h" #include "skia/ext/analysis_canvas.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkSize.h" #include "ui/gfx/rect_conversions.h" #include "ui/gfx/size_conversions.h" #include "ui/gfx/skia_util.h" namespace cc { PicturePileImpl::ClonesForDrawing::ClonesForDrawing( const PicturePileImpl* pile, int num_threads) { for (int i = 0; i < num_threads; i++) { scoped_refptr<PicturePileImpl> clone = PicturePileImpl::CreateCloneForDrawing(pile, i); clones_.push_back(clone); } } PicturePileImpl::ClonesForDrawing::~ClonesForDrawing() { } scoped_refptr<PicturePileImpl> PicturePileImpl::Create() { return make_scoped_refptr(new PicturePileImpl); } scoped_refptr<PicturePileImpl> PicturePileImpl::CreateFromOther( const PicturePileBase* other) { return make_scoped_refptr(new PicturePileImpl(other)); } scoped_refptr<PicturePileImpl> PicturePileImpl::CreateCloneForDrawing( const PicturePileImpl* other, unsigned thread_index) { return make_scoped_refptr(new PicturePileImpl(other, thread_index)); } PicturePileImpl::PicturePileImpl() : clones_for_drawing_(ClonesForDrawing(this, 0)) { } PicturePileImpl::PicturePileImpl(const PicturePileBase* other) : PicturePileBase(other), clones_for_drawing_(ClonesForDrawing(this, num_raster_threads())) { } PicturePileImpl::PicturePileImpl( const PicturePileImpl* other, unsigned thread_index) : PicturePileBase(other, thread_index), clones_for_drawing_(ClonesForDrawing(this, 0)) { } PicturePileImpl::~PicturePileImpl() { } PicturePileImpl* PicturePileImpl::GetCloneForDrawingOnThread( unsigned thread_index) const { CHECK_GT(clones_for_drawing_.clones_.size(), thread_index); return clones_for_drawing_.clones_[thread_index].get(); } void PicturePileImpl::RasterDirect( SkCanvas* canvas, gfx::Rect canvas_rect, float contents_scale, RasterStats* raster_stats) { RasterCommon(canvas, NULL, canvas_rect, contents_scale, raster_stats); } void PicturePileImpl::RasterForAnalysis( skia::AnalysisCanvas* canvas, gfx::Rect canvas_rect, float contents_scale) { RasterCommon(canvas, canvas, canvas_rect, contents_scale, NULL); } void PicturePileImpl::RasterToBitmap( SkCanvas* canvas, gfx::Rect canvas_rect, float contents_scale, RasterStats* raster_stats) { #ifndef NDEBUG // Any non-painted areas will be left in this color. canvas->clear(DebugColors::NonPaintedFillColor()); #endif // NDEBUG // If this picture has opaque contents, it is guaranteeing that it will // draw an opaque rect the size of the layer. If it is not, then we must // clear this canvas ourselves. if (!contents_opaque_) { // Clearing is about ~4x faster than drawing a rect even if the content // isn't covering a majority of the canvas. canvas->clear(SK_ColorTRANSPARENT); } else { // Even if it is opaque, on any rasterizations that touch the edge of the // layer, we also need to raster the background color underneath the last // texel (since the recording won't cover it) and outside the last texel // (due to linear filtering when using this texture). gfx::SizeF total_content_size = gfx::ScaleSize(tiling_.total_size(), contents_scale); gfx::Rect content_rect(gfx::ToCeiledSize(total_content_size)); gfx::Rect deflated_content_rect = content_rect; content_rect.Intersect(canvas_rect); // The final texel of content may only be partially covered by a // rasterization; this rect represents the content rect that is fully // covered by content. deflated_content_rect.Inset(0, 0, 1, 1); deflated_content_rect.Intersect(canvas_rect); if (!deflated_content_rect.Contains(canvas_rect)) { // Drawing at most 2 x 2 x (canvas width + canvas height) texels is 2-3X // faster than clearing, so special case this. canvas->save(); gfx::Rect inflated_content_rect = content_rect; inflated_content_rect.Inset(0, 0, -1, -1); canvas->clipRect(gfx::RectToSkRect(inflated_content_rect), SkRegion::kReplace_Op); canvas->clipRect(gfx::RectToSkRect(deflated_content_rect), SkRegion::kDifference_Op); canvas->drawColor(background_color_, SkXfermode::kSrc_Mode); canvas->restore(); } } RasterCommon(canvas, NULL, canvas_rect, contents_scale, raster_stats); } void PicturePileImpl::RasterCommon( SkCanvas* canvas, SkDrawPictureCallback* callback, gfx::Rect canvas_rect, float contents_scale, RasterStats* raster_stats) { DCHECK(contents_scale >= min_contents_scale_); canvas->translate(-canvas_rect.x(), -canvas_rect.y()); gfx::SizeF total_content_size = gfx::ScaleSize(tiling_.total_size(), contents_scale); gfx::Rect total_content_rect(gfx::ToCeiledSize(total_content_size)); gfx::Rect content_rect = total_content_rect; content_rect.Intersect(canvas_rect); // Rasterize the collection of relevant picture piles. gfx::Rect layer_rect = gfx::ScaleToEnclosingRect( content_rect, 1.f / contents_scale); canvas->clipRect(gfx::RectToSkRect(content_rect), SkRegion::kIntersect_Op); Region unclipped(content_rect); if (raster_stats) { raster_stats->total_pixels_rasterized = 0; raster_stats->total_rasterize_time = base::TimeDelta::FromSeconds(0); raster_stats->best_rasterize_time = base::TimeDelta::FromSeconds(0); } for (TilingData::Iterator tile_iter(&tiling_, layer_rect); tile_iter; ++tile_iter) { PictureListMap::iterator map_iter = picture_list_map_.find(tile_iter.index()); if (map_iter == picture_list_map_.end()) continue; PictureList& pic_list= map_iter->second; if (pic_list.empty()) continue; // Raster through the picture list top down, using clips to make sure that // pictures on top are not overdrawn by pictures on the bottom. for (PictureList::reverse_iterator i = pic_list.rbegin(); i != pic_list.rend(); ++i) { // This is intentionally *enclosed* rect, so that the clip is aligned on // integral post-scale content pixels and does not extend past the edges // of the picture's layer rect. The min_contents_scale enforces that // enough buffer pixels have been added such that the enclosed rect // encompasses all invalidated pixels at any larger scale level. gfx::Rect content_clip = gfx::ScaleToEnclosedRect( (*i)->LayerRect(), contents_scale); DCHECK(!content_clip.IsEmpty()) << "Layer rect: " << (*i)->LayerRect().ToString() << "Contents scale: " << contents_scale; content_clip.Intersect(canvas_rect); if (!unclipped.Intersects(content_clip)) continue; base::TimeDelta total_duration = base::TimeDelta::FromInternalValue(0); base::TimeDelta best_duration = base::TimeDelta::FromInternalValue(std::numeric_limits<int64>::max()); int repeat_count = std::max(1, slow_down_raster_scale_factor_for_debug_); TRACE_EVENT0(benchmark_instrumentation::kCategory, benchmark_instrumentation::kRasterLoop); for (int j = 0; j < repeat_count; ++j) { base::TimeTicks start_time; if (raster_stats) start_time = base::TimeTicks::HighResNow(); (*i)->Raster(canvas, callback, content_clip, contents_scale); if (raster_stats) { base::TimeDelta duration = base::TimeTicks::HighResNow() - start_time; total_duration += duration; best_duration = std::min(best_duration, duration); } } if (raster_stats) { raster_stats->total_pixels_rasterized += repeat_count * content_clip.width() * content_clip.height(); raster_stats->total_rasterize_time += total_duration; raster_stats->best_rasterize_time += best_duration; } if (show_debug_picture_borders_) { gfx::Rect border = gfx::ScaleToEnclosedRect( (*i)->LayerRect(), contents_scale); border.Inset(0, 0, 1, 1); SkPaint picture_border_paint; picture_border_paint.setColor(DebugColors::PictureBorderColor()); canvas->drawLine(border.x(), border.y(), border.right(), border.y(), picture_border_paint); canvas->drawLine(border.right(), border.y(), border.right(), border.bottom(), picture_border_paint); canvas->drawLine(border.right(), border.bottom(), border.x(), border.bottom(), picture_border_paint); canvas->drawLine(border.x(), border.bottom(), border.x(), border.y(), picture_border_paint); } // Don't allow pictures underneath to draw where this picture did. canvas->clipRect( gfx::RectToSkRect(content_clip), SkRegion::kDifference_Op); unclipped.Subtract(content_clip); } } #ifndef NDEBUG // Fill the remaining clip with debug color. This allows us to // distinguish between non painted areas and problems with missing // pictures. SkPaint paint; paint.setColor(DebugColors::MissingPictureFillColor()); paint.setXfermodeMode(SkXfermode::kSrc_Mode); canvas->drawPaint(paint); #endif // NDEBUG // We should always paint some part of |content_rect|. DCHECK(!unclipped.Contains(content_rect)); } skia::RefPtr<SkPicture> PicturePileImpl::GetFlattenedPicture() { TRACE_EVENT0("cc", "PicturePileImpl::GetFlattenedPicture"); gfx::Rect layer_rect(tiling_.total_size()); skia::RefPtr<SkPicture> picture = skia::AdoptRef(new SkPicture); if (layer_rect.IsEmpty()) return picture; SkCanvas* canvas = picture->beginRecording( layer_rect.width(), layer_rect.height(), SkPicture::kUsePathBoundsForClip_RecordingFlag); RasterToBitmap(canvas, layer_rect, 1.0, NULL); picture->endRecording(); return picture; } void PicturePileImpl::AnalyzeInRect(gfx::Rect content_rect, float contents_scale, PicturePileImpl::Analysis* analysis) { DCHECK(analysis); TRACE_EVENT0("cc", "PicturePileImpl::AnalyzeInRect"); gfx::Rect layer_rect = gfx::ScaleToEnclosingRect( content_rect, 1.0f / contents_scale); layer_rect.Intersect(gfx::Rect(tiling_.total_size())); SkBitmap empty_bitmap; empty_bitmap.setConfig(SkBitmap::kNo_Config, layer_rect.width(), layer_rect.height()); skia::AnalysisDevice device(empty_bitmap); skia::AnalysisCanvas canvas(&device); RasterForAnalysis(&canvas, layer_rect, 1.0f); analysis->is_solid_color = canvas.GetColorIfSolid(&analysis->solid_color); analysis->has_text = canvas.HasText(); } PicturePileImpl::Analysis::Analysis() : is_solid_color(false), has_text(false) { } PicturePileImpl::Analysis::~Analysis() { } PicturePileImpl::PixelRefIterator::PixelRefIterator( gfx::Rect content_rect, float contents_scale, const PicturePileImpl* picture_pile) : picture_pile_(picture_pile), layer_rect_(gfx::ScaleToEnclosingRect( content_rect, 1.f / contents_scale)), tile_iterator_(&picture_pile_->tiling_, layer_rect_), picture_list_(NULL) { // Early out if there isn't a single tile. if (!tile_iterator_) return; if (AdvanceToTileWithPictures()) AdvanceToPictureWithPixelRefs(); } PicturePileImpl::PixelRefIterator::~PixelRefIterator() { } PicturePileImpl::PixelRefIterator& PicturePileImpl::PixelRefIterator::operator++() { ++pixel_ref_iterator_; if (pixel_ref_iterator_) return *this; ++picture_list_iterator_; AdvanceToPictureWithPixelRefs(); return *this; } bool PicturePileImpl::PixelRefIterator::AdvanceToTileWithPictures() { for (; tile_iterator_; ++tile_iterator_) { PictureListMap::const_iterator map_iterator = picture_pile_->picture_list_map_.find(tile_iterator_.index()); if (map_iterator != picture_pile_->picture_list_map_.end()) { picture_list_ = &map_iterator->second; picture_list_iterator_ = picture_list_->begin(); return true; } } return false; } void PicturePileImpl::PixelRefIterator::AdvanceToPictureWithPixelRefs() { DCHECK(tile_iterator_); do { for (; picture_list_iterator_ != picture_list_->end(); ++picture_list_iterator_) { pixel_ref_iterator_ = Picture::PixelRefIterator(layer_rect_, picture_list_iterator_->get()); if (pixel_ref_iterator_) return; } ++tile_iterator_; } while (AdvanceToTileWithPictures()); } void PicturePileImpl::DidBeginTracing() { gfx::Rect layer_rect(tiling_.total_size()); for (PictureListMap::iterator pli = picture_list_map_.begin(); pli != picture_list_map_.end(); pli++) { PictureList& picture_list = (*pli).second; for (PictureList::iterator picture = picture_list.begin(); picture != picture_list.end(); picture++) { (*picture)->EmitTraceSnapshot(); } } } } // namespace cc
13,603
4,355
#include "device.h" #include "context.h" #ifdef USE_ARM_PLACE #ifdef PLATFORM_ANDROID #include <unistd.h> #include <sys/syscall.h> #include <sys/system_properties.h> #include "cpu_info.h" #endif //PLATFORM_ANDROID #if __APPLE__ #include "TargetConditionals.h" #if TARGET_OS_IPHONE #include <sys/types.h> #include <sys/sysctl.h> #include <mach/machine.h> #endif //TARGET_OS_IPHONE #endif //__APPLE__ namespace anakin{ namespace saber{ int arm_get_cpucount() { #ifdef PLATFORM_ANDROID // get cpu count from /sys/devices/system/cpu/cpunum/uevent int max_cpu_count = 20; int count = 0; for (int i = 0; i < max_cpu_count; ++i) { char path[256]; snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/uevent", i); FILE* fp = fopen(path, "rb"); if (!fp) { break; } count++; fclose(fp); } if (count < 1) { count = 1; } return count; #elif defined(TARGET_IOS) int count = 0; size_t len = sizeof(count); sysctlbyname("hw.ncpu", &count, &len, NULL, 0); if (count < 1) { count = 1; } return count; #else return 1; #endif } void arm_get_cpu_arch(std::vector<ARMArch>& archs){ #ifdef PLATFORM_ANDROID archs.clear(); //! get CPU ARCH FILE* fp = fopen("/proc/cpuinfo", "rb"); if (!fp) { return; } char line[1024]; while (!feof(fp)) { char* s = fgets(line, 1024, fp); if (!s) { break; } if (strstr(line, "part") != NULL) { int arch_id = 0; sscanf(s, "CPU part\t: %x", &arch_id); switch (arch_id) { case 0xd03: archs.push_back(A53); break; case 0xd05: archs.push_back(A55); break; case 0xd07: archs.push_back(A57); break; case 0xd08: archs.push_back(A72); break; case 0xd09: archs.push_back(A73); break; case 0xd0a: archs.push_back(A75); break; case 0xd40: archs.push_back(A76); break; case 0x804: // 855 archs.push_back(A76); break; case 0x805: // 855 archs.push_back(A55); break; case 0x802: // 845 archs.push_back(A75); break; case 0x803: // 845 archs.push_back(A55); break; case 0x800: // 835 archs.push_back(A73); break; case 0x205: // 820 archs.push_back(A72); break; default: LOG(ERROR) << "unknow type"; archs.push_back(ARM_UNKOWN); } } } fclose(fp); int cpu_count = arm_get_cpucount(); if (archs.size() < cpu_count) { for (int i = archs.size(); i < cpu_count; ++i) { archs.push_back(archs[i - 1]); } } #endif #ifdef TARGET_IOS int cpu_count = arm_get_cpucount(); for(int i = 0; i < cpu_count; ++i){ archs.push_back(APPLE); } #endif } void set_default_cache(DeviceInfo<ARM>& dev){ int cpu_count = arm_get_cpucount(); dev._L1_cache.resize(cpu_count); dev._L2_cache.resize(cpu_count); dev._L3_cache.resize(cpu_count); #ifdef TARGET_IOS for (int i = 0; i < cpu_count; ++i){ dev._L1_cache[i] = 64 * 1024; dev._L2_cache[i] = 2048 * 1024; dev._L3_cache[i] = 0; } #else for (int i = 0; i < cpu_count; ++i){ dev._L1_cache[i] = 32 * 1024; dev._L2_cache[i] = 512 * 1024; dev._L3_cache[i] = 0; } #endif } size_t arm_get_meminfo() { #ifdef PLATFORM_ANDROID // get cpu count from /proc/cpuinfo FILE* fp = fopen("/proc/meminfo", "rb"); if (!fp) { return 1; } size_t memsize = 0; char line[1024]; while (!feof(fp)) { char* s = fgets(line, 1024, fp); if (!s) { break; } sscanf(s, "MemTotal: %d kB", &memsize); } fclose(fp); return memsize; #elif defined(TARGET_IOS) // to be implemented printf("not implemented\n"); return 0; #endif } #ifdef PLATFORM_ANDROID std::string arm_get_cpu_name(){ std::string cpu_name; FILE* fp = fopen("/proc/cpuinfo", "rb"); if (!fp) { return ""; } char line[1024]; while (!feof(fp)) { char* s = fgets(line, 1024, fp); if (!s) { break; } if (strstr(line, "Hardware") != NULL){ cpu_name = std::string(line); } } // cpu name concat board name, platform name and chip name char board_name[128]; char platform_name[128]; char chip_name[128]; __system_property_get("ro.product.board", board_name); __system_property_get("ro.board.platform", platform_name); __system_property_get("ro.chipname", chip_name); cpu_name = cpu_name + "_" + board_name + "_" + platform_name + "_" + chip_name; std::transform(cpu_name.begin(), cpu_name.end(), cpu_name.begin(), ::toupper); LOG(INFO) << "CPU Name : " << cpu_name; fclose(fp); return cpu_name; } int get_max_freq_khz(int cpuid) { // first try, for all possible cpu char path[256]; snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpufreq/stats/cpu%d/time_in_state",\ cpuid); FILE* fp = fopen(path, "rb"); if (!fp) { // second try, for online cpu snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/cpufreq/stats/time_in_state",\ cpuid); fp = fopen(path, "rb"); } int max_freq_khz = 0; if (fp){ while (!feof(fp)) { int freq_khz = 0; int nscan = fscanf(fp, "%d %*d", &freq_khz); if (nscan != 1) { break; } if (freq_khz > max_freq_khz) { max_freq_khz = freq_khz; } } } if (max_freq_khz == 0 || !fp){ // third try, for online cpu snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq",\ cpuid); fp = fopen(path, "rb"); if (!fp) { return -1; } int max_freq_khz = -1; fscanf(fp, "%d", &max_freq_khz); fclose(fp); return max_freq_khz; } fclose(fp); return max_freq_khz; } int arm_sort_cpuid_by_max_frequency(int cpu_count, std::vector<int>& cpuids, \ std::vector<int>& cpu_freq, std::vector<int>& cluster_ids) { if (cpu_count == 0) { return 0; } cpuids.resize(cpu_count); cluster_ids.resize(cpu_count); for (int i = 0; i < cpu_count; i++) { cpuids[i] = i; } // sort cpuid as big core first //simple bubble sort for (int i = 0; i < cpu_count; i++) { for (int j = i+1; j < cpu_count; j++) { if (cpu_freq[i] < cpu_freq[j]) { // swap int tmp = cpuids[i]; cpuids[i] = cpuids[j]; cpuids[j] = tmp; } } } // SMP int mid_max_freq_khz = (cpu_freq[cpuids[0]] + cpu_freq[cpuids[cpu_count - 1]]) / 2; for (int i = 0; i < cpu_count; i++) { cpuids[i] = i; if (cpu_freq[i] >= mid_max_freq_khz) { cluster_ids[i] = 0; } else{ cluster_ids[i] = 1; } } return 0; } int check_online(std::vector<int>& core_ids){ if (core_ids.size() == 0){ return 0; } char path[256]; int online = 1; for (int i = 0; i < core_ids.size(); ++i){ snprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/online",\ core_ids[i]); FILE* fp = fopen(path, "rb"); if (!fp){ return 0; } int cur_online = 0; fscanf(fp, "%d", &cur_online); online &= cur_online; fclose(fp); } return online; } int set_sched_affinity(const std::vector<int>& cpuids) { // cpu_set_t definition // ref http://stackoverflow.com/questions/16319725/android-set-thread-affinity #define CPU_SETSIZE 1024 #define __NCPUBITS (8 * sizeof (unsigned long)) typedef struct { unsigned long __bits[CPU_SETSIZE / __NCPUBITS]; } cpu_set_t; #define CPU_SET(cpu, cpusetp) \ ((cpusetp)->__bits[(cpu)/__NCPUBITS] |= (1UL << ((cpu) % __NCPUBITS))) #define CPU_ZERO(cpusetp) \ memset((cpusetp), 0, sizeof(cpu_set_t)) // set affinity for thread #ifdef __GLIBC__ pid_t pid = syscall(SYS_gettid); #else pid_t pid = gettid(); #endif cpu_set_t mask; CPU_ZERO(&mask); for (int i = 0; i < cpuids.size(); i++) { CPU_SET(cpuids[i], &mask); } int syscallret = syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask); if (syscallret) { LOG(ERROR) << "syscall error" << syscallret; return -1; } return 0; } #endif //android template <> void Device<ARM>::create_stream() { _compute_stream.resize(_max_stream); _data_stream.resize(_max_stream); for (int i = 0; i < _max_stream; ++i) { _compute_stream[i] = nullptr; _data_stream[i] = nullptr; } } template <> void Device<ARM>::get_info() { set_default_cache(_info); _info._compute_core_num = arm_get_cpucount(); _info._max_memory = arm_get_meminfo(); //get max freq #ifdef PLATFORM_ANDROID std::vector<int> max_freq(_info._compute_core_num); for (int i = 0; i < _info._compute_core_num; ++i){ max_freq[i] = get_max_freq_khz(i) / 1000; } std::string cpu_name = arm_get_cpu_name(); if (get_cpu_info_from_name(_info, cpu_name) != SaberSuccess){ arm_sort_cpuid_by_max_frequency(_info._compute_core_num, _info._core_ids, max_freq, _info._cluster_ids); _info._big_core_ids.clear(); _info._little_core_ids.clear(); for (int i = 0; i < _info._cluster_ids.size(); ++i) { if (_info._cluster_ids[i] == 0) { _info._big_core_ids.push_back(_info._core_ids[i]); } else { _info._little_core_ids.push_back(_info._core_ids[i]); } } arm_get_cpu_arch(_info._archs); } LOG(INFO) << "ARM multiprocessors number: " << _info._compute_core_num; for (int i = 0; i < _info._compute_core_num; ++i) { LOG(INFO) <<"ARM multiprocessors ID:" << _info._core_ids[i] << ", frequence:" << max_freq[i] << \ ", cluster ID: " << _info._cluster_ids[_info._core_ids[i]] << ", CPU ARCH: " << _info._archs[i]; } LOG(INFO) << "L1 Cache size is: "; if (_info._big_core_ids.size() > 0){ LOG(INFO) << "big core: " << _info._L1_cache[_info._big_core_ids[0]] / 1024 << "KB"; } if (_info._little_core_ids.size() > 0){ LOG(INFO) << "little core: " << _info._L1_cache[_info._little_core_ids[0]] / 1024 << "KB"; } LOG(INFO) << "L2 Cache size is: "; if (_info._big_core_ids.size() > 0){ LOG(INFO) << "big core: " << _info._L2_cache[_info._big_core_ids[0]] / 1024 << "KB"; } if (_info._little_core_ids.size() > 0){ LOG(INFO) << "little core: " << _info._L2_cache[_info._little_core_ids[0]] / 1024 << "KB"; } LOG(INFO) << "Total memory: " << _info._max_memory << "KB"; _info._max_frequence = max_freq[0]; for (int j = 1; j < _info._compute_core_num; ++j) { if (_info._max_frequence < max_freq[j]){ _info._max_frequence = max_freq[j]; } } #elif defined(TARGET_IOS) arm_get_cpu_arch(_info._archs); #endif } template <> void Context<ARM>::bind_dev() { #ifdef USE_OPENMP int num_threads = _act_ids.size(); omp_set_num_threads(num_threads); #ifdef PLATFORM_ANDROID std::vector<int> ssarets; for (int j = 0; j < num_threads; ++j) { ssarets.push_back(0); } #pragma omp parallel for for (int i = 0; i < num_threads; i++) { ssarets[i] = set_sched_affinity(_act_ids); } for (int i = 0; i < num_threads; i++) { if (ssarets[i] != 0) { LOG(ERROR) << "set cpu affinity failed, cpuID: " << _act_ids[i]; return; } } #endif //PLATFORM_ANDROID #else //USE_OPENMP #ifdef PLATFORM_ANDROID std::vector<int> cpuid1; cpuid1.push_back(_act_ids[0]); int ssaret = set_sched_affinity(cpuid1); if (ssaret != 0) { printf("set cpu affinity failed, cpuID: %d\n", _act_ids[0]); return; } #endif //PLATFORM_ANDROID #endif//USE_OPENMP } template <> void Context<ARM>::set_run_mode(PowerMode mode, int threads) { int big_core_size = devs[_device_id]._info._big_core_ids.size(); int small_core_size = devs[_device_id]._info._little_core_ids.size(); #ifdef USE_OPENMP if (threads > big_core_size + small_core_size) { threads = big_core_size + small_core_size; } _count++; int shift_num = (_count / 10) % big_core_size; switch (mode) { case SABER_POWER_FULL: _mode = mode; _act_ids.clear(); for (int i = 0; i < threads; ++i) { if (i < big_core_size) { _act_ids.push_back(devs[_device_id]._info._big_core_ids[i]); } else { _act_ids.push_back(devs[_device_id]._info._little_core_ids[i - big_core_size]); } } if (_act_ids.size() == 0) { _act_ids.push_back(0); } break; case SABER_POWER_HIGH: _act_ids.clear(); if (big_core_size > 0) { _mode = SABER_POWER_HIGH; if (threads > big_core_size) { LOG(ERROR) << "threads: " << threads << ", exceed the big cores size: " << big_core_size; _act_ids = devs[_device_id]._info._big_core_ids; } else { for (int i = 0; i < threads; ++i) { _act_ids.push_back(devs[_device_id]._info._big_core_ids[devs[_device_id]._info._big_core_ids.size() - 1 - i]); } } } else { _mode = SABER_POWER_LOW; LOG(ERROR) << "HIGH POWER MODE is not support, switch to little cores"; if (threads > small_core_size) { _act_ids = devs[_device_id]._info._little_core_ids; } else { for (int i = 0; i < threads; ++i) { _act_ids.push_back(devs[_device_id]._info._little_core_ids[i]); } } } if (_act_ids.size() == 0) { _act_ids.push_back(0); } break; case SABER_POWER_LOW: _act_ids.clear(); if (small_core_size > 0) { _mode = SABER_POWER_LOW; if (threads > small_core_size) { LOG(WARNING) << "threads: " << threads << ", exceed the little cores size:" << small_core_size; _act_ids = devs[_device_id]._info._little_core_ids; } else { for (int i = 0; i < threads; ++i) { _act_ids.push_back(devs[_device_id]._info._little_core_ids[i]); } } } else { _mode = SABER_POWER_HIGH; LOG(WARNING) << "LOW POWER MODE is not support, switch to big cores"; if (threads > big_core_size) { _act_ids = devs[_device_id]._info._big_core_ids; } else { for (int i = 0; i < threads; ++i) { _act_ids.push_back(devs[_device_id]._info._big_core_ids[i]); } } } if (_act_ids.size() == 0) { _act_ids.push_back(0); } break; case SABER_POWER_NO_BIND: _mode = SABER_POWER_NO_BIND; _act_ids.clear(); if (threads > devs[_device_id]._info._core_ids.size()) { _act_ids.resize(devs[_device_id]._info._core_ids.size()); } else { _act_ids.resize(threads); } break; case SABER_POWER_RAND_HIGH: _act_ids.clear(); if (big_core_size > 0) { _mode = SABER_POWER_RAND_HIGH; if (threads > big_core_size) { LOG(WARNING) << "threads: " << threads << ", exceed the big cores size: " << big_core_size; _act_ids = devs[_device_id]._info._big_core_ids; } else { for (int i = 0; i < threads; ++i) { _act_ids.push_back(devs[_device_id]._info._big_core_ids[(i + shift_num) % big_core_size]); } } } else { _mode = SABER_POWER_LOW; LOG(WARNING) << "HIGH POWER MODE is not support, switch to little cores"; if (threads > small_core_size) { _act_ids = devs[_device_id]._info._little_core_ids; } else { for (int i = 0; i < threads; ++i) { _act_ids.push_back(devs[_device_id]._info._little_core_ids[i]); } } } if (_act_ids.size() == 0) { _act_ids.push_back(0); } break; case SABER_POWER_RAND_LOW: _act_ids.clear(); if (small_core_size > 0) { _mode = SABER_POWER_RAND_LOW; if (threads > small_core_size) { LOG(WARNING) << "threads: " << threads << ", exceed the little cores size: " << small_core_size; _act_ids = devs[0]._info._little_core_ids; } else { for (int i = 0; i < threads; ++i) { _act_ids.push_back(devs[_device_id]._info._little_core_ids[(i + shift_num) % small_core_size]); } } } else { _mode = SABER_POWER_HIGH; LOG(WARNING) << "LOW POWER MODE is not support, switch to big cores"; if (threads > big_core_size) { _act_ids = devs[_device_id]._info._big_core_ids; } else { for (int i = 0; i < threads; ++i) { _act_ids.push_back(devs[_device_id]._info._big_core_ids[i]); } } } if (_act_ids.size() == 0) { _act_ids.push_back(0); } break; } if (_mode == SABER_POWER_NO_BIND) { int threads = _act_ids.size(); omp_set_num_threads(threads); } else { if (check_online(_act_ids)){ bind_dev(); } else { LOG(INFO) << "some cpu is offline, switch to NO BIND MODE"; int threads = _act_ids.size(); omp_set_num_threads(threads); } } #else if (big_core_size > 0){ _act_ids = {devs[_device_id]._info._big_core_ids[0]}; } else { _act_ids = {0}; } #endif _arch = devs[_device_id]._info._archs[_act_ids[0]]; } template <> PowerMode Context<ARM>::get_mode() const{ return _mode; } template <> ARMArch Context<ARM>::get_arch() const{ return _arch; } template <> void Context<ARM>::set_arch(ARMArch arch) { _arch = arch; } template <> void Context<ARM>::set_cache(int l1size, int l2size, int l3size) { int cpu_count = arm_get_cpucount(); devs[_device_id]._info._L1_cache.resize(cpu_count); devs[_device_id]._info._L2_cache.resize(cpu_count); devs[_device_id]._info._L3_cache.resize(cpu_count); for (int i = 0;i < cpu_count; ++i){ devs[_device_id]._info._L1_cache[i] = l1size; devs[_device_id]._info._L2_cache[i] = l2size; devs[_device_id]._info._L3_cache[i] = l3size; } int temp_mem_size = 2 * (l1size + l2size); _work_space.reshape(Shape({1, 1, 1, temp_mem_size})); } template<> int Context<ARM>::get_l1_cache_size() const{ return devs[_device_id]._info._L1_cache[_act_ids[0]]; } template<> int Context<ARM>::get_l2_cache_size() const{ return devs[_device_id]._info._L2_cache[_act_ids[0]]; } template<> int Context<ARM>::get_l3_cache_size() const{ return devs[_device_id]._info._L3_cache[_act_ids[0]]; } template<> void* Context<ARM>::get_work_space() { return (void*)_work_space.mutable_data(); } template<> int Context<ARM>::get_threads() const { return _act_ids.size(); } template<> SaberStatus Context<ARM>::workspace_extend(Shape sh) { int count = sh.count(); Shape old = _work_space.shape(); _work_space.reshape(Shape({1, 1, 1, count + devs[_device_id]._info._L2_cache[_act_ids[0]] / sizeof(float)})); if (_work_space.data() == nullptr) { _work_space.re_alloc(old, AK_FLOAT); return SaberInvalidValue; } return SaberSuccess; } } //namespace saber } //namespace anakin #endif //USE_ARM_PLACE
21,562
7,930
// updated Thu Apr 25 21:55:03 PDT 2019 #include <cassert> #include <GL/gl.h> #include "Rectangle.h" Rectangle::Rectangle(double red, double green, double blue) : Game_object(red, green, blue, RECTANGLE) { Register("rotation", 0.0); } /* virtual */ void Rectangle::build_display_list() { assert(m_display_list); glNewList(m_display_list, GL_COMPILE); glMatrixMode(GL_MODELVIEW); glPushMatrix(); if (attribute<double>("rotation") != 0) { double center_x = attribute<int>("x") + object_width/2.0; double center_y = attribute<int>("y") + object_height/2.0; glTranslated(center_x, center_y, 0); glRotated(attribute<double>("rotation"), 0, 0, 1); glTranslated(-center_x, -center_y, 0); } glColor3f(attribute<double>("red"), attribute<double>("green"), attribute<double>("blue")); glBegin(GL_QUADS); glVertex2i(attribute<int>("x"), attribute<int>("y")); glVertex2i(attribute<int>("x") + object_width, attribute<int>("y")); glVertex2i(attribute<int>("x") + object_width, attribute<int>("y") + object_height); glVertex2i(attribute<int>("x"), attribute<int>("y") + object_height); glEnd(); glPopMatrix(); glEndList(); }
1,180
462
#include "itkImage.h" #include "itkImageFileReader.h" #include "itkImageFileWriter.h" #include "itkResampleImageFilter.h" #include "itkIdentityTransform.h" #include "itkAntiAliasBinaryImageFilter.h" #include "itkImageRegionIterator.h" #include "itkChangeInformationImageFilter.h" #include "string.h" #include "itkBSplineInterpolateImageFunction.h" #include "OptionParser.h" optparse::OptionParser buildParser() { const std::string usage = "%prog [OPTION]"; const std::string version = "%prog 0.1"; const std::string desc = "A command line tool that resamples given mri/binary volumes to have isotropic voxel spacing...."; //const std::string epilog = "note: --numthreads 0 means use system default (usually max number supported).\n"; const std::string epilog = ""; optparse::OptionParser parser = optparse::OptionParser() .usage(usage) .version(version) .description(desc) .epilog(epilog); parser.add_option("--inFilename").action("store").type("string").set_default("").help("The filename of the input image to be resampled."); parser.add_option("--outFilename").action("store").type("string").set_default("").help("The filename of the output resampled image."); parser.add_option("--isBinaryImage").action("store").type("bool").set_default(false).help("A flag to treat the input image as a binary image (specialized resampling pipeline) [default disabled]."); parser.add_option("--isoSpacing").action("store").type("float").set_default("").help("The isotropic spacing in all dimensions."); parser.add_option("--sizeX").action("store").type("int").set_default(0).help("Image size in x-direction (optional, if set to 0, the size is autmatically estimated from the input image)."); parser.add_option("--sizeY").action("store").type("int").set_default(0).help("Image size in y-direction (optional, if set to 0, the size is autmatically estimated from the input image)."); parser.add_option("--sizeZ").action("store").type("int").set_default(0).help("Image size in z-direction (optional, if set to 0, the size is autmatically estimated from the input image)."); parser.add_option("--isCenterImageOn").action("store").type("bool").set_default(false).help("A flag to center the image, i.e. change the origin in the image header to the physcial coordinates of the first voxel (lower left corner) [default disabled]."); return parser; } //this has been added for image region iteration as the image was not updated even after set template<typename TImage> void DeepCopy(typename TImage::Pointer input, typename TImage::Pointer output) { output->SetRegions(input->GetLargestPossibleRegion()); output->Allocate(); itk::ImageRegionConstIterator<TImage> inputIterator(input, input->GetLargestPossibleRegion()); itk::ImageRegionIterator<TImage> outputIterator(output, output->GetLargestPossibleRegion()); while(!inputIterator.IsAtEnd()) { outputIterator.Set(inputIterator.Get()); ++inputIterator; ++outputIterator; } } int main( int argc, char * argv[] ) { optparse::OptionParser parser = buildParser(); optparse::Values & options = parser.parse_args(argc,argv); std::vector<std::string> args = parser.args(); if(argc < 4) { parser.print_help(); return EXIT_FAILURE; } std::string inFilename = (std::string) options.get("inFilename"); std::string outFilename = (std::string) options.get("outFilename"); int sizeX = (int) options.get("sizeX"); int sizeY = (int) options.get("sizeY"); int sizeZ = (int) options.get("sizeZ"); float isoSpacing = (float) options.get("isoSpacing"); bool isBinaryImage = (bool) options.get("isBinaryImage"); bool isCenterImageOn = (bool) options.get("isCenterImageOn"); if(isBinaryImage==true) { typedef float InputPixelType; typedef float InternalPixelType; typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( inFilename ); InputImageType::ConstPointer inputImage = reader->GetOutput(); try { reader->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught!" << std::endl; std::cerr << excep << std::endl; } typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::ResampleImageFilter<InternalImageType, OutputImageType > ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); typedef itk::IdentityTransform< double, Dimension > TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); resampler->SetTransform( transform ); //typedef itk::LinearInterpolateImageFunction<InternalImageType, double > InterpolatorType; typedef itk::BSplineInterpolateImageFunction<InternalImageType, double, double> InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); interpolator->SetSplineOrder(3); resampler->SetInterpolator( interpolator ); //this is to overcome padding that was occuring after resampling step due to enlargement of size as per input resampler->SetDefaultPixelValue( -1); OutputImageType::SpacingType spacing; spacing[0] = isoSpacing; spacing[1] = isoSpacing; spacing[2] = isoSpacing; resampler->SetOutputSpacing( spacing ); resampler->SetOutputOrigin( inputImage->GetOrigin() ); resampler->SetOutputDirection( inputImage->GetDirection() ); InputImageType::SizeType outputSize; InputImageType::SizeType inputSize =inputImage->GetLargestPossibleRegion().GetSize(); typedef InputImageType::SizeType::SizeValueType SizeValueType; const InputImageType::SpacingType& inputSpacing = inputImage->GetSpacing(); if(sizeX == 0 || sizeY == 0 || sizeZ == 0){ sizeX = std::ceil(inputSize[0] * inputSpacing[0] / isoSpacing); sizeY = std::ceil(inputSize[1] * inputSpacing[1] / isoSpacing); sizeZ = std::ceil((inputSize[2] - 1 ) * inputSpacing[2] / isoSpacing); } outputSize[0] = static_cast<SizeValueType>( sizeX ); outputSize[1] = static_cast<SizeValueType>( sizeY ); outputSize[2] = static_cast<SizeValueType>( sizeZ ); std::cout<<"InputFileName:"<<inFilename<<std::endl; std::cout<<"InputSize:"<<inputSize[0]<<" "<<inputSize[1]<<" "<<inputSize[2]<<std::endl; std::cout<<"OutputSize:"<<outputSize[0]<<" "<<outputSize[1]<<" "<<outputSize[2]<<std::endl; std::cout<<"InputSpacing:"<<inputSpacing[0]<<" "<<inputSpacing[1]<<" "<<inputSpacing[2]<<std::endl; std::cout<<"OutputSpacing:"<<isoSpacing<<std::endl; resampler->SetSize( outputSize); /*Anti aliasing for binary images*/ typedef itk::AntiAliasBinaryImageFilter< InternalImageType, InternalImageType > FilterType; FilterType::Pointer antialiasFilter = FilterType::New(); antialiasFilter->SetInput( reader->GetOutput() ); antialiasFilter->SetMaximumRMSError( 0.01); antialiasFilter->SetNumberOfIterations( 50 ); antialiasFilter->Update(); /*resampling the binary image*/ resampler->SetInput( antialiasFilter->GetOutput() ); resampler->Update(); OutputImageType::Pointer resampledImage = resampler->GetOutput(); OutputImageType::Pointer outputImage = OutputImageType::New(); DeepCopy<OutputImageType>(resampledImage, outputImage); outputImage->SetSpacing( spacing ); outputImage->SetOrigin( inputImage->GetOrigin() ); itk::ImageRegionIterator<OutputImageType> imageIterator(resampledImage, resampledImage->GetLargestPossibleRegion()); itk::ImageRegionIterator<OutputImageType> outIterator(outputImage, outputImage->GetLargestPossibleRegion()); /*thresholding for binary images*/ while(!imageIterator.IsAtEnd()) { OutputPixelType val = imageIterator.Get(); if(val>=0) outIterator.Set((OutputPixelType)1); else outIterator.Set((OutputPixelType)0); ++imageIterator; ++outIterator; } typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outFilename ); // center volume if indicated (i.e. move (0,0,0) to the center of the bounding box) typedef itk::ChangeInformationImageFilter< OutputImageType > ImageInfoFilterType; ImageInfoFilterType::Pointer infoFilter = ImageInfoFilterType::New(); if(isCenterImageOn == true) { std::cout << "CENTER IS ON ... " << std::endl; // itk assumes center to be at pixel(0,0,0) - lower left corner so if we explicitly modify // the origin to the region center, any subsequent processing will force the origin to be at the corner and moves the image region accordingly infoFilter->SetInput(outputImage); //infoFilter->SetOutputOrigin( origin ); //infoFilter->ChangeOriginOn(); infoFilter->CenterImageOn(); infoFilter->Update(); writer->SetInput( infoFilter->GetOutput() ); } else writer->SetInput(outputImage); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } return EXIT_SUCCESS; } //for MRI images else { // typedef unsigned short InputPixelType; // typedef unsigned short InternalPixelType; // typedef unsigned short OutputPixelType; typedef float InputPixelType; typedef float InternalPixelType; typedef float OutputPixelType; const unsigned int Dimension = 3; typedef itk::Image< InputPixelType, Dimension > InputImageType; typedef itk::Image< InternalPixelType, Dimension > InternalImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( inFilename ); InputImageType::ConstPointer inputImage = reader->GetOutput(); try { reader->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught!" << std::endl; std::cerr << excep << std::endl; } typedef itk::Image< OutputPixelType, Dimension > OutputImageType; typedef itk::ResampleImageFilter<InternalImageType, OutputImageType > ResampleFilterType; ResampleFilterType::Pointer resampler = ResampleFilterType::New(); typedef itk::IdentityTransform< double, Dimension > TransformType; TransformType::Pointer transform = TransformType::New(); transform->SetIdentity(); resampler->SetTransform( transform ); typedef itk::LinearInterpolateImageFunction<InternalImageType, double > InterpolatorType; InterpolatorType::Pointer interpolator = InterpolatorType::New(); resampler->SetInterpolator( interpolator ); //this is to overcome padding that was occuring after resampling step due to enlargement of size as per input resampler->SetDefaultPixelValue( 0 ); OutputImageType::SpacingType spacing; spacing[0] = isoSpacing; spacing[1] = isoSpacing; spacing[2] = isoSpacing; resampler->SetOutputSpacing( spacing ); resampler->SetOutputOrigin( inputImage->GetOrigin() ); resampler->SetOutputDirection( inputImage->GetDirection() ); InputImageType::SizeType outputSize; InputImageType::SizeType inputSize =inputImage->GetLargestPossibleRegion().GetSize(); typedef InputImageType::SizeType::SizeValueType SizeValueType; const InputImageType::SpacingType& inputSpacing = inputImage->GetSpacing(); if(sizeX == 0 || sizeY == 0 || sizeZ == 0){ sizeX = std::ceil(inputSize[0] * inputSpacing[0] / isoSpacing); sizeY = std::ceil(inputSize[1] * inputSpacing[1] / isoSpacing); sizeZ = std::ceil((inputSize[2] - 1 ) * inputSpacing[2] / isoSpacing); } outputSize[0] = static_cast<SizeValueType>( sizeX ); outputSize[1] = static_cast<SizeValueType>( sizeY ); outputSize[2] = static_cast<SizeValueType>( sizeZ ); std::cout<<"InputFileName:"<<inFilename<<std::endl; std::cout<<"InputSize:"<<inputSize[0]<<" "<<inputSize[1]<<" "<<inputSize[2]<<std::endl; std::cout<<"OutputSize:"<<outputSize[0]<<" "<<outputSize[1]<<" "<<outputSize[2]<<std::endl; std::cout<<"InputSpacing:"<<inputSpacing[0]<<" "<<inputSpacing[1]<<" "<<inputSpacing[2]<<std::endl; std::cout<<"OutputSpacing:"<<isoSpacing<<std::endl; resampler->SetSize( outputSize); /*resampling the non binary images*/ resampler->SetInput(reader->GetOutput() ); resampler->Update(); OutputImageType::Pointer resampledImage = resampler->GetOutput(); OutputImageType::Pointer outputImage = resampler->GetOutput(); outputImage->SetSpacing( spacing ); outputImage->SetOrigin( inputImage->GetOrigin() ); typedef itk::ImageFileWriter< OutputImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName( outFilename ); // center volume if indicated (i.e. move (0,0,0) to the center of the bounding box) typedef itk::ChangeInformationImageFilter< OutputImageType > ImageInfoFilterType; ImageInfoFilterType::Pointer infoFilter = ImageInfoFilterType::New(); if(isCenterImageOn) { std::cout << "CENTER IS ON ... " << std::endl; // itk assumes center to be at pixel(0,0,0) - lower left corner so if we explicitly modify // the origin to the region center, any subsequent processing will force the origin to be at the corner and moves the image region accordingly infoFilter->SetInput(outputImage); //infoFilter->SetOutputOrigin( origin ); //infoFilter->ChangeOriginOn(); infoFilter->CenterImageOn(); infoFilter->Update(); writer->SetInput( infoFilter->GetOutput() ); } else writer->SetInput(resampler->GetOutput()); try { writer->Update(); } catch( itk::ExceptionObject & excep ) { std::cerr << "Exception caught !" << std::endl; std::cerr << excep << std::endl; } return EXIT_SUCCESS; } }
15,475
4,390
/* Copyright 2020, RespiraWorks 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. */ //////////////////////////////////////////////////////////////////// // // This file contains code to setup, send and receive data on the I²C channel // See header file for implementation philosophy. // //////////////////////////////////////////////////////////////////// #include "i2c.h" #include <cstring> #include "clocks.h" #include "gpio.h" #if defined(BARE_STM32) I2C::STM32Channel i2c1; #else I2C::Channel i2c1; #endif // BARE_STM32 namespace I2C { // Reference abbreviations ([RM], [PCB], etc) are defined in hal/README.md void initialize() { // Enable I2C1 and DMA2 peripheral clocks (we use DMA2 to send/receive data) enable_peripheral_clock(PeripheralID::I2C1); enable_peripheral_clock(PeripheralID::DMA2); // The following pins are used as i2c1 bus on the rev-1 PCB (see [PCB]): // Set Pin Function to I²C, [DS] Table 17 (pg 77) GPIO::alternate_function(GPIO::Port::B, /*pin =*/8, GPIO::AlternativeFuncion::AF4); // I2C1_SCL GPIO::alternate_function(GPIO::Port::B, /*pin =*/9, GPIO::AlternativeFuncion::AF4); // I2C1_SDA // Set output speed to Fast GPIO::output_speed(GPIO::Port::B, 8, GPIO::OutSpeed::Fast); GPIO::output_speed(GPIO::Port::B, 9, GPIO::OutSpeed::Fast); // Set open drain mode GPIO::output_type(GPIO::Port::B, 8, GPIO::OutType::OpenDrain); GPIO::output_type(GPIO::Port::B, 9, GPIO::OutType::OpenDrain); // Set Pull Up resistors GPIO::pull_up(GPIO::Port::B, 8); GPIO::pull_up(GPIO::Port::B, 9); Interrupts::singleton().EnableInterrupt(InterruptVector::I2c1Event, IntPriority::Low); Interrupts::singleton().EnableInterrupt(InterruptVector::I2c1Error, IntPriority::Low); Interrupts::singleton().EnableInterrupt(InterruptVector::Dma2Channel6, IntPriority::Low); Interrupts::singleton().EnableInterrupt(InterruptVector::Dma2Channel7, IntPriority::Low); // init i2c1 #if defined(BARE_STM32) i2c1.Init(I2C1Base, DMA::Base::DMA2, I2C::Speed::Fast); #endif } bool Channel::SendRequest(const Request &request) { *(request.processed) = false; // We need to ensure thread safety as this function might be // called from a timer interrupt as well as the main loop. // Also, because our ISR change the transfer_in_progress_ member variable. BlockInterrupts block; // Queue the request if possible: check that there is room in the index // buffer if (buffer_.IsFull()) { return false; } // Add the current queue_ index into the buffer if (buffer_.Put(ind_queue_)) { queue_[ind_queue_] = request; } else { return false; } // In case of a write request, copy data to our write buffer if (request.direction == ExchangeDirection::Write) { if (!CopyDataToWriteBuffer(request.data, request.size)) { return false; } // update the request's data pointer to the write buffer instead of the // caller's scope variable queue_[ind_queue_].data = &write_buffer_[write_buffer_index_]; // update the write buffer index write_buffer_index_ += request.size; } // increment ind_queue_, which is the index at which the next request will // be put in the queue, with wrapping around the queue. if (++ind_queue_ >= QueueLength) { ind_queue_ = 0; } if (!transfer_in_progress_) { StartTransfer(); } // if a transfer is already in progress, this request will be initiated by // the interrupt handlers, our work is done! return true; } bool Channel::CopyDataToWriteBuffer(const void *data, const uint16_t size) { // This protected function is only called from an already thread safe // function, but leaning on the safe side here, I am disabling interrupts // for this one anyway, in case someone changes the design of the I²C class. BlockInterrupts block; // Check if the empty space at the end of the buffer is big enough to // store all of the data if (write_buffer_index_ + size > WriteBufferSize) { // It isn't ==> Check if the empty space at the beginning of the buffer // is big enough to store all of the data instead if (size >= write_buffer_start_) { // There is no contiguous space left in buffer that is big enough, // we can't safely send this Write request. return false; } // We can write at the beginning of the buffer, need to remember that we // wrap at that index in order to properly wrap when updating // write_buffer_start_ when the (previous) transfer will end. wrapping_index_ = write_buffer_index_; write_buffer_index_ = 0; } memcpy(&write_buffer_[write_buffer_index_], data, size); return true; } void Channel::StartTransfer() { transfer_in_progress_ = true; // In DMA mode, a single request can lead to several transfers, when it is // longer than 255 bytes. Therefore we need to check whether this call is a // continuation of a long request or a new request. // Also in case of transfer error, we may need to re-send the last request if (remaining_size_ == 0) { // Ensure thread safety BlockInterrupts block; // This indicates the last request has been successfully sent, hence we // will send the next request in the queue. std::optional<uint8_t> index = buffer_.Get(); if (index == std::nullopt) { // no request in the queue transfer_in_progress_ = false; return; } last_request_ = queue_[*index]; next_data_ = reinterpret_cast<uint8_t *>(last_request_.data); remaining_size_ = last_request_.size; error_retry_ = MaxRetries; } SetupI2CTransfer(); } // Method called by interrupt handler when dma is disabled. This method // transfers data to/from the tx/rx registers from/to *request.data void Channel::TransferByte() { if (remaining_size_ == 0) { // this shouldn't happen, but just to be safe, we stop here. return; } if (last_request_.direction == ExchangeDirection::Read) { ReceiveByte(); } else { SendByte(); } if (--remaining_size_ > 0) { // increment next_data_ pointer only in case we are still expecting more // data to prevent unwarranted memory access next_data_ += sizeof(uint8_t); }; } void Channel::EndTransfer() { // Ensure thread safety BlockInterrupts block; *last_request_.processed = true; if (last_request_.direction == ExchangeDirection::Write) { // free the part of the write buffer that was dedicated to this request write_buffer_start_ += last_request_.size; if (write_buffer_start_ >= wrapping_index_) { // We don't allow data in the same request to wrap around, so we // must detect that the next write data actually starts at index 0 // to properly free the end of the buffer as well write_buffer_start_ = 0; } } transfer_in_progress_ = false; } void Channel::I2CEventHandler() { if (!transfer_in_progress_) { return; } // resend the request in case the slave NACK'd our request if (NackDetected()) { // clear the nack ClearNack(); // the slave is non-responsive --> start the request anew next_data_ = reinterpret_cast<uint8_t *>(last_request_.data); remaining_size_ = last_request_.size; StartTransfer(); } // When we are using DMA, NACK is the only I²C event we are dealing with if (dma_enable_) { return; } if (NextByteNeeded()) { // carry on with the current transfer TransferByte(); } if (TransferReload()) { // To continue a request that is longer than 255 bits, all we need to do // is write a non-zero transfer size, and set the reload byte // accordingly (see [RM] p1151 (Write request) and 1155 (Read request)) WriteTransferSize(); } if (TransferComplete()) { // Send stop condition StopTransfer(); // Clean necessary states EndTransfer(); // And start the next one (if any) StartTransfer(); } } void Channel::I2CErrorHandler() { // I²C error --> clear all error flags (except those that are SMBus only) ClearErrors(); // and restart the request up to error_retry_ times if (--error_retry_ > 0) { next_data_ = reinterpret_cast<uint8_t *>(last_request_.data); remaining_size_ = last_request_.size; } else { // skip this request and go to next one; remaining_size_ = 0; } StartTransfer(); } void STM32Channel::Init(I2CReg *i2c, DMA::Base dma, Speed speed) { i2c_ = i2c; dma_ = dma; // Disable I²C peripheral i2c_->control_reg1.enable = 0; // Set I²C speed using timing values from [RM] table 182 i2c_->timing.full_reg = static_cast<uint32_t>(speed); // Setup DMA channels // if (dma != nullptr) { SetupDMAChannels(dma); // } // enable I²C peripheral i2c_->control_reg1.enable = 1; // configure I²C interrupts i2c_->control_reg1.nack_interrupts = 1; i2c_->control_reg1.error_interrupts = 1; // in DMA mode, we do not treat the transfer-specific ones if (!dma_enable_) { i2c_->control_reg1.rx_interrupts = 1; i2c_->control_reg1.tx_interrupts = 1; i2c_->control_reg1.tx_complete_interrupts = 1; } else { i2c_->control_reg1.rx_interrupts = 0; i2c_->control_reg1.tx_interrupts = 0; i2c_->control_reg1.tx_complete_interrupts = 0; } } void STM32Channel::SetupI2CTransfer() { // set transfer-specific registers per [RM] p1149 to 1158 i2c_->control2.slave_addr_7b = last_request_.slave_address & 0x7f; i2c_->control2.transfer_direction = static_cast<bool>(last_request_.direction); if (dma_enable_) { SetupDMATransfer(); } WriteTransferSize(); i2c_->control2.start = 1; } // Write the remaining size to the appropriate register with reload logic void STM32Channel::WriteTransferSize() { if (remaining_size_ <= 255) { i2c_->control2.n_bytes = static_cast<uint8_t>(remaining_size_); i2c_->control2.reload = 0; } else { i2c_->control2.n_bytes = 255; // Transfer reload is not currently supported by our HAL in DMA mode, // we will treat a reload as a new transfer. In effect this means we // will have to reissue the I²C header and start condition. // It also means that any request that has a (functional) header inside // its data and is longer than 255 bytes may not be processed correctly // by the I²C slave, as it will be split (this is referred to as a // Restart condition rather than Reload) if (!dma_enable_) { i2c_->control2.reload = 1; } else { i2c_->control2.reload = 0; } } } // DMA functions are only meaningful in BARE_STM32 void STM32Channel::SetupDMAChannels(const DMA::Base dma) { // DMA mapping for I²C (see [RM] p299) static struct { DMA::Base dma_base; volatile void *i2c_base; DMA::Channel tx_channel_id; DMA::Channel rx_channel_id; uint8_t request_number; } DmaMap[] = { {DMA::Base::DMA1, I2C1Base, DMA::Channel::Chan6, DMA::Channel::Chan7, 3}, {DMA::Base::DMA1, I2C2Base, DMA::Channel::Chan4, DMA::Channel::Chan5, 3}, {DMA::Base::DMA1, I2C3Base, DMA::Channel::Chan2, DMA::Channel::Chan3, 3}, {DMA::Base::DMA2, I2C1Base, DMA::Channel::Chan7, DMA::Channel::Chan6, 5}, {DMA::Base::DMA2, I2C4Base, DMA::Channel::Chan2, DMA::Channel::Chan1, 0}, }; for (auto &map : DmaMap) { if (dma == map.dma_base && i2c_ == map.i2c_base) { auto *dma_register = DMA::get_register(dma); dma_ = dma; tx_channel_ = &dma_register->channel[static_cast<uint8_t>(map.tx_channel_id)]; rx_channel_ = &dma_register->channel[static_cast<uint8_t>(map.rx_channel_id)]; // Tell the STM32 that those two DMA channels are used for I2C DMA::SelectChannel(dma, map.rx_channel_id, map.request_number); DMA::SelectChannel(dma, map.tx_channel_id, map.request_number); // configure both DMA channels to handle I²C transfers ConfigureDMAChannel(rx_channel_, ExchangeDirection::Read); ConfigureDMAChannel(tx_channel_, ExchangeDirection::Write); dma_enable_ = true; i2c_->control_reg1.dma_rx = 1; i2c_->control_reg1.dma_tx = 1; break; } } } void I2C::STM32Channel::ConfigureDMAChannel(volatile DmaReg::ChannelRegs *channel, ExchangeDirection direction) { channel->config.priority = 0b01; // medium priority channel->config.tx_error_interrupt = 1; // interrupt on error channel->config.half_tx_interrupt = 0; // no half-transfer interrupt channel->config.tx_complete_interrupt = 1; // interrupt on DMA complete channel->config.mem2mem = 0; // memory-to-memory mode disabled channel->config.memory_size = static_cast<uint8_t>(DMA::TransferSize::Byte); channel->config.peripheral_size = static_cast<uint8_t>(DMA::TransferSize::Byte); channel->config.memory_increment = 1; // increment dest address channel->config.peripheral_increment = 0; // don't increment source address channel->config.circular = 0; if (direction == ExchangeDirection::Read) { channel->config.direction = static_cast<uint8_t>(DMA::ChannelDir::PeripheralToMemory); channel->peripheral_address = &(i2c_->rx_data); } else { channel->config.direction = static_cast<uint8_t>(DMA::ChannelDir::MemoryToPeripheral); channel->peripheral_address = &(i2c_->tx_data); } } void STM32Channel::SetupDMATransfer() { if (!dma_enable_) { return; } // to be on the safe size, disable both channels in case they weren't // (likely when this is called as a "retry after error") rx_channel_->config.enable = 0; tx_channel_->config.enable = 0; volatile DmaReg::ChannelRegs *channel{nullptr}; if (last_request_.direction == ExchangeDirection::Read) { channel = rx_channel_; } else { channel = tx_channel_; } channel->memory_address = next_data_; if (remaining_size_ <= 255) { channel->count = remaining_size_; } else { channel->count = 255; } // when using DMA, we need to use autoend, otherwise the STOP condition // which we issue at the end of the DMA transfer (which means the last byte // has been written to the register) may arrive before the last byte is // actually written on the line. Tests with both DMA and I2C interrupts // enabled to send Stop at the end of the I2C transfer were inconclusive. i2c_->control2.autoend = 1; channel->config.enable = 1; } void STM32Channel::DMAIntHandler(DMA::Channel chan) { if (!dma_enable_ || !transfer_in_progress_) return; auto *dma_register = DMA::get_register(dma_); dma_register->channel[static_cast<uint8_t>(chan)].config.enable = 0; if (DMA::IntStatus(dma_, chan, DMA::Interrupt::TransferComplete)) { if (remaining_size_ > 255) { // decrement remaining size by 255 (the size of the DMA transfer) remaining_size_ = static_cast<uint16_t>(remaining_size_ - 255); next_data_ += 255 * sizeof(uint8_t); } else { remaining_size_ = 0; EndTransfer(); } } else if (DMA::IntStatus(dma_, chan, DMA::Interrupt::TransferError)) { // we are dealing with an error --> reset transfer (up to MaxRetries // times) if (--error_retry_ > 0) { next_data_ = reinterpret_cast<uint8_t *>(last_request_.data); remaining_size_ = last_request_.size; } else { // skip this request and go to next request; remaining_size_ = 0; } } // clear all interrupts and (re-)start the current or next transfer DMA::ClearInt(dma_, chan, DMA::Interrupt::Global); StartTransfer(); } } // namespace I2C
15,981
5,510
// Copyright 2019 Carnegie Mellon University. See LICENSE file for terms. #include "test.hpp" int main() { path_start(); int n=INT_RAND, k=INT_RAND, j=INT_RAND; int x=0; if ( n == 0 ) { x++; } if (k == 0) { x++; } if (j == 0) { x++; } if (x == 3) { path_goal(); } }
309
154
/*************************************************************** * * Copyright (C) 1990-2008, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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. * ***************************************************************/ /*************************************************************** * Headers ***************************************************************/ #include "condor_common.h" #include "condor_config.h" #include "condor_uid.h" #include "hibernator.tools.h" #include "path_utils.h" #include "../condor_daemon_core.V6/condor_daemon_core.h" /*************************************************************** * UserDefinedToolsHibernator class ***************************************************************/ UserDefinedToolsHibernator::UserDefinedToolsHibernator () throw () : HibernatorBase (), m_keyword ( "HIBERNATE" ), m_reaper_id ( -1 ) { for ( unsigned i = 0; i <= 10; ++i ) { m_tool_paths[i] = NULL; } configure (); } UserDefinedToolsHibernator::UserDefinedToolsHibernator ( const MyString &keyword ) throw () : HibernatorBase (), m_keyword ( keyword ), m_reaper_id ( -1 ) { for ( unsigned i = 0; i <= 10; ++i ) { m_tool_paths[i] = NULL; } configure (); } UserDefinedToolsHibernator::~UserDefinedToolsHibernator () throw () { for ( unsigned i = 1; i <= 10; ++i ) { if ( NULL != m_tool_paths[i] ) { free ( m_tool_paths[i] ); m_tool_paths[i] = NULL; } } if ( -1 != m_reaper_id ) { daemonCore->Cancel_Reaper ( m_reaper_id ); } } const char* UserDefinedToolsHibernator::getMethod ( void ) const { return "user defined tools"; } /** We define a 'C' style Reaper for use in configure() to eliminate the problem of a cast being made between different pointer to member representations (because of multiple inheritance--C++ Reapers require the object to be of type Service); If we used a C++ style Reaper the compiler may generate incorrect code. */ int UserDefinedToolsHibernator::userDefinedToolsHibernatorReaper ( int pid, int ) { /** Make sure the hibernator didn't leak any processes */ daemonCore->Kill_Family ( pid ); return TRUE; } void UserDefinedToolsHibernator::configure () { MyString name, error; unsigned states = HibernatorBase::NONE; const char *description = NULL; char *arguments = NULL; HibernatorBase::SLEEP_STATE state = HibernatorBase::NONE; bool ok = false; /** There are no tools for S0, or "NONE" */ m_tool_paths[0] = NULL; /** Pull the paths for the rest of the sleep states from the configuration file */ for ( unsigned i = 1; i <= 10; ++i ) { /** Clean out the old path information */ if ( NULL != m_tool_paths[i] ) { free ( m_tool_paths[i] ); m_tool_paths[i] = NULL; } /** Convert the current index to the sleep state equivalent */ state = HibernatorBase::intToSleepState ( i ); if ( HibernatorBase::NONE == state ) { continue; } /** Convert the sleep state to a human consumable description */ description = HibernatorBase::sleepStateToString ( state ); if ( NULL == description ) { continue; } dprintf ( D_FULLDEBUG, "UserDefinedToolsHibernator: state = %d, desc = %s\n", state, "S1" ); /** Build the tool look-up parameter for the tool's path */ name.formatstr ( "%s_USER_%s_TOOL", "HIBERNATE", "S1" ); /** Grab the user defined executable path */ m_tool_paths[i] = validateExecutablePath ( name.Value () ); if ( NULL != m_tool_paths[i] ) { /** Make the path the first argument to Create_Process */ m_tool_args[i].AppendArg ( m_tool_paths[i] ); /** Build the tool look-up parameter for the tool's argument list */ name.formatstr ( "%s_USER_%s_ARGS", m_keyword.Value(), description ); /** Grab the command's arguments */ arguments = param ( name.Value () ); if ( NULL != arguments ) { /** Parse the command-line arguments */ ok = m_tool_args[i].AppendArgsV1WackedOrV2Quoted ( arguments, &error ); if ( !ok ) { dprintf ( D_FULLDEBUG, "UserDefinedToolsHibernator::configure: failed " "to parse the tool arguments defined in the " "configuration file: %s\n", error.Value() ); } /** Dump the param'd value */ free ( arguments ); } /** Tally the supported state */ states |= state; } else { dprintf ( D_FULLDEBUG, "UserDefinedToolsHibernator::configure: the executable " "(%s) defined in the configuration file is invalid.\n", m_tool_paths[i] ); } } /** Now set the supported states */ setStates ( states ); /** Finally, register the reaper that will clean up after the user defined tool and its children */ m_reaper_id = daemonCore->Register_Reaper ( "UserDefinedToolsHibernator Reaper", (ReaperHandlercpp) &UserDefinedToolsHibernator::userDefinedToolsHibernatorReaper, "UserDefinedToolsHibernator Reaper", NULL ); } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterState ( HibernatorBase::SLEEP_STATE state ) const { /** Make sure a tool for this sleep state has been defined */ unsigned index = sleepStateToInt ( state ); if ( NULL == m_tool_paths[index] ) { dprintf ( D_FULLDEBUG, "Hibernator::%s tool not configured.\n", HibernatorBase::sleepStateToString ( state ) ); return HibernatorBase::NONE; } /** Tell DaemonCore to register the process family so we can safely kill everything from the reaper */ FamilyInfo fi; fi.max_snapshot_interval = param_integer ( "PID_SNAPSHOT_INTERVAL", 15 ); /** Run the user tool */ int pid = daemonCore->Create_Process ( m_tool_paths[index], m_tool_args[index], PRIV_CONDOR_FINAL, m_reaper_id, FALSE, FALSE, NULL, NULL, &fi ); if ( FALSE == pid ) { dprintf ( D_ALWAYS, "UserDefinedToolsHibernator::enterState: Create_Process() " "failed\n" ); return HibernatorBase::NONE; } return state; } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterStateStandBy ( bool /*force*/ ) const { return enterState ( HibernatorBase::S1 ); } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterStateSuspend ( bool /*force*/ ) const { return enterState ( HibernatorBase::S3 ); } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterStateHibernate ( bool /*force*/ ) const { return enterState ( HibernatorBase::S4 ); } HibernatorBase::SLEEP_STATE UserDefinedToolsHibernator::enterStatePowerOff ( bool /*force*/ ) const { return enterState ( HibernatorBase::S5 ); }
7,124
2,626
// This file is part of AsmJit project <https://asmjit.com> // // See asmjit.h or LICENSE.md for license and copyright information // SPDX-License-Identifier: Zlib #include "../core/api-build_p.h" #if !defined(ASMJIT_NO_AARCH64) && !defined(ASMJIT_NO_BUILDER) #include "../arm/a64assembler.h" #include "../arm/a64builder.h" #include "../arm/a64emithelper_p.h" ASMJIT_BEGIN_SUB_NAMESPACE(a64) // a64::Builder - Construction & Destruction // ========================================= Builder::Builder(CodeHolder* code) noexcept : BaseBuilder() { _archMask = uint64_t(1) << uint32_t(Arch::kAArch64); assignEmitterFuncs(this); if (code) code->attach(this); } Builder::~Builder() noexcept {} // a64::Builder - Events // ===================== Error Builder::onAttach(CodeHolder* code) noexcept { return Base::onAttach(code); } Error Builder::onDetach(CodeHolder* code) noexcept { return Base::onDetach(code); } // a64::Builder - Finalize // ======================= Error Builder::finalize() { ASMJIT_PROPAGATE(runPasses()); Assembler a(_code); a.addEncodingOptions(encodingOptions()); a.addDiagnosticOptions(diagnosticOptions()); return serializeTo(&a); } ASMJIT_END_SUB_NAMESPACE #endif // !ASMJIT_NO_AARCH64 && !ASMJIT_NO_BUILDER
1,263
494
// bin/convert-ali.cc // Copyright 2009-2011 Microsoft Corporation // 2013 Johns Hopkins University (author: Daniel Povey) // See ../../COPYING for clarification regarding multiple 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 // // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include "base/kaldi-common.h" #include "util/common-utils.h" #include "gmm/am-diag-gmm.h" #include "hmm/transition-model.h" #include "hmm/hmm-utils.h" #include "hmm/tree-accu.h" // for ReadPhoneMap int main(int argc, char *argv[]) { using namespace kaldi; typedef kaldi::int32 int32; try { const char *usage = "Convert alignments from one decision-tree/model to another\n" "Usage: convert-ali [options] <old-model> <new-model> <new-tree> " "<old-alignments-rspecifier> <new-alignments-wspecifier>\n" "e.g.: \n" " convert-ali old/final.mdl new/0.mdl new/tree ark:old/ali.1 ark:new/ali.1\n"; int32 frame_subsampling_factor = 1; bool reorder = true; std::string phone_map_rxfilename; ParseOptions po(usage); po.Register("phone-map", &phone_map_rxfilename, "File name containing old->new phone mapping (each line is: " "old-integer-id new-integer-id)"); po.Register("reorder", &reorder, "True if you want the converted alignments to be 'reordered' " "versus the way they appear in the HmmTopology object"); po.Register("frame-subsampling-factor", &frame_subsampling_factor, "Can be used in converting alignments to reduced frame rates."); po.Read(argc, argv); if (po.NumArgs() != 5) { po.PrintUsage(); exit(1); } std::string old_model_filename = po.GetArg(1); std::string new_model_filename = po.GetArg(2); std::string new_tree_filename = po.GetArg(3); std::string old_alignments_rspecifier = po.GetArg(4); std::string new_alignments_wspecifier = po.GetArg(5); std::vector<int32> phone_map; if (phone_map_rxfilename != "") { // read phone map. ReadPhoneMap(phone_map_rxfilename, &phone_map); } SequentialInt32VectorReader alignment_reader(old_alignments_rspecifier); Int32VectorWriter alignment_writer(new_alignments_wspecifier); TransitionModel old_trans_model; ReadKaldiObject(old_model_filename, &old_trans_model); TransitionModel new_trans_model; ReadKaldiObject(new_model_filename, &new_trans_model); if (!(old_trans_model.GetTopo() == new_trans_model.GetTopo())) KALDI_WARN << "Toplogies of models are not equal: " << "conversion may not be correct or may fail."; ContextDependency new_ctx_dep; // the tree. ReadKaldiObject(new_tree_filename, &new_ctx_dep); int num_success = 0, num_fail = 0; for (; !alignment_reader.Done(); alignment_reader.Next()) { std::string key = alignment_reader.Key(); const std::vector<int32> &old_alignment = alignment_reader.Value(); std::vector<int32> new_alignment; if (ConvertAlignment(old_trans_model, new_trans_model, new_ctx_dep, old_alignment, frame_subsampling_factor, reorder, (phone_map_rxfilename != "" ? &phone_map : NULL), &new_alignment)) { alignment_writer.Write(key, new_alignment); num_success++; } else { KALDI_WARN << "Could not convert alignment for key " << key <<" (possibly truncated alignment?)"; num_fail++; } } KALDI_LOG << "Succeeded converting alignments for " << num_success << " files, failed for " << num_fail; if (num_success != 0) return 0; else return 1; } catch(const std::exception &e) { std::cerr << e.what(); return -1; } }
4,465
1,473
/* NxS Tabpages - written by Saivert */ //#include "StdAfx.h" #include "nxstabpages.h" NxS_TabPages::~NxS_TabPages() { Clear(); } HWND NxS_TabPages::SetTabCtrl(HWND NewTabCtrl) { HWND tmp; tmp = m_hwTab; if (IsWindow(NewTabCtrl)) { if (GetCount()>0) TabCtrl_DeleteAllItems(m_hwTab); m_hwTab = NewTabCtrl; if (GetCount()>0) TabCtrl_DeleteAllItems(m_hwTab); TabCtrl_SetItemExtra(m_hwTab, NXSTABPAGES_TABITEMSIZE); } return tmp; } bool NxS_TabPages::DelPage(int index) { TABITEM item; if (TabCtrl_GetItem(m_hwTab, index, &item)) { if (item.dlghandle) { NMHDR hdr; hdr.code = PSN_RESET; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (TRUE==GetWindowLong(item.dlghandle, DWL_MSGRESULT)) return false; } DestroyWindow(item.dlghandle); } TabCtrl_DeleteItem(m_hwTab, index); return true; } return false; } bool NxS_TabPages::GetPage(int index, TABITEM &tp) { return TabCtrl_GetItem(m_hwTab, index, &tp)>0; } NxS_TabPages::TABITEM& NxS_TabPages::Pages(int index) { TabCtrl_GetItem(m_hwTab, index, &m_tptemp); return m_tptemp; } bool NxS_TabPages::SendApply() { bool res=true; TABITEM item; //First we check if the active page wants to loose activation if (m_curwnd) { NMHDR hdr; hdr.code = PSN_KILLACTIVE; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT)) return false; } } //If the active page said OK, we send a PSN_APPLY notification message to //all the pages. Any one of the pages can return PSNRET_INVALID_NOCHANGEPAGE //to make SendApply() return false. This is a clue to keep the host dialog open. for (int i=0; i<GetCount(); i++) { if (TabCtrl_GetItem(m_hwTab, i, &item)) { if (item.dlghandle) { NMHDR hdr; hdr.code = PSN_APPLY; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (PSNRET_INVALID_NOCHANGEPAGE==GetWindowLong(item.dlghandle, DWL_MSGRESULT)) res=false; } } } } return res; } bool NxS_TabPages::Clear(void) { int i; while ((i = GetCount()) > 0) { if (!DelPage(i-1)) return false; } m_curwnd=NULL; //There's no longer an active dialog now... return true; } bool NxS_TabPages::HandleNotifications(WPARAM wParam, LPARAM lParam) { int idTabCtl = (int) LOWORD(wParam); LPNMHDR lpnmhdr = (LPNMHDR) lParam; if (lpnmhdr->hwndFrom == m_hwTab) { if (lpnmhdr->code == TCN_SELCHANGING) { NMHDR hdr; hdr.code = PSN_KILLACTIVE; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT)) return true; } } if (lpnmhdr->code == TCN_SELCHANGE) { return SelectPage(GetSelPage()); } } if (lpnmhdr->code == TTN_NEEDTEXT) { LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT) lParam; TABITEM item; //Make sure it's our tab control's tooltip calling in... if (lpnmhdr->hwndFrom != TabCtrl_GetToolTips(m_hwTab)) return false; TabCtrl_GetItem(m_hwTab, lpttt->hdr.idFrom, &item); lpttt->hinst = IS_INTRESOURCE(item.tip)?m_hinst:NULL; lpttt->lpszText = item.tip; } return false; } int NxS_TabPages::AddPage(char* lpszTitle, char* lpszDlgRes, DLGPROC lpfnDlgProc, char* lpszTip) { TABITEM i; if (!lpszDlgRes) return 0; if (IS_INTRESOURCE(lpszDlgRes)) i.dialog = lpszDlgRes; else i.SetDlgRes(lpszDlgRes); if (IS_INTRESOURCE(lpszTip)) i.tip = lpszTip; else i.SetTip(lpszTip); if (!lpszTitle) { int len; HWND hwTemp; hwTemp = CreateDialog(m_hinst,(LPCTSTR)lpszDlgRes, GetDesktopWindow(), lpfnDlgProc); len = GetWindowTextLength(hwTemp)+1; i.title = new char[len]; GetWindowText(hwTemp, i.title, len); DestroyWindow(hwTemp); } else i.SetTitle(lpszTitle); i.dlgproc = lpfnDlgProc; i.dlghandle = NULL; //Dialog not created yet... i.itemhdr.mask = TCIF_TEXT|TCIF_PARAM; i.itemhdr.pszText = i.title; return TabCtrl_InsertItem(m_hwTab, GetCount(), &i); } bool NxS_TabPages::SelectPage(int index) { HWND hwndDlg; TABITEM item; hwndDlg = GetParent(m_hwTab); if (index >= 0) { if (m_curwnd) { NMHDR hdr; hdr.code = PSN_KILLACTIVE; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(m_curwnd, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (TRUE==GetWindowLong(m_curwnd, DWL_MSGRESULT)) return false; } ShowWindow(m_curwnd, SW_HIDE); } if (!TabCtrl_GetItem(m_hwTab, index, &item)) return false; if (NULL==item.dlghandle) { item.SetDlgHandle( CreateDialogParam(m_hinst, item.dialog, hwndDlg, item.dlgproc, LPARAM(&item)) ); SetWindowLong(item.dlghandle, GWL_STYLE, WS_CHILD); SetWindowLong(item.dlghandle, GWL_EXSTYLE, WS_EX_CONTROLPARENT); SetParent(item.dlghandle, hwndDlg); EnableThemeDlgTexture(item.dlghandle, m_UseDlgTexture?ETDT_ENABLETAB:ETDT_DISABLE); //Update item.dlghandle (application data item) TabCtrl_SetItem(m_hwTab, index, &item); } { NMHDR hdr; hdr.code = PSN_SETACTIVE; hdr.hwndFrom = (HWND)this; hdr.idFrom = 0; if (SendMessage(item.dlghandle, WM_NOTIFY, 0, (LPARAM)&hdr)) { if (0==GetWindowLong(item.dlghandle, DWL_MSGRESULT)) return false; } } if (m_curwnd=item.dlghandle) { RECT r; GetWindowRect(m_hwTab,&r); TabCtrl_AdjustRect(m_hwTab, FALSE, &r); MapWindowPoints(HWND_DESKTOP, hwndDlg, LPPOINT(&r), 2); //Make right & bottom be the width & height r.right -= r.left; r.bottom -= r.top; SetWindowPos(item.dlghandle, 0, r.left, r.top, r.right, r.bottom, SWP_NOACTIVATE|SWP_NOZORDER); ShowWindow(item.dlghandle,SW_SHOWNA); } TabCtrl_SetCurSel(m_hwTab, index); } return true; } void NxS_TabPages::AdjustPageSize(void) { RECT r; GetWindowRect(m_hwTab,&r); TabCtrl_AdjustRect(m_hwTab, FALSE, &r); MapWindowPoints(HWND_DESKTOP, GetParent(m_hwTab), LPPOINT(&r), 2); //Make right & bottom be the width & height r.right -= r.left; r.bottom -= r.top; SetWindowPos(m_curwnd, 0, r.left, r.top, r.right, r.bottom, SWP_NOACTIVATE|SWP_NOZORDER); } bool NxS_TabPages::SetUseThemedDlgTexture(bool use) { bool prev=m_UseDlgTexture; // If there are already some pages added, // change the state for these pages' dialogs. if (int count=GetCount()) { for (int i=0;i<count;i++) { if (HWND hwndDlg=Pages(i).dlghandle) EnableThemeDlgTexture(hwndDlg, use?ETDT_ENABLETAB:ETDT_DISABLE); } } return prev; } // A wrapper for the "EnableThemeDialogTexture" function located in // UXTHEME.DLL. When you call this with the handle of a dialog, the // dialog's background get a texture that matches the current theme. // This only works on a Windows XP machine. HRESULT NxS_TabPages::EnableThemeDlgTexture(HWND hwnd, DWORD flags) { typedef HRESULT (WINAPI * ENABLETHEMEDIALOGTEXTURE)(HWND, DWORD); ENABLETHEMEDIALOGTEXTURE pfnETDT; HINSTANCE hDll; HRESULT res=-1; if (NULL != (hDll = LoadLibrary(TEXT("uxtheme.dll")))) { if (NULL != (pfnETDT = (ENABLETHEMEDIALOGTEXTURE)GetProcAddress(hDll, "EnableThemeDialogTexture"))) { res = pfnETDT(hwnd, ETDT_ENABLETAB); } FreeLibrary(hDll); } return res; } //#EOF
7,629
3,689
// // 2_inSearchOfAnEasyProblem.cpp // competitive_programming // // Created by The Times of Hacker on 05/04/20. // Copyright © 2020 isharma. All rights reserved. // #include<iostream> #include<math.h> using namespace std; int main(){ int n; int temp[101]; cin >> n; bool flag = true; for (int i = 0; i<n; i++){ cin>>temp[i]; if(temp[i]){ flag=false; } } if(flag){ cout<<"EASY"; } else{ cout<<"HARD"; } return 0; }
529
208
#pragma once #include <memory> #include <string> #include <unordered_set> #include <vector> namespace opossum { class AbstractCardinalityEstimator; class AbstractCostEstimator; class AbstractLQPNode; class LogicalPlanRootNode; class LQPSubqueryExpression; class AbstractRule { public: virtual ~AbstractRule() = default; /** * This function applies the concrete Optimizer Rule to an LQP. * The default implementation * (1) optimizes the root LQP * (2) optimizes all (nested) subquery LQPs of the optimized root LQP, one-by-one. * * IMPORTANT NOTES ON OPTIMIZING SUBQUERY LQPS: * * Multiple Expressions in different nodes might reference the same LQP. Most commonly this will be the case * for a ProjectionNode computing a subquery and a subsequent PredicateNode filtering based on it. * We do not WANT to optimize the LQP twice (optimization takes time after all) and we CANNOT optimize it * twice, since, e.g., a non-deterministic rule, could produce two different LQPs while optimizing and then the * SubqueryExpression in the PredicateNode couldn't be resolved to a column anymore. There are more subtle * ways LQPs might break in this scenario, and frankly, this is one of the weak links in the expression system... * * ...long story short: * !!! * EACH UNIQUE SUB-LQP IS ONLY OPTIMIZED ONCE, EVEN IF IT OCCURS IN DIFFERENT NODES/EXPRESSIONS. * !!! * * Rules can define their own strategy of optimizing subquery LQPs by overriding this function. See, for example, the * StoredTableColumnAlignmentRule. */ virtual void apply_to_plan(const std::shared_ptr<LogicalPlanRootNode>& lqp_root) const; virtual std::string name() const = 0; std::shared_ptr<AbstractCostEstimator> cost_estimator; protected: /** * This function applies the concrete rule to the given plan, but not to its subquery plans. * * DO NOT CALL THIS FUNCTION RECURSIVELY! * The reason for this can be found in diamond LQPs: When using "trivial" recursion, we would go down both on the * left and the right side of the diamond. On both sides, we would reach the bottom of the diamond. From there, we * would look at each node twice. visit_lqp prevents this by tracking which nodes have already been visited and * avoiding visiting a node twice. */ virtual void _apply_to_plan_without_subqueries(const std::shared_ptr<AbstractLQPNode>& lqp_root) const = 0; }; } // namespace opossum
2,525
776
#ifdef PEGASUS_OS_AIX #ifndef __UNIX_SWAPSPACECHECK_PRIVATE_H #define __UNIX_SWAPSPACECHECK_PRIVATE_H #endif #endif
122
66
// Copyright 2020 modio. All Rights Reserved. // Released under MIT. #include "BlueprintCallbackProxies/CallbackProxy_GetAllModFiles.h" #include "ModioSubsystem.h" #include "Engine/Engine.h" UCallbackProxy_GetAllModfiles::UCallbackProxy_GetAllModfiles(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } UCallbackProxy_GetAllModfiles* UCallbackProxy_GetAllModfiles::GetAllModfiles(UObject* WorldContext, int32 ModId) { UCallbackProxy_GetAllModfiles* Proxy = NewObject<UCallbackProxy_GetAllModfiles>(); Proxy->SetFlags(RF_StrongRefOnFrame); Proxy->ModId = ModId; Proxy->WorldContextObject = WorldContext; return Proxy; } void UCallbackProxy_GetAllModfiles::Activate() { UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull); FModioSubsystemPtr Modio = FModioSubsystem::Get(World); if (Modio.IsValid()) { Modio->GetAllModfiles(this->ModId, FModioModfileArrayDelegate::CreateUObject(this, &UCallbackProxy_GetAllModfiles::OnGetAllModfilesDelegate)); } else { // @todonow: Make something more pretty than this FModioResponse Response; TArray<FModioModfile> Mods; OnFailure.Broadcast(Response, Mods); } } void UCallbackProxy_GetAllModfiles::OnGetAllModfilesDelegate(FModioResponse Response, const TArray<FModioModfile>& Modfiles) { if (Response.Code >= 200 && Response.Code < 300) { OnSuccess.Broadcast(Response, Modfiles); } else { OnFailure.Broadcast(Response, Modfiles); } }
1,504
525
#pragma once #include <string> #include <vector> #include <boost/smart_ptr.hpp> #include <boost/algorithm/string.hpp> #include "vfspp_compiler_detection.h" #include "vfspp_export.h" namespace vfspp { class IFileSystemEntry; typedef std::string string_type; typedef boost::shared_ptr<IFileSystemEntry> FileEntryPointer; const char DirectorySeparatorChar = '/'; const char * const DirectorySeparatorStr = "/"; enum EntryType { UNKNOWN, DIRECTORY, FILE }; enum Operations { OP_READ = 1 << 0, OP_WRITE = 1 << 1, OP_DELETE = 1 << 2, OP_CREATE = 1 << 3 }; class VFSPP_EXPORT InvalidOperationException : public std::exception { public: InvalidOperationException(const string_type& message = "Invalid operation!") throw() : msg(message) {} virtual ~InvalidOperationException() throw() {} const char* what() const throw() VFSPP_OVERRIDE { return msg.c_str(); } private: string_type msg; }; class VFSPP_EXPORT FileSystemException : public std::exception { public: FileSystemException(const string_type& message = "Invalid operation!") throw() : msg(message) {} virtual ~FileSystemException() throw() {} const char* what() const throw() VFSPP_OVERRIDE { return msg.c_str(); } private: string_type msg; }; class VFSPP_EXPORT IFileSystemEntry { public: enum OpenMode { MODE_READ = 1 << 0, MODE_WRITE = 1 << 1, MODE_MEMORY_MAPPED = 1 << 2, }; protected: string_type path; public: IFileSystemEntry(const string_type& pathIn); virtual ~IFileSystemEntry() {} bool isRoot() const { return path.size() == 0; } const string_type& getPath() const { return path; } virtual FileEntryPointer getChild(const string_type& path) = 0; virtual size_t numChildren() = 0; virtual void listChildren(std::vector<FileEntryPointer>& outVector) = 0; virtual boost::shared_ptr<std::streambuf> open(int mode = MODE_READ) = 0; virtual EntryType getType() const = 0; virtual bool deleteChild(const string_type& name) = 0; virtual FileEntryPointer createEntry(EntryType type, const string_type& name) = 0; virtual void rename(const string_type& newPath) = 0; virtual time_t lastWriteTime() = 0; }; class VFSPP_EXPORT IFileSystem { public: virtual ~IFileSystem() {} virtual IFileSystemEntry* getRootEntry() = 0; virtual int supportedOperations() const = 0; virtual string_type getName() const = 0; }; }
2,414
919
// Copyright 2019 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 "base/strings/strcat.h" #include "chrome/browser/ash/app_mode/kiosk_app_manager.h" #include "chrome/browser/ash/app_mode/kiosk_app_types.h" #include "chrome/browser/ash/app_mode/web_app/mock_web_kiosk_app_launcher.h" #include "chrome/browser/ash/login/app_mode/kiosk_launch_controller.h" #include "chrome/browser/ash/login/test/kiosk_test_helpers.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/external_provider_impl.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/webui/chromeos/login/app_launch_splash_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/fake_app_launch_splash_screen_handler.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/testing_profile.h" #include "components/account_id/account_id.h" #include "components/policy/core/browser/browser_policy_connector.h" #include "components/policy/core/common/mock_configuration_policy_provider.h" #include "components/policy/policy_constants.h" #include "components/session_manager/core/session_manager.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/browser_test.h" #include "extensions/browser/extension_system.h" #include "extensions/browser/pref_names.h" #include "extensions/browser/test_extension_registry_observer.h" #include "extensions/common/extension.h" #include "extensions/common/extension_builder.h" #include "testing/gtest/include/gtest/gtest.h" namespace ash { using ::testing::_; const char kExtensionId[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; const char kExtensionName[] = "extension_name"; const char kInvalidExtensionId[] = "invalid_id"; const char kInvalidExtensionName[] = "invalid_name"; // URL of Chrome Web. const char kExtensionUpdateUrl[] = "https://clients2.google.com/service/update2/crx"; class KioskLaunchControllerTest : public InProcessBrowserTest, public ::testing::WithParamInterface<KioskAppType> { public: using AppState = KioskLaunchController::AppState; using NetworkUIState = KioskLaunchController::NetworkUIState; KioskLaunchControllerTest() = default; KioskLaunchControllerTest(const KioskLaunchControllerTest&) = delete; KioskLaunchControllerTest& operator=(const KioskLaunchControllerTest&) = delete; void SetUpOnMainThread() override { InProcessBrowserTest::SetUpOnMainThread(); auto app_launcher = std::make_unique<MockWebKioskAppLauncher>(); view_ = std::make_unique<FakeAppLaunchSplashScreenHandler>(); app_launcher_ = app_launcher.get(); disable_wait_timer_and_login_operations_for_testing_ = KioskLaunchController::DisableWaitTimerAndLoginOperationsForTesting(); controller_ = KioskLaunchController::CreateForTesting( view_.get(), std::move(app_launcher)); switch (GetParam()) { case KioskAppType::kArcApp: kiosk_app_id_ = KioskAppId::ForArcApp(EmptyAccountId()); break; case KioskAppType::kChromeApp: kiosk_app_id_ = KioskAppId::ForChromeApp(std::string()); KioskAppManager::Get()->AddAppForTest(std::string(), EmptyAccountId(), GURL(), std::string()); break; case KioskAppType::kWebApp: kiosk_app_id_ = KioskAppId::ForWebApp(EmptyAccountId()); break; } } KioskLaunchController* controller() { return controller_.get(); } KioskAppLauncher::Delegate* launch_controls() { return static_cast<KioskAppLauncher::Delegate*>(controller_.get()); } KioskProfileLoader::Delegate* profile_controls() { return static_cast<KioskProfileLoader::Delegate*>(controller_.get()); } AppLaunchSplashScreenView::Delegate* view_controls() { return static_cast<AppLaunchSplashScreenView::Delegate*>(controller_.get()); } MockWebKioskAppLauncher* launcher() { return app_launcher_; } void ExpectState(AppState app_state, NetworkUIState network_state) { EXPECT_EQ(app_state, controller_->app_state_); EXPECT_EQ(network_state, controller_->network_ui_state_); } void ExpectViewState(AppLaunchSplashScreenView::AppLaunchState launch_state) { EXPECT_EQ(launch_state, view_->GetAppLaunchState()); } void FireSplashScreenTimer() { controller_->OnTimerFire(); } void SetOnline(bool online) { view_->SetNetworkReady(online); static_cast<AppLaunchSplashScreenView::Delegate*>(controller_.get()) ->OnNetworkStateChanged(online); } Profile* profile() { return browser()->profile(); } FakeAppLaunchSplashScreenHandler* view() { return view_.get(); } KioskAppId kiosk_app_id() { return kiosk_app_id_; } private: ScopedCanConfigureNetwork can_configure_network_for_testing_{true, false}; std::unique_ptr<base::AutoReset<bool>> disable_wait_timer_and_login_operations_for_testing_; std::unique_ptr<FakeAppLaunchSplashScreenHandler> view_; MockWebKioskAppLauncher* app_launcher_; // owned by `controller_`. std::unique_ptr<KioskLaunchController> controller_; KioskAppId kiosk_app_id_; }; IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, RegularFlow) { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppInstalling(); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); launch_controls()->OnAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, AlreadyInstalled) { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->OnAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, ConfigureNetworkBeforeProfile) { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); // User presses the hotkey. view_controls()->OnNetworkConfigRequested(); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNeedToShow); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kShowingNetworkConfigureUI); // WebKioskAppLauncher::Initialize call is synchronous, we have to call the // response now. launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), RestartLauncher()).Times(1); view_controls()->OnNetworkConfigFinished(); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingProfile); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); launch_controls()->OnAppPrepared(); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); // Skipping INSTALLED state since there splash screen timer is stopped when // network configure ui was shown. launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, ConfigureNetworkDuringInstallation) { SetOnline(false); controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppInstalling(); // User presses the hotkey, current installation is canceled. EXPECT_CALL(*launcher(), RestartLauncher()).Times(1); view_controls()->OnNetworkConfigRequested(); // Launcher restart causes network to be requested again. launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), RestartLauncher()).Times(1); view_controls()->OnNetworkConfigFinished(); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingProfile); launch_controls()->OnAppInstalling(); ExpectState(AppState::kInstallingApp, NetworkUIState::kNotShowing); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); launch_controls()->OnAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerTest, ConnectionLostDuringInstallation) { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingNetwork); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppInstalling(); ExpectState(AppState::kInstallingApp, NetworkUIState::kNotShowing); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); SetOnline(false); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kShowing); // view state? EXPECT_CALL(*launcher(), RestartLauncher()).Times(1); view_controls()->OnNetworkConfigFinished(); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kPreparingProfile); launch_controls()->OnAppInstalling(); ExpectState(AppState::kInstallingApp, NetworkUIState::kNotShowing); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); launch_controls()->OnAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } INSTANTIATE_TEST_SUITE_P(All, KioskLaunchControllerTest, testing::Values(KioskAppType::kArcApp, KioskAppType::kChromeApp, KioskAppType::kWebApp)); class KioskLaunchControllerWithExtensionTest : public KioskLaunchControllerTest { public: void SetupForceList(const std::string& extension_id) { std::unique_ptr<base::Value> dict = extensions::DictionaryBuilder() .Set(extension_id, extensions::DictionaryBuilder() .Set(extensions::ExternalProviderImpl::kExternalUpdateUrl, kExtensionUpdateUrl) .Build()) .Build(); ProfileManager::GetPrimaryUserProfile()->GetPrefs()->Set( extensions::pref_names::kInstallForceList, std::move(*dict)); base::Value list(base::Value::Type::LIST); list.Append(base::StrCat({extension_id, ";", kExtensionUpdateUrl})); policy::PolicyMap map; map.Set(policy::key::kExtensionInstallForcelist, policy::POLICY_LEVEL_MANDATORY, policy::POLICY_SCOPE_USER, policy::POLICY_SOURCE_CLOUD, std::move(list), nullptr); extensions::ExtensionRegistry* registry = extensions::ExtensionRegistry::Get( ProfileManager::GetPrimaryUserProfile()); extensions::TestExtensionRegistryObserver install_observer(registry); policy_provider_.UpdateChromePolicy(map); base::RunLoop().RunUntilIdle(); } void PreRunTestOnMainThread() override { SetupForceList(kExtensionId); InProcessBrowserTest::PreRunTestOnMainThread(); } extensions::ForceInstalledTracker* force_installed_tracker() { return extensions::ExtensionSystem::Get(profile()) ->extension_service() ->force_installed_tracker(); } void RunUntilAppPrepared() { controller()->Start(kiosk_app_id(), false); ExpectState(AppState::kCreatingProfile, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), Initialize()).Times(1); profile_controls()->OnProfileLoaded(profile()); launch_controls()->InitializeNetwork(); ExpectState(AppState::kInitNetwork, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), ContinueWithNetworkReady()).Times(1); SetOnline(true); launch_controls()->OnAppInstalling(); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingApplication); launch_controls()->OnAppPrepared(); } void SetExtensionLoaded(const std::string& extension_id, const std::string& extension_name) { auto ext = extensions::ExtensionBuilder(extension_name) .SetID(extension_id) .Build(); force_installed_tracker()->OnExtensionLoaded(profile(), ext.get()); } void SetExtensionReady(const std::string& extension_id, const std::string& extension_name) { auto ext = extensions::ExtensionBuilder(extension_name) .SetID(extension_id) .Build(); force_installed_tracker()->OnExtensionReady(profile(), ext.get()); } policy::MockConfigurationPolicyProvider policy_provider_; }; IN_PROC_BROWSER_TEST_P(KioskLaunchControllerWithExtensionTest, ExtensionLoadedBeforeAppPrepared) { SetExtensionReady(kExtensionId, kExtensionName); RunUntilAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } IN_PROC_BROWSER_TEST_P(KioskLaunchControllerWithExtensionTest, ExtensionLoadedAfterAppPrepared) { RunUntilAppPrepared(); ExpectState(AppState::kInstallingExtensions, NetworkUIState::kNotShowing); ExpectViewState( AppLaunchSplashScreenView::AppLaunchState::kInstallingExtension); SetExtensionReady(kExtensionId, kExtensionName); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); ExpectViewState(AppLaunchSplashScreenView::AppLaunchState::kWaitingAppWindow); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); } INSTANTIATE_TEST_SUITE_P(All, KioskLaunchControllerWithExtensionTest, testing::Values(KioskAppType::kArcApp, KioskAppType::kChromeApp, KioskAppType::kWebApp)); class KioskLaunchControllerWithInvalidExtensionTest : public KioskLaunchControllerWithExtensionTest { public: void SetUpInProcessBrowserTestFixture() override { base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs"); EXPECT_CALL(policy_provider_, IsInitializationComplete(_)) .WillRepeatedly(testing::Return(true)); EXPECT_CALL(policy_provider_, IsFirstPolicyLoadComplete(_)) .WillRepeatedly(testing::Return(true)); policy::BrowserPolicyConnector::SetPolicyProviderForTesting( &policy_provider_); } void PreRunTestOnMainThread() override { SetupForceList(kInvalidExtensionId); InProcessBrowserTest::PreRunTestOnMainThread(); } }; IN_PROC_BROWSER_TEST_P(KioskLaunchControllerWithInvalidExtensionTest, InvalidExtensionInstallForceListPolicy) { SetExtensionLoaded(kInvalidExtensionId, kInvalidExtensionName); RunUntilAppPrepared(); ExpectState(AppState::kInstalled, NetworkUIState::kNotShowing); EXPECT_CALL(*launcher(), LaunchApp()).Times(1); FireSplashScreenTimer(); launch_controls()->OnAppLaunched(); ExpectState(AppState::kLaunched, NetworkUIState::kNotShowing); EXPECT_TRUE(session_manager::SessionManager::Get()->IsSessionStarted()); EXPECT_EQ(view()->GetErrorMessageType(), KioskAppLaunchError::Error::kExtensionsPolicyInvalid); } INSTANTIATE_TEST_SUITE_P(All, KioskLaunchControllerWithInvalidExtensionTest, testing::Values(KioskAppType::kArcApp, KioskAppType::kChromeApp, KioskAppType::kWebApp)); } // namespace ash
19,398
6,003
class Point { public: constexpr Point(double xVal = 0, double yVal = 0) noexcept : x(xVal), y(yVal) { } constexpr double xValue() const noexcept { return x; } constexpr double yValue() const noexcept { return y; } void setX(double newX) noexcept { x = newX; } void setY(double newY) noexcept { y = newY; } private: double x, y; }; constexpr Point midpoint(const Point& p1, const Point& p2) noexcept { return { (p1.xValue() + p2.xValue()) / 2, (p2.yValue() + p2.yValue()) / 2 }; } int main() { constexpr Point p1(9.4, 27.7); constexpr Point p2(28.8, 5.3); constexpr auto mid = midpoint(p1, p2); return 0; }
744
280
#pragma once #include <cmath> #include <iomanip> #include <limits> #include <sstream> #include <string> #include <vector> #include "points.hpp" #include "vec3.hpp" using namespace std::string_literals; // Cube has a position, a width (x), a height (y) and a depth (z) class Cube { protected: const Vec3 m_pos; // center position of the cube const double m_whd[3]; // width, height and depth public: Cube(double _x, double _y, double _z, double _w, double _h, double _d) : m_pos { _x, _y, _z } , m_whd { _w, _h, _d } { } Cube(double _x, double _y, double _z, double _whd) // same width, height and depth : m_pos { _x, _y, _z } , m_whd { _whd, _whd, _whd } { } Cube(const Vec3 _pos, double _w, double _h, double _d) : m_pos { _pos } , m_whd { _w, _h, _d } { } Cube(const Vec3 _pos, double _whd) // same width, height and depth : m_pos { _pos } , m_whd { _whd, _whd, _whd } { } const std::string str() const; double x() const; double y() const; double z() const; double w() const; double h() const; double d() const; const Vec3 pos() const; const Vec3 normal(const Vec3 p) const; const Vec3 p0() const; const Vec3 p1() const; const Vec3 p2() const; const Vec3 p3() const; const Vec3 p4() const; const Vec3 p5() const; const Vec3 p6() const; const Vec3 p7() const; const Points points() const; }; // str returns a string representation of the cube // The string function returns a constant string ("const std::string"), // and does not modify anything ("const"). inline const std::string Cube::str() const { std::stringstream ss; ss << "cube: ("s << m_pos << ", "s << m_whd[0] << ", "s << m_whd[1] << ", "s << m_whd[2] << ")"s; return ss.str(); } // Implement support for the << operator, by calling the Vec3 str method inline std::ostream& operator<<(std::ostream& os, const Cube& s) { os << s.str(); return os; } double Cube::x() const { return m_pos.x(); } double Cube::y() const { return m_pos.y(); } double Cube::z() const { return m_pos.z(); } double Cube::w() const { return m_whd[0]; } double Cube::h() const { return m_whd[1]; } double Cube::d() const { return m_whd[2]; } const Vec3 Cube::pos() const { return m_pos; } // m_pos is the center position // rv is the "radius offset // left bottom front point of the cube (-, -, -) const Vec3 Cube::p0() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { -r0, -r1, -r2 }; } // right bottom front point of the cube (+, -, -) const Vec3 Cube::p1() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { r0, -r1, -r2 }; } // right bottom back point of the cube (+, -, +) const Vec3 Cube::p2() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { r0, -r1, r2 }; } // left bottom back point of the cube (-, -, +) const Vec3 Cube::p3() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { -r0, -r1, r2 }; } // left top front point of the cube (-, +, -) const Vec3 Cube::p4() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { -r0, r1, -r2 }; } // right top front point of the cube (+, +, -) const Vec3 Cube::p5() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; // const double r = m_w / 2.0; return m_pos + Vec3 { r0, r1, -r2 }; } // right top back point of the cube (+, +, +) const Vec3 Cube::p6() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; return m_pos + Vec3 { r0, r1, r2 }; } // left top back point of the cube (-, +, +) const Vec3 Cube::p7() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; return m_pos + Vec3 { -r0, r1, r2 }; } // points returns a vector of ordered points for this cube const Points Cube::points() const { const double r0 = m_whd[0] / 2.0; const double r1 = m_whd[1] / 2.0; const double r2 = m_whd[2] / 2.0; return Points { std::move(m_pos + Vec3 { -r0, -r1, -r2 }), std::move(m_pos + Vec3 { r0, -r1, -r2 }), std::move(m_pos + Vec3 { r0, -r1, r2 }), std::move(m_pos + Vec3 { -r0, -r1, r2 }), std::move(m_pos + Vec3 { -r0, r1, -r2 }), std::move(m_pos + Vec3 { r0, r1, -r2 }), std::move(m_pos + Vec3 { r0, r1, r2 }), std::move(m_pos + Vec3 { -r0, r1, r2 }), }; } // Get the normal sticking out from the cube at the point p on the surface of the cube const Vec3 Cube::normal(const Vec3 p) const { // BAH. None of the plans work. This function is a work in progress. // 1. Find the closest three points on the cube. // 2. Treat those three points as a face and find the normal from that. // 3. ::intify that normal to get a cube normal. Points xs = this->points(); // TODO: This can be made faster by passing in a distance_squared cache pointer to // each *_closest_* function call. size_t smallest_ai = index_closest(xs, p); size_t smallest_bi = index_closest_except(xs, p, std::vector<size_t> { smallest_ai }); size_t smallest_ci = index_closest_except(xs, p, std::vector<size_t> { smallest_ai, smallest_bi }); size_t smallest_di = index_closest_except( xs, p, std::vector<size_t> { smallest_ai, smallest_bi, smallest_ci }); // Okay, now create vectors that are from the center of the cube to these 3 closest points const Vec3 av = xs[smallest_ai] - m_pos; const Vec3 bv = xs[smallest_bi] - m_pos; const Vec3 cv = xs[smallest_ci] - m_pos; const Vec3 dv = xs[smallest_di] - m_pos; // Average the vectors const Vec3 average_closest = (av + bv + cv + dv) / 4; // Just return the clostest vertex, from the center and to that one, // then normalize and intify. // return av.normalize().intify(); // Normalize the average const Vec3 average_closest_normalized = average_closest.normalize(); // Intify the averaged normal to get a normal that points straight out return average_closest_normalized.intify(); }
6,847
2,727
#include <azule/core/Processor.h> #include <azule/utilities/PimplImpl.h> using namespace azule; class Processor::Impl { public: std::vector<std::function<void(std::chrono::microseconds)>> fixedFunctions; std::vector<std::function<void(std::chrono::microseconds)>> variableFunctions; std::vector<std::function<void(std::chrono::microseconds)>> renderFunctions; }; Processor::Processor() { } Processor::~Processor() { } void Processor::fixed(std::chrono::microseconds x) { for(const auto& f : this->pimpl->fixedFunctions) { f(x); } } void Processor::variable(std::chrono::microseconds x) { for(const auto& f : this->pimpl->variableFunctions) { f(x); } } void Processor::render(std::chrono::microseconds x) { for(const auto& f : this->pimpl->renderFunctions) { f(x); } } void Processor::addFixedFunction(const std::function<void(std::chrono::microseconds)>& x) { this->pimpl->fixedFunctions.push_back(x); } void Processor::addVariableFunction(const std::function<void(std::chrono::microseconds)>& x) { this->pimpl->variableFunctions.push_back(x); } void Processor::addRenderFunction(const std::function<void(std::chrono::microseconds)>& x) { this->pimpl->renderFunctions.push_back(x); }
1,215
459
#include "baldr/compression_utils.h" namespace valhalla { namespace baldr { /* Deflates data with gzip or zlib wrapper * @param src_func function which modifies the stream to read more input * @param dst_func function which modifies the stream to write more output * @param level what compression level to use * @param gzip whether or not to write a gzip header instead of a zlib one * @return returns true if the stream was successfully inflated, false otherwise */ bool deflate(const std::function<int(z_stream&)>& src_func, const std::function<void(z_stream&)>& dst_func, int level, bool gzip) { // initialize the stream // add 16 to window bits for gzip header instead of zlib header, 9 is max speed z_stream stream{}; if (deflateInit2(&stream, level, Z_DEFLATED, gzip ? 15 + 16 : 15, 9, Z_DEFAULT_STRATEGY) != Z_OK) return false; int flush = Z_NO_FLUSH; int code = Z_OK; do { // if we need more src material try { if (stream.avail_in == 0) flush = src_func(stream); } catch (...) { deflateEnd(&stream); return false; } do { // if we need more space in the dst try { if (stream.avail_out == 0) dst_func(stream); } catch (...) { deflateEnd(&stream); return false; } // only one fatal error to worry about code = deflate(&stream, flush); if (code == Z_STREAM_ERROR) { deflateEnd(&stream); return false; } // only stop when we've got nothing more to put in the dst buffer } while (stream.avail_out == 0); // only stop when we signaled that we have no more input } while (flush != Z_FINISH); // hand back the final buffer dst_func(stream); // if we got here we expected to finish but weren't thats not good deflateEnd(&stream); return true; } /* Inflates gzip or zlib wrapped deflated data * @param src_func function which modifies the stream to read more input * @param dst_func function which modifies the stream to write more output * @return returns true if the stream was successfully inflated, false otherwise */ bool inflate(const std::function<void(z_stream&)>& src_func, const std::function<int(z_stream&)>& dst_func) { // initialize the stream // MAX_WBITS is the max size of the window and should be 15, this will work with headerless // defalted streams to work with gzip add 16, to work with both gzip and libz add 32 z_stream stream{}; if (inflateInit2(&stream, MAX_WBITS + 32) != Z_OK) return false; int flush = Z_NO_FLUSH; int code = Z_OK; do { // if we need more src material try { if (stream.avail_in == 0) src_func(stream); if (stream.avail_in == 0) throw; } catch (...) { inflateEnd(&stream); return false; } do { // if we need more space in the dst try { if (stream.avail_out == 0) flush = dst_func(stream); } catch (...) { inflateEnd(&stream); return false; } // several fatal errors to worry about code = inflate(&stream, flush); switch (code) { case Z_STREAM_ERROR: case Z_NEED_DICT: case Z_DATA_ERROR: case Z_MEM_ERROR: inflateEnd(&stream); return false; } // only stop when we've got nothing more to put in the dst buffer } while (stream.avail_out == 0); // only stop when we reached the end of the stream } while (code != Z_STREAM_END); // hand back the final buffer dst_func(stream); // if we got here we expected to finish but weren't thats not good inflateEnd(&stream); return true; } } // namespace baldr } // namespace valhalla
3,793
1,194
#include <parrlib/utils2d/AxisAlignedBoundingBox2D.h> #include <iostream> #include <parrlib/Matrix3f.h> #include <parrlib/otherutil.h> #include <parrlib/stringutils.h> AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(){} //AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(float v) { vmax = v; vmin = v; } AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 v) : vmin(v), vmax(v) {} AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 min, vec2 max) : vmin(min), vmax(max) { align(); } AxisAlignedBoundingBox2D::AxisAlignedBoundingBox2D(vec2 min, vec2 max, bool doalign) : vmin(min), vmax(max), doalign(doalign) { align(); } bool AxisAlignedBoundingBox2D::intersects(AxisAlignedBoundingBox2D const& bb) const { return vmin.x < bb.maxx() && vmax.x > bb.minx() && vmin.y < bb.maxy() && vmax.y > bb.miny(); } void AxisAlignedBoundingBox2D::rescale(vec2 const& v) { if (v.x < vmin.x) vmin.x = v.x; else if (v.x > vmax.x) vmax.x = v.x; if (v.y < vmin.y) vmin.y = v.y; else if (v.y > vmax.y) vmax.y = v.y; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::rescaled(vec2 const& v) const { aabb2 bb = *this; bb.rescale(v); return bb; } void AxisAlignedBoundingBox2D::narrow(AxisAlignedBoundingBox2D const& bb) { if (vmin.x < bb.fmin().x) vmin.x = bb.fmin().x; if (vmin.y < bb.fmin().y) vmin.y = bb.fmin().y; if (vmax.x > bb.fmax().x) vmax.x = bb.fmax().x; if (vmax.y > bb.fmax().y) vmax.y = bb.fmax().y; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::narrowed(AxisAlignedBoundingBox2D const& bb) const { aabb2 tbb = *this; tbb.narrow(bb); return tbb; } void AxisAlignedBoundingBox2D::fit(AxisAlignedBoundingBox2D const& bb) { *this = fitted(bb); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fitted(AxisAlignedBoundingBox2D const& bb) { vec2 p = bb.size() / size(); float scale = outl::minfabs(p.x, p.y); return (centered() * scale + bb.center()); } bool AxisAlignedBoundingBox2D::inside(AxisAlignedBoundingBox2D const& bb) const { return vmin.x >= bb.minx() && vmin.y >= bb.miny() && vmax.x <= bb.maxx() && vmax.y <= bb.maxy(); } bool AxisAlignedBoundingBox2D::pointInside(vec2 const& v) const { return v.x >= vmin.x && v.x <= vmax.x && v.y >= vmin.y && v.y <= vmax.y; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+(vec2 const& v) const { return aabb2(vmin + v, vmax + v); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-(vec2 const& v) const { return aabb2(vmin - v, vmax - v); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*(vec2 const& v) const { return aabb2(vmin * v, vmax * v); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/(vec2 const& v) const { return aabb2(vmin / v, vmax / v); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin + bb.fmin(), vmax + bb.fmax()); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin - bb.fmin(), vmax - bb.fmax()); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin * bb.fmin(), vmax * bb.fmax()); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/(AxisAlignedBoundingBox2D const& bb) const { return aabb2(vmin / bb.fmin(), vmax / bb.fmax()); } AxisAlignedBoundingBox2D operator+ (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v + bb.fmin(), v + bb.fmax() }; } AxisAlignedBoundingBox2D operator- (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v - bb.fmin(), v - bb.fmax() }; } AxisAlignedBoundingBox2D operator* (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v * bb.fmin(), v * bb.fmax() }; } AxisAlignedBoundingBox2D operator/ (vec2 const& v, AxisAlignedBoundingBox2D const& bb) { return { v / bb.fmin(), v / bb.fmax() }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+=(vec2 const& v) { vmin += v; vmax += v; return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-=(vec2 const& v) { vmin -= v; vmax -= v; return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*=(vec2 const& v) { vmin *= v; vmax *= v; return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/=(vec2 const& v) { vmin /= v; vmax /= v; return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator+=(AxisAlignedBoundingBox2D const& bb) { vmin += bb.fmin(); vmax += bb.fmax(); return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator-=(AxisAlignedBoundingBox2D const& bb) { vmin -= bb.fmin(); vmax -= bb.fmax(); return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator*=(AxisAlignedBoundingBox2D const& bb) { vmin *= bb.fmin(); vmax *= bb.fmax(); return *this; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::operator/=(AxisAlignedBoundingBox2D const& bb) { vmin /= bb.fmin(); vmax /= bb.fmax(); return *this; } bool AxisAlignedBoundingBox2D::operator==(float f) const { return vmin == f && vmax == f; } bool AxisAlignedBoundingBox2D::operator!=(float f) const { return vmin != f && vmax != f; } bool AxisAlignedBoundingBox2D::operator==(AxisAlignedBoundingBox2D const& f) const { return vmin == f.fmin() && vmax == f.fmax(); } bool AxisAlignedBoundingBox2D::operator!=(AxisAlignedBoundingBox2D const& f) const { return vmin != f.fmin() && vmax != f.fmax(); } void AxisAlignedBoundingBox2D::align() { if (!doalign) return; if (vmin.x > vmax.x) std::swap(vmin.x, vmax.x); if (vmin.y > vmax.y) std::swap(vmin.y, vmax.y); } void AxisAlignedBoundingBox2D::fmaxr(vec2 max) { this->vmax = max; align(); } vec2 AxisAlignedBoundingBox2D::fmax() const { return vmax; } void AxisAlignedBoundingBox2D::fminr(vec2 min) { this->vmin = min; align(); } vec2 AxisAlignedBoundingBox2D::fmin() const { return vmin; } vec2 AxisAlignedBoundingBox2D::center() const { return (vmin + vmax) / 2.f; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::centered() const { return *this - center(); } float AxisAlignedBoundingBox2D::minx() const { return vmin.x; } float AxisAlignedBoundingBox2D::miny() const { return vmin.y; } float AxisAlignedBoundingBox2D::maxx() const { return vmax.x; } float AxisAlignedBoundingBox2D::maxy() const { return vmax.y; } void AxisAlignedBoundingBox2D::maxxr(float f) { vmax.x = f; } void AxisAlignedBoundingBox2D::maxyr(float f) { vmax.y = f; } void AxisAlignedBoundingBox2D::minxr(float f) { vmin.x = f; } void AxisAlignedBoundingBox2D::minyr(float f) { vmin.y = f; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::maxx(float f) const { return aabb2{ vmin, {f, vmax.y} }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::maxy(float f) const { return aabb2{ vmin, {vmax.x, f} }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::minx(float f) const { return aabb2{ { f, vmin.y }, vmax }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::miny(float f) const { return aabb2{ { vmin.x, f }, vmax }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fmax(vec2 vmax) const { return aabb2{ vmin, vmax }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::fmin(vec2 vmin) const { return aabb2{ vmin, vmax }; } vec2 AxisAlignedBoundingBox2D::get(int i) const { switch (i) { case 0: return {vmin.x, vmin.y}; case 1: return {vmin.x, vmax.y}; case 2: return {vmax.x, vmax.y}; case 3: return {vmax.x, vmin.y}; } return 0.f; } float AxisAlignedBoundingBox2D::getSingle(int i) const { return i == 0 ? vmin.x : i == 1 ? vmin.y : i == 2 ? vmax.x : i == 3 ? vmax.y : 0.f; } vec2 AxisAlignedBoundingBox2D::operator[](int const& i) const { return get(i); } std::array<vec2, 4> AxisAlignedBoundingBox2D::toVerts() const { return { get(0), get(1), get(2), get(3) }; } vec2 AxisAlignedBoundingBox2D::edgeCenter(int i) const { return ((*this)[i] + (*this)[(i+1)%4])/2.f; } vec2 AxisAlignedBoundingBox2D::size() const { return vmax - vmin; } float AxisAlignedBoundingBox2D::sizex() const { return vmax.x - vmin.x; } float AxisAlignedBoundingBox2D::sizey() const { return vmax.y - vmin.y; } void AxisAlignedBoundingBox2D::scale(vec2 const& scale) { *this = scaled(scale); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::scaled(vec2 const& scale) const { return centered()*scale + center(); } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::movedIn(vec2 const& delta) const { return { vmin + delta, vmax - delta }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::movedOut(vec2 const& delta) const { return { vmin - delta, vmax + delta }; } AxisAlignedBoundingBox2D AxisAlignedBoundingBox2D::forcedIn(AxisAlignedBoundingBox2D const& bb) const{ if (inside(bb)) return *this; //just return if it's already inside if (size() > bb.size()) return bb; aabb2 resbb = *this; if (sizex() > bb.sizex()) resbb = resbb.scaled(vec2(bb.sizex()/sizex() , 1.f)); if (sizey() > bb.sizey()) resbb = resbb.scaled(vec2(1.f, bb.sizey()/sizey())); //translate along x axis if necessary bool xtrasl = false; if (resbb.minx() < bb.minx()) { resbb += vec2x(bb.minx() - resbb.minx()); xtrasl = true; } if (!xtrasl && resbb.maxx() > bb.maxx()) { resbb += vec2x(bb.maxx() - resbb.maxx()); xtrasl = true; } bool ytrasl = false; if (resbb.miny() < bb.fmin().y) { resbb += vec2y(bb.miny() - resbb.miny()); ytrasl = true; } if (!ytrasl && resbb.maxy() > bb.maxy()) { resbb += vec2y(bb.maxy() - resbb.maxy()); ytrasl = true; } return resbb; } std::string AxisAlignedBoundingBox2D::toString() const { std::stringstream ss; ss << "(" << vmin << ", " << vmax << ")"; return ss.str(); } std::ostream& operator<<(std::ostream& os, AxisAlignedBoundingBox2D const& bb) { return os << bb.toString(); } std::wostream& operator<<(std::wostream& os, AxisAlignedBoundingBox2D const& bb) { return os << stru::towstr(bb.toString()); } AxisAlignedBoundingBox2D aabb2s(vec2 const& size) { return { -size/2.f, size/2.f }; }
9,905
4,120
#include <windows.h> #include <thread> #include "game.h" #include "particles.h" #include "math.h" #define pressed(c) GetAsyncKeyState(c) void Game::update() { Option BSIZE_X = value(m_op[OP_BSIZE_X]); Option BSIZE_Y = value(m_op[OP_BSIZE_Y]); Option PSPEED = value(m_op[OP_PSPEED]); if(m_plr.health() > 0) { m_plr.display_healthbar(m_board, {1, BSIZE_Y - 1}, PLAYER_HBARS); m_plr.display_health(m_board, {1 + PLAYER_HBARS, BSIZE_Y - 1}); if(m_enemies.size() > 0) for(int i = 0; i < m_enemies.size(); i++) { Entity &enemy = m_enemies[i]; if(enemy.health() > 0) { int _rand = rand(); std::thread([&]() { enemy.display(m_board); if(m_frame % 20 == 0) enemy.move({1, 0}); else if(m_frame % 10 == 0) enemy.move({-1, 0}); if(m_frame % (_rand % ENEMY_FIRERATE + 1) == 0) enemy.fire(m_board, DBULLET); }).detach(); } else m_enemies.m_data.erase(m_enemies.begin() + i); } else { m_board.clear(true); Sprite YouWon = {{{ SPRITE_YOUWON }}, m_op}; YouWon.write(m_board, { (BSIZE_X - YOUWON_SIZE_X) / 2, (BSIZE_Y - YOUWON_SIZE_Y) / 2}); m_board.display(); throw 0; } } else { m_board.clear(true); Sprite GameOver = {{{ SPRITE_GAMEOVER }}, m_op}; GameOver.write(m_board, { (BSIZE_X - GAMEOVER_SIZE_X) / 2, (BSIZE_Y - GAMEOVER_SIZE_Y) / 2}); m_board.display(); throw 0; } m_plr.display(m_board); for(Particle *particle : m_particles) particle->update(this); m_board.display(this); if ( pressed(VK_LEFT) || pressed('a') || pressed('A') ) m_plr.move({-PSPEED, 0}); else if ( pressed(VK_RIGHT) || pressed('d') || pressed('D') ) m_plr.move({PSPEED, 0}); if ( (pressed(VK_UP) || pressed('w') || pressed('W') || pressed(' ')) && m_frame % PLAYER_FIRERATE == 0 ) m_plr.fire(m_board, UBULLET); m_board.clear(); m_frame++; }
1,982
1,066
/* DDS, a bridge double dummy solver. Copyright (C) 2006-2014 by Bo Haglund / 2014-2018 by Bo Haglund & Soren Hein. See LICENSE and README. */ #include "dds.h" #include "PBN.h" int IsCard(const char cardChar); int ConvertFromPBN( char const * dealBuff, unsigned int remainCards[DDS_HANDS][DDS_SUITS]) { for (int h = 0; h < DDS_HANDS; h++) for (int s = 0; s < DDS_SUITS; s++) remainCards[h][s] = 0; int bp = 0; while (((dealBuff[bp] != 'W') && (dealBuff[bp] != 'N') && (dealBuff[bp] != 'E') && (dealBuff[bp] != 'S') && (dealBuff[bp] != 'w') && (dealBuff[bp] != 'n') && (dealBuff[bp] != 'e') && (dealBuff[bp] != 's')) && (bp < 3)) bp++; if (bp >= 3) return 0; int first; if ((dealBuff[bp] == 'N') || (dealBuff[bp] == 'n')) first = 0; else if ((dealBuff[bp] == 'E') || (dealBuff[bp] == 'e')) first = 1; else if ((dealBuff[bp] == 'S') || (dealBuff[bp] == 's')) first = 2; else first = 3; bp++; bp++; int handRelFirst = 0; int suitInHand = 0; int card, hand; while ((bp < 80) && (dealBuff[bp] != '\0')) { card = IsCard(dealBuff[bp]); if (card) { switch (first) { case 0: hand = handRelFirst; break; case 1: if (handRelFirst == 0) hand = 1; else if (handRelFirst == 3) hand = 0; else hand = handRelFirst + 1; break; case 2: if (handRelFirst == 0) hand = 2; else if (handRelFirst == 1) hand = 3; else hand = handRelFirst - 2; break; default: if (handRelFirst == 0) hand = 3; else hand = handRelFirst - 1; } remainCards[hand][suitInHand] |= static_cast<unsigned>((bitMapRank[card] << 2)); } else if (dealBuff[bp] == '.') suitInHand++; else if (dealBuff[bp] == ' ') { handRelFirst++; suitInHand = 0; } bp++; } return RETURN_NO_FAULT; } int IsCard(const char cardChar) { switch (cardChar) { case '2': return 2; case '3': return 3; case '4': return 4; case '5': return 5; case '6': return 6; case '7': return 7; case '8': return 8; case '9': return 9; case 'T': case 't': return 10; case 'J': case 'j': return 11; case 'Q': case 'q': return 12; case 'K': case 'k': return 13; case 'A': case 'a': return 14; default: return 0; } } int ConvertPlayFromPBN( const playTracePBN& playPBN, playTraceBin& playBin) { const int n = playPBN.number; if (n < 0 || n > 52) return RETURN_PLAY_FAULT; playBin.number = n; for (int i = 0; i < 2 * n; i += 2) { char suit = playPBN.cards[i]; int s; if (suit == 's' || suit == 'S') s = 0; else if (suit == 'h' || suit == 'H') s = 1; else if (suit == 'd' || suit == 'D') s = 2; else if (suit == 'c' || suit == 'C') s = 3; else return RETURN_PLAY_FAULT; playBin.suit[i >> 1] = s; int rank = IsCard(playPBN.cards[i+1]); if (rank == 0) return RETURN_PLAY_FAULT; playBin.rank[i >> 1] = rank; } return RETURN_NO_FAULT; }
3,377
1,434
// iopyright 2010-2015 RethinkDB, all rights reserved. #include "clustering/administration/auth/permissions_artificial_table_backend.hpp" #include "errors.hpp" #include <boost/algorithm/string/join.hpp> #include "clustering/administration/artificial_reql_cluster_interface.hpp" #include "clustering/administration/auth/username.hpp" #include "clustering/administration/datum_adapter.hpp" #include "clustering/administration/tables/name_resolver.hpp" namespace auth { permissions_artificial_table_backend_t::permissions_artificial_table_backend_t( rdb_context_t *rdb_context, lifetime_t<name_resolver_t const &> name_resolver, std::shared_ptr<semilattice_readwrite_view_t<auth_semilattice_metadata_t>> auth_semilattice_view, std::shared_ptr<semilattice_read_view_t<cluster_semilattice_metadata_t>> cluster_semilattice_view, admin_identifier_format_t identifier_format) : base_artificial_table_backend_t( name_string_t::guarantee_valid("permissions"), rdb_context, name_resolver, auth_semilattice_view, cluster_semilattice_view), m_name_resolver(name_resolver), m_identifier_format(identifier_format) { } bool permissions_artificial_table_backend_t::read_all_rows_as_vector( UNUSED auth::user_context_t const &user_context, UNUSED signal_t *interruptor, std::vector<ql::datum_t> *rows_out, UNUSED admin_err_t *error_out) { rows_out->clear(); on_thread_t on_thread(home_thread()); cluster_semilattice_metadata_t cluster_metadata = m_name_resolver.get_cluster_metadata(); // The "admin" user is faked here { ql::datum_t row; if (global_to_datum( username_t("admin"), permissions_t(tribool::True, tribool::True, tribool::True, tribool::True), &row)) { rows_out->push_back(std::move(row)); } } { ql::datum_t row; if (database_to_datum( username_t("admin"), artificial_reql_cluster_interface_t::database_id, permissions_t(tribool::True, tribool::True, tribool::True), cluster_metadata, &row)) { rows_out->push_back(std::move(row)); } } auth_semilattice_metadata_t auth_metadata = m_auth_semilattice_view->get(); for (auto const &user : auth_metadata.m_users) { if (user.first.is_admin() || !static_cast<bool>(user.second.get_ref())) { // The "admin" user is faked above and not displayed from the metadata. continue; } ql::datum_t username = convert_string_to_datum(user.first.to_string()); { ql::datum_t row; if (global_to_datum( user.first, user.second.get_ref()->get_global_permissions(), &row)) { rows_out->push_back(std::move(row)); } } for (auto const &database : user.second.get_ref()->get_database_permissions()) { ql::datum_t row; if (database_to_datum( user.first, database.first, database.second, cluster_metadata, &row)) { rows_out->push_back(std::move(row)); } } for (auto const &table : user.second.get_ref()->get_table_permissions()) { // `table_to_datum` will look up the database ql::datum_t row; if (table_to_datum( user.first, r_nullopt, table.first, table.second, cluster_metadata, &row)) { rows_out->push_back(std::move(row)); } } } return true; } bool permissions_artificial_table_backend_t::read_row( UNUSED auth::user_context_t const &user_context, ql::datum_t primary_key, UNUSED signal_t *interruptor, ql::datum_t *row_out, UNUSED admin_err_t *error_out) { *row_out = ql::datum_t(); on_thread_t on_thread(home_thread()); cluster_semilattice_metadata_t cluster_metadata = m_name_resolver.get_cluster_metadata(); username_t username; database_id_t database_id; namespace_id_t table_id; uint8_t array_size = parse_primary_key( primary_key, cluster_metadata, &username, &database_id, &table_id); if (array_size == 0) { return true; } if (username.is_admin()) { switch (array_size) { case 1: global_to_datum( username, permissions_t(tribool::True, tribool::True, tribool::True, tribool::True), row_out); break; case 2: if (database_id == artificial_reql_cluster_interface_t::database_id) { database_to_datum( username, database_id, permissions_t(tribool::True, tribool::True, tribool::True), cluster_metadata, row_out); } break; } return true; } auth_semilattice_metadata_t auth_metadata = m_auth_semilattice_view->get(); auto user = auth_metadata.m_users.find(username); if (user == auth_metadata.m_users.end() || !static_cast<bool>(user->second.get_ref())) { return true; } // Note these functions will only set `row_out` on success. switch (array_size) { case 1: global_to_datum( username, user->second.get_ref()->get_global_permissions(), row_out); break; case 2: database_to_datum( username, database_id, user->second.get_ref()->get_database_permissions(database_id), cluster_metadata, row_out); break; case 3: table_to_datum( username, make_optional(database_id), table_id, user->second.get_ref()->get_table_permissions(table_id), cluster_metadata, row_out); break; } return true; } bool permissions_artificial_table_backend_t::write_row( UNUSED auth::user_context_t const &user_context, ql::datum_t primary_key, bool pkey_was_autogenerated, ql::datum_t *new_value_inout, UNUSED signal_t *interruptor, admin_err_t *error_out) { on_thread_t on_thread(home_thread()); if (pkey_was_autogenerated) { *error_out = admin_err_t{ "You must specify a primary key.", query_state_t::FAILED}; return false; } cluster_semilattice_metadata_t cluster_metadata = m_cluster_semilattice_view->get(); username_t username_primary; database_id_t database_id_primary; namespace_id_t table_id_primary; uint8_t array_size = parse_primary_key( primary_key, cluster_metadata, &username_primary, &database_id_primary, &table_id_primary, error_out); if (array_size == 0) { return false; } if (username_primary.is_admin()) { *error_out = admin_err_t{ "The permissions of the user `" + username_primary.to_string() + "` can't be modified.", query_state_t::FAILED}; return false; } auth_semilattice_metadata_t auth_metadata = m_auth_semilattice_view->get(); auto user = auth_metadata.m_users.find(username_primary); if (user == auth_metadata.m_users.end() || !static_cast<bool>(user->second.get_ref())) { *error_out = admin_err_t{ "No user named `" + username_primary.to_string() + "`.", query_state_t::FAILED}; return false; } if (new_value_inout->has()) { std::set<std::string> keys; for (size_t i = 0; i < new_value_inout->obj_size(); ++i) { keys.insert(new_value_inout->get_pair(i).first.to_std()); } keys.erase("id"); ql::datum_t username = new_value_inout->get_field("user", ql::NOTHROW); if (username.has()) { keys.erase("user"); if (username_t(username.as_str().to_std()) != username_primary) { *error_out = admin_err_t{ "The key `user` does not match the primary key.", query_state_t::FAILED}; return false; } } if (array_size > 1) { ql::datum_t database = new_value_inout->get_field("database", ql::NOTHROW); if (database.has()) { keys.erase("database"); switch (m_identifier_format) { case admin_identifier_format_t::name: { name_string_t database_name; if (!convert_name_from_datum( database, "database name", &database_name, error_out)) { return false; } if (m_name_resolver.database_id_to_name( database_id_primary, cluster_metadata ).get() != database_name) { *error_out = admin_err_t{ "The key `database` does not match the primary key.", query_state_t::FAILED}; return false; } } break; case admin_identifier_format_t::uuid: { database_id_t database_id_secondary; if (!convert_uuid_from_datum( database, &database_id_secondary, error_out)) { return false; } if (database_id_primary != database_id_secondary) { *error_out = admin_err_t{ "The key `database` does not match the primary key.", query_state_t::FAILED}; return false; } } break; } } } if (array_size > 2) { ql::datum_t table = new_value_inout->get_field("table", ql::NOTHROW); if (table.has()) { keys.erase("table"); switch (m_identifier_format) { case admin_identifier_format_t::name: { name_string_t table_name; if (!convert_name_from_datum( table, "table name", &table_name, error_out)) { return false; } optional<table_basic_config_t> table_basic_config = m_name_resolver.table_id_to_basic_config( table_id_primary, make_optional(database_id_primary)); if (!static_cast<bool>(table_basic_config) || table_basic_config->name != table_name) { *error_out = admin_err_t{ "The key `table` does not match the primary key.", query_state_t::FAILED}; return false; } } break; case admin_identifier_format_t::uuid: { namespace_id_t table_id_secondary; if (!convert_uuid_from_datum( table, &table_id_secondary, error_out)) { return false; } if (table_id_primary != table_id_secondary) { *error_out = admin_err_t{ "The key `table` does not match the primary key.", query_state_t::FAILED}; return false; } } break; } } } bool is_indeterminate = false; ql::datum_t permissions = new_value_inout->get_field("permissions", ql::NOTHROW); if (permissions.has()) { keys.erase("permissions"); try { switch (array_size) { case 1: user->second.apply_write( [&](optional<auth::user_t> *inner_user) { auto &permissions_ref = inner_user->get().get_global_permissions(); permissions_ref.merge(permissions); is_indeterminate = permissions_ref.is_indeterminate(); }); break; case 2: user->second.apply_write( [&](optional<auth::user_t> *inner_user) { auto &permissions_ref = inner_user->get().get_database_permissions( database_id_primary); permissions_ref.merge(permissions); is_indeterminate = permissions_ref.is_indeterminate(); }); break; case 3: user->second.apply_write( [&](optional<auth::user_t> *inner_user) { auto &permissions_ref = inner_user->get().get_table_permissions( table_id_primary); permissions_ref.merge(permissions); is_indeterminate = permissions_ref.is_indeterminate(); }); break; } } catch (admin_op_exc_t const &admin_op_exc) { *error_out = admin_op_exc.to_admin_err(); return false; } } else { *error_out = admin_err_t{ "Expected a field `permissions`.", query_state_t::FAILED}; return false; } if (!keys.empty()) { *error_out = admin_err_t{ "Unexpected key(s) `" + boost::algorithm::join(keys, "`, `") + "`.", query_state_t::FAILED}; return false; } // Updating the permissions to indeterminate is considered equal to a deletion if (is_indeterminate) { *new_value_inout = ql::datum_t(); } } else { switch (array_size) { case 1: user->second.apply_write([](optional<auth::user_t> *inner_user) { inner_user->get().set_global_permissions( permissions_t( tribool::Indeterminate, tribool::Indeterminate, tribool::Indeterminate, tribool::Indeterminate)); }); break; case 2: user->second.apply_write([&](optional<auth::user_t> *inner_user) { inner_user->get().set_database_permissions( database_id_primary, permissions_t( tribool::Indeterminate, tribool::Indeterminate, tribool::Indeterminate)); }); break; case 3: user->second.apply_write([&](optional<auth::user_t> *inner_user) { inner_user->get().set_table_permissions( table_id_primary, permissions_t( tribool::Indeterminate, tribool::Indeterminate, tribool::Indeterminate)); }); break; } } m_auth_semilattice_view->join(auth_metadata); return true; } uint8_t permissions_artificial_table_backend_t::parse_primary_key( ql::datum_t const &primary_key, cluster_semilattice_metadata_t const &cluster_metadata, username_t *username_out, database_id_t *database_id_out, namespace_id_t *table_id_out, admin_err_t *admin_err_out) { if (primary_key.get_type() != ql::datum_t::R_ARRAY || primary_key.arr_size() < 1 || primary_key.arr_size() > 3) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ "Expected an array of one to three items in the primary key, got " + primary_key.print() + ".", query_state_t::FAILED}; } return 0; } ql::datum_t username = primary_key.get(0, ql::NOTHROW); if (username.get_type() != ql::datum_t::R_STR) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ "Expected a string as the username, got " + username.print() + ".", query_state_t::FAILED}; } return 0; } *username_out = username_t(username.as_str().to_std()); if (primary_key.arr_size() > 1) { ql::datum_t database = primary_key.get(1, ql::NOTHROW); if (database.get_type() != ql::datum_t::R_STR || !str_to_uuid(database.as_str().to_std(), database_id_out)) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ "Expected a UUID as the database, got " + database.print() + ".", query_state_t::FAILED}; } return 0; } optional<name_string_t> database_name = m_name_resolver.database_id_to_name(*database_id_out, cluster_metadata); if (!static_cast<bool>(database_name)) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ strprintf( "No database with UUID `%s` exists.", uuid_to_str(*database_id_out).c_str()), query_state_t::FAILED}; } return 0; } } if (primary_key.arr_size() > 2) { ql::datum_t table = primary_key.get(2, ql::NOTHROW); if (table.get_type() != ql::datum_t::R_STR || !str_to_uuid(table.as_str().to_std(), table_id_out)) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ "Expected a UUID as the table, got " + table.print() + ".", query_state_t::FAILED}; } return 0; } optional<table_basic_config_t> table_basic_config = m_name_resolver.table_id_to_basic_config(*table_id_out); if (!static_cast<bool>(table_basic_config)) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ strprintf( "No table with UUID `%s` exists.", uuid_to_str(*table_id_out).c_str()), query_state_t::FAILED}; } return 0; } if (table_basic_config->database != *database_id_out) { if (admin_err_out != nullptr) { *admin_err_out = admin_err_t{ strprintf( "No table with UUID `%s` exists.", uuid_to_str(*table_id_out).c_str()), query_state_t::FAILED}; } return 0; } } return primary_key.arr_size(); } bool permissions_artificial_table_backend_t::global_to_datum( username_t const &username, permissions_t const &permissions, ql::datum_t *datum_out) { ql::datum_t permissions_datum = permissions.to_datum(); if (permissions_datum.get_type() != ql::datum_t::R_NULL) { ql::datum_object_builder_t builder; ql::datum_array_builder_t id_builder(ql::configured_limits_t::unlimited); id_builder.add(convert_string_to_datum(username.to_string())); builder.overwrite("id", std::move(id_builder).to_datum()); builder.overwrite("permissions", std::move(permissions_datum)); builder.overwrite("user", convert_string_to_datum(username.to_string())); *datum_out = std::move(builder).to_datum(); return true; } return false; } bool permissions_artificial_table_backend_t::database_to_datum( username_t const &username, database_id_t const &database_id, permissions_t const &permissions, cluster_semilattice_metadata_t const &cluster_metadata, ql::datum_t *datum_out) { ql::datum_t permissions_datum = permissions.to_datum(); if (permissions_datum.get_type() != ql::datum_t::R_NULL) { ql::datum_object_builder_t builder; ql::datum_array_builder_t id_builder(ql::configured_limits_t::unlimited); id_builder.add(convert_string_to_datum(username.to_string())); id_builder.add(convert_uuid_to_datum(database_id)); ql::datum_t database_name_or_uuid; switch (m_identifier_format) { case admin_identifier_format_t::name: { optional<name_string_t> database_name = m_name_resolver.database_id_to_name( database_id, cluster_metadata); database_name_or_uuid = ql::datum_t(database_name.value_or( name_string_t::guarantee_valid("__deleted_database__")).str()); } break; case admin_identifier_format_t::uuid: database_name_or_uuid = ql::datum_t(uuid_to_str(database_id)); break; } builder.overwrite("database", std::move(database_name_or_uuid)); builder.overwrite("id", std::move(id_builder).to_datum()); builder.overwrite("permissions", std::move(permissions_datum)); builder.overwrite("user", convert_string_to_datum(username.to_string())); *datum_out = std::move(builder).to_datum(); return true; } return false; } bool permissions_artificial_table_backend_t::table_to_datum( username_t const &username, optional<database_id_t> const &database_id, namespace_id_t const &table_id, permissions_t const &permissions, cluster_semilattice_metadata_t const &cluster_metadata, ql::datum_t *datum_out) { optional<table_basic_config_t> table_basic_config = m_name_resolver.table_id_to_basic_config(table_id, database_id); if (!static_cast<bool>(table_basic_config)) { return false; } ql::datum_t permissions_datum = permissions.to_datum(); if (permissions_datum.get_type() != ql::datum_t::R_NULL) { ql::datum_object_builder_t builder; ql::datum_array_builder_t id_builder(ql::configured_limits_t::unlimited); id_builder.add(convert_string_to_datum(username.to_string())); id_builder.add(convert_uuid_to_datum(table_basic_config->database)); id_builder.add(convert_uuid_to_datum(table_id)); ql::datum_t database_name_or_uuid; ql::datum_t table_name_or_uuid; switch (m_identifier_format) { case admin_identifier_format_t::name: { optional<name_string_t> database_name = m_name_resolver.database_id_to_name( table_basic_config->database, cluster_metadata); database_name_or_uuid = ql::datum_t(database_name.value_or( name_string_t::guarantee_valid("__deleted_database__")).str()); table_name_or_uuid = ql::datum_t(table_basic_config->name.str()); } break; case admin_identifier_format_t::uuid: database_name_or_uuid = ql::datum_t(uuid_to_str(table_basic_config->database)); table_name_or_uuid = ql::datum_t(uuid_to_str(table_id)); break; } builder.overwrite("database", std::move(database_name_or_uuid)); builder.overwrite("id", std::move(id_builder).to_datum()); builder.overwrite("permissions", std::move(permissions_datum)); builder.overwrite("table", std::move(table_name_or_uuid)); builder.overwrite("user", convert_string_to_datum(username.to_string())); *datum_out = std::move(builder).to_datum(); return true; } return false; } } // namespace auth
25,928
7,379
#include "logging/logger_asynchronous.h" #include <chrono> #include "logging/manager.h" namespace logging { logger_asynchronous::logger_asynchronous() : state_{static_cast<unsigned>(state::off)} { start(); } logger_asynchronous::~logger_asynchronous() { stop(); } void logger_asynchronous::start() { unsigned state = state_.load(std::memory_order_acquire); if (state == static_cast<unsigned>(state::working) || state == static_cast<unsigned>(state::starting)) { return; } while (state == static_cast<unsigned>(state::stopping)) { std::this_thread::sleep_for(std::chrono::microseconds(100)); state = state_.load(std::memory_order_acquire); } if (state == static_cast<unsigned>(state::off)) { if (state_.compare_exchange_strong( state, static_cast<unsigned>(state::starting), std::memory_order_release, std::memory_order_relaxed)) { worker_ = std::move(std::thread{[this](){ work(); }}); while(state_.load(std::memory_order_acquire) != static_cast<unsigned>(state::working)) { std::this_thread::sleep_for(std::chrono::microseconds(100)); } } } } void logger_asynchronous::stop() { unsigned state = state_.load(std::memory_order_acquire); if (state == static_cast<unsigned>(state::off) || state == static_cast<unsigned>(state::stopping)) { return; } while (state == static_cast<unsigned>(state::starting)) { std::this_thread::sleep_for(std::chrono::microseconds(100)); state = state_.load(std::memory_order_acquire); } if (state == static_cast<unsigned>(state::working)) { if (state_.compare_exchange_strong( state, static_cast<unsigned>(state::stopping), std::memory_order_release, std::memory_order_relaxed)) { write_condition_.notify_one(); while(state_.load(std::memory_order_acquire) != static_cast<unsigned>(state::off)) { std::this_thread::sleep_for(std::chrono::microseconds(100)); } if (worker_.joinable()) { worker_.join(); } } } } void logger_asynchronous::dispatch(const logging::record& record) { auto state = state_.load(std::memory_order_acquire); if (state == static_cast<unsigned>(state::off) || state == static_cast<unsigned>(state::stopping)) { return; } { std::unique_lock<std::mutex> lock(mutex_); records_.emplace(record); } write_condition_.notify_one(); } void logger_asynchronous::work() { state_.store(static_cast<unsigned>(state::working), std::memory_order_release); bool is_records_queue_empty{true}; while(state_.load(std::memory_order_acquire) != static_cast<unsigned>(state::stopping) || is_records_queue_empty == false) { std::queue<logging::record> buffer; std::unique_lock<std::mutex> lock(mutex_); if (records_.empty()) { write_condition_.wait(lock); } std::swap(records_, buffer); lock.unlock(); while(!buffer.empty()) { auto item = buffer.front(); if (auto sink{manager::instance().find_sink(item.sink_name)}) { if (sink->check_level(item.level)) { sink->write(item); } } buffer.pop(); } lock.lock(); is_records_queue_empty = records_.empty(); } state_.store(static_cast<unsigned>(state::off), std::memory_order_release); } }
3,336
1,095
/* * Copyright (C) 1999-2000 Harri Porten (porten@kde.org) * Copyright (C) 2008-2019 Apple Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * */ #include "config.h" #include "ObjectConstructor.h" #include "BuiltinNames.h" #include "JSArray.h" #include "JSCInlines.h" #include "JSImmutableButterfly.h" #include "PropertyDescriptor.h" #include "PropertyNameArray.h" #include "Symbol.h" namespace JSC { EncodedJSValue JSC_HOST_CALL objectConstructorAssign(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorValues(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorGetPrototypeOf(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorSetPrototypeOf(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertyNames(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorDefineProperty(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorDefineProperties(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorCreate(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorSeal(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorFreeze(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorPreventExtensions(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorIsSealed(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorIsFrozen(JSGlobalObject*, CallFrame*); EncodedJSValue JSC_HOST_CALL objectConstructorIsExtensible(JSGlobalObject*, CallFrame*); } #include "ObjectConstructor.lut.h" namespace JSC { STATIC_ASSERT_IS_TRIVIALLY_DESTRUCTIBLE(ObjectConstructor); const ClassInfo ObjectConstructor::s_info = { "Function", &InternalFunction::s_info, &objectConstructorTable, nullptr, CREATE_METHOD_TABLE(ObjectConstructor) }; /* Source for ObjectConstructor.lut.h @begin objectConstructorTable getPrototypeOf objectConstructorGetPrototypeOf DontEnum|Function 1 ObjectGetPrototypeOfIntrinsic setPrototypeOf objectConstructorSetPrototypeOf DontEnum|Function 2 getOwnPropertyDescriptor objectConstructorGetOwnPropertyDescriptor DontEnum|Function 2 getOwnPropertyDescriptors objectConstructorGetOwnPropertyDescriptors DontEnum|Function 1 getOwnPropertyNames objectConstructorGetOwnPropertyNames DontEnum|Function 1 getOwnPropertySymbols objectConstructorGetOwnPropertySymbols DontEnum|Function 1 keys objectConstructorKeys DontEnum|Function 1 ObjectKeysIntrinsic defineProperty objectConstructorDefineProperty DontEnum|Function 3 defineProperties objectConstructorDefineProperties DontEnum|Function 2 create objectConstructorCreate DontEnum|Function 2 ObjectCreateIntrinsic seal objectConstructorSeal DontEnum|Function 1 freeze objectConstructorFreeze DontEnum|Function 1 preventExtensions objectConstructorPreventExtensions DontEnum|Function 1 isSealed objectConstructorIsSealed DontEnum|Function 1 isFrozen objectConstructorIsFrozen DontEnum|Function 1 isExtensible objectConstructorIsExtensible DontEnum|Function 1 is objectConstructorIs DontEnum|Function 2 ObjectIsIntrinsic assign objectConstructorAssign DontEnum|Function 2 values objectConstructorValues DontEnum|Function 1 entries JSBuiltin DontEnum|Function 1 fromEntries JSBuiltin DontEnum|Function 1 @end */ static EncodedJSValue JSC_HOST_CALL callObjectConstructor(JSGlobalObject*, CallFrame*); static EncodedJSValue JSC_HOST_CALL constructWithObjectConstructor(JSGlobalObject*, CallFrame*); ObjectConstructor::ObjectConstructor(VM& vm, Structure* structure) : InternalFunction(vm, structure, callObjectConstructor, constructWithObjectConstructor) { } void ObjectConstructor::finishCreation(VM& vm, JSGlobalObject* globalObject, ObjectPrototype* objectPrototype) { Base::finishCreation(vm, vm.propertyNames->Object.string(), NameAdditionMode::WithoutStructureTransition); putDirectWithoutTransition(vm, vm.propertyNames->prototype, objectPrototype, PropertyAttribute::DontEnum | PropertyAttribute::DontDelete | PropertyAttribute::ReadOnly); putDirectWithoutTransition(vm, vm.propertyNames->length, jsNumber(1), PropertyAttribute::ReadOnly | PropertyAttribute::DontEnum); JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().createPrivateName(), objectConstructorCreate, static_cast<unsigned>(PropertyAttribute::DontEnum), 2); JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().definePropertyPrivateName(), objectConstructorDefineProperty, static_cast<unsigned>(PropertyAttribute::DontEnum), 3); JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().getPrototypeOfPrivateName(), objectConstructorGetPrototypeOf, static_cast<unsigned>(PropertyAttribute::DontEnum), 1); JSC_NATIVE_FUNCTION_WITHOUT_TRANSITION(vm.propertyNames->builtinNames().getOwnPropertyNamesPrivateName(), objectConstructorGetOwnPropertyNames, static_cast<unsigned>(PropertyAttribute::DontEnum), 1); } // ES 19.1.1.1 Object([value]) static ALWAYS_INLINE JSObject* constructObjectWithNewTarget(JSGlobalObject* globalObject, CallFrame* callFrame, JSValue newTarget) { VM& vm = globalObject->vm(); ObjectConstructor* objectConstructor = jsCast<ObjectConstructor*>(callFrame->jsCallee()); auto scope = DECLARE_THROW_SCOPE(vm); // We need to check newTarget condition in this caller side instead of InternalFunction::createSubclassStructure side. // Since if we found this condition is met, we should not fall into the type conversion in the step 3. // 1. If NewTarget is neither undefined nor the active function, then if (newTarget && newTarget != objectConstructor) { // a. Return ? OrdinaryCreateFromConstructor(NewTarget, "%ObjectPrototype%"). Structure* baseStructure = getFunctionRealm(vm, asObject(newTarget))->objectStructureForObjectConstructor(); Structure* objectStructure = InternalFunction::createSubclassStructure(globalObject, asObject(newTarget), baseStructure); RETURN_IF_EXCEPTION(scope, nullptr); return constructEmptyObject(vm, objectStructure); } // 2. If value is null, undefined or not supplied, return ObjectCreate(%ObjectPrototype%). JSValue argument = callFrame->argument(0); if (argument.isUndefinedOrNull()) return constructEmptyObject(vm, globalObject->objectStructureForObjectConstructor()); // 3. Return ToObject(value). RELEASE_AND_RETURN(scope, argument.toObject(globalObject)); } static EncodedJSValue JSC_HOST_CALL constructWithObjectConstructor(JSGlobalObject* globalObject, CallFrame* callFrame) { return JSValue::encode(constructObjectWithNewTarget(globalObject, callFrame, callFrame->newTarget())); } static EncodedJSValue JSC_HOST_CALL callObjectConstructor(JSGlobalObject* globalObject, CallFrame* callFrame) { return JSValue::encode(constructObjectWithNewTarget(globalObject, callFrame, JSValue())); } EncodedJSValue JSC_HOST_CALL objectConstructorGetPrototypeOf(JSGlobalObject* globalObject, CallFrame* callFrame) { return JSValue::encode(callFrame->argument(0).getPrototype(globalObject)); } EncodedJSValue JSC_HOST_CALL objectConstructorSetPrototypeOf(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue objectValue = callFrame->argument(0); if (objectValue.isUndefinedOrNull()) return throwVMTypeError(globalObject, scope, "Cannot set prototype of undefined or null"_s); JSValue protoValue = callFrame->argument(1); if (!protoValue.isObject() && !protoValue.isNull()) return throwVMTypeError(globalObject, scope, "Prototype value can only be an object or null"_s); JSObject* object = objectValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); bool shouldThrowIfCantSet = true; bool didSetPrototype = object->setPrototype(vm, globalObject, protoValue, shouldThrowIfCantSet); EXCEPTION_ASSERT_UNUSED(didSetPrototype, scope.exception() || didSetPrototype); return JSValue::encode(objectValue); } JSValue objectConstructorGetOwnPropertyDescriptor(JSGlobalObject* globalObject, JSObject* object, const Identifier& propertyName) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); PropertyDescriptor descriptor; if (!object->getOwnPropertyDescriptor(globalObject, propertyName, descriptor)) RELEASE_AND_RETURN(scope, jsUndefined()); RETURN_IF_EXCEPTION(scope, { }); JSObject* result = constructObjectFromPropertyDescriptor(globalObject, descriptor); scope.assertNoException(); ASSERT(result); return result; } JSValue objectConstructorGetOwnPropertyDescriptors(JSGlobalObject* globalObject, JSObject* object) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); PropertyNameArray properties(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); object->methodTable(vm)->getOwnPropertyNames(object, globalObject, properties, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, { }); JSObject* descriptors = constructEmptyObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); for (auto& propertyName : properties) { PropertyDescriptor descriptor; bool didGetDescriptor = object->getOwnPropertyDescriptor(globalObject, propertyName, descriptor); RETURN_IF_EXCEPTION(scope, { }); if (!didGetDescriptor) continue; JSObject* fromDescriptor = constructObjectFromPropertyDescriptor(globalObject, descriptor); scope.assertNoException(); ASSERT(fromDescriptor); PutPropertySlot slot(descriptors); descriptors->putOwnDataPropertyMayBeIndex(globalObject, propertyName, fromDescriptor, slot); scope.assertNoException(); } return descriptors; } EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertyDescriptor(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); auto propertyName = callFrame->argument(1).toPropertyKey(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(objectConstructorGetOwnPropertyDescriptor(globalObject, object, propertyName))); } EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertyDescriptors(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(objectConstructorGetOwnPropertyDescriptors(globalObject, object))); } // FIXME: Use the enumeration cache. EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertyNames(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(ownPropertyKeys(globalObject, object, PropertyNameMode::Strings, DontEnumPropertiesMode::Include))); } // FIXME: Use the enumeration cache. EncodedJSValue JSC_HOST_CALL objectConstructorGetOwnPropertySymbols(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(ownPropertyKeys(globalObject, object, PropertyNameMode::Symbols, DontEnumPropertiesMode::Include))); } EncodedJSValue JSC_HOST_CALL objectConstructorKeys(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSObject* object = callFrame->argument(0).toObject(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); RELEASE_AND_RETURN(scope, JSValue::encode(ownPropertyKeys(globalObject, object, PropertyNameMode::Strings, DontEnumPropertiesMode::Exclude))); } EncodedJSValue JSC_HOST_CALL objectConstructorAssign(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue targetValue = callFrame->argument(0); if (targetValue.isUndefinedOrNull()) return throwVMTypeError(globalObject, scope, "Object.assign requires that input parameter not be null or undefined"_s); JSObject* target = targetValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); // FIXME: Extend this for non JSFinalObject. For example, we would like to use this fast path for function objects too. // https://bugs.webkit.org/show_bug.cgi?id=185358 bool targetCanPerformFastPut = jsDynamicCast<JSFinalObject*>(vm, target) && target->canPerformFastPutInlineExcludingProto(vm); Vector<RefPtr<UniquedStringImpl>, 8> properties; MarkedArgumentBuffer values; unsigned argsCount = callFrame->argumentCount(); for (unsigned i = 1; i < argsCount; ++i) { JSValue sourceValue = callFrame->uncheckedArgument(i); if (sourceValue.isUndefinedOrNull()) continue; JSObject* source = sourceValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); if (targetCanPerformFastPut) { if (!source->staticPropertiesReified(vm)) { source->reifyAllStaticProperties(globalObject); RETURN_IF_EXCEPTION(scope, { }); } auto canPerformFastPropertyEnumerationForObjectAssign = [] (Structure* structure) { if (structure->typeInfo().overridesGetOwnPropertySlot()) return false; if (structure->typeInfo().overridesAnyFormOfGetPropertyNames()) return false; // FIXME: Indexed properties can be handled. // https://bugs.webkit.org/show_bug.cgi?id=185358 if (hasIndexedProperties(structure->indexingType())) return false; if (structure->hasGetterSetterProperties()) return false; if (structure->hasReadOnlyOrGetterSetterPropertiesExcludingProto()) return false; if (structure->hasCustomGetterSetterProperties()) return false; if (structure->isUncacheableDictionary()) return false; // Cannot perform fast [[Put]] to |target| if the property names of the |source| contain "__proto__". if (structure->hasUnderscoreProtoPropertyExcludingOriginalProto()) return false; return true; }; if (canPerformFastPropertyEnumerationForObjectAssign(source->structure(vm))) { // |source| Structure does not have any getters. And target can perform fast put. // So enumerating properties and putting properties are non observable. // FIXME: It doesn't seem like we should have to do this in two phases, but // we're running into crashes where it appears that source is transitioning // under us, and even ends up in a state where it has a null butterfly. My // leading hypothesis here is that we fire some value replacement watchpoint // that ends up transitioning the structure underneath us. // https://bugs.webkit.org/show_bug.cgi?id=187837 // Do not clear since Vector::clear shrinks the backing store. properties.resize(0); values.clear(); source->structure(vm)->forEachProperty(vm, [&] (const PropertyMapEntry& entry) -> bool { if (entry.attributes & PropertyAttribute::DontEnum) return true; PropertyName propertyName(entry.key); if (propertyName.isPrivateName()) return true; properties.append(entry.key); values.appendWithCrashOnOverflow(source->getDirect(entry.offset)); return true; }); for (size_t i = 0; i < properties.size(); ++i) { // FIXME: We could put properties in a batching manner to accelerate Object.assign more. // https://bugs.webkit.org/show_bug.cgi?id=185358 PutPropertySlot putPropertySlot(target, true); target->putOwnDataProperty(vm, properties[i].get(), values.at(i), putPropertySlot); } continue; } } // [[GetOwnPropertyNames]], [[Get]] etc. could modify target object and invalidate this assumption. // For example, [[Get]] of source object could configure setter to target object. So disable the fast path. targetCanPerformFastPut = false; PropertyNameArray properties(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); source->methodTable(vm)->getOwnPropertyNames(source, globalObject, properties, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, { }); auto assign = [&] (PropertyName propertyName) { PropertySlot slot(source, PropertySlot::InternalMethodType::GetOwnProperty); bool hasProperty = source->methodTable(vm)->getOwnPropertySlot(source, globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, void()); if (!hasProperty) return; if (slot.attributes() & PropertyAttribute::DontEnum) return; JSValue value; if (LIKELY(!slot.isTaintedByOpaqueObject())) value = slot.getValue(globalObject, propertyName); else value = source->get(globalObject, propertyName); RETURN_IF_EXCEPTION(scope, void()); PutPropertySlot putPropertySlot(target, true); target->putInline(globalObject, propertyName, value, putPropertySlot); }; // First loop is for strings. Second loop is for symbols to keep standardized order requirement in the spec. // https://tc39.github.io/ecma262/#sec-ordinaryownpropertykeys bool foundSymbol = false; unsigned numProperties = properties.size(); for (unsigned j = 0; j < numProperties; j++) { const auto& propertyName = properties[j]; if (propertyName.isSymbol()) { foundSymbol = true; continue; } assign(propertyName); RETURN_IF_EXCEPTION(scope, { }); } if (foundSymbol) { for (unsigned j = 0; j < numProperties; j++) { const auto& propertyName = properties[j]; if (propertyName.isSymbol()) { ASSERT(!propertyName.isPrivateName()); assign(propertyName); RETURN_IF_EXCEPTION(scope, { }); } } } } return JSValue::encode(target); } EncodedJSValue JSC_HOST_CALL objectConstructorValues(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue targetValue = callFrame->argument(0); if (targetValue.isUndefinedOrNull()) return throwVMTypeError(globalObject, scope, "Object.values requires that input parameter not be null or undefined"_s); JSObject* target = targetValue.toObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); JSArray* values = constructEmptyArray(globalObject, nullptr); RETURN_IF_EXCEPTION(scope, { }); PropertyNameArray properties(vm, PropertyNameMode::Strings, PrivateSymbolMode::Exclude); target->methodTable(vm)->getOwnPropertyNames(target, globalObject, properties, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, { }); unsigned index = 0; auto addValue = [&] (PropertyName propertyName) { PropertySlot slot(target, PropertySlot::InternalMethodType::GetOwnProperty); bool hasProperty = target->methodTable(vm)->getOwnPropertySlot(target, globalObject, propertyName, slot); RETURN_IF_EXCEPTION(scope, void()); if (!hasProperty) return; if (slot.attributes() & PropertyAttribute::DontEnum) return; JSValue value; if (LIKELY(!slot.isTaintedByOpaqueObject())) value = slot.getValue(globalObject, propertyName); else value = target->get(globalObject, propertyName); RETURN_IF_EXCEPTION(scope, void()); values->putDirectIndex(globalObject, index++, value); }; for (unsigned i = 0, numProperties = properties.size(); i < numProperties; i++) { const auto& propertyName = properties[i]; if (propertyName.isSymbol()) continue; addValue(propertyName); RETURN_IF_EXCEPTION(scope, { }); } return JSValue::encode(values); } // ES6 6.2.4.5 ToPropertyDescriptor // https://tc39.github.io/ecma262/#sec-topropertydescriptor bool toPropertyDescriptor(JSGlobalObject* globalObject, JSValue in, PropertyDescriptor& desc) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (!in.isObject()) { throwTypeError(globalObject, scope, "Property description must be an object."_s); return false; } JSObject* description = asObject(in); bool hasProperty = description->hasProperty(globalObject, vm.propertyNames->enumerable); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue value = description->get(globalObject, vm.propertyNames->enumerable); RETURN_IF_EXCEPTION(scope, false); desc.setEnumerable(value.toBoolean(globalObject)); } else RETURN_IF_EXCEPTION(scope, false); hasProperty = description->hasProperty(globalObject, vm.propertyNames->configurable); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue value = description->get(globalObject, vm.propertyNames->configurable); RETURN_IF_EXCEPTION(scope, false); desc.setConfigurable(value.toBoolean(globalObject)); } else RETURN_IF_EXCEPTION(scope, false); JSValue value; hasProperty = description->hasProperty(globalObject, vm.propertyNames->value); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue value = description->get(globalObject, vm.propertyNames->value); RETURN_IF_EXCEPTION(scope, false); desc.setValue(value); } else RETURN_IF_EXCEPTION(scope, false); hasProperty = description->hasProperty(globalObject, vm.propertyNames->writable); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue value = description->get(globalObject, vm.propertyNames->writable); RETURN_IF_EXCEPTION(scope, false); desc.setWritable(value.toBoolean(globalObject)); } else RETURN_IF_EXCEPTION(scope, false); hasProperty = description->hasProperty(globalObject, vm.propertyNames->get); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue get = description->get(globalObject, vm.propertyNames->get); RETURN_IF_EXCEPTION(scope, false); if (!get.isUndefined() && !get.isCallable(vm)) { throwTypeError(globalObject, scope, "Getter must be a function."_s); return false; } desc.setGetter(get); } else RETURN_IF_EXCEPTION(scope, false); hasProperty = description->hasProperty(globalObject, vm.propertyNames->set); EXCEPTION_ASSERT(!scope.exception() || !hasProperty); if (hasProperty) { JSValue set = description->get(globalObject, vm.propertyNames->set); RETURN_IF_EXCEPTION(scope, false); if (!set.isUndefined() && !set.isCallable(vm)) { throwTypeError(globalObject, scope, "Setter must be a function."_s); return false; } desc.setSetter(set); } else RETURN_IF_EXCEPTION(scope, false); if (!desc.isAccessorDescriptor()) return true; if (desc.value()) { throwTypeError(globalObject, scope, "Invalid property. 'value' present on property with getter or setter."_s); return false; } if (desc.writablePresent()) { throwTypeError(globalObject, scope, "Invalid property. 'writable' present on property with getter or setter."_s); return false; } return true; } EncodedJSValue JSC_HOST_CALL objectConstructorDefineProperty(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (!callFrame->argument(0).isObject()) return throwVMTypeError(globalObject, scope, "Properties can only be defined on Objects."_s); JSObject* obj = asObject(callFrame->argument(0)); auto propertyName = callFrame->argument(1).toPropertyKey(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); PropertyDescriptor descriptor; auto success = toPropertyDescriptor(globalObject, callFrame->argument(2), descriptor); EXCEPTION_ASSERT(!scope.exception() == success); if (!success) return JSValue::encode(jsNull()); ASSERT((descriptor.attributes() & PropertyAttribute::Accessor) || (!descriptor.isAccessorDescriptor())); scope.assertNoException(); obj->methodTable(vm)->defineOwnProperty(obj, globalObject, propertyName, descriptor, true); RELEASE_AND_RETURN(scope, JSValue::encode(obj)); } static JSValue defineProperties(JSGlobalObject* globalObject, JSObject* object, JSObject* properties) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); PropertyNameArray propertyNames(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); asObject(properties)->methodTable(vm)->getOwnPropertyNames(asObject(properties), globalObject, propertyNames, EnumerationMode(DontEnumPropertiesMode::Exclude)); RETURN_IF_EXCEPTION(scope, { }); size_t numProperties = propertyNames.size(); Vector<PropertyDescriptor> descriptors; MarkedArgumentBuffer markBuffer; #define RETURN_IF_EXCEPTION_CLEARING_OVERFLOW(value) do { \ if (scope.exception()) { \ markBuffer.overflowCheckNotNeeded(); \ return value; \ } \ } while (false) for (size_t i = 0; i < numProperties; i++) { JSValue prop = properties->get(globalObject, propertyNames[i]); RETURN_IF_EXCEPTION_CLEARING_OVERFLOW({ }); PropertyDescriptor descriptor; toPropertyDescriptor(globalObject, prop, descriptor); RETURN_IF_EXCEPTION_CLEARING_OVERFLOW({ }); descriptors.append(descriptor); // Ensure we mark all the values that we're accumulating if (descriptor.isDataDescriptor() && descriptor.value()) markBuffer.append(descriptor.value()); if (descriptor.isAccessorDescriptor()) { if (descriptor.getter()) markBuffer.append(descriptor.getter()); if (descriptor.setter()) markBuffer.append(descriptor.setter()); } } RELEASE_ASSERT(!markBuffer.hasOverflowed()); #undef RETURN_IF_EXCEPTION_CLEARING_OVERFLOW for (size_t i = 0; i < numProperties; i++) { auto& propertyName = propertyNames[i]; ASSERT(!propertyName.isPrivateName()); object->methodTable(vm)->defineOwnProperty(object, globalObject, propertyName, descriptors[i], true); RETURN_IF_EXCEPTION(scope, { }); } return object; } EncodedJSValue JSC_HOST_CALL objectConstructorDefineProperties(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (!callFrame->argument(0).isObject()) return throwVMTypeError(globalObject, scope, "Properties can only be defined on Objects."_s); JSObject* targetObj = asObject(callFrame->argument(0)); JSObject* props = callFrame->argument(1).toObject(globalObject); EXCEPTION_ASSERT(!!scope.exception() == !props); if (UNLIKELY(!props)) return encodedJSValue(); RELEASE_AND_RETURN(scope, JSValue::encode(defineProperties(globalObject, targetObj, props))); } EncodedJSValue JSC_HOST_CALL objectConstructorCreate(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue proto = callFrame->argument(0); if (!proto.isObject() && !proto.isNull()) return throwVMTypeError(globalObject, scope, "Object prototype may only be an Object or null."_s); JSObject* newObject = proto.isObject() ? constructEmptyObject(globalObject, asObject(proto)) : constructEmptyObject(vm, globalObject->nullPrototypeObjectStructure()); if (callFrame->argument(1).isUndefined()) return JSValue::encode(newObject); JSObject* properties = callFrame->uncheckedArgument(1).toObject(globalObject); RETURN_IF_EXCEPTION(scope, { }); RELEASE_AND_RETURN(scope, JSValue::encode(defineProperties(globalObject, newObject, properties))); } enum class IntegrityLevel { Sealed, Frozen }; template<IntegrityLevel level> bool setIntegrityLevel(JSGlobalObject* globalObject, VM& vm, JSObject* object) { // See https://tc39.github.io/ecma262/#sec-setintegritylevel. auto scope = DECLARE_THROW_SCOPE(vm); bool success = object->methodTable(vm)->preventExtensions(object, globalObject); RETURN_IF_EXCEPTION(scope, false); if (UNLIKELY(!success)) return false; PropertyNameArray properties(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); object->methodTable(vm)->getOwnPropertyNames(object, globalObject, properties, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, false); PropertyNameArray::const_iterator end = properties.end(); for (PropertyNameArray::const_iterator iter = properties.begin(); iter != end; ++iter) { auto& propertyName = *iter; ASSERT(!propertyName.isPrivateName()); PropertyDescriptor desc; if (level == IntegrityLevel::Sealed) desc.setConfigurable(false); else { bool hasPropertyDescriptor = object->getOwnPropertyDescriptor(globalObject, propertyName, desc); RETURN_IF_EXCEPTION(scope, false); if (!hasPropertyDescriptor) continue; if (desc.isDataDescriptor()) desc.setWritable(false); desc.setConfigurable(false); } object->methodTable(vm)->defineOwnProperty(object, globalObject, propertyName, desc, true); RETURN_IF_EXCEPTION(scope, false); } return true; } template<IntegrityLevel level> bool testIntegrityLevel(JSGlobalObject* globalObject, VM& vm, JSObject* object) { auto scope = DECLARE_THROW_SCOPE(vm); // 1. Assert: Type(O) is Object. // 2. Assert: level is either "sealed" or "frozen". // 3. Let status be ?IsExtensible(O). bool status = object->isExtensible(globalObject); RETURN_IF_EXCEPTION(scope, { }); // 4. If status is true, return false. if (status) return false; // 6. Let keys be ? O.[[OwnPropertyKeys]](). PropertyNameArray keys(vm, PropertyNameMode::StringsAndSymbols, PrivateSymbolMode::Exclude); object->methodTable(vm)->getOwnPropertyNames(object, globalObject, keys, EnumerationMode(DontEnumPropertiesMode::Include)); RETURN_IF_EXCEPTION(scope, { }); // 7. For each element k of keys, do PropertyNameArray::const_iterator end = keys.end(); for (PropertyNameArray::const_iterator iter = keys.begin(); iter != end; ++iter) { auto& propertyName = *iter; ASSERT(!propertyName.isPrivateName()); // a. Let currentDesc be ? O.[[GetOwnProperty]](k) PropertyDescriptor desc; bool didGetDescriptor = object->getOwnPropertyDescriptor(globalObject, propertyName, desc); RETURN_IF_EXCEPTION(scope, { }); // b. If currentDesc is not undefined, then if (!didGetDescriptor) continue; // i. If currentDesc.[[Configurable]] is true, return false. if (desc.configurable()) return false; // ii. If level is "frozen" and IsDataDescriptor(currentDesc) is true, then // 1. If currentDesc.[[Writable]] is true, return false. if (level == IntegrityLevel::Frozen && desc.isDataDescriptor() && desc.writable()) return false; } return true; } JSObject* objectConstructorSeal(JSGlobalObject* globalObject, JSObject* object) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (jsDynamicCast<JSFinalObject*>(vm, object) && !hasIndexedProperties(object->indexingType())) { object->seal(vm); return object; } bool success = setIntegrityLevel<IntegrityLevel::Sealed>(globalObject, vm, object); RETURN_IF_EXCEPTION(scope, nullptr); if (UNLIKELY(!success)) { throwTypeError(globalObject, scope, "Unable to prevent extension in Object.seal"_s); return nullptr; } return object; } EncodedJSValue JSC_HOST_CALL objectConstructorSeal(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 1. If Type(O) is not Object, return O. JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(obj); RELEASE_AND_RETURN(scope, JSValue::encode(objectConstructorSeal(globalObject, asObject(obj)))); } JSObject* objectConstructorFreeze(JSGlobalObject* globalObject, JSObject* object) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); if (jsDynamicCast<JSFinalObject*>(vm, object) && !hasIndexedProperties(object->indexingType())) { object->freeze(vm); return object; } bool success = setIntegrityLevel<IntegrityLevel::Frozen>(globalObject, vm, object); RETURN_IF_EXCEPTION(scope, nullptr); if (UNLIKELY(!success)) { throwTypeError(globalObject, scope, "Unable to prevent extension in Object.freeze"_s); return nullptr; } return object; } EncodedJSValue JSC_HOST_CALL objectConstructorFreeze(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); // 1. If Type(O) is not Object, return O. JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(obj); JSObject* result = objectConstructorFreeze(globalObject, asObject(obj)); RETURN_IF_EXCEPTION(scope, encodedJSValue()); return JSValue::encode(result); } EncodedJSValue JSC_HOST_CALL objectConstructorPreventExtensions(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue argument = callFrame->argument(0); if (!argument.isObject()) return JSValue::encode(argument); JSObject* object = asObject(argument); bool status = object->methodTable(vm)->preventExtensions(object, globalObject); RETURN_IF_EXCEPTION(scope, { }); if (UNLIKELY(!status)) return throwVMTypeError(globalObject, scope, "Unable to prevent extension in Object.preventExtensions"_s); return JSValue::encode(object); } EncodedJSValue JSC_HOST_CALL objectConstructorIsSealed(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); // 1. If Type(O) is not Object, return true. JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(jsBoolean(true)); JSObject* object = asObject(obj); // Quick check for final objects. if (jsDynamicCast<JSFinalObject*>(vm, object) && !hasIndexedProperties(object->indexingType())) return JSValue::encode(jsBoolean(object->isSealed(vm))); // 2. Return ? TestIntegrityLevel(O, "sealed"). return JSValue::encode(jsBoolean(testIntegrityLevel<IntegrityLevel::Sealed>(globalObject, vm, object))); } EncodedJSValue JSC_HOST_CALL objectConstructorIsFrozen(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); // 1. If Type(O) is not Object, return true. JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(jsBoolean(true)); JSObject* object = asObject(obj); // Quick check for final objects. if (jsDynamicCast<JSFinalObject*>(vm, object) && !hasIndexedProperties(object->indexingType())) return JSValue::encode(jsBoolean(object->isFrozen(vm))); // 2. Return ? TestIntegrityLevel(O, "frozen"). return JSValue::encode(jsBoolean(testIntegrityLevel<IntegrityLevel::Frozen>(globalObject, vm, object))); } EncodedJSValue JSC_HOST_CALL objectConstructorIsExtensible(JSGlobalObject* globalObject, CallFrame* callFrame) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); JSValue obj = callFrame->argument(0); if (!obj.isObject()) return JSValue::encode(jsBoolean(false)); JSObject* object = asObject(obj); bool isExtensible = object->isExtensible(globalObject); RETURN_IF_EXCEPTION(scope, encodedJSValue()); return JSValue::encode(jsBoolean(isExtensible)); } EncodedJSValue JSC_HOST_CALL objectConstructorIs(JSGlobalObject* globalObject, CallFrame* callFrame) { return JSValue::encode(jsBoolean(sameValue(globalObject, callFrame->argument(0), callFrame->argument(1)))); } JSArray* ownPropertyKeys(JSGlobalObject* globalObject, JSObject* object, PropertyNameMode propertyNameMode, DontEnumPropertiesMode dontEnumPropertiesMode) { VM& vm = globalObject->vm(); auto scope = DECLARE_THROW_SCOPE(vm); bool isObjectKeys = propertyNameMode == PropertyNameMode::Strings && dontEnumPropertiesMode == DontEnumPropertiesMode::Exclude; // We attempt to look up own property keys cache in Object.keys case. if (isObjectKeys) { if (LIKELY(!globalObject->isHavingABadTime())) { if (auto* immutableButterfly = object->structure(vm)->cachedOwnKeys()) { Structure* arrayStructure = globalObject->originalArrayStructureForIndexingType(immutableButterfly->indexingMode()); return JSArray::createWithButterfly(vm, nullptr, arrayStructure, immutableButterfly->toButterfly()); } } } PropertyNameArray properties(vm, propertyNameMode, PrivateSymbolMode::Exclude); object->methodTable(vm)->getOwnPropertyNames(object, globalObject, properties, EnumerationMode(dontEnumPropertiesMode)); RETURN_IF_EXCEPTION(scope, nullptr); if (propertyNameMode != PropertyNameMode::StringsAndSymbols) { ASSERT(propertyNameMode == PropertyNameMode::Strings || propertyNameMode == PropertyNameMode::Symbols); if (properties.size() < MIN_SPARSE_ARRAY_INDEX) { if (LIKELY(!globalObject->isHavingABadTime())) { if (isObjectKeys) { Structure* structure = object->structure(vm); if (structure->canCacheOwnKeys()) { auto* cachedButterfly = structure->cachedOwnKeysIgnoringSentinel(); if (cachedButterfly == StructureRareData::cachedOwnKeysSentinel()) { size_t numProperties = properties.size(); auto* newButterfly = JSImmutableButterfly::create(vm, CopyOnWriteArrayWithContiguous, numProperties); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; ASSERT(!identifier.isSymbol()); newButterfly->setIndex(vm, i, jsOwnedString(vm, identifier.string())); } structure->setCachedOwnKeys(vm, newButterfly); Structure* arrayStructure = globalObject->originalArrayStructureForIndexingType(newButterfly->indexingMode()); return JSArray::createWithButterfly(vm, nullptr, arrayStructure, newButterfly->toButterfly()); } if (cachedButterfly == nullptr) structure->setCachedOwnKeys(vm, StructureRareData::cachedOwnKeysSentinel()); } } size_t numProperties = properties.size(); JSArray* keys = JSArray::create(vm, globalObject->originalArrayStructureForIndexingType(ArrayWithContiguous), numProperties); WriteBarrier<Unknown>* buffer = keys->butterfly()->contiguous().data(); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; if (propertyNameMode == PropertyNameMode::Strings) { ASSERT(!identifier.isSymbol()); buffer[i].set(vm, keys, jsOwnedString(vm, identifier.string())); } else { ASSERT(identifier.isSymbol()); buffer[i].set(vm, keys, Symbol::create(vm, static_cast<SymbolImpl&>(*identifier.impl()))); } } return keys; } } } JSArray* keys = constructEmptyArray(globalObject, nullptr); RETURN_IF_EXCEPTION(scope, nullptr); unsigned index = 0; auto pushDirect = [&] (JSGlobalObject* globalObject, JSArray* array, JSValue value) { array->putDirectIndex(globalObject, index++, value); }; switch (propertyNameMode) { case PropertyNameMode::Strings: { size_t numProperties = properties.size(); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; ASSERT(!identifier.isSymbol()); pushDirect(globalObject, keys, jsOwnedString(vm, identifier.string())); RETURN_IF_EXCEPTION(scope, nullptr); } break; } case PropertyNameMode::Symbols: { size_t numProperties = properties.size(); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; ASSERT(identifier.isSymbol()); ASSERT(!identifier.isPrivateName()); pushDirect(globalObject, keys, Symbol::create(vm, static_cast<SymbolImpl&>(*identifier.impl()))); RETURN_IF_EXCEPTION(scope, nullptr); } break; } case PropertyNameMode::StringsAndSymbols: { Vector<Identifier, 16> propertySymbols; size_t numProperties = properties.size(); for (size_t i = 0; i < numProperties; i++) { const auto& identifier = properties[i]; if (identifier.isSymbol()) { ASSERT(!identifier.isPrivateName()); propertySymbols.append(identifier); continue; } pushDirect(globalObject, keys, jsOwnedString(vm, identifier.string())); RETURN_IF_EXCEPTION(scope, nullptr); } // To ensure the order defined in the spec (9.1.12), we append symbols at the last elements of keys. for (const auto& identifier : propertySymbols) { pushDirect(globalObject, keys, Symbol::create(vm, static_cast<SymbolImpl&>(*identifier.impl()))); RETURN_IF_EXCEPTION(scope, nullptr); } break; } } return keys; } } // namespace JSC
45,547
12,958
#include <mgapiall.h> #include <stdlib.h> #include <string.h> #include <windows.h> #include <stddef.h> #include <math.h> static int lasterr = 0; static void Normalize (double *xp, double *yp, double *zp) { // normalize double x = *xp, y = *yp, z = *zp; double mag = sqrt(x*x + y*y + z*z); x /= mag; y /= mag; z /= mag; *xp = x; *yp = y; *zp = z; } static void freenode (mgrec *db) { if (db->next) freenode (db->next); if (db->child) freenode (db->child); free (db); } inline void exch_char (char *a, char *b) { *a ^= *b; *b ^= *a; *a ^= *b; } inline short swap_short (short num) { short data = num; char *cnum = (char *) &data; exch_char (&cnum[1], &cnum[0]); return data; } inline int swap_int (int num) { int data = num; char *cnum = (char *) &data; exch_char (&cnum[3], &cnum[0]); exch_char (&cnum[2], &cnum[1]); return data; } inline float swap_float (float num) { float data = num; char *cnum = (char *) &data; exch_char (&cnum[3], &cnum[0]); exch_char (&cnum[2], &cnum[1]); return data; } inline double swap_double (double num) { double data = num; char *cnum = (char *) &data; exch_char (&cnum[7], &cnum[0]); exch_char (&cnum[6], &cnum[1]); exch_char (&cnum[5], &cnum[2]); exch_char (&cnum[4], &cnum[3]); return data; } struct { FltTypes type; const char *name; } FltNames[] = { #define MKENT(x) { x, #x } MKENT(fltHeader), MKENT(fltGroup), MKENT(fltIcoord), MKENT(fltVU), MKENT(fltVV), MKENT(fltVertex), MKENT(fltPolyMaterial), MKENT(fltDiffuse), MKENT(fltMatAlpha), MKENT(fltPolygon), MKENT(fltBsp), MKENT(fltSwitch), MKENT(fltDof), MKENT(fltLightPoint), MKENT(fltPolyTransparency), MKENT(fltGcLightMode), MKENT(fltPolyTexture), MKENT(fltMatrix), MKENT(fltVColor), MKENT(fltLpDirectionalityType), MKENT(fltLpBackColor), MKENT(fltPolyMgTemplate), MKENT(fltPolyLineStyle), MKENT(fltPolyDrawType), MKENT(fltDPlaneA), MKENT(fltDPlaneB), MKENT(fltDPlaneC), MKENT(fltDPlaneD), MKENT(fltDofPutAnchorX), MKENT(fltDofPutAnchorY), MKENT(fltDofPutAnchorZ), MKENT(fltDofPutAlignX), MKENT(fltDofPutAlignY), MKENT(fltDofPutAlignZ), MKENT(fltDofPutTrackX), MKENT(fltDofPutTrackY), MKENT(fltDofPutTrackZ), MKENT(fltDofMaxX), MKENT(fltDofMinX), MKENT(fltXref), MKENT(fltLodSwitchIn), MKENT(fltXrefFilename), MKENT(fltLod) }; static const int FltSize = sizeof(FltNames) / sizeof(FltNames[0]); static int mgIgnoreRec (OpCode type) { #if 1 return 0; #else switch (type) { case OPCODE_POLYGON: case OPCODE_BINARY_SEPARATING_PLANE: case OPCODE_SWITCH_BEAD: case OPCODE_DEGREE_OF_FREEDOM: case OPCODE_LIGHT_SOURCE_RECORD: case OPCODE_LEVEL_OF_DETAIL: case OPCODE_VERTEX_LIST: case OPCODE_COLOR_TABLE: case OPCODE_HEADER: case OPCODE_TEXT_COMMENT: case OPCODE_TEXTURE_REFERENCE_RECORD: case OPCODE_VERTEX_PALETTE: case OPCODE_VERTEX_WITH_NORMAL: case OPCODE_VERTEX_WITH_NORMAL_AND_UV: case OPCODE_VERTEX_WITH_UV: case OPCODE_MATERIAL_TABLE: case OPCODE_PUSH_LEVEL: case OPCODE_POP_LEVEL: case OPCODE_MATERIAL_PALETTE: case OPCODE_VERTEX_COORDINATE: return 0; default: return 1; } #endif } static int mgIsAncillary (OpCode type) { switch (type) { case OPCODE_TEXT_COMMENT: case OPCODE_LONG_IDENTIFIER: case OPCODE_REPLICATE_CODE: case OPCODE_ROAD_ZONE: case OPCODE_TRANSFORMATION_MATRIX: case OPCODE_VECTOR: case OPCODE_BOUNDING_BOX: case OPCODE_CAT_DATA: case OPCODE_EXTENSION: case OPCODE_VERTEX_COORDINATE: case OPCODE_VERTEX_WITH_NORMAL: case OPCODE_VERTEX_WITH_NORMAL_AND_UV: case OPCODE_VERTEX_WITH_UV: return 1; default: return 0; } } static int mgIsPalette (OpCode type) { switch (type) { case OPCODE_VERTEX_PALETTE: case OPCODE_COLOR_TABLE: case OPCODE_COLOR_NAME_PALETTE: case OPCODE_MATERIAL_PALETTE: case OPCODE_TEXTURE_REFERENCE_RECORD: case OPCODE_EYEPOINT_AND_TRACKPLANE_POSITION: case OPCODE_LINKAGE_RECORD: case OPCODE_SOUND_PALETTE: case OPCODE_LIGHT_SOURCE_PALETTE: case OPCODE_LINE_STYLE_RECORD: case OPCODE_TEXTURE_MAPPING_PALETTE: case OPCODE_MATERIAL_TABLE: return 1; default: return 0; } } const char *FindFltName (FltTypes f) { for (int i = 0; i < FltSize; i++) { if (FltNames[i].type == f) return FltNames[i].name; } return 0; } static int mgGetColorInd (mgrec *rec, int ind, int *rgb) { mgrec *pbase = rec; while (pbase -> parent) { pbase = pbase -> parent; } while (pbase && pbase -> type != OPCODE_COLOR_TABLE) { pbase = mgGetNext (pbase); } if (pbase == NULL) return MG_FALSE; if (rec->vrsn > 1500) { if ((unsigned)ind > (pbase -> len - offsetof(struct aflt_ColorRecord, rgb))/4) return MG_FALSE; struct aflt_ColorRecord *cr; cr = (struct aflt_ColorRecord *)pbase->data; *rgb = swap_int(cr -> rgb[ind]); return MG_TRUE; } else { if ((unsigned)ind > (pbase -> len - offsetof(struct flt_ColorRecord, rgb))/4) return MG_FALSE; struct flt_ColorRecord *cr; cr = (struct flt_ColorRecord *)pbase->data; *rgb = swap_int(cr -> rgb[ind]); return MG_TRUE; } } void mgInit (int type, void *param) { } char *mgGetName (mgrec *rec) { mgrec *p; for (p = rec->next; p && mgIsAncillary(p->type); p = p -> next) { if (p->type == OPCODE_LONG_IDENTIFIER) { char *comm = (char *)malloc (p->len - 4 + 1); memcpy (comm, p->data+4, p->len - 4); comm[p->len - 4] = '\0'; return comm; } } char *comm = (char *)malloc (8); memcpy (comm, rec->data+4, 8); return comm; } char * mgRec2Filename (mgrec *rec) { char *comm = (char *)malloc (9); strcpy (comm, "filename"); return comm; } mgrec *mgGetChild (mgrec *rec) { if (rec -> child) return rec->child; mgrec *p; for (p = rec->next; p && (mgIsAncillary(p->type) || mgIsPalette(p->type)); p = p->next) if (p->child) return p->child; return 0; } mgrec *mgGetParent (mgrec *rec) { return rec -> parent; } void mgExit () { } mgrec *mgGetNext (mgrec *rec) { mgrec *p; for (p = rec->next; p && (mgIsAncillary(p->type) || mgIsPalette(p->type)); p = p->next) continue; return p; } int mgIsCode (mgrec *rec, FltTypes type) { char buf[1024]; switch (type) { case fltPolygon: return rec->type == OPCODE_POLYGON; case fltBsp: return rec->type == OPCODE_BINARY_SEPARATING_PLANE; case fltSwitch: return rec->type == OPCODE_SWITCH_BEAD; case fltDof: return rec->type == OPCODE_DEGREE_OF_FREEDOM; case fltLightPoint: return rec->type == OPCODE_LIGHT_SOURCE_RECORD; case fltLod: return rec->type == OPCODE_LEVEL_OF_DETAIL; case fltVertex: return rec->type == OPCODE_VERTEX_LIST; default: sprintf (buf, "Unknown FltType %d %s\n", type, FindFltName(type)); OutputDebugString(buf); break; } return MG_FALSE; } void mgGetLastError (char *err, int size) { sprintf (err, "Error number %d", lasterr); } void mgFree (char *data) { free (data); } char *mgGetComment (mgrec *record) { while (record && record -> type != OPCODE_TEXT_COMMENT) { record = record -> next; } if (record) { char *comm = (char *)malloc (record -> len - 4); memcpy (comm, record -> data, record -> len - 4); return comm; } return 0; } int mgGetFirstTexture (mgrec *record, int *texind, char *texname) { return MG_FALSE; while (record && record -> type != OPCODE_TEXTURE_REFERENCE_RECORD) { record = record -> next; } if (record) { #if 0 if (record->vrsn > 1500) { OutputDebugString ("Version 1500 textures not supported yet\n"); return MG_FALSE; } #endif struct flt_TexturePatternRecord *tr = (struct flt_TexturePatternRecord *)record -> data; *texind = swap_int(tr -> patternIndex); strcpy (texname, tr -> filename); return MG_TRUE; } return MG_FALSE; } int mgGetNextTexture (mgrec *record, int *texind, char *texname) { if (record->vrsn > 1500) { OutputDebugString ("Version 1500 textures not supported yet\n"); return MG_FALSE; } while (record && record -> type != OPCODE_TEXTURE_REFERENCE_RECORD) { record = record -> next; } if (record == NULL) return MG_FALSE; while (record && record -> type == OPCODE_TEXTURE_REFERENCE_RECORD) { struct flt_TexturePatternRecord *tr = (struct flt_TexturePatternRecord *)record -> data; int ind = swap_int(tr -> patternIndex); if (ind > *texind) { *texind = ind; strcpy (texname, tr -> filename); return MG_TRUE; } record = record->next; } return MG_FALSE; } static mgrec *GetVertex (mgrec *rec, int n) { while (rec -> parent) rec = rec->parent; while (rec && rec -> type != OPCODE_VERTEX_PALETTE) rec = rec->next; if (rec == 0) return 0; int voff = rec->len; rec = rec->next; for (int i = 0; rec && voff < n; i++) { if (voff == n) return rec; voff += rec -> len; rec = rec->next; } return rec; } static int mgGetVertexNormal (mgrec *rec, double *i, double *j, double *k) { if (rec -> type != OPCODE_VERTEX_LIST) { OutputDebugString("GetVertexNormal not a vertex list\n"); return MG_FALSE; } int *vtx = (int *)rec->data; mgrec *vr = GetVertex (rec, *vtx); if (vr == NULL) { OutputDebugString("GetVertexNormal no vertex list\n"); return MG_FALSE; } switch (vr -> type) { case OPCODE_VERTEX_WITH_NORMAL: { struct flt_VertexCoordinateNormal *vn = (struct flt_VertexCoordinateNormal *)vr->data; *i = swap_float (vn->nx); *j = swap_float (vn->ny); *k = swap_float (vn->nz); return MG_TRUE; } case OPCODE_VERTEX_WITH_NORMAL_AND_UV: { struct flt_VertexCoordinateTextureNormal *vn = (struct flt_VertexCoordinateTextureNormal *)vr->data; *i = swap_float (vn->nx); *j = swap_float (vn->ny); *k = swap_float (vn->nz); return MG_TRUE; } default: return MG_FALSE; } } int mgGetVtxNormal (mgrec *rec, float *i, float *j, float *k) { double i1, j1, k1; if (mgGetVertexNormal (rec, &i1, &j1, &k1) == MG_TRUE) { *i = (float)i1; *j = (float)j1; *k = (float)k1; return MG_TRUE; } return MG_FALSE; } int mgGetVtxColorRGB (mgrec *rec, short *r, short *g, short *b) { if (rec -> type != OPCODE_VERTEX_LIST) { OutputDebugString("mgGetVtxColorRGB not a vertex list\n"); } int *vtx = (int *)rec->data; mgrec *vr = GetVertex (rec, *vtx); if (vr == NULL) { char buf[1024]; sprintf (buf, "No vertex reference found for %d\n", *vtx); OutputDebugString (buf); return MG_FALSE; } struct flt_VertexCoordinate *vc = (struct flt_VertexCoordinate *)vr->data; int pc= swap_short(vc -> vertexColor); int colind = pc >> 7; int colint = pc & 0x7f; int rgb; if (mgGetColorInd (rec, colind, &rgb) != MG_TRUE) return MG_FALSE; *r = (rgb & 0xff) * colint / 127; *g = ((rgb>>8) & 0xff) * colint / 127; *b = ((rgb>>16) & 0xff) * colint / 127; return MG_TRUE; } int mgGetIcoord (mgrec *rec, FltTypes type, double *x, double *y, double *z) { if (type != fltIcoord) { OutputDebugString("Not fltIcoord\n"); return MG_FALSE; } if (rec -> type == OPCODE_VERTEX_LIST) { int *vtx = (int *)rec->data; mgrec *vr = GetVertex (rec, *vtx); if (vr == NULL) { char buf[1024]; sprintf (buf, "No vertex reference found for %d\n", *vtx); OutputDebugString (buf); return MG_FALSE; } struct flt_VertexCoordinate *vc = (struct flt_VertexCoordinate *)vr->data; *x = swap_double (vc -> x); *y = swap_double (vc -> y); *z = swap_double (vc -> z); return MG_TRUE; } return MG_FALSE; } static int mgVtxFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec -> type != OPCODE_VERTEX_LIST) return MG_FALSE; int *vtx = (int *)rec->data; mgrec *vr = GetVertex (rec, *vtx); if (vr == NULL) { char buf[1024]; sprintf (buf, "No vertex reference found for %d\n", *vtx); OutputDebugString (buf); return MG_FALSE; } switch (type) { case fltVU: { if (vr -> type == OPCODE_VERTEX_WITH_NORMAL_AND_UV) { struct flt_VertexCoordinateTextureNormal *vt = (struct flt_VertexCoordinateTextureNormal *) vr -> data; *(float *)ptr = swap_float(vt -> u); break; } else if (vr -> type = OPCODE_VERTEX_WITH_UV) { struct flt_VertexCoordinateTexture *vt = (struct flt_VertexCoordinateTexture *) vr -> data; *(float *)ptr = swap_float(vt -> u); break; } else return MG_FALSE; } break; case fltVV: { if (vr -> type == OPCODE_VERTEX_WITH_NORMAL_AND_UV) { struct flt_VertexCoordinateTextureNormal *vt = (struct flt_VertexCoordinateTextureNormal *) vr -> data; *(float *)ptr = swap_float(vt -> v); break; } else if (vr -> type = OPCODE_VERTEX_WITH_UV) { struct flt_VertexCoordinateTexture *vt = (struct flt_VertexCoordinateTexture *) vr -> data; *(float *)ptr = swap_float(vt -> v); break; } else return MG_FALSE; } break; default: return MG_FALSE; } return MG_TRUE; } static int mgBspFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec -> type != OPCODE_BINARY_SEPARATING_PLANE) return 0; struct aflt_BinarySeparatingPlane *bsp = (struct aflt_BinarySeparatingPlane *)rec -> data; switch (type) { case fltDPlaneA: *(double *)ptr = swap_double(bsp->a); break; case fltDPlaneB: *(double *)ptr = swap_double(bsp->b); break; case fltDPlaneC: *(double *)ptr = swap_double(bsp->c); break; case fltDPlaneD: *(double *)ptr = swap_double(bsp->d); break; default: OutputDebugString ("Unknown BSP\n"); break; } return 1; } static int mgPolyFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec -> type != OPCODE_POLYGON) return 0; if (rec -> vrsn > 1500) { struct aflt_PolygonRecord *pr = (struct aflt_PolygonRecord *)rec->data; switch (type) { case fltPolyMaterial: { *(short *)ptr = swap_short(pr->materialCode); break; } case fltPolyTransparency: { *(short*)ptr = swap_short (pr->transparency); break; } case fltPolyMgTemplate: { *(char *)ptr = pr->templateTransparency; break; } case fltGcLightMode: { *(char *)ptr = pr->lightMode; break; } case fltPolyTexture: { *(short*)ptr = swap_short (pr->textureNo); break; } case fltPolyLineStyle: { *(char *)ptr = pr->linestyle; break; } case fltPolyDrawType: { *(char *)ptr = pr->howToDraw; break; } default: OutputDebugString ("Unknown poly attr\n"); break; } } else { struct flt_PolygonRecord *pr = (struct flt_PolygonRecord *)rec->data; switch (type) { case fltPolyMaterial: { *(short *)ptr = swap_short(pr->materialCode); break; } case fltPolyTransparency: { *(short*)ptr = swap_short (pr->transparency); break; } case fltPolyMgTemplate: { *(char *)ptr = pr->templateTransparency; break; } case fltGcLightMode: { *(char *)ptr = pr->lightMode; break; } case fltPolyTexture: { *(short*)ptr = swap_short (pr->textureNo); break; } case fltPolyLineStyle: { *(char *)ptr = pr->linestyle; break; } case fltPolyDrawType: { *(char *)ptr = pr->howToDraw; break; } default: OutputDebugString ("Unknown poly attr\n"); break; } } return 1; } static int mgDofFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec -> type != OPCODE_DEGREE_OF_FREEDOM) return 0; if (rec -> vrsn > 1500) { struct aflt_DegreeOfFreedomRecord *dof = (struct aflt_DegreeOfFreedomRecord *)rec->data; switch (type) { case fltDofPutAnchorX: { *(double *)ptr = swap_double(dof->originx); break; } case fltDofPutAnchorY: { *(double *)ptr = swap_double(dof->originy); break; } case fltDofPutAnchorZ: { *(double *)ptr = swap_double(dof->originz); break; } case fltDofPutAlignX: { *(double *)ptr = swap_double(dof->pointxaxis_x); break; } case fltDofPutAlignY: { *(double *)ptr = swap_double(dof->pointxaxis_y); break; } case fltDofPutAlignZ: { *(double *)ptr = swap_double(dof->pointxaxis_z); break; } case fltDofPutTrackX: { *(double *)ptr = swap_double(dof->pointxyplane_x); break; } case fltDofPutTrackY: { *(double *)ptr = swap_double(dof->pointxyplane_y); break; } case fltDofPutTrackZ: { *(double *)ptr = swap_double(dof->pointxyplane_z); break; } case fltDofMaxX: { *(double *)ptr = swap_double(dof->maxx); break; } case fltDofMinX: { *(double *)ptr = swap_double(dof->minx); break; } default: OutputDebugString ("Unknown DOF attr\n"); break; } } else { struct flt_DegreeOfFreedomRecord *dof = (struct flt_DegreeOfFreedomRecord *)rec->data; switch (type) { case fltDofPutAnchorX: { *(double *)ptr = swap_double(dof->originx); break; } case fltDofPutAnchorY: { *(double *)ptr = swap_double(dof->originy); break; } case fltDofPutAnchorZ: { *(double *)ptr = swap_double(dof->originz); break; } case fltDofPutAlignX: { *(double *)ptr = swap_double(dof->pointxaxis_x); break; } case fltDofPutAlignY: { *(double *)ptr = swap_double(dof->pointxaxis_y); break; } case fltDofPutAlignZ: { *(double *)ptr = swap_double(dof->pointxaxis_z); break; } case fltDofPutTrackX: { *(double *)ptr = swap_double(dof->pointxyplane_x); break; } case fltDofPutTrackY: { *(double *)ptr = swap_double(dof->pointxyplane_y); break; } case fltDofPutTrackZ: { *(double *)ptr = swap_double(dof->pointxyplane_z); break; } case fltDofMaxX: { *(double *)ptr = swap_double(dof->maxx); break; } case fltDofMinX: { *(double *)ptr = swap_double(dof->minx); break; } default: OutputDebugString ("Unknown DOF attr\n"); break; } } return 1; } static int mgMatFetch (mgrec *rec, FltTypes type, void *ptr) { if (rec->vrsn > 1500) { OutputDebugString ("mgMatFetch doesn't support 1500\n"); return MG_FALSE; } if (rec -> type != OPCODE_MATERIAL_TABLE) return MG_FALSE; struct flt_MaterialTable *mt = (struct flt_MaterialTable *)rec -> data; switch (type) { case fltMatAlpha: *(float *)ptr = swap_float (mt -> alpha); break; default: return MG_FALSE; } return MG_TRUE; } int mgGetAttList (mgrec *rec, ...) { va_list ap; FltTypes type; int count = 0; va_start(ap, rec); while ((type = va_arg(ap, FltTypes)) != 0) { switch (type) { case fltVU: case fltVV: { float *fp = va_arg (ap, float *); if (mgVtxFetch (rec, type, fp)) count ++; } break; case fltDPlaneA: case fltDPlaneB: case fltDPlaneC: case fltDPlaneD: { double *dp = va_arg(ap, double *); if (mgBspFetch (rec, type, dp)) count ++; } break; case fltPolyMaterial: { short *mind = va_arg(ap, short *); if (mgPolyFetch(rec, type, mind)) count ++; } break; case fltPolyTransparency: { short *tp = va_arg(ap, short *); if (mgPolyFetch(rec, type, tp)) count ++; } break; case fltPolyMgTemplate: { char *cp = va_arg(ap, char *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltGcLightMode: { char *cp = va_arg(ap, char *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltPolyTexture: { short *cp = va_arg(ap, short *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltPolyLineStyle: { char *cp = va_arg(ap, char *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltPolyDrawType: { char *cp = va_arg(ap, char *); if (mgPolyFetch (rec, type, cp)) count ++; } break; case fltMatAlpha: { float *fp = va_arg (ap, float *); if (mgMatFetch (rec, type, fp)) count ++; } break; case fltDofPutAnchorX: case fltDofPutAnchorY: case fltDofPutAnchorZ: case fltDofPutAlignX: case fltDofPutAlignY: case fltDofPutAlignZ: case fltDofPutTrackX: case fltDofPutTrackY: case fltDofPutTrackZ: case fltDofMaxX: case fltDofMinX: { double *dp = va_arg(ap, double *); if (mgDofFetch (rec, type, dp)) count ++; } break; default: { char buf[1024]; sprintf (buf, "Unsupported attr type %d %s\n", type, FindFltName(type)); OutputDebugString(buf); va_arg (ap, char *); // best guess } break; } } va_end (ap); return count; } static short getshort (FILE *fp) { int c1 = getc(fp); int c2 = getc(fp); return (c1 << 8) | c2; } static mgrec *mgReadSequence (FILE *fp, mgrec *prnt, int vrsn); static mgrec *mgReadRecord (FILE *fp, mgrec *prnt, int vrsn) { mgrec *rec = NULL; while (rec == NULL) { short type = getshort(fp); if (feof(fp)) return 0; rec = (mgrec *)calloc (1, sizeof *rec); rec->type = (OpCode)type; rec->len = getshort(fp); rec->data = (char *) calloc (1, rec -> len); rec->vrsn = vrsn; rec->parent = prnt; memcpy (rec->data, &rec->type, 2); memcpy (rec->data+2, &rec->len, 2); fread (rec -> data + 4, rec -> len - 4, 1, fp); if (mgIgnoreRec (rec->type)) { free (rec->data); free (rec); rec = NULL; } else if (rec->type == OPCODE_PUSH_LEVEL) { rec -> child = mgReadSequence(fp, prnt, vrsn); } else if (rec -> type == OPCODE_VERTEX_LIST) { // recode this as a sequence mgrec *last = rec; char *data = rec -> data; struct flt_VertexList *vl = (struct flt_VertexList *)data; rec -> data = (char *)malloc(sizeof (int)); *(int*)rec -> data = swap_int(vl->offset[0]); for (int i = 1; i < (rec->len - 4) / 4; i++) { last->next = (mgrec *)calloc (1, sizeof *rec); last = last->next; last -> type = rec -> type; last -> len = rec -> len; last -> parent = prnt; last -> vrsn = vrsn; last -> data = (char *)malloc(sizeof(int)); *(int*)last -> data = swap_int(vl->offset[i]); } free (data); } } return rec; } static mgrec *mgReadSequence (FILE *fp, mgrec *prnt, int vrsn) { mgrec *base = 0; mgrec *cur = base; mgrec *np; int pcount = 0; while (np = mgReadRecord (fp, base, vrsn)) { if (np -> type == OPCODE_PUSH_LEVEL) { pcount ++; if (cur == NULL) { cur = np -> child; if (base == NULL) base = cur; } else { cur-> child = np -> child; } np -> child = NULL; freenode (np); if (cur) { for (np = cur -> child; np; np = np -> next) { np -> parent = base; } } } else if (np -> type == OPCODE_POP_LEVEL) { freenode (np); pcount --; if (pcount <= 0) break; } else { if (base == 0) { cur = base = np; } else cur->next = np; np ->parent = prnt; while (cur -> next) { cur->parent = prnt; cur = cur->next; } } } return base; } mgrec *mgOpenDb (char *filename) { FILE *fp = fopen(filename, "rb"); if (fp == NULL) return NULL; mgrec *base = mgReadRecord (fp, 0, 0); if (base->type != OPCODE_HEADER) { return NULL; } struct flt_HeaderRecord *fh = (struct flt_HeaderRecord *)base->data; printf ("Version %d, db version %d\n", swap_int(fh->formatRev), swap_int(fh->DBRev)); base -> next = mgReadSequence (fp, 0, swap_int(fh->formatRev)); fclose (fp); if (base->type != OPCODE_HEADER) { return NULL; } return base; } void mgCloseDb (mgrec *db) { // freenode (db); } mgrec *mgGetMaterial (mgrec *db, int matind) { if (db -> vrsn > 1500) { OutputDebugString ("mgGetMaterial doesn't support 1500\n"); return MG_FALSE; } mgrec *pbase = db; while (pbase -> parent) { pbase = pbase -> parent; } while (pbase && pbase -> type != OPCODE_MATERIAL_TABLE) { pbase = pbase -> next; } if (pbase == NULL) return 0; if (pbase -> child) { for (mgrec *cp = pbase -> child; cp; cp = cp -> next) { if (cp -> xdata == matind) return cp; } } flt_MaterialRecord *fmr = (flt_MaterialRecord *)pbase->data; if (matind < 0 || matind > 64) return 0; mgrec *mr = (mgrec *) calloc (1, sizeof *mr); mr -> type = OPCODE_MATERIAL_TABLE; mr -> parent = pbase; mr -> xdata = matind; mr -> next = pbase -> child; pbase->child = mr; mr -> data = (char *)calloc (1, sizeof (flt_MaterialTable)); memcpy (mr -> data, &fmr -> mat[matind], sizeof (flt_MaterialTable)); return mr; } static int mgFind15Material (mgrec *db, int matind, short *r, short *g, short *b) { mgrec *pbase = db; while (pbase -> parent) { pbase = pbase -> parent; } while (pbase && pbase -> type != OPCODE_MATERIAL_PALETTE) { pbase = pbase -> next; } if (pbase == NULL) return 0; while (pbase->type == OPCODE_MATERIAL_PALETTE) { aflt_MaterialRecord *matrec = (aflt_MaterialRecord *)pbase->data; if (swap_int(matrec->materialIndex) == matind) { *r = (short)(255.0f * swap_float(matrec->diffuseRed)); *g = (short)(255.0f * swap_float(matrec->diffuseGreen)); *b = (short)(255.0f * swap_float(matrec->diffuseBlue)); return MG_TRUE; } pbase = pbase->next; } return MG_FALSE; } static int mgFind14Material (mgrec *db, int matind, short *r, short *g, short *b) { mgrec *pbase = mgGetMaterial(db, matind); if (pbase == NULL) return MG_FALSE; flt_MaterialTable *matrec = (flt_MaterialTable *)pbase->data; *r = (short)(255.0f * swap_float(matrec->diffuseRed)); *g = (short)(255.0f * swap_float(matrec->diffuseGreen)); *b = (short)(255.0f * swap_float(matrec->diffuseBlue)); return MG_TRUE; } int mgGetPolyColorRGB (mgrec *rec, short *r, short *g, short *b) { if (rec -> type != OPCODE_POLYGON) return MG_FALSE; int colindex; int colintens; if (strncmp (rec->data + 4, "f45", 3) == 0 || strncmp (rec->data + 4, "f42", 3) == 0) { *r =0; *g = 255; *b = 0; return MG_TRUE; } if (rec->vrsn > 1500) { struct aflt_PolygonRecord *pr; pr = (struct aflt_PolygonRecord *)rec->data; int mc = swap_short(pr->materialCode); if (mc != -1) { return mgFind15Material (rec, mc, r, g, b); } else { int pc = swap_short (pr->primaryColor); colindex = pc >> 7; colintens = pc & 0x7f; } } else { struct flt_PolygonRecord *pr; pr = (struct flt_PolygonRecord *)rec->data; int mc = swap_short(pr->materialCode); if (mc != -1) { return mgFind14Material (rec, mc, r, g, b); } unsigned short pc = swap_short (pr->primaryColor); colindex = pc >> 7; colintens = pc & 0x7f; } int rgb; if (mgGetColorInd (rec, colindex, &rgb) != MG_TRUE) return MG_FALSE; *r = (rgb & 0xff) * colintens / 127; *g = ((rgb>>8) & 0xff) * colintens / 127; *b = ((rgb>>16) & 0xff) * colintens / 127; return MG_TRUE; } static int mgGetFaceFromVertexNormal (mgrec *vert, double *i, double *j, double *k) { double i1, j1, k1; double nx = 0.0, ny = 0.0, nz = 0.0; int count = 0; while (vert) { if (mgGetVertexNormal(vert, &i1, &j1, &k1) != MG_TRUE) return MG_FALSE; nx += i1; ny += j1; nz += k1; count ++; vert = mgGetNext (vert); } nx /= count; ny /= count; nz /= count; Normalize (&nx, &ny, &nz); *i = nx; *j = ny; *k = nz; return MG_TRUE; } int mgGetPolyNormal(mgrec *rec, double *i, double *j, double *k) { mgrec *child = mgGetChild (rec); if (child == 0 || child -> type != OPCODE_VERTEX_LIST) { OutputDebugString ("No child with vertex\n"); return MG_FALSE; } if (mgGetFaceFromVertexNormal (child, i, j, k) == MG_TRUE) return MG_TRUE; // otherwise compute it ourself. OutputDebugString ("Got to calculate our own normal\n"); double x1, y1, z1; if (mgGetIcoord (child, fltIcoord, &x1, &y1, &z1) == MG_FALSE) { OutputDebugString ("No vertex 1\n"); return MG_FALSE; } double x2, y2, z2; child = child -> next; if (mgGetIcoord (child, fltIcoord, &x2, &y2, &z2) == MG_FALSE) { OutputDebugString ("No vertex 2\n"); return MG_FALSE; } double x3, y3, z3; child = child -> next; if (mgGetIcoord (child, fltIcoord, &x3, &y3, &z3) == MG_FALSE) { OutputDebugString ("No vertex 3\n"); return MG_FALSE; } // 2 - 1 = u x1 = x2 - x1; y1 = y2 - y1; z1 = z2 - z1; // 3 - 2 = v x2 = x3 - x2; y2 = y3 - y2; z2 = z3 - z2; // u cross v x3 = y1 * z2 + z1 * y2; y3 = z1 * x2 + x1 * z2; z3 = x1 * y2 + y1 * x2; Normalize (&x3, &y3, &z3); *i = x3; *j = y3; *k = z3; return MG_TRUE; } int mgGetMatrix (mgrec *rec, FltTypes type, mgmatrix *mat) { OutputDebugString("mgGetmatrix not implemented\n"); return MG_FALSE; } int mgGetNormColor (mgrec *rec, FltTypes type, float *r, float *g, float *b) { if (rec->vrsn > 1500) { OutputDebugString ("mgGetNormColor not supported in 1500\n"); return MG_FALSE; } if (rec -> type != OPCODE_MATERIAL_TABLE) return MG_FALSE; struct flt_MaterialTable *mt = (struct flt_MaterialTable *)rec -> data; switch (type) { case fltDiffuse: *r = swap_float(mt->diffuseRed); *g = swap_float(mt->diffuseGreen); *b = swap_float(mt->diffuseBlue); break; default: OutputDebugString ("Unknown type for GetNormColor\n"); return MG_FALSE; } return MG_TRUE; } int mgIndex2RGB (mgrec *rec, int colind, float intensity, short *r, short *g, short *b) { OutputDebugString("mgIndex2RGB not implemented\n"); return MG_FALSE; } void mgSetMessagesEnabled (int, int) { }
29,800
13,050
#ifndef __OBOTCHA_HTTP_HEADER_CONNECTION_HPP__ #define __OBOTCHA_HTTP_HEADER_CONNECTION_HPP__ #include "Object.hpp" #include "StrongPointer.hpp" #include "String.hpp" #include "ArrayList.hpp" namespace obotcha { DECLARE_CLASS(HttpHeaderConnection) { public: _HttpHeaderConnection(); _HttpHeaderConnection(String); void import(String); void set(String); String get(); String toString(); private: String type; }; } #endif
459
167
/* xf86drmMode.h uses the following license: * Copyright (c) 2007-2008 Tungsten Graphics, Inc., Cedar Park, Texas. * Copyright (c) 2007-2008 Dave Airlie <airlied@linux.ie> * Copyright (c) 2007-2008 Jakob Bornecrantz <wallbraker@gmail.com> * * 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 "stack.hpp" #include "convert/char.hpp" #include <drm/drm_mode.h> #include <xf86drmMode.h> LUA_METATABLE_NAMED(drm_clip_rect); LUA_METATABLE_NAMED(_drmModeConnector); LUA_METATABLE_NAMED(drmModeConnection); LUA_METATABLE_NAMED(_drmModeEncoder); LUA_METATABLE_NAMED(_drmModeObjectProperties); LUA_METATABLE_NAMED(_drmModePlane); LUA_METATABLE_NAMED(_drmModeProperty); LUA_METATABLE_NAMED(_drmModePropertyBlob); LUA_METATABLE_NAMED(_drmModePlaneRes); LUA_METATABLE_NAMED(drmModeSubPixel); LUA_METATABLE_NAMED(_drmModeModeInfo); LUA_METATABLE_NAMED(_drmModeRes); LUA_METATABLE_NAMED(_drmModeFB); LUA_METATABLE_NAMED(_drmModeCrtc); extern "C" int luaopen_xf86drmMode(lua_State* const state);
2,026
795
#include "Mesh.h" Mesh::Mesh() { } Mesh::~Mesh() { Vertexs.clear(); Normals.clear(); Uvs.clear(); Objects.clear(); } void Mesh::setName(std::string name){ Name = name; } std::string* Mesh::getName(){ return &Name; } void Mesh::AddVertex(float x, float y, float z) { glm::vec3 vertex(x, y, z); Vertexs.push_back(vertex); } void Mesh::AddNormal(float x, float y, float z) { glm::vec3 normal(x, y, z); Normals.push_back(normal); } void Mesh::AddUv(float u, float v) { glm::vec2 uv(u, v); Uvs.push_back(uv); } void Mesh::AddMaterialGroup(MaterialGroup newMG) { Objects.push_back(newMG); } MaterialGroup* Mesh::getLastMaterialGroup() { return &Objects.back(); } unsigned long Mesh::getVertexsSize() { return Vertexs.size(); } unsigned long Mesh::getNormalsize() { return Normals.size(); } unsigned long Mesh::getUvsSize() { return Uvs.size(); } void Mesh::Print() { printf("Object Name: %s\n -Number of Vertex: %d\n -Number of Normals: %d\n -Number of Uvs: %d\n-Number of Materials Groups: %d\n", Name.c_str(), Vertexs.size(), Normals.size(), Uvs.size(), Objects.size()); for (int i = 0; i < Objects.size(); i++) Objects[i].Print(); } void Mesh::GenBuffers() { int size = Objects.size(); sizeFaces = 0; for (int i = 0; i < size; i++) { int numTriangle = Objects[i].getTriangles()->size() / 3; Objects[i].setOffsetandCount(sizeFaces, numTriangle); sizeFaces += numTriangle; } float* BufferData = new float [sizeFaces * (3+3+2)]; int cont = 0; for (int i = 0; i < size; i++) { std::vector<unsigned int>* faces = Objects[i].getTriangles(); int sizeFace = faces->size(); for (int j = 0; j < sizeFace; j += 3, cont += 8) { BufferData[cont] = Vertexs[(*faces)[j]].x; BufferData[cont + 1] = Vertexs[(*faces)[j]].y; BufferData[cont + 2] = Vertexs[(*faces)[j]].z; BufferData[cont + 3] = Normals[(*faces)[j + 1]].x; BufferData[cont + 4] = Normals[(*faces)[j + 1]].y; BufferData[cont + 5] = Normals[(*faces)[j + 1]].z; BufferData[cont + 6] = Uvs[(*faces)[j + 2]].x; BufferData[cont + 7] = Uvs[(*faces)[j + 2]].y; } } glGenVertexArrays(1, &VertexArrayID); glBindVertexArray(VertexArrayID); GLuint vbo; glGenBuffers(1, &vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, (sizeFaces * 8) * sizeof(float), BufferData, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)0); glEnableVertexAttribArray(1); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)(sizeof(float) * 3)); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 8, (void*)(sizeof(float) * 6)); delete BufferData; glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); } void Mesh::render(GLuint MaterialAmbientID, GLuint MaterialDiffuseID, GLuint MaterialSpecularID, GLuint ShinninesID) { glBindVertexArray(VertexArrayID); unsigned int size = Objects.size(); for (int i = 0; i < size; i++) Objects[i].render(MaterialAmbientID, MaterialDiffuseID, MaterialSpecularID, ShinninesID); }
3,256
1,398
#pragma once namespace cgp { /** Base class for small fixed-size vectors (vec3, mat3, etc.). * buffer_stack structure is a generic fixed-size vector, essentially equivalent to a std::array. * In addition to std::array syntax, buffer_stack provides extra convenient functions (similar to buffer) for numerical vectors +, -, *, / as well as strict bounds checking. */ // template <typename T, int N> struct buffer_stack; } #include "implementation/buffer_stack.hpp" #include "implementation/buffer_stack2.hpp" #include "implementation/buffer_stack3.hpp" #include "implementation/buffer_stack4.hpp" #include "special_types/special_types.hpp"
667
186
/** * @author : Maruf Tuhin * @School : CUET CSE 11 * @Topcoder : the_redback * @CodeForces : the_redback * @UVA : the_redback * @link : http://www.fb.com/maruf.2hin */ #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long llu; #define ft first #define sd second #define mp make_pair #define pb(x) push_back(x) #define all(x) x.begin(),x.end() #define allr(x) x.rbegin(),x.rend() #define mem(a,b) memset(a,b,sizeof(a)) #define meminf(a) memset(a,126,sizeof(a)) #define inf 1e7 #define eps 1e-9 #define mod 1000000007 #define NN 10100 #define z 4000 //cout << setfill('0') << setw(3) << a << endl; //cout << fixed << setprecision(20) << a << endl; struct D { int pos,cnt; }a[60]; bool flag[NN]; bool comp(D aa,D bb) { return aa.pos<bb.pos; } struct CatsOnTheLineDiv2 { string getAnswer(vector <int> position, vector <int> count, int time) { string ret; int n=count.size(); int i,j,k,l; for(i=0;i<count.size();i++) { a[i].pos=position[i]; a[i].cnt=count[i]; } sort(a,a+n,comp); mem(flag,0); int low=-inf; int high=inf; for(i=0;i<n;i++) { low=a[i].pos-time+z; high=a[i].pos+time+z; int cnt=0; while(low<=high && cnt<a[i].cnt) { if(flag[low]==0) { cnt++; flag[low]=1; } low++; } if(cnt<a[i].cnt) return "Impossible"; } return "Possible"; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const string &Expected, const string &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {7}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 3; string Arg3 = "Possible"; verify_case(0, Arg3, getAnswer(Arg0, Arg1, Arg2)); } void test_case_1() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {8}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; string Arg3 = "Impossible"; verify_case(1, Arg3, getAnswer(Arg0, Arg1, Arg2)); } void test_case_2() { int Arr0[] = {0, 1}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3, 1}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 0; string Arg3 = "Impossible"; verify_case(2, Arg3, getAnswer(Arg0, Arg1, Arg2)); } void test_case_3() { int Arr0[] = {5, 0, 2}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {2, 3, 5}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 2; string Arg3 = "Impossible"; verify_case(3, Arg3, getAnswer(Arg0, Arg1, Arg2)); } void test_case_4() { int Arr0[] = {5, 1, -10, 7, 12, 2, 10, 20}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {3, 4, 2, 7, 1, 4, 3, 4}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arg2 = 6; string Arg3 = "Possible"; verify_case(4, Arg3, getAnswer(Arg0, Arg1, Arg2)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CatsOnTheLineDiv2 ___test; ___test.run_test(-1); int gbase; cin>>gbase; // erase this line if you are not using dev-cpp! :) return 0; } // END CUT HERE
4,342
1,742
// // Created by lab on 16-12-27. // #include "reconstruct.h" namespace tracker{ void Triangulate::Reconstruct3d(vector<Point2f> &matched_L, vector<Point2f> &matched_R, vector<Point3f> &coord_3d) { size_t num_points=matched_L.size(); //double pixel_size=4.65e-3; //Z=b*f/d float d,Z,Y,X; //cout<<"debug info.."<<endl; for(size_t i=0;i<num_points;i++) { //* Transform them into the same world coordinate. d=matched_L[i].x-matched_R[i].x; Z=baseline*f/(d*pixel_size); Y=pixel_size*Z*(matched_L[i].y-this->camera_matrix.at<float>(1,2))/f; X=pixel_size*Z*(matched_L[i].x-this->camera_matrix.at<float>(0,2))/f; //cout<<"X["<<i<<"]:"<<X<<endl; //* Cartesian coordinate system.(0,0,0) is right at perspective point coord_3d.push_back(Point3d(X,-Y,-Z)); } } }
924
370
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2017-2019 The WaykiChain Developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "assetdb.h" #include "commons/uint256.h" #include "commons/util/util.h" #include <stdint.h> using namespace std; bool CAssetDBCache::GetAsset(const TokenSymbol &tokenSymbol, CAsset &asset) { return assetCache.GetData(tokenSymbol, asset); } bool CAssetDBCache::HaveAsset(const TokenSymbol &tokenSymbol) { return assetCache.HaveData(tokenSymbol); } bool CAssetDBCache::SaveAsset(const CAsset &asset) { return assetCache.SetData(asset.symbol, asset); } bool CAssetDBCache::ExistAssetSymbol(const TokenSymbol &tokenSymbol) { return assetCache.HaveData(tokenSymbol); } shared_ptr<string> CAssetDBCache::CheckTransferCoinSymbol(const TokenSymbol &symbol) { size_t coinSymbolSize = symbol.size(); if (coinSymbolSize == 0 || coinSymbolSize > MAX_TOKEN_SYMBOL_LEN) { return make_shared<string>("empty or too long"); } if ((coinSymbolSize < MIN_ASSET_SYMBOL_LEN && !kCoinTypeSet.count(symbol)) || (coinSymbolSize >= MIN_ASSET_SYMBOL_LEN && !HaveAsset(symbol))) return make_shared<string>("unsupported symbol"); return nullptr; } bool CAssetDBCache::AddAssetTradingPair(const CAssetTradingPair &assetTradingPair) { return assetTradingPairCache.SetData(assetTradingPair, 1); } bool CAssetDBCache::EraseAssetTradingPair(const CAssetTradingPair &assetTradingPair) { return assetTradingPairCache.EraseData(assetTradingPair); } bool CAssetDBCache::ExistAssetTradingPair(const CAssetTradingPair &assetTradingPair) { return assetTradingPairCache.HaveData(assetTradingPair); } bool CAssetDBCache::Flush() { assetCache.Flush(); assetTradingPairCache.Flush(); return true; }
1,898
640
#include <common.hpp> #include "json_parser.hpp" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <boost/lexical_cast.hpp> using namespace circle; template <typename T> inline T clone(const T &v) { return v; } template <typename T> struct object_type { typedef T type; }; template <> struct object_type<int> { typedef circle::int64_t type; }; template <> struct object_type<unsigned> { typedef circle::int64_t type; }; template <> struct object_type<char *> { typedef string type; }; template <> struct object_type<const char *> { typedef string type; }; template <size_t N> struct object_type<char [N]> { typedef string type; }; template <size_t N> struct object_type<const char [N]> { typedef string type; }; struct insert_object_t { insert_object_t(json::json_object_map &obj, string &jstr): obj(obj), jstr(jstr), n() { } template <typename T> void operator()(const T &val, const string &vstr) { const string key = "val" + boost::lexical_cast<string>(++n); obj[key] = static_cast<typename object_type<T>::type>(val); jstr.insert(jstr.length()-1, ",\""+key+"\":"+vstr); } json::json_object_map &obj; string &jstr; unsigned n; }; BOOST_AUTO_TEST_CASE(json_parse_test) { BOOST_CHECK(json::parse_json("[]") == json::json_object_value(json::json_array_type())); json::json_object_value obj((json::json_object_map())); json::json_object_map &om = boost::get<json::json_object_map>(obj); BOOST_CHECK(json::parse_json("{}") == obj); string jstr = "{\"null\":null}"; insert_object_t ins(om, jstr); om["null"] = json::null_t(); BOOST_CHECK(json::parse_json(jstr) == obj); ins(10, "10"); BOOST_CHECK(json::parse_json(jstr) == obj); ins(10., "10."); BOOST_CHECK(json::parse_json(jstr) == obj); ins("str", "\"str\""); BOOST_CHECK(json::parse_json(jstr) == obj); ins("", "\"\""); BOOST_CHECK(json::parse_json(jstr) == obj); ins(true, "true"); BOOST_CHECK(json::parse_json(jstr) == obj); ins(false, "false"); BOOST_CHECK(json::parse_json(jstr) == obj); ins(0, "0"); BOOST_CHECK(json::parse_json(jstr) == obj); ins(clone(obj), clone(jstr)); BOOST_CHECK(json::parse_json(jstr) == obj); ins(-5, "-5"); ins(-3., "-3."); ins("3.3", "\"3.3\""); ins("null", "\"null\""); BOOST_CHECK(json::parse_json(jstr) == obj); ins(clone(obj), clone(jstr)); BOOST_CHECK(json::parse_json(jstr) == obj); }
2,411
945
struct foo { int a; int b; int c; int d; int e; int f; int g; int h; int i; int j; int k; int l; int m; int n; int o; int p; int q; int r; foo(int X) : a(X), b(X+1), c(X+3), d(X+5), e(X+7), f(X+9), g(X+11), h(X+13), i(X+15), j(X+17), k(X+19), l(X+21), m(X+23), n(X+25), o(X+27), p(X+29), q(X+31), r(X+33) {} }; struct wrapint { int x; wrapint(int X) : x(X) {} }; int main() { foo f00_1(0); foo *f00_ptr = new foo(12); f00_1.a++; // Set break point at this line. wrapint test_cast('A' + 256*'B' + 256*256*'C'+ 256*256*256*'D'); return 0; }
781
407
/******************************************************************************* * Copyright (c) 2018, 2018 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at http://eclipse.org/legal/epl-2.0 * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception [1] and GNU General Public * License, version 2 with the OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #ifndef CPP_BINDING_RUNTIME_INCL #define CPP_BINDING_RUNTIME_INCL #define TOSTR(x) #x #define LINETOSTR(x) TOSTR(x) #define ARG_SETUP(baretype, ptrImpl, byVarArg, parmArg) \ TR::baretype *ptrImpl = NULL; \ TR::baretype **byVarArg = NULL; \ if (parmArg) \ { \ byVarArg = &ptrImpl; \ if (*parmArg) \ ptrImpl = reinterpret_cast<TR::baretype *>((*parmArg)->_impl); \ } #define ARG_RETURN(baretype, ptrImpl, parmArg) \ if (parmArg) \ { \ GET_CLIENT_OBJECT(clientObj, baretype, ptrImpl); \ *parmArg = clientObj; \ } #define ARRAY_ARG_SETUP(baretype, arraySize, arrayImpl, parmArg) \ TR::baretype **arrayImpl = new TR::baretype *[arraySize]; \ for (uint32_t i=0;i < arraySize;i++) \ { \ if (parmArg[i] != NULL) \ arrayImpl[i] = reinterpret_cast<TR::baretype *>((parmArg[i])->_impl); \ else \ arrayImpl[i] = NULL; \ } #define ARRAY_ARG_RETURN(baretype, arraySize, arrayImpl, parmArg) \ for (uint32_t i=0;i < arraySize;i++) \ { \ if (arrayImpl[i] != NULL) \ { \ GET_CLIENT_OBJECT(clientObj, baretype, arrayImpl[i]) \ parmArg[i] = clientObj; \ } \ else \ parmArg[i] = NULL; \ } // This macro defines clientObj in the scope where macro is used #define GET_CLIENT_OBJECT(clientObj, baretype, implObj) \ baretype *clientObj = NULL; \ if (implObj != NULL) \ { \ clientObj = reinterpret_cast<baretype *>(implObj->client()); \ } #endif // defined(CPP_BINDING_RUNTIME_INCL)
4,024
1,043