hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
64816aed810016f0fc3c0a944e40d5a6f95082a4
2,502
cpp
C++
thrift/lib/cpp/transport/THDFSFileTransport.cpp
CacheboxInc/fbthrift
b894dd9192ea4684c0067c93bb2ba2b9547749ec
[ "Apache-2.0" ]
null
null
null
thrift/lib/cpp/transport/THDFSFileTransport.cpp
CacheboxInc/fbthrift
b894dd9192ea4684c0067c93bb2ba2b9547749ec
[ "Apache-2.0" ]
null
null
null
thrift/lib/cpp/transport/THDFSFileTransport.cpp
CacheboxInc/fbthrift
b894dd9192ea4684c0067c93bb2ba2b9547749ec
[ "Apache-2.0" ]
null
null
null
/* * 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. */ #include <thrift/lib/cpp/transport/THDFSFileTransport.h> #include <hdfs.h> using namespace std; using std::shared_ptr; namespace apache { namespace thrift { namespace transport { void THDFSFileTransport::open() { // THDFSFileTransport does not handle resource alloc/release. // An open HDFSFile handle must exist by now if (!isOpen()) { throw TTransportException(TTransportException::NOT_OPEN, "THDFSFileTransport::open()"); } } void THDFSFileTransport::close() { // THDFSFileTransport does not handle resource alloc/release return; } uint32_t THDFSFileTransport::read(uint8_t* buf, uint32_t len) { tSize rv = hdfsRead(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len); if (rv < 0) { int errno_copy = errno; throw TTransportException(TTransportException::UNKNOWN, "THDFSFileTransport::read()", errno_copy); } else if (rv == 0) { throw TTransportException(TTransportException::END_OF_FILE, "THDFSFileTransport::read()"); } return rv; } void THDFSFileTransport::write(const uint8_t* buf, uint32_t len) { tSize rv = hdfsWrite(hdfsFile_->getFS()->getHandle(), (hdfsFile)hdfsFile_->getHandle(), buf, len); if (rv < 0) { int errno_copy = errno; throw TTransportException(TTransportException::UNKNOWN, "THDFSFileTransport::write()", errno_copy); } else if (rv != len) { throw TTransportException(TTransportException::INTERRUPTED, "THDFSFileTransport::write()"); } } }}} // apache::thrift::transport
36.26087
100
0.672662
CacheboxInc
6482b6702810493c8f2e97a4f76bb0627b5d6b58
4,399
cpp
C++
src/SWCharEst.cpp
tehilinski/SWCharEst
8e07be7888c3aab0d565906d3c49d4fdc078aab8
[ "Apache-2.0" ]
null
null
null
src/SWCharEst.cpp
tehilinski/SWCharEst
8e07be7888c3aab0d565906d3c49d4fdc078aab8
[ "Apache-2.0" ]
null
null
null
src/SWCharEst.cpp
tehilinski/SWCharEst
8e07be7888c3aab0d565906d3c49d4fdc078aab8
[ "Apache-2.0" ]
null
null
null
//----------------------------------------------------------------------------- // file SWCharEst.h // class teh::SWCharEst // brief Estimate values for wilting point, field capacity, // saturated water content, and saturated hydraulic conductivity // from soil texture and organic matter. // Output units are, respectively, // volume fraction, volume fraction, volume fraction, cm/sec. // Uses the equations from Saxton & Rawls, 2006. // Spreadsheet available at: // http://hydrolab.arsusda.gov/soilwater/Index.htm // author Thomas E. Hilinski <https://github.com/tehilinski> // copyright Copyright 2020 Thomas E. Hilinski. All rights reserved. // This software library, including source code and documentation, // is licensed under the Apache License version 2.0. // See the file "LICENSE.md" for more information. //----------------------------------------------------------------------------- #include "SWCharEst.h" #include <cmath> #include <iostream> using std::cout; using std::endl; #undef DEBUG_SWCharEst //#define DEBUG_SWCharEst namespace teh { void SWCharEst::Usage () { char const NL = '\n'; cout << "\nUsage:" << NL << " teh::SWCharEst::Usage();" << NL << " teh::SWCharEst swc();" << NL << " std::vector<float> results = swc.Get( sand-fraction, clay-fraction, SOM-percent );" << NL << "Arguments:" << NL << " sand-fraction = sand weight fraction (0-1)" << NL << " clay-fraction = clay weight fraction (0-1)" << NL << " SOM-percent = soil organic matter (weight %)" << NL << "Results:" << NL << " WP = wilting point (volume %)" << NL << " FC = field capacity (volume %)" << NL << " thetaS = saturated water content (volume %)" << NL << " Ks = Saturated hydraulic conductivity (cm/sec)" << endl; } bool SWCharEst::CheckArgs ( float const sand, // sand fraction (0-1) float const clay, // clay fraction (0-1) float const ompc) // organic matter wt % { bool ok = true; if ( sand < 0.0f || sand > 1.0f ) ok = false; if ( clay < 0.0f || clay > 1.0f ) ok = false; if ( ompc < 0.0f || ompc > 70.0f ) ok = false; if ( sand + clay > 1.0f ) ok = false; return ok; } std::vector<float> & SWCharEst::Get ( // returns WP, FC, thetaS, Ks float const sand, // sand fraction (0-1) float const clay, // clay fraction (0-1) float const ompc) // organic matter wt % { results.resize(4); results.assign( 4, 0.0f ); float const om = std::min ( 70.0f, ompc ); // upper limit OM% if ( !CheckArgs(sand, clay, om) ) return results; float const theta1500t = -0.024f * sand + 0.487f * clay + 0.006f * om + 0.005f * sand * om - 0.013f * clay * om + 0.068f * sand * clay + 0.031f; float theta1500 = std::max( 0.01f, // constrain theta1500t + 0.14f * theta1500t - 0.02f ); float const theta33t = -0.251f * sand + 0.195f * clay + 0.011f * om + 0.006f * sand * om - 0.027f * clay * om + 0.452f * sand * clay + 0.299f; float const theta33 = std::min( 0.80f, // constrain theta33t + 1.283f * theta33t * theta33t - 0.374f * theta33t - 0.015f); theta1500 = std::min( theta1500, 0.80f * theta33 ); // constrain float const thetaS33t = 0.278f * sand + 0.034f * clay + 0.022f * om - 0.018f * sand * om - 0.027f * clay * om - 0.584f * sand * clay + 0.078f; float const thetaS33 = thetaS33t + 0.636f * thetaS33t - 0.107f; float const thetaS = theta33 + thetaS33 - 0.097f * sand + 0.043f; float const B = 3.816713f / ( std::log(theta33) - std::log(theta1500) ); float const lamda = 1.0f / B; float const Ks = 1930.0f * std::pow( ( thetaS - theta33 ), (3.0f - lamda) ) / 36000.0; #ifdef DEBUG_SWCharEst char const NL = '\n'; cout << "sand, clay, om = " << sand << " " << clay << " " << om << NL << "theta1500t = " << theta1500t << NL << "theta1500 = " << theta1500 << NL << "theta33t = " << theta33t << NL << "theta33 = " << theta33 << NL << "thetaS33t = " << thetaS33t << NL << "thetaS33 = " << thetaS33 << NL << "thetaS = " << thetaS << NL << "B = " << B << NL << "lamda = " << lamda << NL << "Ks = " << Ks << NL << endl; #endif results[0] = theta1500; // WP results[1] = theta33; // FC results[2] = thetaS; // thetaS results[3] = Ks; // Ks return results; } } // namespace teh
30.130137
97
0.562401
tehilinski
6482bbd062534e9bd835e7aefc027b80aab902a8
8,087
hpp
C++
rclpy/src/rclpy/action_server.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
121
2015-11-19T19:46:09.000Z
2022-03-17T16:36:52.000Z
rclpy/src/rclpy/action_server.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
759
2016-01-29T01:44:19.000Z
2022-03-30T13:37:26.000Z
rclpy/src/rclpy/action_server.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
160
2016-01-12T16:56:21.000Z
2022-03-22T23:20:35.000Z
// Copyright 2021 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLPY__ACTION_SERVER_HPP_ #define RCLPY__ACTION_SERVER_HPP_ #include <pybind11/pybind11.h> #include <rcl_action/rcl_action.h> #include <memory> #include "clock.hpp" #include "destroyable.hpp" #include "node.hpp" #include "wait_set.hpp" namespace py = pybind11; namespace rclpy { /* * This class will create an action server for the given action name. * This client will use the typesupport defined in the action module * provided as pyaction_type to send messages. */ class ActionServer : public Destroyable, public std::enable_shared_from_this<ActionServer> { public: /// Create an action server. /** * Raises AttributeError if action type is invalid * Raises ValueError if action name is invalid * Raises RuntimeError if the action server could not be created. * * \param[in] node Node to add the action server to. * \param[in] rclpy_clock Clock use to create the action server. * \param[in] pyaction_type Action module associated with the action server. * \param[in] pyaction_name Python object containing the action name. * \param[in] goal_service_qos rmw_qos_profile_t object for the goal service. * \param[in] result_service_qos rmw_qos_profile_t object for the result service. * \param[in] cancel_service_qos rmw_qos_profile_t object for the cancel service. * \param[in] feedback_qos rmw_qos_profile_t object for the feedback subscriber. * \param[in] status_qos rmw_qos_profile_t object for the status subscriber. */ ActionServer( Node & node, const rclpy::Clock & rclpy_clock, py::object pyaction_type, const char * action_name, const rmw_qos_profile_t & goal_service_qos, const rmw_qos_profile_t & result_service_qos, const rmw_qos_profile_t & cancel_service_qos, const rmw_qos_profile_t & feedback_topic_qos, const rmw_qos_profile_t & status_topic_qos, double result_timeout); /// Take an action goal request. /** * Raises RCLError if an error occurs in rcl * Raises RuntimeError on failure. * * \param[in] pymsg_type An instance of the type of request message to take. * \return 2-tuple (header, received request message) where the header is an * "rclpy.rmw_request_id_t" type, or * \return 2-tuple (None, None) if there as no message to take */ py::tuple take_goal_request(py::object pymsg_type); /// Send an action goal response. /** * Raises RCLError if an error occurs in rcl * Raises RuntimeError on failure. * * \param[in] header Pointer to the message header. * \param[in] pyresponse The response message to send. */ void send_goal_response( rmw_request_id_t * header, py::object pyresponse); /// Send an action result response. /** * Raises RCLError if an error occurs in rcl * Raises RuntimeError on failure. * * \param[in] pyheader Pointer to the message header. * \param[in] pyresponse The response message to send. */ void send_result_response( rmw_request_id_t * header, py::object pyresponse); /// Take an action cancel request. /** * Raises RCLError if an error occurs in rcl * Raises RuntimeError on failure. * * \param[in] pymsg_type An instance of the type of request message to take. * \return 2-tuple (header, received request message) where the header is an * "rmw_request_id_t" type, or * \return 2-tuple (None, None) if there as no message to take */ py::tuple take_cancel_request(py::object pymsg_type); /// Take an action result request. /** * Raises RCLError if an error occurs in rcl * Raises RuntimeError on failure. * * \param[in] pymsg_type An instance of the type of request message to take. * \return 2-tuple (header, received request message) where the header is an * "rclpy.rmw_request_id_t" type, or * \return 2-tuple (None, None) if there as no message to take */ py::tuple take_result_request(py::object pymsg_type); /// Send an action cancel response. /** * Raises RCLError if an error occurs in rcl * Raises RuntimeError on failure. * * \param[in] pyheader Pointer to the message header. * \param[in] pyresponse The response message to send. */ void send_cancel_response( rmw_request_id_t * header, py::object pyresponse); /// Publish a feedback message from a given action server. /** * Raises RCLError if an error occurs in rcl * Raises RuntimeError on failure while publishing a feedback message. * * \param[in] pymsg The feedback message to publish. */ void publish_feedback(py::object pymsg); /// Publish a status message from a given action server. /** * Raises RCLError if an error occurs in rcl * Raises RuntimeError on failure while publishing a status message. */ void publish_status(); /// Notifies action server that a goal handle reached a terminal state. /** * Raises RCLError if an error occurs in rcl */ void notify_goal_done(); /// Check if a goal is already being tracked by an action server. /* * Raises AttributeError if there is an issue parsing the pygoal_info. * * \param[in] pygoal_info the identifiers of goals that expired, or set to `NULL` if unused * \return True if the goal exists, false otherwise. */ bool goal_exists(py::object pygoal_info); /// Process a cancel request using an action server. /** * This is a non-blocking call. * * Raises RuntimeError on failure while publishing a status message. * Raises RCLError if an error occurs in rcl * * \return the cancel response message */ py::object process_cancel_request( py::object pycancel_request, py::object pycancel_response_type); /// Expires goals associated with an action server. py::tuple expire_goals(int64_t max_num_goals); /// Get the number of wait set entities that make up an action entity. /** * Raises RCLError if an error occurs in rcl * * \return Tuple containing the number of wait set entities: * (num_subscriptions, * num_guard_conditions, * num_timers, * num_clients, * num_services) */ py::tuple get_num_entities(); /// Check if an action entity has any ready wait set entities. /** * This must be called after waiting on the wait set. * Raises RuntimeError on failure. * Raises RCLError if an error occurs in rcl * * \param[in] pywait_set Capsule pointing to the wait set structure. * \return A tuple of booleans representing ready sub-entities. * (is_goal_request_ready, * is_cancel_request_ready, * is_result_request_ready, * is_goal_expired) */ py::tuple is_ready(WaitSet & wait_set); /// Add an action entitiy to a wait set. /** * Raises RuntimeError on failure. * Raises RCLError if an error occurs in rcl * * \param[in] pywait_set Capsule pointer to an rcl_wait_set_t. */ void add_to_waitset(WaitSet & wait_set); /// Get rcl_action_server_t pointer rcl_action_server_t * rcl_ptr() const { return rcl_action_server_.get(); } /// Force an early destruction of this object void destroy() override; private: Node node_; std::shared_ptr<rcl_action_server_t> rcl_action_server_; }; /// Define a pybind11 wrapper for an rcl_time_point_t /** * \param[in] module a pybind11 module to add the definition to */ void define_action_server(py::object module); } // namespace rclpy #endif // RCLPY__ACTION_SERVER_HPP_
31.223938
93
0.709039
RoboStack
648666cb9cf47a42b2ddc9a75f436817a4a5fa04
1,175
cpp
C++
depends/libyarn/src/libyarncommon/Token.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
450
2015-09-05T09:12:51.000Z
2018-08-30T01:45:36.000Z
depends/libyarn/src/libyarncommon/Token.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
1,274
2015-09-22T20:06:16.000Z
2018-08-31T22:14:00.000Z
depends/libyarn/src/libyarncommon/Token.cpp
YangHao666666/hawq
10cff8350f1ba806c6fec64eb67e0e6f6f24786c
[ "Artistic-1.0-Perl", "ISC", "bzip2-1.0.5", "TCL", "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "MIT", "PostgreSQL", "BSD-3-Clause" ]
278
2015-09-21T19:15:06.000Z
2018-08-31T00:36:51.000Z
/* * 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. */ #include "Hash.h" #include "Token.h" using namespace Yarn::Internal; namespace Yarn { size_t Token::hash_value() const { size_t values[] = { StringHasher(identifier), StringHasher(password), StringHasher(kind), StringHasher(service) }; return CombineHasher(values, sizeof(values) / sizeof(values[0])); } }
33.571429
73
0.711489
YangHao666666
6486844a95ba171da71fd56b96a655b1f7b55665
8,566
cpp
C++
common/WhirlyGlobeLib/src/GeographicLib.cpp
akovalov/WhirlyGlobe
09f3e7447ce8c049dedfb92550ff649ad1895bb7
[ "Apache-2.0" ]
null
null
null
common/WhirlyGlobeLib/src/GeographicLib.cpp
akovalov/WhirlyGlobe
09f3e7447ce8c049dedfb92550ff649ad1895bb7
[ "Apache-2.0" ]
null
null
null
common/WhirlyGlobeLib/src/GeographicLib.cpp
akovalov/WhirlyGlobe
09f3e7447ce8c049dedfb92550ff649ad1895bb7
[ "Apache-2.0" ]
null
null
null
// // GeographicLib.cpp // WhirlyGlobeMaplyComponent // // Created by Tim Sylvester on 1/14/22. // Copyright © 2022 mousebird consulting. All rights reserved. // #import "GeographicLib/Geodesic.hpp" #import "GeographicLib/Geocentric.hpp" #import "../include/GeographicLib.h" #import "WhirlyVector.h" #import <cmath> #if !defined(M_2PI) # define M_2PI (2 * M_PI) #endif namespace WhirlyKit { namespace detail { // These have to be functions for now; if they're global variables, // they don't get initialized early enough for the static unit tests. const GeographicLib::Geodesic &wgs84Geodesic() { return GeographicLib::Geodesic::WGS84(); } const GeographicLib::Geocentric &wgs84Geocentric() { return GeographicLib::Geocentric::WGS84(); } } using namespace detail; namespace Geocentric { template <int N> inline static void combine(double* eqA, double* eqB) { if (eqB[0] == 0.0) { return; } if (std::fabs(eqA[0]) >= std::fabs(eqB[0])) { auto const f = eqB[0] / eqA[0]; eqB[0] = 0; for (auto i = 1; i < N; ++i) { eqB[i] -= f * eqA[i]; } } else { auto const f = eqA[0] / eqB[0]; eqA[0] = eqB[0]; eqB[0] = 0; for (auto i = 1; i < N; ++i) { std::swap(eqA[i], eqB[i]); eqB[i] -= f * eqA[i]; } } } // for n = 3, partially solve, zeroing the coefficients below the diagonal. inline static void solveLinear3A(double* eq0, double* eq1, double* eq2) { combine<4>(eq1, eq2); combine<4>(eq0, eq1); combine<3>(eq1 + 1, eq2 + 1); if (eq2[3] != 0.0) { eq2[3] = (eq2[2] == 0 ? INFINITY : eq2[3] / eq2[2]); } eq2[2] = 1; } // Complete the solution started by solveLinear3Lower inline static void solveLinear3B(double* eq0, double* eq1, double* eq2) { eq1[3] -= eq1[2] * eq2[3]; eq1[2] = 0; if (eq1[3] != 0.0) { eq1[3] = (eq1[1] == 0.0 ? INFINITY : eq1[3] / eq1[1]); } eq1[1] = 1; eq0[3] -= eq0[2] * eq2[3] + eq0[1] * eq1[3]; eq0[1] = 0; eq0[2] = 0; if (eq0[3] != 0) { eq0[3] = (eq0[0] == 0.0 ? INFINITY : eq0[3] / eq0[0]); } eq0[0] = 1; } // Project a vector onto the ellipsoid surface static Point3d project(const Point3d &p, const GeographicLib::Geodesic &geo) { const auto re = geo.EquatorialRadius(); const auto rp = re - re * geo.Flattening(); const auto x = p.x(); const auto y = p.y(); const auto z = p.z(); const auto r = std::sqrt((x * x + y * y) / (re * re) + z * z / (rp * rp)); return (r == 0) ? Point3d{ rp, y, z } : // it's a pole Point3d{ x / r, y / r, z / r }; // anything else } const static Point3d ptZero = { 0.0, 0.0, 0.0 }; // Find the intersection of geodesics A-B and C-D. // Returns the intersection point iff CalcInt==true template <bool CalcInt> static inline std::tuple<bool,Point3d> intersection( const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d, const GeographicLib::Geodesic &geo) { // Set equal the equations defining the two geodesics, as defined by the // intersection of the ellipsoid and a plane through its center, and solve // the resulting system of equations, yielding two antipodal solutions. // // ((x4 - x3) * s + x3) * t = (x2 - x1) * r + x1 // ((y4 - y3) * s + y3) * t = (y2 - y1) * r + y1 // ((z4 - z3) * s + z3) * t = (z2 - z1) * r + z1 double e0[4] = { d.x() - c.x(), c.x(), a.x() - b.x(), a.x() }; double e1[4] = { d.y() - c.y(), c.y(), a.y() - b.y(), a.y() }; double e2[4] = { d.z() - c.z(), c.z(), a.z() - b.z(), a.z() }; solveLinear3A(e0, e1, e2); const auto r = e2[3]; if (r >= 0.0 && r <= 1.0) { solveLinear3B(e0, e1, e2); // Solution on the right side, and within the segments? const auto t = e1[3]; if (t > 0.0) { const auto s = e0[3] / t; if (s >= 0.0 && s <= 1.0) { // Yes! Project the solution vector onto the ellipsoid return std::make_tuple(true, CalcInt ? project((b - a) * r + a, geo) : ptZero); } } } return std::make_tuple(false, ptZero); } // Concrete instances for export bool checkIntersection(const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d) { return checkIntersection(a, b, c, d, wgs84Geodesic()); } bool checkIntersection(const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d, const GeographicLib::Geodesic &geo) { return std::get<0>(intersection<false>(a, b, c, d, geo)); } std::tuple<bool,Point3d> findIntersection(const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d, const GeographicLib::Geodesic &geo) { return intersection<true>(a, b, c, d, geo); } std::tuple<bool,Point3d> findIntersection(const Point3d &a, const Point3d &b, const Point3d &c, const Point3d &d) { return findIntersection(a, b, c, d, wgs84Geodesic()); } // Project a geocentric point into the orthographic projection defined by the origin static Point3d projectOrtho(const Point3d &origin, const Point3d &p) { const double sinLat = origin.z(); const double cosLat = std::sqrt(origin.x() * origin.x() + origin.y() * origin.y()); const double sinLon = origin.x() / cosLat; const double cosLon = -origin.y() / cosLat; const double x1 = p.x() * cosLon + p.y() * sinLon; const double y1 = -p.x() * sinLon + p.y() * cosLon; return { x1, y1 * sinLat + p.z() * cosLat, -y1 * cosLat + p.z() * sinLat }; } // Invert orthographic projection static Point3d unprojectOrtho(const Point3d &origin, const Point3d &p) { const double sinLat = origin.z(); const double cosLat = std::sqrt(origin.x() * origin.x() + origin.y() * origin.y()); const double sinLon = origin.x() / cosLat; const double cosLon = -origin.y() / cosLat; const double y1 = p.y() * sinLat - p.z() * cosLat; const double z1 = p.y() * cosLat + p.z() * sinLat; return { p.x() * cosLon - y1 * sinLon, p.x() * sinLon + y1 * cosLon, z1 }; } static const double sinpi4 = std::sin(M_PI_4); // Calculate the angle between two vectors. // Both vectors must be normalized! static double angle(Point3d a, Point3d b) { const double dp = a.dot(b); if (std::fabs(dp) < sinpi4) { return std::acos(dp); } const auto m = a.cross(b).norm(); return (dp < 0) ? M_PI - std::asin(m) : std::asin(m); } // TODO: This isn't fully accounting for eccentricity, so it's not super precise. // (start,end,other)=>(downtrack,crosstrack,length) std::tuple<double,double,double> OrthoDist(const Point3d &gca, const Point3d &gcb, const Point3d &gcc) { // Calculate the unit normal of the geodesic segment const auto geoNorm = gca.cross(gcb).normalized(); // Calculate the unit normal of that and the point of interest const auto orthoNorm = gcc.cross(geoNorm).normalized(); // Find the the point where the line to the target point is perpendicular const auto cp = geoNorm.cross(orthoNorm); // Calculate the angles along and aside the segment const auto t0 = angle(gca, gcb); const auto t1 = angle(cp, gca); const auto t2 = angle(cp, gcc); // Work out which quadrant we're in and fix the signs const auto s1 = (cp.dot(geoNorm.cross(gca)) < 0) ? -1. : 1.; const auto s2 = (gcc.dot(geoNorm) > 0) ? -1. : 1.; // Convert the angles to distances const auto rad = GeographicLib::Constants::WGS84_a(); return { rad * t1 * s1, rad * t2 * s2, rad * t0 }; } double initialHeading(const Point3d &startPt, const Point3d &endPt) { // Find the location of the endpoint in the orthographic projection defined by the start point const auto end = projectOrtho(startPt, endPt); // If x==y==0 they are the same point and the heading is undefined return std::atan2(end.x(), end.y()); } double finalHeading(const Point3d &startPt, const Point3d &endPt) { return std::fmod(initialHeading(endPt, startPt) + M_2PI, M_2PI); } Point3d orthoDirect(const Point3d &start, double azimuthRad, double distMeters) { const double theta = distMeters / wgs84Geodesic().EquatorialRadius(); const double r = sin(theta); const double hdg = M_PI_2 - azimuthRad; return unprojectOrtho(start, { r * std::cos(hdg), r * std::sin(hdg), std::cos(theta) }); } }}
34.401606
211
0.591174
akovalov
648769951a67175b76153f21a463c6257d104af6
236
hpp
C++
include/magpie/default_engine.hpp
acdemiralp/magpie
adc6594784363278e06f1edb1868a72ca6c45612
[ "MIT" ]
4
2020-03-03T15:16:41.000Z
2022-02-06T12:03:39.000Z
include/magpie/default_engine.hpp
acdemiralp/magpie
adc6594784363278e06f1edb1868a72ca6c45612
[ "MIT" ]
null
null
null
include/magpie/default_engine.hpp
acdemiralp/magpie
adc6594784363278e06f1edb1868a72ca6c45612
[ "MIT" ]
1
2021-02-24T14:08:00.000Z
2021-02-24T14:08:00.000Z
#ifndef MAGPIE_DEFAULT_ENGINE_HPP #define MAGPIE_DEFAULT_ENGINE_HPP #include <memory> #include <magpie/core/engine.hpp> #include <magpie/export.hpp> namespace mp { MAGPIE_EXPORT std::unique_ptr<engine> make_default_engine(); } #endif
18.153846
60
0.805085
acdemiralp
64878d579043e3769dfd277a912ca528da67cae5
924
hpp
C++
include/ECS/Events.hpp
InversePalindrome/ProceduralX
f53d734970be4300f06db295d25e1a012b1a8fd9
[ "MIT" ]
2
2020-02-06T14:39:56.000Z
2022-02-27T08:27:54.000Z
include/ECS/Events.hpp
InversePalindrome/ProceduralX
f53d734970be4300f06db295d25e1a012b1a8fd9
[ "MIT" ]
null
null
null
include/ECS/Events.hpp
InversePalindrome/ProceduralX
f53d734970be4300f06db295d25e1a012b1a8fd9
[ "MIT" ]
null
null
null
/* Copyright (c) 2020 Inverse Palindrome ProceduralX - ECS/Events.hpp https://inversepalindrome.com/ */ #pragma once #include "App/Action.hpp" #include "ECS/State.hpp" #include <SFML/System/Vector2.hpp> #include <entt/entt.hpp> namespace ECS { struct ActionTriggered { App::Action action; }; struct MouseMoved { sf::Vector2f mousePosition; }; struct MousePressed { sf::Vector2f mousePosition; }; struct ChangeState { entt::entity entity; State state; }; struct StateChanged { entt::entity entity; State state; }; struct ShootProjectile { entt::entity shooter; }; struct CombatOccurred { entt::entity attacker; entt::entity victim; }; struct CrossedPathPoint { entt::entity crossingEntity; entt::entity pathEntity; }; }
14.666667
37
0.588745
InversePalindrome
64896a0fdd7193b6121f422b0afc983015f9bce6
4,488
cpp
C++
routing/routing_integration_tests/bicycle_turn_test.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
routing/routing_integration_tests/bicycle_turn_test.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
routing/routing_integration_tests/bicycle_turn_test.cpp
imanmoghimiq30/omim
16e8a4feeb9a8fa41a2aaf42a1c9c32f77d9d423
[ "Apache-2.0" ]
null
null
null
#include "testing/testing.hpp" #include "routing/routing_integration_tests/routing_test_tools.hpp" #include "routing/route.hpp" using namespace routing; using namespace routing::turns; UNIT_TEST(RussiaMoscowSevTushinoParkBicycleWayTurnTest) { TRouteResult const routeResult = integration::CalculateRoute(integration::GetVehicleComponents<VehicleType::Bicycle>(), MercatorBounds::FromLatLon(55.87467, 37.43658), {0.0, 0.0}, MercatorBounds::FromLatLon(55.8719, 37.4464)); Route const & route = *routeResult.first; IRouter::ResultCode const result = routeResult.second; TEST_EQUAL(result, IRouter::NoError, ()); integration::TestTurnCount(route, 1); integration::GetNthTurn(route, 0).TestValid().TestDirection(CarDirection::TurnLeft); integration::TestRouteLength(route, 1054.0); } UNIT_TEST(RussiaMoscowGerPanfilovtsev22BicycleWayTurnTest) { TRouteResult const routeResult = integration::CalculateRoute(integration::GetVehicleComponents<VehicleType::Bicycle>(), MercatorBounds::FromLatLon(55.85630, 37.41004), {0.0, 0.0}, MercatorBounds::FromLatLon(55.85717, 37.41052)); Route const & route = *routeResult.first; IRouter::ResultCode const result = routeResult.second; TEST_EQUAL(result, IRouter::NoError, ()); integration::TestTurnCount(route, 2); integration::GetNthTurn(route, 0).TestValid().TestDirection(CarDirection::TurnLeft); integration::GetNthTurn(route, 1).TestValid().TestDirection(CarDirection::TurnLeft); } UNIT_TEST(RussiaMoscowSalameiNerisPossibleTurnCorrectionBicycleWayTurnTest) { TRouteResult const routeResult = integration::CalculateRoute(integration::GetVehicleComponents<VehicleType::Bicycle>(), MercatorBounds::FromLatLon(55.85159, 37.38903), {0.0, 0.0}, MercatorBounds::FromLatLon(55.85157, 37.38813)); Route const & route = *routeResult.first; IRouter::ResultCode const result = routeResult.second; TEST_EQUAL(result, IRouter::NoError, ()); integration::TestTurnCount(route, 1); integration::GetNthTurn(route, 0).TestValid().TestDirection(CarDirection::GoStraight); } UNIT_TEST(RussiaMoscowSevTushinoParkBicycleOnePointTurnTest) { m2::PointD const point = MercatorBounds::FromLatLon(55.8719, 37.4464); TRouteResult const routeResult = integration::CalculateRoute( integration::GetVehicleComponents<VehicleType::Bicycle>(), point, {0.0, 0.0}, point); IRouter::ResultCode const result = routeResult.second; TEST_EQUAL(result, IRouter::IRouter::NoError, ()); } UNIT_TEST(RussiaMoscowPlanernaiOnewayCarRoadTurnTest) { TRouteResult const routeResult = integration::CalculateRoute(integration::GetVehicleComponents<VehicleType::Bicycle>(), MercatorBounds::FromLatLon(55.87012, 37.44028), {0.0, 0.0}, MercatorBounds::FromLatLon(55.87153, 37.43928)); Route const & route = *routeResult.first; IRouter::ResultCode const result = routeResult.second; TEST_EQUAL(result, IRouter::NoError, ()); integration::TestTurnCount(route, 4); integration::GetNthTurn(route, 0).TestValid().TestDirection(CarDirection::TurnLeft); integration::GetNthTurn(route, 1).TestValid().TestDirection(CarDirection::TurnLeft); integration::GetNthTurn(route, 2).TestValid().TestDirection(CarDirection::TurnSlightRight); integration::GetNthTurn(route, 3).TestValid().TestDirection(CarDirection::TurnLeft); integration::TestRouteLength(route, 420.0); } UNIT_TEST(RussiaMoscowSvobodiOnewayBicycleWayTurnTest) { TRouteResult const routeResult = integration::CalculateRoute(integration::GetVehicleComponents<VehicleType::Bicycle>(), MercatorBounds::FromLatLon(55.87277, 37.44002), {0.0, 0.0}, MercatorBounds::FromLatLon(55.87362, 37.43853)); Route const & route = *routeResult.first; IRouter::ResultCode const result = routeResult.second; TEST_EQUAL(result, IRouter::NoError, ()); integration::TestTurnCount(route, 3); integration::GetNthTurn(route, 0).TestValid().TestDirection(CarDirection::TurnLeft); integration::GetNthTurn(route, 1).TestValid().TestDirection(CarDirection::TurnLeft); integration::GetNthTurn(route, 2).TestValid().TestDirection(CarDirection::TurnLeft); integration::TestRouteLength(route, 768.0); }
41.174312
93
0.715241
imanmoghimiq30
52bea262efe12c561e9db59ffca7b6e32e31adb2
762
cc
C++
code/foundation/messaging/staticmessagehandler.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
377
2018-10-24T08:34:21.000Z
2022-03-31T23:37:49.000Z
code/foundation/messaging/staticmessagehandler.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
11
2020-01-22T13:34:46.000Z
2022-03-07T10:07:34.000Z
code/foundation/messaging/staticmessagehandler.cc
sirAgg/nebula
3fbccc73779944aa3e56b9e8acdd6fedd1d38006
[ "BSD-2-Clause" ]
23
2019-07-13T16:28:32.000Z
2022-03-20T09:00:59.000Z
//------------------------------------------------------------------------------ // staticmessagehandler.cc // (C) 2009 Radon Labs GmbH // (C) 2013-2020 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "foundation/stdneb.h" #include "messaging/staticmessagehandler.h" namespace Messaging { //------------------------------------------------------------------------------ /** */ template<> void StaticMessageHandler::Dispatch(const Ptr<Core::RefCounted>& obj, const Ptr<Message>& msg) { n_error("StaticMessageHandler: Unhandled message (objclass=%s, msgclass=%s)!\n", obj->GetClassName().AsCharPtr(), msg->GetClassName().AsCharPtr()); } } // namespace Messaging
34.636364
89
0.492126
sirAgg
52beb0e15483c741bef5c95dfe423fd0773c6ddd
1,346
hpp
C++
include/boost/mpl11/fwd/group.hpp
ldionne/mpl11
927d4339edc0c0cc41fb65ced2bf19d26bcd4a08
[ "BSL-1.0" ]
80
2015-03-09T03:19:12.000Z
2022-03-04T06:44:12.000Z
include/boost/mpl11/fwd/group.hpp
rbock/mpl11
7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277
[ "BSL-1.0" ]
1
2021-07-27T22:37:43.000Z
2021-08-06T17:42:07.000Z
include/boost/mpl11/fwd/group.hpp
rbock/mpl11
7923ad2bdc0d8ddaa6a6254ebf5be2b5c6f5a277
[ "BSL-1.0" ]
8
2015-01-28T00:18:57.000Z
2021-08-06T03:00:49.000Z
/*! * @file * Forward declares the @ref Group typeclass. * * * @copyright Louis Dionne 2014 * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE.md or copy at * http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_MPL11_FWD_GROUP_HPP #define BOOST_MPL11_FWD_GROUP_HPP #include <boost/mpl11/fwd/bool.hpp> namespace boost { namespace mpl11 { /*! * @ingroup typeclasses * @defgroup Group Group * * `Monoid` where all objects have an inverse w.r.t. the binary operation. * * Instances of `Group` must satisfy the following laws: * @code plus x (negate x) == zero plus (negate x) x == zero @endcode * * The method names refer to the group of numbers under addition. * * * ### Methods * `minus` and `negate` * * ### Minimal complete definition * Either `minus` or `negate`. * * @{ */ template <typename Left, typename Right = Left, typename = true_> struct Group; //! Equivalent to `plus<x, negate<y>>`. template <typename x, typename y> struct minus; //! Returns the inverse of `x`. template <typename x> struct negate; //! @} }} // end namespace boost::mpl11 #endif // !BOOST_MPL11_FWD_GROUP_HPP
23.614035
78
0.60104
ldionne
52c0168ef5ef9baf49cf166c8f5310b0a59f2336
41,211
cpp
C++
tests/test_parser/test_primitives/test_directives.cpp
ericcao119/Spimbot
71699d67b9746d078988033b0ace1f180f50fc8c
[ "MIT" ]
null
null
null
tests/test_parser/test_primitives/test_directives.cpp
ericcao119/Spimbot
71699d67b9746d078988033b0ace1f180f50fc8c
[ "MIT" ]
null
null
null
tests/test_parser/test_primitives/test_directives.cpp
ericcao119/Spimbot
71699d67b9746d078988033b0ace1f180f50fc8c
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include <iostream> #include "../table.h" #include "../test_parser.h" #include "parser/directive/directive.h" #include "parser/skipper.h" using namespace client::ast; template <typename P> void parse_dir(char const* input, P const& p, Directive& dir, bool full_match = true) { using boost::spirit::x3::phrase_parse; char const* f(input); char const* l(f + strlen(f)); if (phrase_parse(f, l, p, mips_parser::default_skipper, dir) && (!full_match || (f == l))) { return; } else { throw parse_failed_exception(); } } TEST_CASE("Parse directives", "[parser][directive]") { Directive directive; evaluator<lookup> eval; SECTION("ALIAS") { parse_dir(".alias $0 $1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<AliasDir>(directive).reg1 == 0); REQUIRE(boost::get<AliasDir>(directive).reg2 == 1); parse_dir(".alias $ra $zero", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<AliasDir>(directive).reg1 == 31); REQUIRE(boost::get<AliasDir>(directive).reg2 == 0); REQUIRE_THROWS(parse_dir(".alias $0$1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".alias$0 $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".alias$0$1", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("ALIGN") { parse_dir(".align 2", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<AlignDir>(directive).alignment) == 2); parse_dir(".align 3 + 4 + 9", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<AlignDir>(directive).alignment) == 16); parse_dir(".align 3 + 4 + deadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<AlignDir>(directive).alignment) == 7 + 0xdeadbeef); REQUIRE_THROWS(parse_dir(".align 3 + 4 9", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".align 3 + 4 deadbeef", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("ASCII") { parse_dir(".ascii \"2\"", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<AsciiDir>(directive).size() == 1); REQUIRE(boost::get<AsciiDir>(directive)[0] == "2"); parse_dir(".ascii \"2\", \"abc\"", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<AsciiDir>(directive).size() == 2); REQUIRE(boost::get<AsciiDir>(directive)[0] == "2"); REQUIRE(boost::get<AsciiDir>(directive)[1] == "abc"); REQUIRE_THROWS(parse_dir(".ascii", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".ascii abc", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".ascii \"abc ", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".ascii 2", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("ASCIIZ") { parse_dir(".asciiz \"2\"", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<AsciizDir>(directive).size() == 1); REQUIRE(boost::get<AsciizDir>(directive)[0] == "2"); parse_dir(".asciiz \"2\", \"abc\"", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<AsciizDir>(directive).size() == 2); REQUIRE(boost::get<AsciizDir>(directive)[0] == "2"); REQUIRE(boost::get<AsciizDir>(directive)[1] == "abc"); REQUIRE_THROWS(parse_dir(".asciiz", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".asciiz abc", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".asciiz \"abc ", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".asciiz 2", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("ASM0") { parse_dir(".asm0", mips_parser::ASM_DIRECTIVE, directive); REQUIRE_NOTHROW(boost::get<Asm0Dir>(directive)); REQUIRE_THROWS(parse_dir(".asm0 abc", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("BGNB") { parse_dir(".bgnb 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<BgnbDir>(directive).symno == 123); REQUIRE_THROWS(parse_dir(".bgnb", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".bgnb abc", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("BYTE") { parse_dir(".byte 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list.size()) == 1); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[0]) == 123); parse_dir(".byte 123 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list.size()) == 2); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[1]) == 123); parse_dir(".byte 123, 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list.size()) == 2); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[1]) == 123); parse_dir(".byte 123, 123, 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[1]) == 123); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[2]) == 124); parse_dir(".byte 123, 123 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[1]) == 123); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[2]) == 124); parse_dir(".byte 123 + a0 123 + deadbeef 124 + 0xdeadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[0]) == 123 + variable_table.at("a0")); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[1]) == 123 + variable_table.at("deadbeef")); REQUIRE(eval(boost::get<ByteDir>(directive).expression_list[2]) == 124 + 0xdeadbeef); parse_dir(".byte 123: 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<ByteRepeatDir>(directive).repeat_list.repeat_value) == 123); REQUIRE(eval(boost::get<ByteRepeatDir>(directive).repeat_list.repeat_num) == 124); parse_dir(".byte 123 + 1:124 + 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<ByteRepeatDir>(directive).repeat_list.repeat_value) == 124); REQUIRE(eval(boost::get<ByteRepeatDir>(directive).repeat_list.repeat_num) == 125); REQUIRE_THROWS(parse_dir(".byte", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".byte ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".byte :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("COMM") { parse_dir(".comm ncasl, 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<CommDir>(directive).ident == "ncasl"); REQUIRE(eval(boost::get<CommDir>(directive).expr) == 123); REQUIRE_THROWS(parse_dir(".comm ncasl 123", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".comm", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".comm ,", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("DATA") { parse_dir(".data", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DataDir>(directive).addr.has_value() == false); parse_dir(".data 10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DataDir>(directive).addr.has_value()); REQUIRE(boost::get<DataDir>(directive).addr.value() == 10); parse_dir(".data 0x1f", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DataDir>(directive).addr.has_value()); REQUIRE(boost::get<DataDir>(directive).addr.value() == 0x1f); parse_dir(".data 0b10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DataDir>(directive).addr.has_value()); REQUIRE(boost::get<DataDir>(directive).addr.value() == 0b10); REQUIRE_THROWS(parse_dir(".data ab", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".data 0b10, as", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("KDATA") { parse_dir(".kdata", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<KDataDir>(directive).addr.has_value() == false); parse_dir(".kdata 10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<KDataDir>(directive).addr.has_value()); REQUIRE(boost::get<KDataDir>(directive).addr.value() == 10); parse_dir(".kdata 0x1f", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<KDataDir>(directive).addr.has_value()); REQUIRE(boost::get<KDataDir>(directive).addr.value() == 0x1f); parse_dir(".kdata 0b10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<KDataDir>(directive).addr.has_value()); REQUIRE(boost::get<KDataDir>(directive).addr.value() == 0b10); REQUIRE_THROWS(parse_dir(".kdata ab", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".kdata 0b10, as", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("DOUBLE") { parse_dir(".double 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DoubleDir>(directive).expression_list.size() == 1); REQUIRE(boost::get<DoubleDir>(directive).expression_list[0] == 123); parse_dir(".double 123 124.1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DoubleDir>(directive).expression_list.size() == 2); REQUIRE(boost::get<DoubleDir>(directive).expression_list[0] == 123); REQUIRE(boost::get<DoubleDir>(directive).expression_list[1] == 124.1); parse_dir(".double 123, 1.5", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DoubleDir>(directive).expression_list.size() == 2); REQUIRE(boost::get<DoubleDir>(directive).expression_list[0] == 123); REQUIRE(boost::get<DoubleDir>(directive).expression_list[1] == 1.5); parse_dir(".double 1.23, 1.23, 1.24", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DoubleDir>(directive).expression_list.size() == 3); REQUIRE(boost::get<DoubleDir>(directive).expression_list[0] == 1.23); REQUIRE(boost::get<DoubleDir>(directive).expression_list[1] == 1.23); REQUIRE(boost::get<DoubleDir>(directive).expression_list[2] == 1.24); parse_dir(".double 1.23, 1.23 1.24", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DoubleDir>(directive).expression_list.size() == 3); REQUIRE(boost::get<DoubleDir>(directive).expression_list[0] == 1.23); REQUIRE(boost::get<DoubleDir>(directive).expression_list[1] == 1.23); REQUIRE(boost::get<DoubleDir>(directive).expression_list[2] == 1.24); parse_dir(".double 1e-5: 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DoubleRepeatDir>(directive).repeat_list.repeat_value == 1e-5); REQUIRE(eval(boost::get<DoubleRepeatDir>(directive).repeat_list.repeat_num) == 124); parse_dir(".double 0.5:124 + 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<DoubleRepeatDir>(directive).repeat_list.repeat_value == 0.5); REQUIRE(eval(boost::get<DoubleRepeatDir>(directive).repeat_list.repeat_num) == 125); REQUIRE_THROWS(parse_dir(".double", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".double ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".double :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("END") { parse_dir(".end symno", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<EndDir>(directive).proc_name.has_value()); REQUIRE(boost::get<EndDir>(directive).proc_name.value() == "symno"); parse_dir(".end", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<EndDir>(directive).proc_name.has_value() == false); REQUIRE_THROWS(parse_dir(".end 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".end $a0", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("ENDB") { parse_dir(".endb 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<EndbDir>(directive).symno == 1); REQUIRE_THROWS(parse_dir(".endb", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".endb abs", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".endb $a0", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("ENDR") { parse_dir(".endr", mips_parser::ASM_DIRECTIVE, directive); REQUIRE_NOTHROW(boost::get<EndrDir>(directive)); REQUIRE_THROWS(parse_dir(".endr 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".endr abs", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".endr $a0", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("ENT") { parse_dir(".ent proc_name 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<EntDir>(directive).proc_name == "proc_name"); REQUIRE(boost::get<EntDir>(directive).lex_level.has_value()); REQUIRE(boost::get<EntDir>(directive).lex_level.value() == 1); parse_dir(".ent proc_name", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<EntDir>(directive).proc_name == "proc_name"); REQUIRE(boost::get<EntDir>(directive).lex_level.has_value() == false); REQUIRE_THROWS(parse_dir(".ent 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".ent $a0", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("EXTERN") { parse_dir(".extern proc_name 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<ExternDir>(directive).name == "proc_name"); REQUIRE(boost::get<ExternDir>(directive).number.has_value()); REQUIRE(boost::get<ExternDir>(directive).number.value() == 1); parse_dir(".extern proc_name", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<ExternDir>(directive).name == "proc_name"); REQUIRE(boost::get<ExternDir>(directive).number.has_value() == false); REQUIRE_THROWS(parse_dir(".extern 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".extern $a0", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("ERR") { parse_dir(".err", mips_parser::ASM_DIRECTIVE, directive); REQUIRE_NOTHROW(boost::get<ErrDir>(directive)); REQUIRE_THROWS(parse_dir(".err 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".err abs", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".err $a0", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("FILE") { parse_dir(R"(.file 123 "abc\t")", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FileDir>(directive).file_no == 123); REQUIRE(boost::get<FileDir>(directive).filename == "abc\t"); REQUIRE_THROWS(parse_dir(".file 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".file abs", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".file $a0", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("FLOAT") { parse_dir(".float 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FloatDir>(directive).expression_list.size() == 1); REQUIRE(boost::get<FloatDir>(directive).expression_list[0] == 123); parse_dir(".float 123 124.1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FloatDir>(directive).expression_list.size() == 2); REQUIRE(boost::get<FloatDir>(directive).expression_list[0] == 123); REQUIRE(boost::get<FloatDir>(directive).expression_list[1] == 124.1); parse_dir(".float 123, 1.5", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FloatDir>(directive).expression_list.size() == 2); REQUIRE(boost::get<FloatDir>(directive).expression_list[0] == 123); REQUIRE(boost::get<FloatDir>(directive).expression_list[1] == 1.5); parse_dir(".float 1.23, 1.23, 1.24", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FloatDir>(directive).expression_list.size() == 3); REQUIRE(boost::get<FloatDir>(directive).expression_list[0] == 1.23); REQUIRE(boost::get<FloatDir>(directive).expression_list[1] == 1.23); REQUIRE(boost::get<FloatDir>(directive).expression_list[2] == 1.24); parse_dir(".float 1.23, 1.23 1.24", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FloatDir>(directive).expression_list.size() == 3); REQUIRE(boost::get<FloatDir>(directive).expression_list[0] == 1.23); REQUIRE(boost::get<FloatDir>(directive).expression_list[1] == 1.23); REQUIRE(boost::get<FloatDir>(directive).expression_list[2] == 1.24); parse_dir(".float 1e-5: 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FloatRepeatDir>(directive).repeat_list.repeat_value == 1e-5); REQUIRE(eval(boost::get<FloatRepeatDir>(directive).repeat_list.repeat_num) == 124); parse_dir(".float 0.5:124 + 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FloatRepeatDir>(directive).repeat_list.repeat_value == 0.5); REQUIRE(eval(boost::get<FloatRepeatDir>(directive).repeat_list.repeat_num) == 125); REQUIRE_THROWS(parse_dir(".float", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".float ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".float :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("FMASK") { parse_dir(".fmask 12 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FmaskDir>(directive).mask == 12); REQUIRE(boost::get<FmaskDir>(directive).offset == 123); parse_dir(".fmask 0x12 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FmaskDir>(directive).mask == 0x12); REQUIRE(boost::get<FmaskDir>(directive).offset == 123); parse_dir(".fmask 0b10 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FmaskDir>(directive).mask == 0b10); REQUIRE(boost::get<FmaskDir>(directive).offset == 123); REQUIRE_THROWS(parse_dir(".fmask", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".fmask 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".fmask ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".fmask :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("FRAME") { parse_dir(".frame $0 123 $ra", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<FrameDir>(directive).frame_register == 0); REQUIRE(boost::get<FrameDir>(directive).frame_size == 123); REQUIRE(boost::get<FrameDir>(directive).return_pc_register == 31); REQUIRE_THROWS(parse_dir(".frame", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".frame 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".frame 1 1 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".frame ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".frame :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("GLOBAL") { parse_dir(".globl proc_name", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<GlobalDir>(directive).id == "proc_name"); REQUIRE_THROWS(parse_dir(".globl", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".globl 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".globl $a0", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("HALF") { parse_dir(".half 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list.size()) == 1); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[0]) == 123); parse_dir(".half 123 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list.size()) == 2); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[1]) == 123); parse_dir(".half 123, 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list.size()) == 2); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[1]) == 123); parse_dir(".half 123, 123, 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[1]) == 123); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[2]) == 124); parse_dir(".half 123, 123 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[1]) == 123); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[2]) == 124); parse_dir(".half 123 + a0 123 + deadbeef 124 + 0xdeadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[0]) == 123 + variable_table.at("a0")); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[1]) == 123 + variable_table.at("deadbeef")); REQUIRE(eval(boost::get<HalfDir>(directive).expression_list[2]) == 124 + 0xdeadbeef); parse_dir(".half 123: 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<HalfRepeatDir>(directive).repeat_list.repeat_value) == 123); REQUIRE(eval(boost::get<HalfRepeatDir>(directive).repeat_list.repeat_num) == 124); parse_dir(".half 123 + 1:124 + 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<HalfRepeatDir>(directive).repeat_list.repeat_value) == 124); REQUIRE(eval(boost::get<HalfRepeatDir>(directive).repeat_list.repeat_num) == 125); REQUIRE_THROWS(parse_dir(".half", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".half ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".half :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("LABEL") { parse_dir(".lab label", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<LabelDir>(directive).label_name == "label"); REQUIRE_THROWS(parse_dir(".lab", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".lab 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".lab ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".lab :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("LCOMM") { parse_dir(".lcomm name 1 + 2 * 3", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<LcommDir>(directive).name == "name"); REQUIRE(eval(boost::get<LcommDir>(directive).expr) == 7); REQUIRE_THROWS(parse_dir(".lcomm", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".lcomm name", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".lcomm 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".lcomm ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".lcomm :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("LIVEREG") { parse_dir(".livereg 0x1000 0b10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<LiveregDir>(directive).int_bitmask == 0x1000); REQUIRE(boost::get<LiveregDir>(directive).fp_bitmask == 0b10); parse_dir(".livereg 1000 10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<LiveregDir>(directive).int_bitmask == 1000); REQUIRE(boost::get<LiveregDir>(directive).fp_bitmask == 10); REQUIRE_THROWS(parse_dir(".livereg", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".livereg name", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".livereg 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".livereg ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".livereg :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("LOC") { parse_dir(".loc 1000 10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<LocDir>(directive).file_number == 1000); REQUIRE(boost::get<LocDir>(directive).line_number == 10); REQUIRE_THROWS(parse_dir(".loc 0x1000 0b10", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".loc", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".loc name", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".loc 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".loc ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".loc :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("MASK") { parse_dir(".mask 1000 10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<MaskDir>(directive).mask == 1000); REQUIRE(boost::get<MaskDir>(directive).offset == 10); parse_dir(".mask 0x1000 10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<MaskDir>(directive).mask == 0x1000); REQUIRE(boost::get<MaskDir>(directive).offset == 10); parse_dir(".mask 0b1000 10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<MaskDir>(directive).mask == 0b1000); REQUIRE(boost::get<MaskDir>(directive).offset == 10); REQUIRE_THROWS(parse_dir(".mask 1000 0x10", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".mask 0x1000 0b10", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".mask", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".mask name", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".mask 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".mask ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".mask :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("NOALIAS") { parse_dir(".noalias $0 $ra", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<NoaliasDir>(directive).reg1 == 0); REQUIRE(boost::get<NoaliasDir>(directive).reg2 == 31); REQUIRE_THROWS(parse_dir(".noalias $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".noalias", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".noalias name", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".noalias 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".noalias ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".noalias :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("OPTIONS") { parse_dir(".option noat", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<OptionDir>(directive).option == "noat"); REQUIRE_THROWS(parse_dir(".option $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".option", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".option 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".option ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".option :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("REPEAT") { parse_dir(".repeat deadbeef + 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<RepeatDir>(directive).repeat_num) == 0xdeadbeef + 123); parse_dir(".repeat deadbeef+123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<RepeatDir>(directive).repeat_num) == 0xdeadbeef + 123); REQUIRE_THROWS(parse_dir(".repeat $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".repeat", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".repeat ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".repeat :", mips_parser::ASM_DIRECTIVE, directive)); parse_dir(".repeat name", mips_parser::ASM_DIRECTIVE, directive); REQUIRE_THROWS(eval(boost::get<RepeatDir>(directive).repeat_num)); } SECTION("RDATA") { parse_dir(".rdata 0xdeadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<RDataDir>(directive).address.has_value()); REQUIRE(boost::get<RDataDir>(directive).address.value() == 0xdeadbeef); parse_dir(".rdata 0b1010101", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<RDataDir>(directive).address.has_value()); REQUIRE(boost::get<RDataDir>(directive).address.value() == 0b1010101); parse_dir(".rdata 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<RDataDir>(directive).address.has_value()); REQUIRE(boost::get<RDataDir>(directive).address.value() == 123); parse_dir(".rdata", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<RDataDir>(directive).address.has_value() == false); REQUIRE_THROWS(parse_dir(".rdata $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".rdata ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".rdata :", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".rdata name", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("SDATA") { parse_dir(".sdata 0xdeadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<SDataDir>(directive).address.has_value()); REQUIRE(boost::get<SDataDir>(directive).address.value() == 0xdeadbeef); parse_dir(".sdata 0b1010101", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<SDataDir>(directive).address.has_value()); REQUIRE(boost::get<SDataDir>(directive).address.value() == 0b1010101); parse_dir(".sdata 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<SDataDir>(directive).address.has_value()); REQUIRE(boost::get<SDataDir>(directive).address.value() == 123); parse_dir(".sdata", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<SDataDir>(directive).address.has_value() == false); REQUIRE_THROWS(parse_dir(".sdata $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".sdata ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".sdata :", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".sdata name", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("SET") { parse_dir(".set at", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<SetDir>(directive).option == "at"); parse_dir(".set noat", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<SetDir>(directive).option == "noat"); REQUIRE_THROWS(parse_dir(".set $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".set ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".set :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("SPACE") { parse_dir(".space deadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<SpaceDir>(directive).num_bytes) == 0xdeadbeef); parse_dir(".space 0b10 | 0b1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<SpaceDir>(directive).num_bytes) == 0b11); REQUIRE_THROWS(parse_dir(".space", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".space $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".space ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".space :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("STRUCT") { parse_dir(".struct deadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<StructDir>(directive).num_bytes) == 0xdeadbeef); parse_dir(".struct 0b10 | 0b1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<StructDir>(directive).num_bytes) == 0b11); REQUIRE_THROWS(parse_dir(".struct", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".struct $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".struct ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".struct :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("TEXT") { parse_dir(".text 0xdeadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<TextDir>(directive).addr.has_value()); REQUIRE(boost::get<TextDir>(directive).addr == 0xdeadbeef); parse_dir(".text 0b10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<TextDir>(directive).addr.has_value()); REQUIRE(boost::get<TextDir>(directive).addr == 0b10); parse_dir(".text 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<TextDir>(directive).addr.has_value()); REQUIRE(boost::get<TextDir>(directive).addr == 123); parse_dir(".text", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<TextDir>(directive).addr.has_value() == false); REQUIRE_THROWS(parse_dir(".text $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".text ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".text :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("KTEXT") { parse_dir(".ktext 0xdeadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<KTextDir>(directive).addr.has_value()); REQUIRE(boost::get<KTextDir>(directive).addr.value() == 0xdeadbeef); parse_dir(".ktext 0b10", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<KTextDir>(directive).addr.has_value()); REQUIRE(boost::get<KTextDir>(directive).addr.value() == 0b10); parse_dir(".ktext 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<KTextDir>(directive).addr.has_value()); REQUIRE(boost::get<KTextDir>(directive).addr.value() == 123); parse_dir(".ktext", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<KTextDir>(directive).addr.has_value() == false); REQUIRE_THROWS(parse_dir(".ktext $1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".ktext ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".ktext :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("VERSTAMP") { parse_dir(".verstamp 12 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<VerstampDir>(directive).major_ver == 12); REQUIRE(boost::get<VerstampDir>(directive).minor_ver == 1); REQUIRE_THROWS(parse_dir(".verstamp 30 -1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".verstamp -1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".verstamp 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".verstamp ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".verstamp :", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".verstamp :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("VREG") { parse_dir(".vreg $ra 1 12", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(boost::get<VregDir>(directive).reg == 31); REQUIRE(boost::get<VregDir>(directive).offset == 1); REQUIRE(boost::get<VregDir>(directive).symno == 12); REQUIRE_THROWS(parse_dir(".vreg 30 -1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".vreg $t0 -1 -1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".vreg -1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".vreg 1", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".vreg ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".vreg :", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".vreg :", mips_parser::ASM_DIRECTIVE, directive)); } SECTION("WORD") { parse_dir(".word 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<WordDir>(directive).expression_list.size()) == 1); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[0]) == 123); parse_dir(".word 123 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<WordDir>(directive).expression_list.size()) == 2); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[1]) == 123); parse_dir(".word 123, 123", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<WordDir>(directive).expression_list.size()) == 2); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[1]) == 123); parse_dir(".word 123, 123, 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<WordDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[1]) == 123); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[2]) == 124); parse_dir(".word 123, 123 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<WordDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[0]) == 123); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[1]) == 123); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[2]) == 124); parse_dir(".word 123 + a0 123 + deadbeef 124 + 0xdeadbeef", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<WordDir>(directive).expression_list.size()) == 3); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[0]) == 123 + variable_table.at("a0")); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[1]) == 123 + variable_table.at("deadbeef")); REQUIRE(eval(boost::get<WordDir>(directive).expression_list[2]) == 124 + 0xdeadbeef); parse_dir(".word 123: 124", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<WordRepeatDir>(directive).repeat_list.repeat_value) == 123); REQUIRE(eval(boost::get<WordRepeatDir>(directive).repeat_list.repeat_num) == 124); parse_dir(".word 123 + 1:124 + 1", mips_parser::ASM_DIRECTIVE, directive); REQUIRE(eval(boost::get<WordRepeatDir>(directive).repeat_list.repeat_value) == 124); REQUIRE(eval(boost::get<WordRepeatDir>(directive).repeat_list.repeat_num) == 125); REQUIRE_THROWS(parse_dir(".word", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".word ,", mips_parser::ASM_DIRECTIVE, directive)); REQUIRE_THROWS(parse_dir(".word :", mips_parser::ASM_DIRECTIVE, directive)); } }
54.801862
112
0.674844
ericcao119
52c082f0b5b4595e9dd4666c0c25ca76890faa84
262
cpp
C++
cpp/operator-overloading/call_operator.cpp
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
null
null
null
cpp/operator-overloading/call_operator.cpp
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
1
2016-09-15T07:06:15.000Z
2016-09-15T07:06:15.000Z
cpp/operator-overloading/call_operator.cpp
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; struct Add { int operator()(const int n1, const int n2) { return n1 + n2; } }; int main(void) { auto add_instance = Add(); cout << add_instance(1, 2) << endl; return 0; }
14.555556
49
0.538168
wjiec
52c3dae45df1a9fa234d2c30734c089785bddc41
970
cpp
C++
cf/725div3C.cpp
exoad/competitive-programming
04b4a8d9cd27fd9c1e82783dc685a340cfbd4ec4
[ "MIT" ]
7
2021-08-02T14:04:34.000Z
2022-03-04T02:59:12.000Z
cf/725div3C.cpp
meng-jack/competitive-programming
f2b4fcec1023e8f827f806dcaa0a2b76117b6c7f
[ "MIT" ]
3
2021-11-10T19:32:00.000Z
2021-11-21T17:24:49.000Z
cf/725div3C.cpp
exoad/competitive-programming
04b4a8d9cd27fd9c1e82783dc685a340cfbd4ec4
[ "MIT" ]
1
2021-11-10T19:24:22.000Z
2021-11-10T19:24:22.000Z
#include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <array> #include <algorithm> #include <utility> #include <map> #include <queue> #include <set> #include <cmath> #include <cstdio> #include <cstring> #define ll long long #define ld long double #define eps 1e-8 #define MOD 1000000007 #define INF 0x3f3f3f3f #define INFLL 0x3f3f3f3f3f3f3f3f #define MAXN 1000000 using namespace std; ll a[200005]; void solve() { int n, l, r; cin >> n >> l >> r; for (int i = 1; i <= n; ++i) { cin >> a[i]; } sort(a + 1, a + 1 + n); ll res = 0; for (int i = 1; i < n; ++i) { ll x = l - a[i], y = r - a[i]; ll s = lower_bound(a + i + 1, a + n + 1, x) - a; ll z = upper_bound(a + i + 1, a + n + 1, y) - a; res += (z - s); } cout << res << '\n'; } int main() { cin.tie(0)->sync_with_stdio(0); int T; cin >> T; while (T--) solve(); return 0; }
17.962963
56
0.526804
exoad
52c6589e812a346014aa08688e7d8dfa6ac821ba
8,810
cpp
C++
UiModule/Inworld/ControlPanelManager.cpp
mattire/naali
28c9cdc84c6a85e0151a222e55ae35c9403f0212
[ "Apache-2.0" ]
1
2018-04-02T15:38:10.000Z
2018-04-02T15:38:10.000Z
UiModule/Inworld/ControlPanelManager.cpp
mattire/naali
28c9cdc84c6a85e0151a222e55ae35c9403f0212
[ "Apache-2.0" ]
null
null
null
UiModule/Inworld/ControlPanelManager.cpp
mattire/naali
28c9cdc84c6a85e0151a222e55ae35c9403f0212
[ "Apache-2.0" ]
null
null
null
// For conditions of distribution and use, see copyright notice in license.txt #include "StableHeaders.h" #include "DebugOperatorNew.h" #include "ControlPanelManager.h" #include "Common/AnchorLayoutManager.h" #include "Common/UiAction.h" #include "Common/ControlButtonAction.h" #include "Inworld/ControlPanel/BackdropWidget.h" #include "Inworld/ControlPanel/ControlPanelButton.h" #include "Inworld/ControlPanel/SettingsWidget.h" #include "Inworld/ControlPanel/BindingWidget.h" #include "Inworld/ControlPanel/PersonalWidget.h" #include "Inworld/ControlPanel/LanguageWidget.h" #include "Inworld/ControlPanel/TeleportWidget.h" #include "Inworld/ControlPanel/CacheSettingsWidget.h" #include "Inworld/ControlPanel/ChangeThemeWidget.h" #include <QAction> #include "MemoryLeakCheck.h" namespace CoreUi { ControlPanelManager::ControlPanelManager(QObject *parent, AnchorLayoutManager *layout_manager) : QObject(parent), layout_manager_(layout_manager), backdrop_widget_(new CoreUi::BackdropWidget()), settings_widget_(0), binding_widget_(0), language_widget_(0), teleport_widget_(0), changetheme_widget_(0) { // Controls panel layout_manager_->AddCornerAnchor(backdrop_widget_, Qt::TopRightCorner, Qt::TopRightCorner); CreateBasicControls(); // Settings widget settings_widget_ = new SettingsWidget(layout_manager_->GetScene(), this); ControlButtonAction *settings_action = new ControlButtonAction(GetButtonForType(UiServices::Settings), settings_widget_, this); SetHandler(UiServices::Settings, settings_action); connect(settings_action, SIGNAL(toggled(bool)), SLOT(ToggleSettingsVisibility(bool))); connect(settings_widget_, SIGNAL(Hidden()), SLOT(CheckSettingsButtonStyle())); // Binding widget as settings tab //binding_widget_ = new BindingWidget(settings_widget_); //settings_widget_->AddWidget(binding_widget_, "Controls"); // Adding cache tab cache_settings_widget_ = new CacheSettingsWidget(settings_widget_); settings_widget_->AddWidget(cache_settings_widget_, "Cache"); // Adding a language tab. language_widget_ = new LanguageWidget(settings_widget_); settings_widget_->AddWidget(language_widget_, "Language"); // Personal widget personal_widget_ = new PersonalWidget(); layout_manager_->AddCornerAnchor(personal_widget_, Qt::BottomRightCorner, Qt::BottomRightCorner); // Teleport widget teleport_widget_ = new TeleportWidget(layout_manager_->GetScene(), this); ControlButtonAction *teleport_action = new ControlButtonAction(GetButtonForType(UiServices::Teleport), teleport_widget_, this); SetHandler(UiServices::Teleport, teleport_action); connect(teleport_action, SIGNAL(toggled(bool)), SLOT(ToggleTeleportVisibility(bool))); connect(teleport_widget_, SIGNAL(Hidden()), SLOT(CheckTeleportButtonStyle())); // Adding change theme tab changetheme_widget_ = new ChangeThemeWidget(settings_widget_); settings_widget_->AddWidget(changetheme_widget_, "Change theme"); } ControlPanelManager::~ControlPanelManager() { SAFE_DELETE(settings_widget_); } // Private void ControlPanelManager::CreateBasicControls() { QList<UiServices::ControlButtonType> buttons; buttons << UiServices::Notifications << UiServices::Teleport << UiServices::Settings << UiServices::Quit << UiServices::Build << UiServices::Ether; ControlPanelButton *button = 0; ControlPanelButton *previous_button = 0; foreach(UiServices::ControlButtonType button_type, buttons) { // Create the button and anchor in scene button = new ControlPanelButton(button_type); if (previous_button) layout_manager_->AnchorWidgetsHorizontally(previous_button, button); else layout_manager_->AddCornerAnchor(button, Qt::TopRightCorner, Qt::TopRightCorner); // Add to internal lists control_buttons_.append(button); if (button_type == UiServices::Notifications || button_type == UiServices::Settings || button_type == UiServices::Teleport) backdrop_area_buttons_map_[button_type] = button; connect(button, SIGNAL(ControlButtonClicked(UiServices::ControlButtonType)), SLOT(ControlButtonClicked(UiServices::ControlButtonType))); previous_button = button; } UpdateBackdrop(); } void ControlPanelManager::UpdateBackdrop() { qreal width = 0; foreach (ControlPanelButton *button, backdrop_area_buttons_map_.values()) width += button->GetContentWidth(); backdrop_widget_->SetContentWidth(width); } void ControlPanelManager::ControlButtonClicked(UiServices::ControlButtonType type) { // Hide others if type is toggle core ui switch (type) { case UiServices::Settings: { ControlButtonAction *action_notifications = dynamic_cast<ControlButtonAction*>(action_map_[UiServices::Notifications]); ControlButtonAction *action_teleport = dynamic_cast<ControlButtonAction*>(action_map_[UiServices::Teleport]); if (action_notifications) action_notifications->RequestHide(); if (action_teleport) action_teleport->RequestHide(); break; } case UiServices::Teleport: { ControlButtonAction *action_notifications = dynamic_cast<ControlButtonAction*>(action_map_[UiServices::Notifications]); ControlButtonAction *action_settings = dynamic_cast<ControlButtonAction*>(action_map_[UiServices::Settings]); if (action_notifications) action_notifications->RequestHide(); if (action_settings) action_settings->RequestHide(); break; } case UiServices::Notifications: { ControlButtonAction *action_settings = dynamic_cast<ControlButtonAction*>(action_map_[UiServices::Settings]); ControlButtonAction *action_teleport = dynamic_cast<ControlButtonAction*>(action_map_[UiServices::Teleport]); if (action_settings) action_settings->RequestHide(); if (action_teleport) action_teleport->RequestHide(); break; } default: break; } if (action_map_.contains(type)) action_map_[type]->trigger(); } void ControlPanelManager::ToggleSettingsVisibility(bool visible) { if (visible) settings_widget_->show(); else settings_widget_->AnimatedHide(); } void ControlPanelManager::ToggleTeleportVisibility(bool visible) { if (visible) teleport_widget_->show(); else teleport_widget_->AnimatedHide(); } void ControlPanelManager::CheckSettingsButtonStyle() { backdrop_area_buttons_map_[UiServices::Settings]->CheckStyle(false); } void ControlPanelManager::CheckTeleportButtonStyle() { backdrop_area_buttons_map_[UiServices::Teleport]->CheckStyle(false); } // Public void ControlPanelManager::SetHandler(UiServices::ControlButtonType type, UiServices::UiAction *action) { action_map_[type] = action; } ControlPanelButton *ControlPanelManager::GetButtonForType(UiServices::ControlButtonType type) const { if (backdrop_area_buttons_map_.contains(type)) return backdrop_area_buttons_map_[type]; else return 0; } qreal ControlPanelManager::GetContentHeight() const { return backdrop_widget_->GetContentHeight(); } qreal ControlPanelManager::GetContentWidth() const { return backdrop_widget_->GetContentWidth(); } void ControlPanelManager::SetServiceGetter(QObject *service_getter) { if (binding_widget_) { connect(service_getter, SIGNAL(KeyBindingsChanged(Foundation::KeyBindings*)), binding_widget_, SLOT(UpdateContent(Foundation::KeyBindings*))); connect(binding_widget_, SIGNAL(KeyBindingsUpdated(Foundation::KeyBindings*)), service_getter, SLOT(SetKeyBindings(Foundation::KeyBindings*))); connect(binding_widget_, SIGNAL(RestoreDefaultBindings()), service_getter, SLOT(RestoreKeyBindings())); } } }
38.640351
155
0.668785
mattire
52c67e451150e1475f4bc24b21d7384e46871679
2,072
cpp
C++
src/luanode_os.cpp
mkottman/LuaNode
b059225855939477147c5d4a6e8df3350c0a25fb
[ "MIT" ]
1
2015-06-13T18:00:06.000Z
2015-06-13T18:00:06.000Z
src/luanode_os.cpp
mkottman/LuaNode
b059225855939477147c5d4a6e8df3350c0a25fb
[ "MIT" ]
null
null
null
src/luanode_os.cpp
mkottman/LuaNode
b059225855939477147c5d4a6e8df3350c0a25fb
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "LuaNode.h" #include "luanode_os.h" #include <boost/bind.hpp> using namespace LuaNode; ////////////////////////////////////////////////////////////////////////// /// static void GetHostname_callback(lua_State* L, int callback, int result, std::string hostname) { lua_rawgeti(L, LUA_REGISTRYINDEX, callback); luaL_unref(L, LUA_REGISTRYINDEX, callback); if(result < 0) { lua_pushnil(L); lua_call(L, 1, 0); } else { lua_pushlstring(L, hostname.c_str(), hostname.length()); lua_call(L, 1, 0); } lua_settop(L, 0); } ////////////////////////////////////////////////////////////////////////// /// static int GetHostname(lua_State* L) { luaL_checktype(L, 1, LUA_TFUNCTION); int callback = luaL_ref(L, LUA_REGISTRYINDEX); char hostname[255]; // TODO: gethostname is blocking, should run it in some kind of thread pool int result = gethostname(hostname, 255); LuaNode::GetIoService().post( boost::bind(GetHostname_callback, L, callback, result, std::string(hostname)) ); return 0; } /*static int GetCurrentIP(lua_State* L) { WSADATA sockInfo; // information about Winsock HOSTENT hostinfo; // information about an Internet host CBString ipString; // holds a human-readable IP address string in_addr address; DWORD retval; // generic return value ipString = ""; // Get information about the domain specified in txtDomain. hostinfo = *gethostbyname(""); if(hostinfo.h_addrtype != AF_INET) { lua_pushnil(L); lua_pushstring(strerror(errno)); return 2; } else { // Convert the IP address into a human-readable string. memcpy(&address, hostinfo.h_addr_list[0], 4); ipString = inet_ntoa(address); } // Close the Winsock session. WSACleanup(); return ipString; }*/ ////////////////////////////////////////////////////////////////////////// /// void OS::RegisterFunctions(lua_State* L) { luaL_Reg methods[] = { { "getHostname", GetHostname }, { 0, 0 } }; luaL_register(L, "luanode.os", methods); lua_pop(L, 1); }
26.909091
112
0.602799
mkottman
52c71519541b07cb6c6547e0bed329b622ee47de
5,410
cpp
C++
test/unit/math/rev/mat/fun/quad_form_diag_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
test/unit/math/rev/mat/fun/quad_form_diag_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
test/unit/math/rev/mat/fun/quad_form_diag_test.cpp
jrmie/math
2850ec262181075a5843968e805dc9ad1654e069
[ "BSD-3-Clause" ]
null
null
null
#include <stan/math/rev/mat.hpp> #include <gtest/gtest.h> #include <test/unit/math/rev/mat/fun/expect_matrix_eq.hpp> #include <test/unit/math/rev/mat/util.hpp> #include <vector> using Eigen::Dynamic; using Eigen::Matrix; using stan::math::quad_form_diag; using stan::math::var; TEST(MathMatrix, quadFormDiag2_vv) { Matrix<var, Dynamic, Dynamic> m(3, 3); m << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix<var, Dynamic, 1> v(3); v << 1, 2, 3; Matrix<var, Dynamic, Dynamic> v_m(3, 3); v_m << 1, 0, 0, 0, 2, 0, 0, 0, 3; Matrix<var, Dynamic, Dynamic> v_m_times_m = multiply(v_m, multiply(m, v_m)); expect_matrix_eq(v_m_times_m, quad_form_diag(m, v)); Matrix<var, 1, Dynamic> rv(3); rv << 1, 2, 3; expect_matrix_eq(v_m_times_m, quad_form_diag(m, rv)); } TEST(MathMatrix, quadFormDiag2_vd) { Matrix<var, Dynamic, Dynamic> m1(3, 3); m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix<double, Dynamic, 1> v(3); v << 1, 2, 3; Matrix<var, Dynamic, Dynamic> v_m(3, 3); v_m << 1, 0, 0, 0, 2, 0, 0, 0, 3; Matrix<var, Dynamic, Dynamic> v_m_times_m1 = multiply(v_m, multiply(m1, v_m)); Matrix<var, Dynamic, Dynamic> m2(3, 3); m2 << 1, 2, 3, 4, 5, 6, 7, 8, 9; expect_matrix_eq(v_m_times_m1, quad_form_diag(m2, v)); } TEST(MathMatrix, quadFormDiag2_dv) { Matrix<double, Dynamic, Dynamic> m1(3, 3); m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix<var, Dynamic, 1> v(3); v << 1, 2, 3; Matrix<var, Dynamic, Dynamic> m2(3, 3); m2 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix<var, Dynamic, Dynamic> v_m(3, 3); v_m << 1, 0, 0, 0, 2, 0, 0, 0, 3; Matrix<var, Dynamic, Dynamic> v_m_times_m2 = multiply(v_m, multiply(m2, v_m)); expect_matrix_eq(v_m_times_m2, quad_form_diag(m1, v)); } TEST(MathMatrix, quadFormDiagGrad_vv) { Matrix<var, Dynamic, Dynamic> m1(3, 3); m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix<var, Dynamic, 1> v(3); v << 1, 2, 3; std::vector<var> xs1; for (int i = 0; i < 9; ++i) xs1.push_back(m1(i)); for (int i = 0; i < 3; ++i) xs1.push_back(v(i)); Matrix<var, Dynamic, Dynamic> v_post_multipy_m1 = quad_form_diag(m1, v); var norm1 = v_post_multipy_m1.norm(); std::vector<double> g1; norm1.grad(xs1, g1); Matrix<var, Dynamic, Dynamic> m2(3, 3); m2 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix<var, Dynamic, Dynamic> v_m(3, 3); v_m << 1, 0, 0, 0, 2, 0, 0, 0, 3; std::vector<var> xs2; for (int i = 0; i < 9; ++i) xs2.push_back(m2(i)); for (int i = 0; i < 3; ++i) xs2.push_back(v_m(i, i)); Matrix<var, Dynamic, Dynamic> m_times_vm = multiply(v_m, multiply(m2, v_m)); var norm2 = m_times_vm.norm(); std::vector<double> g2; norm2.grad(xs2, g2); EXPECT_EQ(g1.size(), g2.size()); for (size_t i = 0; i < g1.size(); ++i) EXPECT_FLOAT_EQ(g1[i], g2[i]); } TEST(MathMatrix, quadFormDiagGrad_vd) { Matrix<var, Dynamic, Dynamic> m1(3, 3); m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix<double, Dynamic, 1> v(3); v << 1, 2, 3; std::vector<var> xs1; for (int i = 0; i < 9; ++i) xs1.push_back(m1(i)); Matrix<var, Dynamic, Dynamic> m1_post_multipy_v = quad_form_diag(m1, v); var norm1 = m1_post_multipy_v.norm(); std::vector<double> g1; norm1.grad(xs1, g1); Matrix<var, Dynamic, Dynamic> m2(3, 3); m2 << 1, 2, 3, 4, 5, 6, 7, 8, 9; // OK to use var, just for comparison Matrix<var, Dynamic, Dynamic> v_m(3, 3); v_m << 1, 0, 0, 0, 2, 0, 0, 0, 3; std::vector<var> xs2; for (int i = 0; i < 9; ++i) xs2.push_back(m2(i)); Matrix<var, Dynamic, Dynamic> v_m_times_v_m = multiply(v_m, multiply(m2, v_m)); var norm2 = v_m_times_v_m.norm(); std::vector<double> g2; norm2.grad(xs2, g2); EXPECT_EQ(g1.size(), g2.size()); for (size_t i = 0; i < g1.size(); ++i) EXPECT_FLOAT_EQ(g1[i], g2[i]); } TEST(MathMatrix, quadFormDiagGrad_dv) { Matrix<double, Dynamic, Dynamic> m1(3, 3); m1 << 1, 2, 3, 4, 5, 6, 7, 8, 9; Matrix<var, Dynamic, 1> v(3); v << 1, 2, 3; std::vector<var> xs1; for (int i = 0; i < 3; ++i) xs1.push_back(v(i)); Matrix<var, Dynamic, Dynamic> m1_post_multipy_v = quad_form_diag(m1, v); var norm1 = m1_post_multipy_v.norm(); std::vector<double> g1; norm1.grad(xs1, g1); Matrix<var, Dynamic, Dynamic> m2(3, 3); m2 << 1, 2, 3, 4, 5, 6, 7, 8, 9; // OK to use var, just for comparison Matrix<var, Dynamic, Dynamic> v_m(3, 3); v_m << 1, 0, 0, 0, 2, 0, 0, 0, 3; std::vector<var> xs2; for (int i = 0; i < 3; ++i) xs2.push_back(v_m(i, i)); Matrix<var, Dynamic, Dynamic> v_m_times_v_m = multiply(v_m, multiply(m2, v_m)); var norm2 = v_m_times_v_m.norm(); std::vector<double> g2; norm2.grad(xs2, g2); EXPECT_EQ(g1.size(), g2.size()); for (size_t i = 0; i < g1.size(); ++i) EXPECT_FLOAT_EQ(g1[i], g2[i]); } TEST(MathMatrix, quadFormDiagException) { Matrix<var, Dynamic, Dynamic> m(2, 2); m << 2, 3, 4, 5; EXPECT_THROW(quad_form_diag(m, m), std::invalid_argument); Matrix<var, Dynamic, 1> v(3); v << 1, 2, 3; EXPECT_THROW(quad_form_diag(m, v), std::invalid_argument); } TEST(AgradRevMatrix, check_varis_on_stack) { using stan::math::to_var; stan::math::matrix_d m(3, 3); m << 1, 2, 3, 4, 5, 6, 7, 8, 9; stan::math::vector_d v(3); v << 1, 2, 3; test::check_varis_on_stack(stan::math::quad_form_diag(to_var(m), to_var(v))); test::check_varis_on_stack(stan::math::quad_form_diag(to_var(m), v)); test::check_varis_on_stack(stan::math::quad_form_diag(m, to_var(v))); }
25.280374
80
0.604621
jrmie
52ca9e57cc8f265da9e456b5a5e9b0745932b6c5
3,765
cc
C++
RecoEgamma/EgammaElectronAlgos/src/GsfElectronTools.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
1
2021-01-04T10:25:39.000Z
2021-01-04T10:25:39.000Z
RecoEgamma/EgammaElectronAlgos/src/GsfElectronTools.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
7
2016-07-17T02:34:54.000Z
2019-08-13T07:58:37.000Z
RecoEgamma/EgammaElectronAlgos/src/GsfElectronTools.cc
NTrevisani/cmssw
a212a27526f34eb9507cf8b875c93896e6544781
[ "Apache-2.0" ]
2
2019-09-27T08:33:22.000Z
2019-11-14T10:52:30.000Z
#include "DataFormats/EgammaCandidates/interface/GsfElectronCoreFwd.h" #include "DataFormats/EgammaCandidates/interface/GsfElectronCore.h" #include "DataFormats/ParticleFlowReco/interface/GsfPFRecTrack.h" #include "DataFormats/GsfTrackReco/interface/GsfTrack.h" #include "DataFormats/EgammaReco/interface/ElectronSeedFwd.h" #include "DataFormats/EgammaReco/interface/ElectronSeed.h" #include "RecoEgamma/EgammaElectronAlgos/interface/GsfElectronTools.h" namespace gsfElectronTools { using namespace reco; //======================================================================================= // Code from Puneeth Kalavase //======================================================================================= std::pair<TrackRef, float> getClosestCtfToGsf(GsfTrackRef const& gsfTrackRef, edm::Handle<reco::TrackCollection> const& ctfTracksH) { float maxFracShared = 0; TrackRef ctfTrackRef = TrackRef(); const TrackCollection* ctfTrackCollection = ctfTracksH.product(); // get the Hit Pattern for the gsfTrack const HitPattern& gsfHitPattern = gsfTrackRef->hitPattern(); unsigned int counter = 0; for (auto ctfTkIter = ctfTrackCollection->begin(); ctfTkIter != ctfTrackCollection->end(); ctfTkIter++, counter++) { double dEta = gsfTrackRef->eta() - ctfTkIter->eta(); double dPhi = gsfTrackRef->phi() - ctfTkIter->phi(); double pi = acos(-1.); if (std::abs(dPhi) > pi) dPhi = 2 * pi - std::abs(dPhi); // dont want to look at every single track in the event! if (sqrt(dEta * dEta + dPhi * dPhi) > 0.3) continue; unsigned int shared = 0; int gsfHitCounter = 0; int numGsfInnerHits = 0; int numCtfInnerHits = 0; // get the CTF Track Hit Pattern const HitPattern& ctfHitPattern = ctfTkIter->hitPattern(); for (auto elHitsIt = gsfTrackRef->recHitsBegin(); elHitsIt != gsfTrackRef->recHitsEnd(); elHitsIt++, gsfHitCounter++) { if (!((**elHitsIt).isValid())) //count only valid Hits { continue; } // look only in the pixels/TIB/TID uint32_t gsfHit = gsfHitPattern.getHitPattern(HitPattern::TRACK_HITS, gsfHitCounter); if (!(HitPattern::pixelHitFilter(gsfHit) || HitPattern::stripTIBHitFilter(gsfHit) || HitPattern::stripTIDHitFilter(gsfHit))) { continue; } numGsfInnerHits++; int ctfHitsCounter = 0; numCtfInnerHits = 0; for (auto ctfHitsIt = ctfTkIter->recHitsBegin(); ctfHitsIt != ctfTkIter->recHitsEnd(); ctfHitsIt++, ctfHitsCounter++) { if (!((**ctfHitsIt).isValid())) //count only valid Hits! { continue; } uint32_t ctfHit = ctfHitPattern.getHitPattern(HitPattern::TRACK_HITS, ctfHitsCounter); if (!(HitPattern::pixelHitFilter(ctfHit) || HitPattern::stripTIBHitFilter(ctfHit) || HitPattern::stripTIDHitFilter(ctfHit))) { continue; } numCtfInnerHits++; if ((**elHitsIt).sharesInput(&(**ctfHitsIt), TrackingRecHit::all)) { shared++; break; } } //ctfHits iterator } //gsfHits iterator if ((numGsfInnerHits == 0) || (numCtfInnerHits == 0)) { continue; } if (static_cast<float>(shared) / std::min(numGsfInnerHits, numCtfInnerHits) > maxFracShared) { maxFracShared = static_cast<float>(shared) / std::min(numGsfInnerHits, numCtfInnerHits); ctfTrackRef = TrackRef(ctfTracksH, counter); } } //ctfTrack iterator return make_pair(ctfTrackRef, maxFracShared); } } // namespace gsfElectronTools
36.911765
120
0.60664
NTrevisani
52ccdcbe5e920fbf1fbb9ed34c60f9e093e9a28e
2,692
cc
C++
src/test/play.cc
asveikau/audio
4b8978d5a7855a0ee62cd15b1dd76d35fb6c8290
[ "0BSD" ]
null
null
null
src/test/play.cc
asveikau/audio
4b8978d5a7855a0ee62cd15b1dd76d35fb6c8290
[ "0BSD" ]
null
null
null
src/test/play.cc
asveikau/audio
4b8978d5a7855a0ee62cd15b1dd76d35fb6c8290
[ "0BSD" ]
null
null
null
/* Copyright (C) 2017, 2018 Andrew Sveikauskas Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. */ #define __STDC_FORMAT_MACROS 1 #include <AudioCodec.h> #include <AudioPlayer.h> #include <common/logger.h> #include <stdio.h> #include <string> #include <string.h> #include <errno.h> #include <inttypes.h> #if defined(_WINDOWS) && !defined(PRId64) #define PRId64 "I64d" #endif #if defined(_WINDOWS) int wmain(int argc, wchar_t **argv) #else int main(int argc, char **argv) #endif { log_register_callback( [] (void *np, const char *p) -> void { fputs(p, stderr); }, nullptr ); error err; common::Pointer<common::Stream> file; common::Pointer<audio::Source> src; common::Pointer<audio::Player> player; FILE *f = nullptr; auto files = argv + 1; audio::MetadataReceiver recv; if (!*files) ERROR_SET(&err, unknown, "Usage: test file [file2 ...]"); recv.OnString = [] (audio::StringMetadata type, const std::function<void(std::string&, error*)> &parse, error *err) -> void { std::string str; parse(str, err); if (!ERROR_FAILED(err) && str.length()) { log_printf("Metadata: %s = %s", ToString(type), str.c_str()); } }; recv.OnInteger = [] (audio::IntegerMetadata type, const std::function<void(int64_t&, error*)> &parse, error *err) -> void { int64_t i = 0; parse(i, err); if (!ERROR_FAILED(err)) { log_printf("Metadata: %s = %" PRId64, ToString(type), i); } }; recv.OnBinaryData = [] (audio::BinaryMetadata type, const std::function<void(common::Stream**, error*)> &parse, error *err) -> void { log_printf("Metadata: binary data: %s", ToString(type)); }; audio::RegisterCodecs(); *player.GetAddressOf() = new audio::Player(); player->Initialize(nullptr, &err); ERROR_CHECK(&err); while (*files) { auto filename = *files++; #if defined(_WINDOWS) f = _wfopen(filename, L"rb"); #else f = fopen(filename, "rb"); #endif if (!f) ERROR_SET(&err, errno, errno); common::CreateStream(f, file.GetAddressOf(), &err); ERROR_CHECK(&err); f = nullptr; audio::CodecArgs args; args.Metadata = &recv; audio::OpenCodec(file.Get(), &args, src.GetAddressOf(), &err); ERROR_CHECK(&err); file = nullptr; player->SetSource(src.Get(), &err); ERROR_CHECK(&err); src = nullptr; while (player->Step(&err)); error_clear(&err); } exit: if (f) fclose(f); }
24.472727
134
0.61627
asveikau
52cd10b38babbb6c3d2dc420bf27509c87f84993
1,023
cpp
C++
lib/CAPI/Registration.cpp
sogartar/torch-mlir
19e9fc4ef12d7207eadd3dc9121aebe1555ea8dd
[ "Apache-2.0" ]
213
2021-09-24T03:26:53.000Z
2022-03-30T07:11:48.000Z
lib/CAPI/Registration.cpp
sogartar/torch-mlir
19e9fc4ef12d7207eadd3dc9121aebe1555ea8dd
[ "Apache-2.0" ]
247
2021-09-23T18:49:45.000Z
2022-03-31T17:19:02.000Z
lib/CAPI/Registration.cpp
sogartar/torch-mlir
19e9fc4ef12d7207eadd3dc9121aebe1555ea8dd
[ "Apache-2.0" ]
68
2021-09-23T18:23:20.000Z
2022-03-29T11:18:58.000Z
//===- Registration.cpp - C Interface for MLIR Registration ---------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // Also available under a BSD-style license. See LICENSE. // //===----------------------------------------------------------------------===// #include "torch-mlir-c/Registration.h" #include "mlir/CAPI/IR.h" #include "mlir/Conversion/Passes.h" #include "mlir/Dialect/Linalg/Passes.h" #include "mlir/Transforms/Passes.h" #include "torch-mlir/InitAll.h" void torchMlirRegisterAllDialects(MlirContext context) { mlir::DialectRegistry registry; mlir::torch::registerAllDialects(registry); unwrap(context)->appendDialectRegistry(registry); // TODO: Don't eagerly load once D88162 is in and clients can do this. unwrap(context)->loadAllAvailableDialects(); } void torchMlirRegisterAllPasses() { mlir::torch::registerAllPasses(); }
37.888889
80
0.685239
sogartar
52cfb9fe811594b8ba48bea176f983827194ac2a
500
cpp
C++
widget/labeltest.cpp
malaise/xfreecell
b44169ac15e82f7cbc5379f8ba8b818e9faab611
[ "Unlicense" ]
1
2021-05-01T16:29:08.000Z
2021-05-01T16:29:08.000Z
widget/labeltest.cpp
malaise/xfreecell
b44169ac15e82f7cbc5379f8ba8b818e9faab611
[ "Unlicense" ]
null
null
null
widget/labeltest.cpp
malaise/xfreecell
b44169ac15e82f7cbc5379f8ba8b818e9faab611
[ "Unlicense" ]
null
null
null
#include "widget.h" class TestFrame : public NSFrame { public: TestFrame() : l(""), con(100, 100) { con.add(&l); container(&con); selectInput(ButtonPressMask); } void dispatchEvent(const XEvent&); private: NSLabel l; NSHContainer con; }; void TestFrame::dispatchEvent(const XEvent& ev) { static string str(""); if (ev.type == ButtonPress) { str += 'a'; l.label(str.c_str()); } } int main() { NSInitialize(); TestFrame tf; tf.map(); NSMainLoop(); return 0; }
13.888889
100
0.624
malaise
52d5c3901c7c91fb3eb05603d5b90304ae678533
1,574
hpp
C++
extra/fuzzer/fuzzer_input.hpp
ikrima/immer
2076affd9d814afc019ba8cd8c2b18a6c79c9589
[ "BSL-1.0" ]
1,964
2016-11-19T19:04:31.000Z
2022-03-31T16:31:00.000Z
extra/fuzzer/fuzzer_input.hpp
ikrima/immer
2076affd9d814afc019ba8cd8c2b18a6c79c9589
[ "BSL-1.0" ]
180
2016-11-26T22:46:10.000Z
2022-03-10T10:23:57.000Z
extra/fuzzer/fuzzer_input.hpp
ikrima/immer
2076affd9d814afc019ba8cd8c2b18a6c79c9589
[ "BSL-1.0" ]
133
2016-11-27T17:33:20.000Z
2022-03-07T03:12:49.000Z
// // immer: immutable data structures for C++ // Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente // // This software is distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt // #pragma once #include <cstdint> #include <memory> #include <stdexcept> struct no_more_input : std::exception {}; constexpr auto fuzzer_input_max_size = 1 << 16; struct fuzzer_input { const std::uint8_t* data_; std::size_t size_; const std::uint8_t* next(std::size_t size) { if (size_ < size) throw no_more_input{}; auto r = data_; data_ += size; size_ -= size; return r; } const std::uint8_t* next(std::size_t size, std::size_t align) { auto& p = const_cast<void*&>(reinterpret_cast<const void*&>(data_)); auto r = std::align(align, size, p, size_); if (r == nullptr) throw no_more_input{}; return next(size); } template <typename Fn> int run(Fn step) { if (size_ > fuzzer_input_max_size) return 0; try { while (step(*this)) continue; } catch (const no_more_input&) {}; return 0; } }; template <typename T> const T& read(fuzzer_input& fz) { return *reinterpret_cast<const T*>(fz.next(sizeof(T), alignof(T))); } template <typename T, typename Cond> T read(fuzzer_input& fz, Cond cond) { auto x = read<T>(fz); while (!cond(x)) x = read<T>(fz); return x; }
22.169014
78
0.593393
ikrima
52d5c7ede2e434650fd1b93c18f3793368b04d45
1,278
hpp
C++
bark/world/prediction/prediction_settings.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
bark/world/prediction/prediction_settings.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
bark/world/prediction/prediction_settings.hpp
GAIL-4-BARK/bark
1cfda9ba6e9ec5318fbf01af6b67c242081b516e
[ "MIT" ]
null
null
null
// Copyright (c) 2020 Julian Bernhard, Klemens Esterle, Patrick Hart and // Tobias Kessler // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #ifndef BARK_WORLD_PREDICTION_HPP_ #define BARK_WORLD_PREDICTION_HPP_ #include <unordered_map> #include <typeinfo> #include "bark/models/behavior/behavior_model.hpp" namespace bark { namespace world { class ObservedWorld; typedef std::shared_ptr<ObservedWorld> ObservedWorldPtr; namespace prediction { using world::objects::AgentId; using models::behavior::BehaviorModelPtr; struct PredictionSettings { PredictionSettings() : ego_prediction_model_(), others_prediction_model_() {} PredictionSettings(const BehaviorModelPtr& ego_prediction, const BehaviorModelPtr& others_prediction); virtual ~PredictionSettings() {} BehaviorModelPtr GetEgoPredictionModel() const { return ego_prediction_model_;} BehaviorModelPtr GetOthersPredictionModel() const { return others_prediction_model_;} void ApplySettings(ObservedWorld& observed_world) const; BehaviorModelPtr ego_prediction_model_; BehaviorModelPtr others_prediction_model_; }; } // namespace prediction } // namespace world } // namespace bark #endif // BARK_WORLD_PREDICTION_HPP_
27.191489
104
0.796557
GAIL-4-BARK
52dd178f146251eb972d9851384f266eaaaed542
3,283
cpp
C++
src/wsjcpp_package_downloader_http.cpp
AndreyTomsk/wsjcpp
ea8e149b71e3bece3a6a930d2c9fcdf4d6c93300
[ "MIT" ]
null
null
null
src/wsjcpp_package_downloader_http.cpp
AndreyTomsk/wsjcpp
ea8e149b71e3bece3a6a930d2c9fcdf4d6c93300
[ "MIT" ]
null
null
null
src/wsjcpp_package_downloader_http.cpp
AndreyTomsk/wsjcpp
ea8e149b71e3bece3a6a930d2c9fcdf4d6c93300
[ "MIT" ]
null
null
null
#include "wsjcpp_package_downloader_http.h" #include <wsjcpp_core.h> #include <wsjcpp_package_manager.h> // --------------------------------------------------------------------- // WsjcppPackageDownloaderHttp WsjcppPackageDownloaderHttp::WsjcppPackageDownloaderHttp() : WsjcppPackageDownloaderBase("http") { TAG = "WsjcppPackageDownloaderHttp"; m_sHttpPrefix = "http://"; // from some http:// m_sHttpsPrefix = "https://"; } // --------------------------------------------------------------------- bool WsjcppPackageDownloaderHttp::canDownload(const std::string &sPackage) { return sPackage.compare(0, m_sHttpPrefix.size(), m_sHttpPrefix) == 0 || sPackage.compare(0, m_sHttpsPrefix.size(), m_sHttpsPrefix) == 0; } // --------------------------------------------------------------------- bool WsjcppPackageDownloaderHttp::downloadToCache( const std::string &sPackage, const std::string &sCacheDir, WsjcppPackageManagerDependence &dep, std::string &sError ) { std::cout << "Download package from " << sPackage << " ..." << std::endl; std::string sWsjcppBaseUrl = sPackage; std::string sDownloadedWsjCppYml = sCacheDir + "/wsjcpp.hold.yml"; if (!WsjcppPackageDownloaderBase::downloadFileOverHttps(sWsjcppBaseUrl + "/wsjcpp.yml", sDownloadedWsjCppYml)) { sError = "Could not download " + sWsjcppBaseUrl; // TODO remove from cache return false; } WsjcppPackageManager pkg(sCacheDir, sCacheDir, true); if (!pkg.load()) { sError = "Could not load " + sCacheDir; return false; } // sources std::vector<WsjcppPackageManagerDistributionFile> vSources = pkg.getListOfDistributionFiles(); for (int i = 0; i < vSources.size(); i++) { WsjcppPackageManagerDistributionFile src = vSources[i]; std::string sDownloadedWsjCppSourceFrom = sWsjcppBaseUrl + "/" + src.getSourceFile(); std::string sDownloadedWsjCppSourceTo = sCacheDir + "/" + src.getTargetFile(); WsjcppLog::info(TAG, "\n\t" + sDownloadedWsjCppSourceFrom + " \n\t-> \n\t" + sDownloadedWsjCppSourceTo + "\n\t[sha1:" + src.getSha1() + "]"); if (!WsjcppPackageDownloaderBase::downloadFileOverHttps(sDownloadedWsjCppSourceFrom, sDownloadedWsjCppSourceTo)) { sError = "Could not download " + sDownloadedWsjCppSourceFrom; // TODO remove from cache return false; } std::string sContent = ""; if (!WsjcppCore::readTextFile(sDownloadedWsjCppSourceTo, sContent)) { sError = "Could not read file " + sDownloadedWsjCppSourceTo; return false; } // TODO set calculated sha1 // std::string sSha1 = WsjcppHashes::sha1_calc_hex(sContent); // src.setSha1(sSha1); } std::string sInstallationDir = "./src.wsjcpp/" + WsjcppPackageDownloaderBase::prepareCacheSubFolderName(pkg.getName()); // WsjcppPackageManagerDependence dep; dep.setName(pkg.getName()); dep.setVersion(pkg.getVersion()); dep.setUrl(sPackage); dep.setInstallationDir(sInstallationDir); dep.setOrigin("https://github.com/"); // TODO remove "package-name/version" return true; } // ---------------------------------------------------------------------
39.554217
149
0.614986
AndreyTomsk
52e05e3ae44e9d09543791e7ea859f32e9b44edf
1,840
cpp
C++
GTE/Graphics/GL45/GL45Texture1.cpp
Cadcorp/GeometricTools
5fc64438e05dfb5a2b179eb20e02bb4ed9ddc224
[ "BSL-1.0" ]
null
null
null
GTE/Graphics/GL45/GL45Texture1.cpp
Cadcorp/GeometricTools
5fc64438e05dfb5a2b179eb20e02bb4ed9ddc224
[ "BSL-1.0" ]
1
2021-04-07T09:16:45.000Z
2021-04-07T09:16:45.000Z
GTE/Graphics/GL45/GL45Texture1.cpp
Cadcorp/GeometricTools
5fc64438e05dfb5a2b179eb20e02bb4ed9ddc224
[ "BSL-1.0" ]
null
null
null
// David Eberly, Geometric Tools, Redmond WA 98052 // Copyright (c) 1998-2020 // Distributed under the Boost Software License, Version 1.0. // https://www.boost.org/LICENSE_1_0.txt // https://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // Version: 4.0.2019.08.13 #include <Graphics/GL45/GTGraphicsGL45PCH.h> #include <Graphics/GL45/GL45Texture1.h> using namespace gte; GL45Texture1::~GL45Texture1() { glDeleteTextures(1, &mGLHandle); } GL45Texture1::GL45Texture1(Texture1 const* texture) : GL45TextureSingle(texture, GL_TEXTURE_1D, GL_TEXTURE_BINDING_1D) { // Create a texture structure. glGenTextures(1, &mGLHandle); glBindTexture(GL_TEXTURE_1D, mGLHandle); // Allocate (immutable) texture storage for all levels. auto const length = texture->GetDimension(0); glTexStorage1D(GL_TEXTURE_1D, mNumLevels, mInternalFormat, length); Initialize(); // Cannot leave this texture bound. glBindTexture(GL_TEXTURE_1D, 0); // Create a staging texture if requested. CreateStaging(); } std::shared_ptr<GEObject> GL45Texture1::Create(void*, GraphicsObject const* object) { if (object->GetType() == GT_TEXTURE1) { return std::make_shared<GL45Texture1>( static_cast<Texture1 const*>(object)); } LogError("Invalid object type."); } bool GL45Texture1::CanAutoGenerateMipmaps() const { auto texture = GetTexture(); return texture && texture->HasMipmaps() && texture->WantAutogenerateMipmaps(); } void GL45Texture1::LoadTextureLevel(unsigned int level, void const* data) { auto texture = GetTexture(); if (texture && level < texture->GetNumLevels()) { auto length = texture->GetDimensionFor(level, 0); glTexSubImage1D(GL_TEXTURE_1D, level, 0, length, mExternalFormat, mExternalType, data); } }
27.462687
83
0.704891
Cadcorp
52e33869b7ac78e50ed4222379d2b598741c2b78
1,677
cc
C++
Fireworks/Core/src/FWSimpleProxyHelper.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
Fireworks/Core/src/FWSimpleProxyHelper.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
Fireworks/Core/src/FWSimpleProxyHelper.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
// -*- C++ -*- // // Package: Core // Class : FWSimpleProxyHelper // // Implementation: // <Notes on implementation> // // Original Author: Chris Jones // Created: Tue Dec 2 15:13:22 EST 2008 // // system include files #include <sstream> #include <cassert> #include "FWCore/Utilities/interface/ObjectWithDict.h" #include "FWCore/Utilities/interface/TypeWithDict.h" #include "TClass.h" // user include files #include "Fireworks/Core/interface/FWSimpleProxyHelper.h" #include "Fireworks/Core/interface/FWEventItem.h" // // constants, enums and typedefs // // // static data member definitions // // // constructors and destructor // FWSimpleProxyHelper::FWSimpleProxyHelper(const std::type_info& iType) : m_itemType(&iType), m_objectOffset(0) { } // FWSimpleProxyHelper::FWSimpleProxyHelper(const FWSimpleProxyHelper& rhs) // { // // do actual copying here; // } //FWSimpleProxyHelper::~FWSimpleProxyHelper() //{ //} // // assignment operators // // const FWSimpleProxyHelper& FWSimpleProxyHelper::operator=(const FWSimpleProxyHelper& rhs) // { // //An exception safe implementation is // FWSimpleProxyHelper temp(rhs); // swap(rhs); // // return *this; // } // // member functions // void FWSimpleProxyHelper::itemChanged(const FWEventItem* iItem) { if(nullptr!=iItem) { edm::TypeWithDict baseType(*m_itemType); edm::TypeWithDict mostDerivedType(*(iItem->modelType()->GetTypeInfo())); // The - sign is there because this is the address of a derived object minus the address of the base object. m_objectOffset = -mostDerivedType.getBaseClassOffset(baseType); } } // // static member functions //
20.703704
114
0.697078
nistefan
52e43a8fa579a3887f64b378136869e1d662bc0a
970
hpp
C++
render/camera.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
render/camera.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
render/camera.hpp
vasukas/rodent
91224465eaa89467916971a8c5ed1357fa487bdf
[ "FTL", "CC0-1.0", "CC-BY-4.0", "MIT" ]
null
null
null
#ifndef CAMERA_HPP #define CAMERA_HPP #include "vaslib/vas_math.hpp" class Camera final { public: struct Frame { vec2fp pos = {}; ///< Center position float rot = 0.f; ///< Rotation (radians) float mag = 1.f; ///< Magnification factor }; void set_state(Frame frm); const Frame& get_state() const {return cur;} Frame& mut_state(); void set_vport(Rect vp); void set_vport_full(); ///< Sets full window viewport const Rect& get_vport() const {return vport;} const float* get_full_matrix() const; ///< Returns 4x4 OpenGL projection & view matrix vec2fp mouse_cast(vec2i mou) const; ///< Returns world position from screen coords vec2i direct_cast(vec2fp p) const; ///< Returns screen coords from world position vec2fp coord_size() const; ///< Returns size of viewport in coordinates private: Rect vport = {}; Frame cur; mutable float mx_full[16]; mutable float mx_rev[16]; mutable int mx_req_upd = 3; }; #endif // CAMERA_HPP
23.095238
87
0.698969
vasukas
52eb51c0a9e46fca77c5688bceb55ba918a7d598
150
cpp
C++
Spaceship/chunk.cpp
KYHSGeekCode/Spaceship
9752dbcae95cdce188d319f4f71d3b788c3d991d
[ "Apache-2.0" ]
1
2018-12-08T03:02:03.000Z
2018-12-08T03:02:03.000Z
Spaceship/chunk.cpp
KYHSGeekCode/Spaceship
9752dbcae95cdce188d319f4f71d3b788c3d991d
[ "Apache-2.0" ]
null
null
null
Spaceship/chunk.cpp
KYHSGeekCode/Spaceship
9752dbcae95cdce188d319f4f71d3b788c3d991d
[ "Apache-2.0" ]
null
null
null
#if 0 //chunk.cpp #include "terrain.h" terunit Chunk::GetHeight(terunit x, terunit z) { world.WorldToChunkCoord(this,&x,&z); return 0; }w/ #endif
12.5
46
0.693333
KYHSGeekCode
52ec98c956f21b6c9dc93e765d7c5eb68c593b80
594
cpp
C++
C++/brokenswords.cpp
AllysonWindell/Kattis
5ce1aa108e21416bdf52993ea3bfb5bb86405980
[ "Unlicense" ]
19
2019-09-20T19:08:24.000Z
2022-03-17T11:54:57.000Z
C++/brokenswords.cpp
AllysonWindell/Kattis
5ce1aa108e21416bdf52993ea3bfb5bb86405980
[ "Unlicense" ]
2
2020-11-06T06:40:40.000Z
2021-01-24T08:55:32.000Z
C++/brokenswords.cpp
AllysonWindell/Kattis
5ce1aa108e21416bdf52993ea3bfb5bb86405980
[ "Unlicense" ]
18
2019-08-18T03:51:35.000Z
2021-11-23T04:12:29.000Z
#include <bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(0); int cases, tb = 0, lr = 0; cin >> cases; while (cases-- > 0) { char c; for (int x = 0; x < 2; x++) { cin >> c; if (c == '0') tb++; } for (int x = 0; x < 2; x++) { cin >> c; if (c == '0') lr++; } } int swords = min(tb / 2, lr / 2); int dsword = swords * 2; cout << swords << ' ' << tb - dsword << ' ' << lr - dsword; return 0; }
22
63
0.373737
AllysonWindell
52ee0a7ba587d97104ff0c034c6ab11eb9e79046
676
cpp
C++
contests/Codeforces Round #607 Div 2/Azamon_web_services.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
2
2020-08-27T18:21:04.000Z
2020-08-30T13:24:39.000Z
contests/Codeforces Round #607 Div 2/Azamon_web_services.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
null
null
null
contests/Codeforces Round #607 Div 2/Azamon_web_services.cpp
Razdeep/Codeforces-Solutions
e808575219ec15bc07720d6abafe3c4c8df036f4
[ "MIT" ]
null
null
null
// https://codeforces.com/contest/1281/problem/B #include <iostream> using namespace std; int main() { int tc; cin >> tc; while (tc--) { string me, opponent; cin >> me >> opponent; // Getting smallest lexigraphical string of mine int position; char min_char_so_far; for (int i = 0; i < int(me.size()); ++i) { min_char_so_far = me[i]; position = i; for (int j = i + 1; j < int(me.size()); ++j) { if (me[j] <= min_char_so_far) { min_char_so_far = me[j]; position = j; } } if (min_char_so_far < me[i]) { swap(me[position], me[i]); break; } } cout << (me < opponent ? me : "---") << endl; } return 0; }
18.777778
50
0.553254
Razdeep
52ee55a041b6963ce9c2694cb5d1fc9ca1354771
693
hh
C++
TFM/click-2.0.1/elements/wifi/station/proberequester.hh
wangyang2013/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
3
2018-04-14T14:43:31.000Z
2019-12-06T13:09:58.000Z
TFM/click-2.0.1/elements/wifi/station/proberequester.hh
nfvproject/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
null
null
null
TFM/click-2.0.1/elements/wifi/station/proberequester.hh
nfvproject/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
null
null
null
#ifndef CLICK_PROBEREQUESTER_HH #define CLICK_PROBEREQUESTER_HH #include <click/element.hh> #include <click/etheraddress.hh> CLICK_DECLS class ProbeRequester : public Element { public: ProbeRequester(); ~ProbeRequester(); const char *class_name() const { return "ProbeRequester"; } const char *port_count() const { return PORTS_0_1; } const char *processing() const { return PUSH; } int configure(Vector<String> &, ErrorHandler *); bool can_live_reconfigure() const { return true; } void add_handlers(); void send_probe_request(); bool _debug; EtherAddress _eth; class AvailableRates *_rtable; class WirelessInfo *_winfo; private: }; CLICK_ENDDECLS #endif
20.382353
61
0.74026
wangyang2013
52f1b033de71c4ba54765f24466137a82b890903
3,448
cpp
C++
MSCL/source/mscl/Communication/WsdaFinder.cpp
offworld-projects/MSCL
8388e97c92165e16c26c554aadf1e204ebcf93cf
[ "BSL-1.0", "OpenSSL", "MIT" ]
53
2015-08-28T02:41:41.000Z
2022-03-03T07:50:53.000Z
MSCL/source/mscl/Communication/WsdaFinder.cpp
offworld-projects/MSCL
8388e97c92165e16c26c554aadf1e204ebcf93cf
[ "BSL-1.0", "OpenSSL", "MIT" ]
209
2015-09-30T19:36:11.000Z
2022-03-04T21:52:20.000Z
MSCL/source/mscl/Communication/WsdaFinder.cpp
offworld-projects/MSCL
8388e97c92165e16c26c554aadf1e204ebcf93cf
[ "BSL-1.0", "OpenSSL", "MIT" ]
55
2015-09-03T14:40:01.000Z
2022-02-04T02:02:01.000Z
/******************************************************************************* Copyright(c) 2015-2021 Parker Hannifin Corp. All rights reserved. MIT Licensed. See the included LICENSE.txt for a copy of the full MIT License. *******************************************************************************/ #include "stdafx.h" #include "WsdaFinder.h" #include <tchar.h> namespace mscl { WsdaInfo::WsdaInfo() { } WsdaInfo::WsdaInfo(std::string url, std::string serial) : m_url(url), m_serial(serial) { } std::string WsdaInfo::ipAddress() const { size_t pathStart = std::string::npos; size_t serviceEnd = std::string::npos; if((serviceEnd = m_url.find("://")) != std::string::npos) { pathStart = m_url.find_first_of("/?", serviceEnd + 3); if(pathStart != std::string::npos) { return m_url.substr(serviceEnd + 3, pathStart - (serviceEnd + 3)); } } return ""; } uint16 WsdaInfo::port() const { return 5000; } std::string WsdaInfo::name() const { return m_serial; } WsdaFinder::WsdaFinder() { start(); } WsdaFinder::~WsdaFinder() { m_upnpService.reset(nullptr); if(m_upnpSearchCallback) { m_upnpSearchCallback->Release(); } } void WsdaFinder::start() { m_upnpSearchCallback.reset(new UpnpDeviceFinderCallback()); m_upnpSearchCallback->AddRef(); m_upnpSearchCallback->bindSearchComplete(std::bind(&WsdaFinder::onSearchComplete, this)); m_upnpSearchCallback->bindDeviceAdded(std::bind(&WsdaFinder::onDeviceAdded, this, std::placeholders::_1)); m_upnpService.reset(new UpnpService(*m_upnpSearchCallback, L"urn:www-microstrain-com:device:wsda:1")); } void WsdaFinder::onSearchComplete() { //Note: this search complete callback doesn't actually indicate the process has stopped - // just that it has completed the search for the devices that were already attached when // starting the search. Any new add/remove notifications will still fire. std::unique_lock<std::mutex> lock(m_wsdaMapMutex); m_foundWsdas = m_tempWsdas; m_tempWsdas.clear(); //tell the upnp service to start the search again m_upnpService->setSearchComplete(); } void WsdaFinder::onDeviceAdded(const UpnpDevice& device) { static const std::string ACCEPTED_MODEL_NAME = "WSDA"; int comp = device.modelName.compare(ACCEPTED_MODEL_NAME); if(comp == 0) { std::unique_lock<std::mutex> lock(m_wsdaMapMutex); //add/update the found wsda list, and the temp list m_tempWsdas[device.uniqueDeviceName] = WsdaInfo(device.presentationUrl, device.serialNumber); m_foundWsdas[device.uniqueDeviceName] = WsdaInfo(device.presentationUrl, device.serialNumber); } } WsdaFinder::WsdaMap WsdaFinder::found() { std::unique_lock<std::mutex> lock(m_wsdaMapMutex); //return a copy of the found wsdas return m_foundWsdas; } void WsdaFinder::restart() { std::unique_lock<std::mutex> lock(m_wsdaMapMutex); m_tempWsdas.clear(); m_foundWsdas.clear(); m_upnpService->restartSearch(); } }
29.220339
114
0.587877
offworld-projects
52f1f842f9412a6cdc4292c9b48deb8c23b6f393
15,437
cpp
C++
Framework/Sources/o2/Scene/UI/WidgetLayer.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
181
2015-12-09T08:53:36.000Z
2022-03-26T20:48:39.000Z
Framework/Sources/o2/Scene/UI/WidgetLayer.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
29
2016-04-22T08:24:04.000Z
2022-03-06T07:06:28.000Z
Framework/Sources/o2/Scene/UI/WidgetLayer.cpp
zenkovich/o2
cdbf10271f1bf0f3198c8005b13b66e6ca13a9db
[ "MIT" ]
13
2018-04-24T17:12:04.000Z
2021-11-12T23:49:53.000Z
#include "o2/stdafx.h" #include "WidgetLayer.h" #include "o2/Scene/UI/Widget.h" #include "o2/Scene/UI/WidgetLayout.h" #include "o2/Scene/Scene.h" namespace o2 { WidgetLayer::WidgetLayer(): layout(this), interactableLayout(Vec2F(), Vec2F(1.0f, 1.0f), Vec2F(), Vec2F()), mUID(Math::Random()) {} WidgetLayer::WidgetLayer(const WidgetLayer& other): mDepth(other.mDepth), name(other.name), layout(this, other.layout), mTransparency(other.mTransparency), interactableLayout(other.interactableLayout), mUID(Math::Random()), depth(this), transparency(this) { if (other.mCopyVisitor) other.mCopyVisitor->OnCopy(&other, this); if (other.mDrawable) { mDrawable = other.mDrawable->CloneAs<IRectDrawable>(); mDrawable->SetSerializeEnabled(false); } for (auto child : other.mChildren) { child->mCopyVisitor = other.mCopyVisitor; AddChild(child->CloneAs<WidgetLayer>()); child->mCopyVisitor = nullptr; } } WidgetLayer::~WidgetLayer() { if (mParent) mParent->RemoveChild(this, false); else if (mOwnerWidget) mOwnerWidget->RemoveLayer(this, false); delete mDrawable; for (auto child : mChildren) { child->mParent = nullptr; child->SetOwnerWidget(nullptr); delete child; } mChildren.Clear(); } WidgetLayer& WidgetLayer::operator=(const WidgetLayer& other) { delete mDrawable; for (auto child : mChildren) delete child; mChildren.Clear(); mDrawable = nullptr; mDepth = other.mDepth; name = other.name; if (other.mDrawable) { mDrawable = other.mDrawable->CloneAs<IRectDrawable>(); mDrawable->SetSerializeEnabled(false); } for (auto child : other.mChildren) AddChild(child->CloneAs<WidgetLayer>()); SetTransparency(other.mTransparency); if (mOwnerWidget) mOwnerWidget->UpdateLayersDrawingSequence(); return *this; } Widget* WidgetLayer::GetOwnerWidget() const { if (mOwnerWidget) return mOwnerWidget; return mParent->GetOwnerWidget(); } const WidgetLayer* WidgetLayer::GetPrototypeLink() const { return mPrototypeLink; } void WidgetLayer::SetDrawable(IRectDrawable* drawable) { mDrawable = drawable; if (mDrawable) mDrawable->SetSerializeEnabled(false); if (mOwnerWidget) { mOwnerWidget->UpdateLayersDrawingSequence(); mOwnerWidget->UpdateTransform(); } } IRectDrawable* WidgetLayer::GetDrawable() const { return mDrawable; } void WidgetLayer::Draw() { if (mEnabled && mResTransparency > FLT_EPSILON) mDrawable->Draw(); } bool WidgetLayer::IsEnabled() const { return mEnabled; } bool WidgetLayer::IsEnabledInHierarchy() const { bool parentEnabled = mOwnerWidget ? mOwnerWidget->IsEnabledInHierarchy() : mParent->IsEnabledInHierarchy(); return mEnabled && parentEnabled; } void WidgetLayer::SetEnabled(bool enabled) { mEnabled = enabled; } WidgetLayer* WidgetLayer::AddChild(WidgetLayer* layer) { if (layer->mParent) layer->mParent->RemoveChild(layer, false); else if (layer->mOwnerWidget) layer->mOwnerWidget->RemoveLayer(layer, false); layer->mParent = this; mChildren.Add(layer); layer->SetOwnerWidget(mOwnerWidget); if (mOwnerWidget) { mOwnerWidget->OnLayerAdded(layer); mOwnerWidget->UpdateLayersDrawingSequence(); } if constexpr (IS_EDITOR) { o2Scene.OnObjectChanged(this); o2Scene.OnObjectChanged(layer); } return layer; } void WidgetLayer::RemoveChild(WidgetLayer* layer, bool release /*= true*/) { if (!layer) return; layer->mParent = nullptr; mChildren.Remove(layer); auto lastOwnerWidget = layer->mOwnerWidget; layer->SetOwnerWidget(nullptr); if (release) delete layer; if (lastOwnerWidget) lastOwnerWidget->UpdateLayersDrawingSequence(); if constexpr (IS_EDITOR) o2Scene.OnObjectChanged(this); } void WidgetLayer::RemoveAllChildren() { for (auto child : mChildren) { child->mParent = nullptr; child->SetOwnerWidget(nullptr); delete child; } mChildren.Clear(); if constexpr (IS_EDITOR) o2Scene.OnObjectChanged(this); } void WidgetLayer::SetParent(WidgetLayer* parent) { if (parent) parent->AddChild(this); else { if (mParent) mParent->RemoveChild(this, false); mParent = nullptr; SetOwnerWidget(nullptr); } } WidgetLayer* WidgetLayer::GetParent() const { return mParent; } Vector<WidgetLayer*>& WidgetLayer::GetChildren() { return mChildren; } const Vector<WidgetLayer*>& o2::WidgetLayer::GetChildren() const { return mChildren; } void WidgetLayer::SerializeBasicOverride(DataValue& node) const { if (mPrototypeLink) SerializeWithProto(node); else SerializeRaw(node); OnSerialize(node); } void WidgetLayer::DeserializeBasicOverride(const DataValue& node) { if (node.FindMember("PrototypeLink")) DeserializeWithProto(node); else DeserializeRaw(node); OnDeserialized(node); } void WidgetLayer::SerializeRaw(DataValue& node) const { SerializeBasic(node); if (!mChildren.IsEmpty()) node["Children"] = mChildren; } void WidgetLayer::DeserializeRaw(const DataValue& node) { DeserializeBasic(node); if (auto childrenNode = node.FindMember("Children")) { for (auto& childNode : *childrenNode) { auto layer = mnew WidgetLayer(); AddChild(layer); layer->Deserialize(childNode["Value"]); } } } void WidgetLayer::SerializeWithProto(DataValue& node) const { SerializeDelta(node, *mPrototypeLink); node["PrototypeLink"] = mPrototypeLink->mUID; if (!mChildren.IsEmpty()) { auto& childrenNode = node.AddMember("Children"); childrenNode.SetArray(); for (auto child : mChildren) child->Serialize(childrenNode.AddElement()); } } void WidgetLayer::DeserializeWithProto(const DataValue& node) { if (auto protoNode = node.FindMember("PrototypeLink")) { SceneUID protoUID = *protoNode; if (mParent && mParent->mPrototypeLink) { for (auto protoChild : mParent->mPrototypeLink->mChildren) { if (protoChild->mUID == protoUID) { mPrototypeLink = protoChild; break; } } } else if (mOwnerWidget->mPrototypeLink) { for (auto protoChild : dynamic_cast<Widget*>(mOwnerWidget->mPrototypeLink.Get())->mLayers) { if (protoChild->mUID == protoUID) { mPrototypeLink = protoChild; break; } } } } if (mPrototypeLink) DeserializeDelta(node, *mPrototypeLink); else DeserializeBasic(node); if (auto childrenNode = node.FindMember("Children")) { for (auto& childNode : *childrenNode) { auto layer = mnew WidgetLayer(); AddChild(layer); layer->Deserialize(childNode); } } } void WidgetLayer::OnDeserialized(const DataValue& node) { for (auto child : mChildren) { child->mParent = this; child->mOwnerWidget = mOwnerWidget; } if (mDrawable) mDrawable->SetSerializeEnabled(false); } void WidgetLayer::OnDeserializedDelta(const DataValue& node, const IObject& origin) { OnDeserialized(node); } WidgetLayer* WidgetLayer::AddChildLayer(const String& name, IRectDrawable* drawable, const Layout& layout /*= Layout::Both()*/, float depth /*= 0.0f*/) { if (Math::Equals(depth, 0.0f)) depth = (float)mOwnerWidget->mDrawingLayers.Count(); WidgetLayer* layer = mnew WidgetLayer(); layer->depth = depth; layer->name = name; layer->mDrawable = drawable; layer->layout = layout; return AddChild(layer); } WidgetLayer* WidgetLayer::GetChild(const String& path) { int delPos = path.Find("/"); WString pathPart = path.SubStr(0, delPos); if (pathPart == "..") { if (mParent) { if (delPos == -1) return mParent; else return mParent->GetChild(path.SubStr(delPos + 1)); } return nullptr; } for (auto child : mChildren) { if (child->name == pathPart) { if (delPos == -1) return child; else return child->GetChild(path.SubStr(delPos + 1)); } } return nullptr; } WidgetLayer* WidgetLayer::FindChild(const String& name) { for (auto child : mChildren) { if (child->name == name) return child; WidgetLayer* layer = child->FindChild(name); if (layer) return layer; } return nullptr; } Vector<WidgetLayer*> WidgetLayer::GetAllChilds() const { Vector<WidgetLayer*> res = mChildren; for (auto child : mChildren) { res.Add(child->GetAllChilds()); } return res; } void WidgetLayer::SetDepth(float depth) { mDepth = depth; if (mOwnerWidget) mOwnerWidget->UpdateLayersDrawingSequence(); } float WidgetLayer::GetDepth() const { return mDepth; } void WidgetLayer::SetTransparency(float transparency) { mTransparency = transparency; UpdateResTransparency(); } float WidgetLayer::GetTransparency() { return mTransparency; } float WidgetLayer::GetResTransparency() const { return mResTransparency; } bool WidgetLayer::IsUnderPoint(const Vec2F& point) { return mInteractableArea.IsInside(point); } const RectF& WidgetLayer::GetRect() const { return mAbsolutePosition; } void WidgetLayer::SetOwnerWidget(Widget* owner) { mOwnerWidget = owner; if constexpr (IS_EDITOR) { if (Scene::IsSingletonInitialzed()) { if (mOwnerWidget && mOwnerWidget->IsOnScene()) o2Scene.AddEditableObjectToScene(this); else o2Scene.RemoveEditableObjectFromScene(this); } } for (auto child : mChildren) child->SetOwnerWidget(owner); UpdateResTransparency(); } void WidgetLayer::OnLayoutChanged() { if (mUpdatingLayout) return; mUpdatingLayout = true; if (mOwnerWidget) { mOwnerWidget->UpdateLayersLayouts(); mOwnerWidget->OnChanged(); } mUpdatingLayout = false; } void WidgetLayer::UpdateLayout() { if (mParent) mAbsolutePosition = layout.Calculate(mParent->mAbsolutePosition); else mAbsolutePosition = layout.Calculate(mOwnerWidget->layout->GetWorldRect()); mInteractableArea = interactableLayout.Calculate(mAbsolutePosition); if (mDrawable) mDrawable->SetRect(mAbsolutePosition); for (auto child : mChildren) child->UpdateLayout(); } void WidgetLayer::UpdateResTransparency() { if (mParent) mResTransparency = transparency*mParent->mResTransparency; else if (mOwnerWidget) mResTransparency = transparency*mOwnerWidget->mResTransparency; else mResTransparency = mTransparency; if (mDrawable) mDrawable->SetTransparency(mResTransparency); for (auto child : mChildren) child->UpdateResTransparency(); } void WidgetLayer::OnAddToScene() { if constexpr (IS_EDITOR) o2Scene.AddEditableObjectToScene(this); for (auto layer : mChildren) layer->OnAddToScene(); } void WidgetLayer::OnRemoveFromScene() { if constexpr (IS_EDITOR) o2Scene.RemoveEditableObjectFromScene(this); for (auto layer : mChildren) layer->OnRemoveFromScene(); } Map<String, WidgetLayer*> WidgetLayer::GetAllChildLayers() { Map<String, WidgetLayer*> res; for (auto layer : mChildren) res.Add(layer->name, layer); return res; } void WidgetLayer::InstantiatePrototypeCloneVisitor::OnCopy(const WidgetLayer* source, WidgetLayer* target) { target->mPrototypeLink = source; } void WidgetLayer::MakePrototypeCloneVisitor::OnCopy(const WidgetLayer* source, WidgetLayer* target) { target->mPrototypeLink = source->mPrototypeLink; const_cast<WidgetLayer*>(source)->mPrototypeLink = target; } #if IS_EDITOR bool WidgetLayer::IsOnScene() const { if (mOwnerWidget) return mOwnerWidget->IsOnScene(); return false; } SceneUID WidgetLayer::GetID() const { return mUID; } void WidgetLayer::GenerateNewID(bool childs /*= true*/) { mUID = Math::Random(); if (childs) { for (auto child : mChildren) child->GenerateNewID(true); } } const String& WidgetLayer::GetName() const { return name; } void WidgetLayer::SetName(const String& name) { this->name = name; } Vector<SceneEditableObject*> WidgetLayer::GetEditableChildren() const { return mChildren.DynamicCast<SceneEditableObject*>(); } const SceneEditableObject* o2::WidgetLayer::GetEditableLink() const { return mPrototypeLink; } void WidgetLayer::BeginMakePrototype() const { mCopyVisitor = mnew MakePrototypeCloneVisitor(); } void WidgetLayer::BeginInstantiatePrototype() const { mCopyVisitor = mnew InstantiatePrototypeCloneVisitor(); } SceneEditableObject* WidgetLayer::GetEditableParent() const { if (mParent) return mParent; return &mOwnerWidget->layersEditable; } void WidgetLayer::SetEditableParent(SceneEditableObject* object) { if (auto layer = dynamic_cast<WidgetLayer*>(object)) layer->AddChild(this); else if (auto widget = dynamic_cast<Widget*>(object)) widget->AddLayer(this); else if (auto layers = dynamic_cast<Widget::LayersEditable*>(object)) layers->AddEditableChild(this); } void WidgetLayer::AddEditableChild(SceneEditableObject* object, int idx /*= -1*/) { if (auto layer = dynamic_cast<WidgetLayer*>(object)) AddChild(layer); else if (auto actor = dynamic_cast<Actor*>(object)) mOwnerWidget->AddEditableChild(object, idx); } void WidgetLayer::SetIndexInSiblings(int idx) { if (mParent) { int lastIdx = mParent->mChildren.IndexOf(this); mParent->mChildren.Insert(this, idx); if (idx <= lastIdx) lastIdx++; mParent->mChildren.RemoveAt(lastIdx); } else { int lastIdx = mOwnerWidget->mLayers.IndexOf(this); mOwnerWidget->mLayers.Insert(this, idx); if (idx <= lastIdx) lastIdx++; mOwnerWidget->mLayers.RemoveAt(lastIdx); } } bool WidgetLayer::CanBeParentedTo(const Type& parentType) { return parentType.IsBasedOn(TypeOf(Widget::LayersEditable)); } bool WidgetLayer::IsSupportsDisabling() const { return true; } bool WidgetLayer::IsSupportsLocking() const { return false; } bool WidgetLayer::IsLocked() const { return mIsLocked; } bool WidgetLayer::IsLockedInHierarchy() const { bool lockedParent = mOwnerWidget ? mOwnerWidget->IsLockedInHierarchy() : mParent->IsLockedInHierarchy(); return mIsLocked && lockedParent; } void WidgetLayer::SetLocked(bool locked) { mIsLocked = locked; } bool WidgetLayer::IsSupportsTransforming() const { return true; } Basis WidgetLayer::GetTransform() const { return Basis(mAbsolutePosition.LeftBottom(), Vec2F::Right()*mAbsolutePosition.Width(), Vec2F::Up()*mAbsolutePosition.Height()); } void WidgetLayer::SetTransform(const Basis& transform) { Basis thisTransform = GetTransform(); layout.offsetMin += transform.origin - thisTransform.origin; layout.offsetMax += transform.origin - thisTransform.origin + Vec2F(transform.xv.Length() - thisTransform.xv.Length(), transform.yv.Length() - thisTransform.yv.Length()); } void WidgetLayer::UpdateTransform() { if (mOwnerWidget) { mOwnerWidget->UpdateTransform(); mOwnerWidget->OnChanged(); } } bool WidgetLayer::IsSupportsPivot() const { return false; } void WidgetLayer::SetPivot(const Vec2F& pivot) {} Vec2F WidgetLayer::GetPivot() const { return Vec2F(); } bool WidgetLayer::IsSupportsLayout() const { return true; } Layout WidgetLayer::GetLayout() const { return layout; } void WidgetLayer::SetLayout(const Layout& layout) { this->layout = layout; } void WidgetLayer::OnChanged() { if (mOwnerWidget) mOwnerWidget->OnChanged(); } #endif // IS_EDITOR } DECLARE_CLASS(o2::WidgetLayer);
19.970246
129
0.699035
zenkovich
52f2b58e179e2fe04051d3251addcccef8fdae01
3,921
cc
C++
MathEngine/Functions/Operators/Bitwise.cc
antoniojkim/CalcPlusPlus
33cede17001e0a7038f99ea40dd6f9e433cf6454
[ "MIT" ]
null
null
null
MathEngine/Functions/Operators/Bitwise.cc
antoniojkim/CalcPlusPlus
33cede17001e0a7038f99ea40dd6f9e433cf6454
[ "MIT" ]
null
null
null
MathEngine/Functions/Operators/Bitwise.cc
antoniojkim/CalcPlusPlus
33cede17001e0a7038f99ea40dd6f9e433cf6454
[ "MIT" ]
null
null
null
#include <cmath> #include <numeric> #include <gsl/gsl_math.h> #include <gsl/gsl_complex_math.h> #include <gsl/gsl_sf_gamma.h> #include "../../Expressions/ExpressionFunctions.h" #include "../../Expressions/ExpressionOperations.h" #include "../../Expressions/NumericalExpression.h" #include "../../Utils/Exception.h" #include "../Functions.h" namespace Function { // @Operator lshift: << struct lshift: public OperatorFunctionExpression { lshift(int functionIndex, expression arg): OperatorFunctionExpression(functionIndex, arg) {} double value(const Variables& vars = emptyVars) const override { double l = arg->at(0)->value(vars); double r = arg->at(1)->value(vars); double intpartl, intpartr; if (modf(l, &intpartl) == 0 && modf(r, &intpartr) == 0){ return ((long long int) intpartl) << ((long long int) intpartr); } throw Exception("l << r expects integers. Got: ", arg); } }; MAKE_FUNCTION_EXPRESSION(lshift) // @Operator rshift: >> struct rshift: public OperatorFunctionExpression { rshift(int functionIndex, expression arg): OperatorFunctionExpression(functionIndex, arg) {} double value(const Variables& vars = emptyVars) const override { double l = arg->at(0)->value(vars); double r = arg->at(1)->value(vars); double intpartl, intpartr; if (modf(l, &intpartl) == 0 && modf(r, &intpartr) == 0){ return ((long long int) intpartl) >> ((long long int) intpartr); } throw Exception("l >> r expects integers. Got: ", arg); } }; MAKE_FUNCTION_EXPRESSION(rshift) // @Operator bitwise_and: & struct bitwise_and: public OperatorFunctionExpression { bitwise_and(int functionIndex, expression arg): OperatorFunctionExpression(functionIndex, arg) {} double value(const Variables& vars = emptyVars) const override { double l = arg->at(0)->value(vars); double r = arg->at(1)->value(vars); double intpartl, intpartr; if (modf(l, &intpartl) == 0 && modf(r, &intpartr) == 0){ return ((long long int) intpartl) & ((long long int) intpartr); } throw Exception("l & r expects integers. Got: ", arg); } }; MAKE_FUNCTION_EXPRESSION(bitwise_and) // @Operator bitwise_or: | struct bitwise_or: public OperatorFunctionExpression { bitwise_or(int functionIndex, expression arg): OperatorFunctionExpression(functionIndex, arg) {} double value(const Variables& vars = emptyVars) const override { double l = arg->at(0)->value(vars); double r = arg->at(1)->value(vars); double intpartl, intpartr; if (modf(l, &intpartl) == 0 && modf(r, &intpartr) == 0){ return ((long long int) intpartl) | ((long long int) intpartr); } throw Exception("l | r expects integers. Got: ", arg); } }; MAKE_FUNCTION_EXPRESSION(bitwise_or) // @Operator bitwise_xor: ^| struct bitwise_xor: public OperatorFunctionExpression { bitwise_xor(int functionIndex, expression arg): OperatorFunctionExpression(functionIndex, arg) {} double value(const Variables& vars = emptyVars) const override { double l = arg->at(0)->value(vars); double r = arg->at(1)->value(vars); double intpartl, intpartr; if (modf(l, &intpartl) == 0 && modf(r, &intpartr) == 0){ return ((long long int) intpartl) ^ ((long long int) intpartr); } throw Exception("l ^| r expects integers. Got: ", arg); } }; MAKE_FUNCTION_EXPRESSION(bitwise_xor) }
38.821782
106
0.58327
antoniojkim
52f4bc4288185e16d8c11dbdc80b0de03759b008
19,329
cpp
C++
src/libawkward/Content.cpp
martindurant/awkward-1.0
a3221ee1bab6551dd01d5dd07a1d2dc24fd02c38
[ "BSD-3-Clause" ]
null
null
null
src/libawkward/Content.cpp
martindurant/awkward-1.0
a3221ee1bab6551dd01d5dd07a1d2dc24fd02c38
[ "BSD-3-Clause" ]
null
null
null
src/libawkward/Content.cpp
martindurant/awkward-1.0
a3221ee1bab6551dd01d5dd07a1d2dc24fd02c38
[ "BSD-3-Clause" ]
null
null
null
// BSD 3-Clause License; see https://github.com/jpivarski/awkward-1.0/blob/master/LICENSE #include <sstream> #include "awkward/cpu-kernels/operations.h" #include "awkward/cpu-kernels/reducers.h" #include "awkward/array/RegularArray.h" #include "awkward/array/ListArray.h" #include "awkward/array/EmptyArray.h" #include "awkward/array/UnionArray.h" #include "awkward/array/IndexedArray.h" #include "awkward/array/RecordArray.h" #include "awkward/array/NumpyArray.h" #include "awkward/array/ByteMaskedArray.h" #include "awkward/array/BitMaskedArray.h" #include "awkward/type/ArrayType.h" #include "awkward/Content.h" namespace awkward { Content::Content(const std::shared_ptr<Identities>& identities, const util::Parameters& parameters) : identities_(identities) , parameters_(parameters) { } Content::~Content() { } bool Content::isscalar() const { return false; } const std::shared_ptr<Identities> Content::identities() const { return identities_; } const std::string Content::tostring() const { return tostring_part("", "", ""); } const std::string Content::tojson(bool pretty, int64_t maxdecimals) const { if (pretty) { ToJsonPrettyString builder(maxdecimals); tojson_part(builder); return builder.tostring(); } else { ToJsonString builder(maxdecimals); tojson_part(builder); return builder.tostring(); } } void Content::tojson(FILE* destination, bool pretty, int64_t maxdecimals, int64_t buffersize) const { if (pretty) { ToJsonPrettyFile builder(destination, maxdecimals, buffersize); builder.beginlist(); tojson_part(builder); builder.endlist(); } else { ToJsonFile builder(destination, maxdecimals, buffersize); builder.beginlist(); tojson_part(builder); builder.endlist(); } } int64_t Content::nbytes() const { // FIXME: this is only accurate if all subintervals of allocated arrays are nested // (which is likely, but not guaranteed). In general, it's <= the correct nbytes. std::map<size_t, int64_t> largest; nbytes_part(largest); int64_t out = 0; for (auto pair : largest) { out += pair.second; } return out; } const std::shared_ptr<Content> Content::reduce(const Reducer& reducer, int64_t axis, bool mask, bool keepdims) const { int64_t negaxis = -axis; std::pair<bool, int64_t> branchdepth = branch_depth(); bool branch = branchdepth.first; int64_t depth = branchdepth.second; if (branch) { if (negaxis <= 0) { throw std::invalid_argument("cannot use non-negative axis on a nested list structure of variable depth (negative axis counts from the leaves of the tree; non-negative from the root)"); } if (negaxis > depth) { throw std::invalid_argument(std::string("cannot use axis=") + std::to_string(axis) + std::string(" on a nested list structure that splits into different depths, the minimum of which is depth=") + std::to_string(depth) + std::string(" from the leaves")); } } else { if (negaxis <= 0) { negaxis += depth; } if (!(0 < negaxis && negaxis <= depth)) { throw std::invalid_argument(std::string("axis=") + std::to_string(axis) + std::string(" exceeds the depth of the nested list structure (which is ") + std::to_string(depth) + std::string(")")); } } Index64 parents(length()); struct Error err = awkward_content_reduce_zeroparents_64( parents.ptr().get(), length()); util::handle_error(err, classname(), identities_.get()); std::shared_ptr<Content> next = reduce_next(reducer, negaxis, parents, 1, mask, keepdims); return next.get()->getitem_at_nowrap(0); } const util::Parameters Content::parameters() const { return parameters_; } void Content::setparameters(const util::Parameters& parameters) { parameters_ = parameters; } const std::string Content::parameter(const std::string& key) const { auto item = parameters_.find(key); if (item == parameters_.end()) { return "null"; } return item->second; } void Content::setparameter(const std::string& key, const std::string& value) { parameters_[key] = value; } bool Content::parameter_equals(const std::string& key, const std::string& value) const { return util::parameter_equals(parameters_, key, value); } bool Content::parameters_equal(const util::Parameters& other) const { return util::parameters_equal(parameters_, other); } const std::shared_ptr<Content> Content::merge_as_union(const std::shared_ptr<Content>& other) const { int64_t mylength = length(); int64_t theirlength = other.get()->length(); Index8 tags(mylength + theirlength); Index64 index(mylength + theirlength); std::vector<std::shared_ptr<Content>> contents({ shallow_copy(), other }); struct Error err1 = awkward_unionarray_filltags_to8_const( tags.ptr().get(), 0, mylength, 0); util::handle_error(err1, classname(), identities_.get()); struct Error err2 = awkward_unionarray_fillindex_to64_count( index.ptr().get(), 0, mylength); util::handle_error(err2, classname(), identities_.get()); struct Error err3 = awkward_unionarray_filltags_to8_const( tags.ptr().get(), mylength, theirlength, 1); util::handle_error(err3, classname(), identities_.get()); struct Error err4 = awkward_unionarray_fillindex_to64_count( index.ptr().get(), mylength, theirlength); util::handle_error(err4, classname(), identities_.get()); return std::make_shared<UnionArray8_64>(Identities::none(), util::Parameters(), tags, index, contents); } const std::shared_ptr<Content> Content::rpad_axis0(int64_t target, bool clip) const { if (!clip && target < length()) { return shallow_copy(); } Index64 index(target); struct Error err = awkward_index_rpad_and_clip_axis0_64( index.ptr().get(), target, length()); util::handle_error(err, classname(), identities_.get()); std::shared_ptr<IndexedOptionArray64> next = std::make_shared<IndexedOptionArray64>(Identities::none(), util::Parameters(), index, shallow_copy()); return next.get()->simplify_optiontype(); } const std::shared_ptr<Content> Content::localindex_axis0() const { Index64 localindex(length()); struct Error err = awkward_localindex_64( localindex.ptr().get(), length()); util::handle_error(err, classname(), identities_.get()); return std::make_shared<NumpyArray>(localindex); } const std::shared_ptr<Content> Content::choose_axis0(int64_t n, bool diagonal, const std::shared_ptr<util::RecordLookup>& recordlookup, const util::Parameters& parameters) const { int64_t size = length(); if (diagonal) { size += (n - 1); } int64_t thisn = n; int64_t chooselen; if (thisn > size) { chooselen = 0; } else if (thisn == size) { chooselen = 1; } else { if (thisn * 2 > size) { thisn = size - thisn; } chooselen = size; for (int64_t j = 2; j <= thisn; j++) { chooselen *= (size - j + 1); chooselen /= j; } } std::vector<std::shared_ptr<int64_t>> tocarry; std::vector<int64_t*> tocarryraw; for (int64_t j = 0; j < n; j++) { std::shared_ptr<int64_t> ptr(new int64_t[(size_t)chooselen], util::array_deleter<int64_t>()); tocarry.push_back(ptr); tocarryraw.push_back(ptr.get()); } struct Error err = awkward_regulararray_choose_64( tocarryraw.data(), n, diagonal, length(), 1); util::handle_error(err, classname(), identities_.get()); std::vector<std::shared_ptr<Content>> contents; for (auto ptr : tocarry) { contents.push_back(std::make_shared<IndexedArray64>(Identities::none(), util::Parameters(), Index64(ptr, 0, chooselen), shallow_copy())); } return std::make_shared<RecordArray>(Identities::none(), parameters, contents, recordlookup); } const std::shared_ptr<Content> Content::getitem(const Slice& where) const { std::shared_ptr<Content> next = std::make_shared<RegularArray>(Identities::none(), util::Parameters(), shallow_copy(), length()); std::shared_ptr<SliceItem> nexthead = where.head(); Slice nexttail = where.tail(); Index64 nextadvanced(0); std::shared_ptr<Content> out = next.get()->getitem_next(nexthead, nexttail, nextadvanced); if (out.get()->length() == 0) { return out.get()->getitem_nothing(); } else { return out.get()->getitem_at_nowrap(0); } } const std::shared_ptr<Content> Content::getitem_next(const std::shared_ptr<SliceItem>& head, const Slice& tail, const Index64& advanced) const { if (head.get() == nullptr) { return shallow_copy(); } else if (SliceAt* at = dynamic_cast<SliceAt*>(head.get())) { return getitem_next(*at, tail, advanced); } else if (SliceRange* range = dynamic_cast<SliceRange*>(head.get())) { return getitem_next(*range, tail, advanced); } else if (SliceEllipsis* ellipsis = dynamic_cast<SliceEllipsis*>(head.get())) { return getitem_next(*ellipsis, tail, advanced); } else if (SliceNewAxis* newaxis = dynamic_cast<SliceNewAxis*>(head.get())) { return getitem_next(*newaxis, tail, advanced); } else if (SliceArray64* array = dynamic_cast<SliceArray64*>(head.get())) { return getitem_next(*array, tail, advanced); } else if (SliceField* field = dynamic_cast<SliceField*>(head.get())) { return getitem_next(*field, tail, advanced); } else if (SliceFields* fields = dynamic_cast<SliceFields*>(head.get())) { return getitem_next(*fields, tail, advanced); } else if (SliceMissing64* missing = dynamic_cast<SliceMissing64*>(head.get())) { return getitem_next(*missing, tail, advanced); } else if (SliceJagged64* jagged = dynamic_cast<SliceJagged64*>(head.get())) { return getitem_next(*jagged, tail, advanced); } else { throw std::runtime_error("unrecognized slice type"); } } const std::shared_ptr<Content> Content::getitem_next_jagged(const Index64& slicestarts, const Index64& slicestops, const std::shared_ptr<SliceItem>& slicecontent, const Slice& tail) const { if (SliceArray64* array = dynamic_cast<SliceArray64*>(slicecontent.get())) { return getitem_next_jagged(slicestarts, slicestops, *array, tail); } else if (SliceMissing64* missing = dynamic_cast<SliceMissing64*>(slicecontent.get())) { return getitem_next_jagged(slicestarts, slicestops, *missing, tail); } else if (SliceJagged64* jagged = dynamic_cast<SliceJagged64*>(slicecontent.get())) { return getitem_next_jagged(slicestarts, slicestops, *jagged, tail); } else { throw std::runtime_error("unexpected slice type for getitem_next_jagged"); } } const std::shared_ptr<Content> Content::getitem_next(const SliceEllipsis& ellipsis, const Slice& tail, const Index64& advanced) const { std::pair<int64_t, int64_t> minmax = minmax_depth(); int64_t mindepth = minmax.first; int64_t maxdepth = minmax.second; if (tail.length() == 0 || (mindepth - 1 == tail.dimlength() && maxdepth - 1 == tail.dimlength())) { std::shared_ptr<SliceItem> nexthead = tail.head(); Slice nexttail = tail.tail(); return getitem_next(nexthead, nexttail, advanced); } else if (mindepth - 1 == tail.dimlength() || maxdepth - 1 == tail.dimlength()) { throw std::invalid_argument("ellipsis (...) can't be used on a data structure of different depths"); } else { std::vector<std::shared_ptr<SliceItem>> tailitems = tail.items(); std::vector<std::shared_ptr<SliceItem>> items = { std::make_shared<SliceEllipsis>() }; items.insert(items.end(), tailitems.begin(), tailitems.end()); std::shared_ptr<SliceItem> nexthead = std::make_shared<SliceRange>(Slice::none(), Slice::none(), 1); Slice nexttail(items); return getitem_next(nexthead, nexttail, advanced); } } const std::shared_ptr<Content> Content::getitem_next(const SliceNewAxis& newaxis, const Slice& tail, const Index64& advanced) const { std::shared_ptr<SliceItem> nexthead = tail.head(); Slice nexttail = tail.tail(); return std::make_shared<RegularArray>(Identities::none(), util::Parameters(), getitem_next(nexthead, nexttail, advanced), 1); } const std::shared_ptr<Content> Content::getitem_next(const SliceField& field, const Slice& tail, const Index64& advanced) const { std::shared_ptr<SliceItem> nexthead = tail.head(); Slice nexttail = tail.tail(); return getitem_field(field.key()).get()->getitem_next(nexthead, nexttail, advanced); } const std::shared_ptr<Content> Content::getitem_next(const SliceFields& fields, const Slice& tail, const Index64& advanced) const { std::shared_ptr<SliceItem> nexthead = tail.head(); Slice nexttail = tail.tail(); return getitem_fields(fields.keys()).get()->getitem_next(nexthead, nexttail, advanced); } const std::shared_ptr<Content> getitem_next_regular_missing(const SliceMissing64& missing, const Slice& tail, const Index64& advanced, const RegularArray* raw, int64_t length, const std::string& classname) { Index64 index(missing.index()); Index64 outindex(index.length()*length); struct Error err = awkward_missing_repeat_64( outindex.ptr().get(), index.ptr().get(), index.offset(), index.length(), length, raw->size()); util::handle_error(err, classname, nullptr); IndexedOptionArray64 out(Identities::none(), util::Parameters(), outindex, raw->content()); return std::make_shared<RegularArray>(Identities::none(), util::Parameters(), out.simplify_optiontype(), index.length()); } bool check_missing_jagged_same(const std::shared_ptr<Content>& that, const Index8& bytemask, const SliceMissing64& missing) { if (bytemask.length() != missing.length()) { return false; } Index64 missingindex = missing.index(); bool same; struct Error err = awkward_slicemissing_check_same( &same, bytemask.ptr().get(), bytemask.offset(), missingindex.ptr().get(), missingindex.offset(), bytemask.length()); util::handle_error(err, that.get()->classname(), that.get()->identities().get()); return same; } const std::shared_ptr<Content> check_missing_jagged(const std::shared_ptr<Content>& that, const SliceMissing64& missing) { // FIXME: This function is insufficiently general. While working on something else, // I noticed that it wasn't possible to slice option-type data with a jagged array. // This handles the case where that happens at top-level; the most likely case // for physics analysis, but it should be more deeply considered in general. // // Note that it only replaces the Content that would be passed to // getitem_next(missing.content()) in getitem_next(SliceMissing64) in a particular // scenario; it can probably be generalized by handling more general scenarios. if (that.get()->length() == 1 && dynamic_cast<SliceJagged64*>(missing.content().get())) { std::shared_ptr<Content> tmp1 = that.get()->getitem_at_nowrap(0); std::shared_ptr<Content> tmp2(nullptr); if (IndexedOptionArray32* rawtmp1 = dynamic_cast<IndexedOptionArray32*>(tmp1.get())) { tmp2 = rawtmp1->project(); if (!check_missing_jagged_same(that, rawtmp1->bytemask(), missing)) { return that; } } else if (IndexedOptionArray64* rawtmp1 = dynamic_cast<IndexedOptionArray64*>(tmp1.get())) { tmp2 = rawtmp1->project(); if (!check_missing_jagged_same(that, rawtmp1->bytemask(), missing)) { return that; } } else if (ByteMaskedArray* rawtmp1 = dynamic_cast<ByteMaskedArray*>(tmp1.get())) { tmp2 = rawtmp1->project(); if (!check_missing_jagged_same(that, rawtmp1->bytemask(), missing)) { return that; } } else if (BitMaskedArray* rawtmp1 = dynamic_cast<BitMaskedArray*>(tmp1.get())) { tmp2 = rawtmp1->project(); if (!check_missing_jagged_same(that, rawtmp1->bytemask(), missing)) { return that; } } if (tmp2.get() != nullptr) { return std::make_shared<RegularArray>(Identities::none(), that.get()->parameters(), tmp2, tmp2.get()->length()); } } return that; } const std::shared_ptr<Content> Content::getitem_next(const SliceMissing64& missing, const Slice& tail, const Index64& advanced) const { if (advanced.length() != 0) { throw std::invalid_argument("cannot mix missing values in slice with NumPy-style advanced indexing"); } std::shared_ptr<Content> next = check_missing_jagged(shallow_copy(), missing).get()->getitem_next(missing.content(), tail, advanced); if (RegularArray* raw = dynamic_cast<RegularArray*>(next.get())) { return getitem_next_regular_missing(missing, tail, advanced, raw, length(), classname()); } else if (RecordArray* rec = dynamic_cast<RecordArray*>(next.get())) { if (rec->numfields() == 0) { return next; } std::vector<std::shared_ptr<Content>> contents; for (auto content : rec->contents()) { if (RegularArray* raw = dynamic_cast<RegularArray*>(content.get())) { contents.push_back(getitem_next_regular_missing(missing, tail, advanced, raw, length(), classname())); } else { throw std::runtime_error(std::string("FIXME: unhandled case of SliceMissing with RecordArray containing\n") + content.get()->tostring()); } } return std::make_shared<RecordArray>(Identities::none(), util::Parameters(), contents, rec->recordlookup()); } else { throw std::runtime_error(std::string("FIXME: unhandled case of SliceMissing with\n") + next.get()->tostring()); } } const std::shared_ptr<Content> Content::getitem_next_array_wrap(const std::shared_ptr<Content>& outcontent, const std::vector<int64_t>& shape) const { std::shared_ptr<Content> out = std::make_shared<RegularArray>(Identities::none(), util::Parameters(), outcontent, (int64_t)shape[shape.size() - 1]); for (int64_t i = (int64_t)shape.size() - 2; i >= 0; i--) { out = std::make_shared<RegularArray>(Identities::none(), util::Parameters(), out, (int64_t)shape[(size_t)i]); } return out; } const std::string Content::parameters_tostring(const std::string& indent, const std::string& pre, const std::string& post) const { if (parameters_.empty()) { return ""; } else { std::stringstream out; out << indent << pre << "<parameters>\n"; for (auto pair : parameters_) { out << indent << " <param key=" << util::quote(pair.first, true) << ">" << pair.second << "</param>\n"; } out << indent << "</parameters>" << post; return out.str(); } } const int64_t Content::axis_wrap_if_negative(int64_t axis) const { if (axis < 0) { throw std::runtime_error("FIXME: negative axis not implemented yet"); } return axis; } }
39.206897
261
0.663407
martindurant
52f4eaf5f0c362899643d2eecb1792d0c0958e1c
3,223
hpp
C++
include/vcd/actions/header.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
1
2019-04-30T17:56:23.000Z
2019-04-30T17:56:23.000Z
include/vcd/actions/header.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
null
null
null
include/vcd/actions/header.hpp
qedalab/vcd_assert
40da307e60600fc4a814d4bba4679001f49f4375
[ "BSD-2-Clause" ]
4
2018-08-01T08:32:00.000Z
2019-12-18T06:34:33.000Z
// ============================================================================ // Copyright 2018 Paul le Roux and Calvin Maree // // 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. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // ============================================================================ #ifndef LIBVCD_EVENTS_HEADER_HPP #define LIBVCD_EVENTS_HEADER_HPP #include "../types/header_reader.hpp" #include "./scope.hpp" #include "./time_scale.hpp" #include "./var.hpp" #include "parse/actions/apply/string.hpp" #include "parse/actions/storage/function.hpp" #include <string> namespace VCD::Actions { using namespace Parse; struct VersionAction : single_dispatch< Grammar::string_before_end, apply<Apply::string> > { using state = std::string; }; struct DateAction : single_dispatch< Grammar::string_before_end, apply<Apply::string> > { using state = std::string; }; using HeaderVarFunctionType = void (HeaderReader::*)(VariableView); using HeaderScopeFunctionType = void (HeaderReader::*)(ScopeDataView); using HeaderTimeScaleFunctionType = void (HeaderReader::*)(TimeScaleView); struct HeaderAction : multi_dispatch< Grammar::date_command, inner_action< DateAction, Storage::function<&HeaderReader::date>>, Grammar::timescale_command, inner_action< TimeScaleAction, Storage::function< static_cast<HeaderTimeScaleFunctionType>(&HeaderReader::timescale)>>, Grammar::version_command, inner_action< VersionAction, Storage::function<&HeaderReader::version>>, Grammar::scope_command, inner_action< ScopeAction, Storage::function< static_cast<HeaderScopeFunctionType >(&HeaderReader::scope)>>, Grammar::upscope_command, apply0<UpscopeApply>, Grammar::var_command, inner_action< VarAction, Storage::function< static_cast<HeaderVarFunctionType>(&HeaderReader::var)>> > { using state = HeaderReader; }; } // namespace VCD::Actions #endif // LIBVCD_EVENTS_HEADER_HPP
37.917647
81
0.710828
qedalab
52fff7790f5b13d4453334e2c13d2f7235f8c493
1,361
hxx
C++
main/oox/source/ppt/animationtypes.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/oox/source/ppt/animationtypes.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/oox/source/ppt/animationtypes.hxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ #ifndef OOX_POWERPOINT_ANIMATIONTYPES_HXX #define OOX_POWERPOINT_ANIMATIONTYPES_HXX #include <com/sun/star/uno/Any.hxx> #include <com/sun/star/xml/sax/XFastAttributeList.hpp> namespace oox { namespace ppt { // ST_TLTime ::com::sun::star::uno::Any GetTime( const ::rtl::OUString & val ); // ST_TLTimeAnimateValueTime ::com::sun::star::uno::Any GetTimeAnimateValueTime( const ::rtl::OUString & val ); } } #endif
30.931818
82
0.674504
Grosskopf
5e0107d605be9ad35c1666ebec2e55d49b15c0c1
1,679
hpp
C++
mjolnir/core/LoaderBase.hpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
12
2017-02-01T08:28:38.000Z
2018-08-25T15:47:51.000Z
mjolnir/core/LoaderBase.hpp
Mjolnir-MD/Mjolnir
043df4080720837042c6b67a5495ecae198bc2b3
[ "MIT" ]
60
2019-01-14T08:11:33.000Z
2021-07-29T08:26:36.000Z
mjolnir/core/LoaderBase.hpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
8
2019-01-13T11:03:31.000Z
2021-08-01T11:38:00.000Z
#ifndef MJOLNIR_CORE_LOADER_BASE_HPP #define MJOLNIR_CORE_LOADER_BASE_HPP #include <mjolnir/util/binary_io.hpp> #include <fstream> #include <string> namespace mjolnir { template<typename traitsT> class System; template<typename traitsT> class LoaderBase { public: using traits_type = traitsT; using real_type = typename traits_type::real_type; using coordinate_type = typename traits_type::coordinate_type; using system_type = System<traits_type>; public: LoaderBase() = default; virtual ~LoaderBase() {} // open files, read header, etc. virtual void initialize() = 0; virtual std::size_t num_particles() const noexcept = 0; virtual std::size_t num_frames() const noexcept = 0; virtual bool is_eof() const noexcept = 0; // load the next snapshot and write it into the system. // If there are no snapshot any more, return false. // If the number of particles differs from system, throws runtime_error. virtual bool load_next(system_type&) = 0; // for testing purpose. virtual std::string const& filename() const noexcept = 0; }; } // mjolnir #ifdef MJOLNIR_SEPARATE_BUILD #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/BoundaryCondition.hpp> namespace mjolnir { extern template class LoaderBase<SimulatorTraits<double, UnlimitedBoundary>>; extern template class LoaderBase<SimulatorTraits<float, UnlimitedBoundary>>; extern template class LoaderBase<SimulatorTraits<double, CuboidalPeriodicBoundary>>; extern template class LoaderBase<SimulatorTraits<float, CuboidalPeriodicBoundary>>; } // mjolnir #endif #endif//MJOLNIR_CORE_LOADER_BASE_HPP
28.948276
84
0.7433
yutakasi634
5e0113474c9d183dab50d3cceeaa606b8ad63077
1,330
cpp
C++
libcxx/test/libcxx/localization/locales/locale/locale.types/locale.id/id.pass.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
libcxx/test/libcxx/localization/locales/locale/locale.types/locale.id/id.pass.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
libcxx/test/libcxx/localization/locales/locale/locale.types/locale.id/id.pass.cpp
medismailben/llvm-project
e334a839032fe500c3bba22bf976ab7af13ce1c1
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <locale> // class locale::id // { // public: // id(); // void operator=(const id&) = delete; // id(const id&) = delete; // }; // This test isn't portable #include <locale> #include <cassert> #include "test_macros.h" std::locale::id id0; std::locale::id id2; std::locale::id id1; int main(int, char**) { long id = id0.__get(); assert(id0.__get() == id+0); assert(id0.__get() == id+0); assert(id0.__get() == id+0); assert(id1.__get() == id+1); assert(id1.__get() == id+1); assert(id1.__get() == id+1); assert(id2.__get() == id+2); assert(id2.__get() == id+2); assert(id2.__get() == id+2); assert(id0.__get() == id+0); assert(id0.__get() == id+0); assert(id0.__get() == id+0); assert(id1.__get() == id+1); assert(id1.__get() == id+1); assert(id1.__get() == id+1); assert(id2.__get() == id+2); assert(id2.__get() == id+2); assert(id2.__get() == id+2); return 0; }
24.62963
80
0.503759
medismailben
5e025c22728d8531b6057985689aa9b830f7eb1c
783
cpp
C++
leetcode/count-artifacts-that-can-be-extracted/attempt-1.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
leetcode/count-artifacts-that-can-be-extracted/attempt-1.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
leetcode/count-artifacts-that-can-be-extracted/attempt-1.cpp
Yash-Singh1/competitive-programming
3b9d278ed8138ab614e2a3d748627db8f4a2cdbd
[ "MIT" ]
null
null
null
class Solution { public: int digArtifacts(int n, vector<vector<int>>& artifacts, vector<vector<int>>& dig) { int dugUp{0}; int usedDigs[dig.size()]; for (auto artifact: artifacts) { int artifactEntries{(artifact[2] - artifact[0] + 1) * (artifact[3] - artifact[1] + 1)}; bool used{false}; for (int i{0}; i < dig.size(); ++i) { if (usedDigs[i] == 0) continue; vector<int> digSpot {dig[i]}; if (digSpot[0] >= artifact[0] && digSpot[1] >= artifact[1] && digSpot[0] <= artifact[2] && digSpot[1] <= artifact[3]) { --artifactEntries; usedDigs[i] = 1; } } if (artifactEntries == 0) { ++dugUp; } } return dugUp; } };
32.625
131
0.492976
Yash-Singh1
5e08a8afea7f5395c0c049681f78e61f71a77d34
3,131
cpp
C++
graph-source-code/527-E/10330073.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/527-E/10330073.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/527-E/10330073.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ //#pragma comment(linker,"/STACK:102400000,102400000") #include <iostream> #include <cstdio> #include <cstdlib> #include <cassert> #include <climits> #include <ctime> #include <numeric> #include <vector> #include <algorithm> #include <bitset> #include <cmath> #include <cstring> #include <iomanip> #include <complex> #include <deque> #include <functional> #include <list> #include <map> #include <string> #include <sstream> #include <set> #include <stack> #include <queue> using namespace std; template<class T> inline T sqr(T x) { return x * x; } typedef long long LL; typedef unsigned long long ULL; typedef long double LD; typedef pair<int, int> PII; typedef pair<PII, int> PIII; typedef pair<LL, LL> PLL; typedef pair<LL, int> PLI; typedef pair<LD, LD> PDD; #define MP make_pair #define PB push_back #define sz(x) ((int)(x).size()) #define clr(ar,val) memset(ar, val, sizeof(ar)) #define istr stringstream #define FOR(i,n) for(int i=0;i<(n);++i) #define forIt(mp,it) for(__typeof(mp.begin()) it = mp.begin();it!=mp.end();it++) const double EPS = 1e-6; const int INF = 0x3fffffff; const LL LINF = INF * 1ll * INF; const double PI = acos(-1.0); #define lson l,mid,rt<<1 #define rson mid+1,r,rt<<1|1 #define lowbit(u) (u&(-u)) using namespace std; #define MAXN 100005 #define MAXM 1000005 int vis[MAXM]; int circle[MAXM]; int tot,cnt; int head[MAXN],nxt[MAXM],e[MAXM]; int in[MAXN],out[MAXN]; int deg[MAXN]; int cur[MAXN]; void addEdge(int u,int v){ e[cnt] = v; int tmp = head[u]; head[u] = cnt; nxt[cnt++] = tmp; } void dfs(int u){ for(;~cur[u];cur[u] = nxt[cur[u]]){ if(vis[cur[u]]) continue; vis[cur[u]] = vis[cur[u]^1] = 1; dfs(e[cur[u]]); if(cur[u]==-1) break; } circle[tot++] = u; } int main(void){ #ifndef ONLINE_JUDGE freopen("/Users/mac/Desktop/data.in","r",stdin); #endif vector<PII> ans; int n,m; scanf("%d %d",&n,&m); memset(head,-1,sizeof(head)); FOR(i,m){ int a,b; scanf("%d %d",&a,&b); deg[a]++,deg[b]++; addEdge(a,b); addEdge(b,a); } int last = -1; for(int i = 1;i<=n;i++){ if(deg[i]%2==1){ if(~last){ addEdge(last,i); addEdge(i,last); last = -1; }else last = i; } } for(int i = 1;i<=n;i++) cur[i] = head[i]; for(int i = 1;i<=n;i++){ if(~cur[i]){ tot = 0; dfs(i); for(int j = 1;j<tot;j++){ if(j&1) ans.PB(MP(circle[j],circle[j-1])); else ans.PB(MP(circle[j-1],circle[j])); } //FOR(j,tot) cout<<circle[j]<<" ";cout<<endl; } } int sz = ans.size(); for(int i = 0;i<sz;i++){ out[ans[i].first]++; in[ans[i].second]++; } vector<int> nin,nout; for(int i = 1;i<=n;i++){ if(in[i]%2) nin.PB(i); if(out[i]%2) nout.PB(i); } int x = min(nin.size(),nout.size()); for(int i = 0;i<x;i++) ans.PB(MP(nout[i],nin[i])); for(int i = x;i<(int)nin.size();i++) ans.PB(MP(1,nin[i])); for(int i = x;i<(int)nout.size();i++) ans.PB(MP(nout[i],1)); sz = ans.size(); printf("%d\n",sz); for(int i = 0;i<sz;i++) printf("%d %d\n",ans[i].first,ans[i].second); return 0; }
22.205674
81
0.577132
AmrARaouf
5e0b38e92a8b35b43b6f54cb1eca6e73d084200e
676
cpp
C++
kernel/Devices/DebugPort/DebugPort.cpp
AymenSekhri/CyanOS
1e42772911299a40aab0e7aac50181b180941800
[ "MIT" ]
63
2020-06-18T11:04:07.000Z
2022-02-24T09:01:44.000Z
kernel/Devices/DebugPort/DebugPort.cpp
AymenSekhri/CyanOS
1e42772911299a40aab0e7aac50181b180941800
[ "MIT" ]
4
2020-08-31T23:07:37.000Z
2021-06-08T21:54:02.000Z
kernel/Devices/DebugPort/DebugPort.cpp
AymenSekhri/CyanOS
1e42772911299a40aab0e7aac50181b180941800
[ "MIT" ]
9
2020-08-03T13:48:50.000Z
2022-03-31T11:50:59.000Z
#include "DebugPort.h" #include "Arch/x86/Asm.h" #include <Clib.h> void DebugPort::write(const char* data, size_t size, DebugColor color) { char num[3]; itoa(num, static_cast<int>(color), 10); put("\x1B[", 2); put(num, 2); put('m'); put(data, size); put("\x1B[0m", 4); } void DebugPort::write(const char* data, DebugColor color) { char num[3]; itoa(num, static_cast<int>(color), 10); put("\x1B[", 2); put(num, 2); put('m'); put(data, strlen(data)); put("\x1B[0m", 4); } void DebugPort::put(const char* data, size_t size) { for (size_t i = 0; i < size; i++) { out8(DEBUG_PORT, data[i]); } } void DebugPort::put(const char data) { out8(DEBUG_PORT, data); }
18.777778
70
0.628698
AymenSekhri
5e0c84d6167976c417d34aff3e5df3a17edee939
2,569
cpp
C++
src/value.cpp
RAttab/reflect
b600898e4537febade510125daf41736db2ecfcc
[ "BSD-2-Clause" ]
45
2015-03-24T09:35:46.000Z
2021-05-06T11:50:34.000Z
src/value.cpp
RAttab/reflect
b600898e4537febade510125daf41736db2ecfcc
[ "BSD-2-Clause" ]
null
null
null
src/value.cpp
RAttab/reflect
b600898e4537febade510125daf41736db2ecfcc
[ "BSD-2-Clause" ]
11
2015-01-27T12:08:21.000Z
2020-08-29T16:34:13.000Z
/* value.cpp -*- C++ -*- Rémi Attab (remi.attab@gmail.com), 25 Mar 2014 FreeBSD-style copyright and disclaimer apply Value implementation. */ #include "reflect.h" namespace reflect { /******************************************************************************/ /* VALUE */ /******************************************************************************/ Value:: Value() : value_(nullptr) {} // This is required to avoid trigerring the templated constructor for Value when // trying to copy non-const Values. This is common in data-structures like // vectors where entries would get infinitely wrapped in layers of Values // everytime a resize takes place. Value:: Value(Value& other) : arg(other.arg), value_(other.value_), storage(other.storage) {} Value:: Value(const Value& other) : arg(other.arg), value_(other.value_), storage(other.storage) {} Value& Value:: operator=(const Value& other) { if (this == &other) return *this; arg = other.arg; value_ = other.value_; storage = other.storage; return *this; } Value:: Value(Value&& other) : arg(std::move(other.arg)), value_(std::move(other.value_)), storage(std::move(other.storage)) {} Value& Value:: operator=(Value&& other) { if (this == &other) return *this; arg = std::move(other.arg); value_ = std::move(other.value_); storage = std::move(other.storage); return *this; } const std::string& Value:: typeId() const { return type()->id(); } bool Value:: is(const std::string& trait) const { return type()->is(trait); } Value Value:: copy() const { if (!type()->isCopiable()) reflectError("<%s> is not copiable", type()->id()); return type()->construct(*this); } Value Value:: move() { if (!type()->isMovable()) reflectError("<%s> is not movable", type()->id()); Value arg = rvalue(); *this = Value(); return arg.type()->construct(arg); } Value Value:: toConst() const { Value result(*this); result.arg = Argument(type(), RefType::RValue, true); return result; } Value Value:: rvalue() const { Value result(*this); result.arg = Argument(type(), RefType::RValue, isConst()); return result; } bool Value:: operator!() const { if (type()->hasFunction("operator!")) return call<bool>("operator!"); return !((bool) *this); } Value:: operator bool() const { return call<bool>("operator bool()"); } } // reflect
17.965035
80
0.561308
RAttab
5e0cf0ee09c930b9e8238716dba0b750e68126b4
3,128
cpp
C++
src/rosrtls/messages/rtls_pose.cpp
valentinbarral/rosrtls
0da845db11381fb6e8b1b4c7da0bc2fe60aa0afa
[ "MIT" ]
null
null
null
src/rosrtls/messages/rtls_pose.cpp
valentinbarral/rosrtls
0da845db11381fb6e8b1b4c7da0bc2fe60aa0afa
[ "MIT" ]
null
null
null
src/rosrtls/messages/rtls_pose.cpp
valentinbarral/rosrtls
0da845db11381fb6e8b1b4c7da0bc2fe60aa0afa
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2020 Group of Electronic Technology and Communications. University of A Coruna. 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 "rtls_pose.h" #include "restclient-cpp/connection.h" #include "restclient-cpp/restclient.h" #include <json.hpp> using json = nlohmann::json; RTLSPose::RTLSPose(std::string token, std::string url, std::string route, std::string targetDeviceId, std::string scenarioId, std::string levelId){ this->_token = token; this->_url = url; this->_route = route; this->_targetDeviceId = targetDeviceId; this->_scenarioId = scenarioId; this->_levelId = levelId; RestClient::init(); } RTLSPose::~RTLSPose() { RestClient::disable(); } void RTLSPose::newPose(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr& pose_msg) { std::vector<double> covarianceVector; std::string fullUrl = this->_url + this->_targetDeviceId; ROS_DEBUG("New pose to send in rtls_pose. Full URL: %s", fullUrl.c_str());; RestClient::Connection* conn = new RestClient::Connection(fullUrl); RestClient::HeaderFields headers; headers["Content-Type"] = "application/json"; headers["x-access-token"] = this->_token; conn->SetHeaders(headers); json jsonMsg; json jsonPosition, jsonError, jsonEstimate, jsonPose; jsonMsg["techName"] = "UWB"; jsonEstimate["timestamp"] = (double) pose_msg->header.stamp.sec + ((double) pose_msg->header.stamp.nsec)/1e9; jsonEstimate["timeWindow"] = 0; jsonError["type"] = "geometric"; jsonError["covariance"] = pose_msg->pose.covariance; jsonEstimate["error"] = jsonError; jsonPosition["type"] = "geometric"; jsonPose["position"] = {pose_msg->pose.pose.position.x,pose_msg->pose.pose.position.y,pose_msg->pose.pose.position.z}; jsonPose["quaternion"] = {pose_msg->pose.pose.orientation.x,pose_msg->pose.pose.orientation.y,pose_msg->pose.pose.orientation.z,pose_msg->pose.pose.orientation.w}; jsonPosition["pose"] = jsonPose; jsonEstimate["position"]["posData"] = jsonPosition; jsonMsg["estimate"] = jsonEstimate; RestClient::Response r = conn->post(this->_route, jsonMsg.dump()); ROS_DEBUG("%s", r.body.c_str()); }
34.373626
164
0.750639
valentinbarral
5e0e76c5d205136e1d434d25d8c7e1a25c2b9e00
4,945
cc
C++
plugins/header_rewrite/conditions_geo_maxmind.cc
dsouza93/trafficserver
941f994388faecde741db4b9e6d03a753d2038be
[ "Apache-2.0" ]
1
2021-06-13T16:20:12.000Z
2021-06-13T16:20:12.000Z
plugins/header_rewrite/conditions_geo_maxmind.cc
lvf25/trafficserver
3d584af796bad1e9e3c03b2af5485b630ffedafb
[ "Apache-2.0" ]
null
null
null
plugins/header_rewrite/conditions_geo_maxmind.cc
lvf25/trafficserver
3d584af796bad1e9e3c03b2af5485b630ffedafb
[ "Apache-2.0" ]
1
2020-02-11T03:40:20.000Z
2020-02-11T03:40:20.000Z
/* 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. */ ////////////////////////////////////////////////////////////////////////////////////////////// // conditions_geo_maxmind.cc: Implementation of the ConditionGeo class based on MaxMindDB // // #include <unistd.h> #include <arpa/inet.h> #include "ts/ts.h" #include "conditions_geo.h" #include <maxminddb.h> MMDB_s *gMaxMindDB = nullptr; void MMConditionGeo::initLibrary(const std::string &path) { if (path.empty()) { TSDebug(PLUGIN_NAME, "Empty MaxMind db path specified. Not initializing!"); return; } if (gMaxMindDB != nullptr) { TSDebug(PLUGIN_NAME, "Maxmind library already initialized"); return; } gMaxMindDB = new MMDB_s; int status = MMDB_open(path.c_str(), MMDB_MODE_MMAP, gMaxMindDB); if (MMDB_SUCCESS != status) { TSDebug(PLUGIN_NAME, "Cannot open %s - %s", path.c_str(), MMDB_strerror(status)); delete gMaxMindDB; return; } TSDebug(PLUGIN_NAME, "Loaded %s", path.c_str()); } std::string MMConditionGeo::get_geo_string(const sockaddr *addr) const { std::string ret = "(unknown)"; int mmdb_error; if (gMaxMindDB == nullptr) { TSDebug(PLUGIN_NAME, "MaxMind not initialized; using default value"); return ret; } MMDB_lookup_result_s result = MMDB_lookup_sockaddr(gMaxMindDB, addr, &mmdb_error); if (MMDB_SUCCESS != mmdb_error) { TSDebug(PLUGIN_NAME, "Error during sockaddr lookup: %s", MMDB_strerror(mmdb_error)); return ret; } MMDB_entry_data_list_s *entry_data_list = nullptr; if (!result.found_entry) { TSDebug(PLUGIN_NAME, "No entry for this IP was found"); return ret; } int status = MMDB_get_entry_data_list(&result.entry, &entry_data_list); if (MMDB_SUCCESS != status) { TSDebug(PLUGIN_NAME, "Error looking up entry data: %s", MMDB_strerror(status)); return ret; } if (entry_data_list == nullptr) { TSDebug(PLUGIN_NAME, "No data found"); return ret; } const char *field_name; switch (_geo_qual) { case GEO_QUAL_COUNTRY: field_name = "country_code"; break; case GEO_QUAL_ASN_NAME: field_name = "autonomous_system_organization"; break; default: TSDebug(PLUGIN_NAME, "Unsupported field %d", _geo_qual); return ret; break; } MMDB_entry_data_s entry_data; status = MMDB_get_value(&result.entry, &entry_data, field_name, NULL); if (MMDB_SUCCESS != status) { TSDebug(PLUGIN_NAME, "ERROR on get value asn value: %s", MMDB_strerror(status)); return ret; } ret = std::string(entry_data.utf8_string, entry_data.data_size); if (NULL != entry_data_list) { MMDB_free_entry_data_list(entry_data_list); } return ret; } int64_t MMConditionGeo::get_geo_int(const sockaddr *addr) const { int64_t ret = -1; int mmdb_error; if (gMaxMindDB == nullptr) { TSDebug(PLUGIN_NAME, "MaxMind not initialized; using default value"); return ret; } MMDB_lookup_result_s result = MMDB_lookup_sockaddr(gMaxMindDB, addr, &mmdb_error); if (MMDB_SUCCESS != mmdb_error) { TSDebug(PLUGIN_NAME, "Error during sockaddr lookup: %s", MMDB_strerror(mmdb_error)); return ret; } MMDB_entry_data_list_s *entry_data_list = nullptr; if (!result.found_entry) { TSDebug(PLUGIN_NAME, "No entry for this IP was found"); return ret; } int status = MMDB_get_entry_data_list(&result.entry, &entry_data_list); if (MMDB_SUCCESS != status) { TSDebug(PLUGIN_NAME, "Error looking up entry data: %s", MMDB_strerror(status)); return ret; } if (entry_data_list == nullptr) { TSDebug(PLUGIN_NAME, "No data found"); return ret; } const char *field_name; switch (_geo_qual) { case GEO_QUAL_ASN: field_name = "autonomous_system_number"; break; default: TSDebug(PLUGIN_NAME, "Unsupported field %d", _geo_qual); return ret; break; } MMDB_entry_data_s entry_data; status = MMDB_get_value(&result.entry, &entry_data, field_name, NULL); if (MMDB_SUCCESS != status) { TSDebug(PLUGIN_NAME, "ERROR on get value asn value: %s", MMDB_strerror(status)); return ret; } ret = entry_data.uint32; if (NULL != entry_data_list) { MMDB_free_entry_data_list(entry_data_list); } return ret; }
26.72973
94
0.695248
dsouza93
5e0ecfc5113812c3d487f1630c404c3619e03da4
6,480
cpp
C++
examples/RPG/PlayerStates.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
examples/RPG/PlayerStates.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
examples/RPG/PlayerStates.cpp
xcasadio/casaengine
19e34c0457265435c28667df7f2e5c137d954b98
[ "MIT" ]
null
null
null
#include "PlayerStates.h" #include "Game\Game.h" #include "PlayerController.h" #include "CharacterEnum.h" #include "MessageType.h" ////////////////////////////////////////////////////////////////////////// /** * */ PlayerStateIdle::PlayerStateIdle() { } /** * */ PlayerStateIdle::~PlayerStateIdle() { } /** * */ void PlayerStateIdle::Enter(IController* pController_) { PlayerController* pPlayerController = dynamic_cast<PlayerController*>(pController_); //TODO selon la direction definir l'animation Vector2F joyDir = Vector2F::Zero(); pPlayerController->GetPlayer()->Move(joyDir); if (pPlayerController->GetPlayer()->InFuryMode() == true) { //pPlayerController->GetHero()->SetCurrentAnimation(static_cast<int>(Character::AnimationIndices::FURY_IDLE)); pPlayerController->GetPlayer()->SetCurrentAnimationByName("swordman_stand"); } else { //pPlayerController->GetHero()->SetCurrentAnimation(static_cast<int>(Character::AnimationIndices::IDLE)); pPlayerController->GetPlayer()->SetCurrentAnimationByName("swordman_stand"); } } /** * */ void PlayerStateIdle::Execute(IController* pController_, const GameTime& elpasedTime_) { PlayerController* pPlayerController = dynamic_cast<PlayerController*>(pController_); //PlayerIndex playerIndex = c.PlayerIndex; orientation dir; Vector2F joyDir; if (pPlayerController->GetPlayer()->FuryModeEnabling() == true) { pPlayerController->FSM()->ChangeState(pPlayerController->GetState(static_cast<int>(TO_FURY_MODE))); return; } else if (pPlayerController->GetPlayer()->FuryModeDesabling() == true) { pPlayerController->FSM()->ChangeState(pPlayerController->GetState(static_cast<int>(TO_NORMAL_MODE))); return; } else if (pPlayerController->IsAttackButtonPressed() == true) { pPlayerController->FSM()->ChangeState(pPlayerController->GetState(static_cast<int>(ATTACK_1))); return; } dir = pPlayerController->GetDirectionFromInput(joyDir); if (dir != 0) { pPlayerController->GetPlayer()->SetOrientation(dir); } if (joyDir.x != 0.0f || joyDir.y != 0.0f) { //pPlayerController->FSM()->ChangeState(pPlayerController->GetState((int)PlayerControllerState::MOVING)); //return; /*if (charac.InFuryMode == true) { controller.Character.SetCurrentAnimation((int)Character.Character.AnimationIndices.FuryModeRun); } else {*/ pPlayerController->GetPlayer()->Move(joyDir); //pPlayerController->GetHero()->SetCurrentAnimation(static_cast<int>(Character::AnimationIndices::RUN)); pPlayerController->GetPlayer()->SetCurrentAnimationByName("swordman_walk"); //} } else // used to immobilized the character { joyDir = Vector2F::Zero(); pPlayerController->GetPlayer()->Move(joyDir); //pPlayerController->GetHero()->SetCurrentAnimation(static_cast<int>(Character::AnimationIndices::IDLE)); pPlayerController->GetPlayer()->SetCurrentAnimationByName("swordman_stand"); } } /** * */ void PlayerStateIdle::Exit(IController* pController_) { } /** * */ bool PlayerStateIdle::OnMessage(IController* pController_, const Telegram&) { return false; } ////////////////////////////////////////////////////////////////////////// /** * */ PlayerStateAttack::PlayerStateAttack() { } /** * */ PlayerStateAttack::~PlayerStateAttack() { } /** * */ void PlayerStateAttack::Enter(IController* pController_) { PlayerController* pPlayerController = dynamic_cast<PlayerController*>(pController_); //ranged attack reset // pPlayerController->GetHero()->AttackChargingValue(0.0f); // pPlayerController->GetHero()->IsAttackReleasing(false); // pPlayerController->GetHero()->AttackCharging(false); if (pPlayerController->GetPlayer()->FuryModeDesabling() == true) { pPlayerController->FSM()->ChangeState(pPlayerController->GetState(static_cast<int>(TO_NORMAL_MODE))); return; } // pPlayerController->GetHero()->DoANewAttack(); // pPlayerController->GetHero()->SetComboNumber(0); Vector2F joyDir = Vector2F::Zero(); pPlayerController->GetPlayer()->Move(joyDir); /*if (pPlayerController->GetHero()->InFuryMode() == true) { pPlayerController->GetHero()->SetCurrentAnimation(static_cast<int>(Character::AnimationIndices::FURY_ATTACK1)); } else*/ { //pPlayerController->GetHero()->SetCurrentAnimation(static_cast<int>(Character::AnimationIndices::ATTACK1)); pPlayerController->GetPlayer()->SetCurrentAnimationByName("swordman_attack"); } } /** * */ void PlayerStateAttack::Execute(IController* pController_, const GameTime& elpasedTime_) { //PlayerController* pPlayerController = dynamic_cast<PlayerController*>(pController_); //if (pPlayerController->GetHero()->AttackType() == Character::AttackType::Melee) { // if (pPlayerController->GetHero()->ComboNumber() == 0 // && pPlayerController->GetHero()->Animation2DPlayer.CurrentAnimation.CurrentFrameIndex >= 4 // && pPlayerController->IsAttackButtonPressed() == true) // { // pPlayerController->GetHero()->SetComboNumber(1); // } } // else // { // if (c.IsAttackButtonPressed(false) == true // && charac.IsAttackCharging == true // && charac.IsAttackReleasing == false) // { // charac.AttackChargingValue += elpasedTime_; // } // else if (c.IsAttackButtonPressed(false) == false) // { // charac.IsAttackReleasing = true; // } // } } /** * */ void PlayerStateAttack::Exit(IController* pController_) { } /** * */ bool PlayerStateAttack::OnMessage(IController* pController_, const Telegram& msg) { PlayerController* pPlayerController = dynamic_cast<PlayerController*>(pController_); if (msg.Msg == ANIMATION_FINISHED) { // if (pPlayerController->GetHero()->AttackType() == AttackType::Melee) { // if (pPlayerController->ComboNumber() == 1) // { // pPlayerController->FSM()->ChangeState(pPlayerController->GetState((int)PlayerControllerState::ATTACK_2)); // } // else { pPlayerController->FSM()->ChangeState(pPlayerController->GetState(static_cast<int>(IDLE))); } } // else // ranged attack // { // //if (charac.IsAttackReleasing == true) // //{ // pPlayerController->FSM()->ChangeState(pPlayerController->GetState((int)PlayerControllerState::ATTACK_2)); // //} // //else // //{ // pPlayerController->GetHero()->IsAttackCharging(true); // //} // } return true; } return false; }
26.557377
115
0.677623
xcasadio
5e128c8ea2389fa1b4b8a28b66725bcf46e13ce8
441
cpp
C++
CodeForces/Complete/300-399/387C-GeorgeAndNumber.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
36
2019-12-27T08:23:08.000Z
2022-01-24T20:35:47.000Z
CodeForces/Complete/300-399/387C-GeorgeAndNumber.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
10
2019-11-13T02:55:18.000Z
2021-10-13T23:28:09.000Z
CodeForces/Complete/300-399/387C-GeorgeAndNumber.cpp
Ashwanigupta9125/code-DS-ALGO
49f6cf7d0c682da669db23619aef3f80697b352b
[ "MIT" ]
53
2020-08-15T11:08:40.000Z
2021-10-09T15:51:38.000Z
#include <iostream> int main(){ std::ios_base::sync_with_stdio(false); std::string s; std::cin >> s; long ind(0), ans(0); while(ind < s.size()){ long cur = ind + 1; while(cur < s.size() && s[cur] == '0'){++cur;} if((cur - ind > ind) || (cur - ind == ind && s[0] < s[ind])){ans = 1;} else{++ans;} ind = cur; } std::cout << ans << std::endl; return 0; }
21
78
0.439909
Ashwanigupta9125
5e153cfdb5a3cbb686dfd3e2fb85717fcffcc061
275
cpp
C++
src/qlift-c-api/qlift-QVBoxLayout.cpp
msenol86/qlift-c-api
b591f1f020a6f35fdaf2a3ffee25aa98662cc027
[ "MIT" ]
null
null
null
src/qlift-c-api/qlift-QVBoxLayout.cpp
msenol86/qlift-c-api
b591f1f020a6f35fdaf2a3ffee25aa98662cc027
[ "MIT" ]
null
null
null
src/qlift-c-api/qlift-QVBoxLayout.cpp
msenol86/qlift-c-api
b591f1f020a6f35fdaf2a3ffee25aa98662cc027
[ "MIT" ]
1
2020-08-18T19:17:21.000Z
2020-08-18T19:17:21.000Z
#include <QVBoxLayout> #include "qlift-QVBoxLayout.h" void* QVBoxLayout_new(void *parent) { return static_cast<void*>(new QVBoxLayout {static_cast<QWidget*>(parent)}); } void QVBoxLayout_delete(void *vBoxLayout) { delete static_cast<QVBoxLayout*>(vBoxLayout); }
19.642857
79
0.741818
msenol86
5e17731587b4d27616943b43893ef0cf40f74b60
5,487
cc
C++
gw6c-messaging/src/windows/pipeio.cc
kevinmark/gw6c-6_0_1
8b774d2164e8964ee132a031b2a028e565b97ab4
[ "BSD-3-Clause" ]
1
2018-01-14T23:24:37.000Z
2018-01-14T23:24:37.000Z
gw6c-messaging/src/windows/pipeio.cc
kevinmark/gw6c-6_0_1
8b774d2164e8964ee132a031b2a028e565b97ab4
[ "BSD-3-Clause" ]
null
null
null
gw6c-messaging/src/windows/pipeio.cc
kevinmark/gw6c-6_0_1
8b774d2164e8964ee132a031b2a028e565b97ab4
[ "BSD-3-Clause" ]
null
null
null
// ************************************************************************** // $Id: pipeio.cc,v 1.4 2008/01/08 19:34:01 cnepveu Exp $ // // Copyright (c) 2007 Hexago Inc. All rights reserved. // // For license information refer to CLIENT-LICENSE.TXT // // Description: // Windows implementation of the PipeIO class. // // Author: Charles Nepveu // // Creation Date: November 2006 // __________________________________________________________________________ // ************************************************************************** #include <gw6cmessaging/pipeio.h> #include <windows.h> #include <assert.h> namespace gw6cmessaging { // -------------------------------------------------------------------------- // Function : PipeIO constructor // // Description: // Will initialize a new PipeIO object. // // Arguments: (none) // // Return values: (N/A) // // -------------------------------------------------------------------------- PipeIO::PipeIO( void ) : IPCServent() { } // -------------------------------------------------------------------------- // Function : PipeIO destructor // // Description: // Will clean-up space allocated during object lifetime. // // Arguments: (none) // // Return values: (N/A) // // -------------------------------------------------------------------------- PipeIO::~PipeIO( void ) { } // -------------------------------------------------------------------------- // Function : CanRead // // Description: // Will verify if a Read operation will be blocking. This is done by // verifying if there's data available for a read operation. // // Arguments: // bCanRead: boolean [OUT], Boolean indicating if there's data to read. // // Return values: // GW6CM_UIS__NOERROR: On successful peek // GW6CM_UIS_PEEKPIPEFAILED: Upon an IO error on the peek. // // -------------------------------------------------------------------------- error_t PipeIO::CanRead( bool& bCanRead ) const { error_t retCode = GW6CM_UIS__NOERROR; DWORD nBytesAvailable; // Verify IPC handle. assert( m_Handle != INVALID_HANDLE_VALUE ); // Take a peek at the pipe to see if we've got stuff to read. if( PeekNamedPipe( m_Handle, NULL, 0, NULL, &nBytesAvailable, NULL ) == 0 ) { // PeekNamedPipe failed. retCode = GW6CM_UIS_PEEKPIPEFAILED; nBytesAvailable = 0; } // Set whether we can read or not. bCanRead = (nBytesAvailable > 0); // Return operation result. return retCode; } // -------------------------------------------------------------------------- // Function : CanWrite // // Description: // Will verify if a Write operation will be blocking. // // Arguments: // bCanWrite: boolean [OUT], Boolean indicating if it's possible to write. // // Return values: // GW6CM_UIS__NOERROR: On successful peek // GW6CM_UIS_PEEKPIPEFAILED: Upon an IO error on the peek. // // -------------------------------------------------------------------------- error_t PipeIO::CanWrite( bool& bCanWrite ) const { error_t retCode = GW6CM_UIS__NOERROR; DWORD dummy; // Verify IPC handle. assert( m_Handle != INVALID_HANDLE_VALUE ); bCanWrite = true; // This (dummy) call to PeekNamedPipe will verify if the handle is valid. if( PeekNamedPipe( m_Handle, NULL, 0, NULL, &dummy, NULL ) == 0 ) { // PeekNamedPipe failed. retCode = GW6CM_UIS_PEEKPIPEFAILED; bCanWrite = false; } // ----------------------------------------------------------- // Writing should not block, except if send buffer is full... // ... and there's no way of knowing that. // ----------------------------------------------------------- // Return operation result. return retCode; } // -------------------------------------------------------------------------- // Function : Read // // Description: // Will attempt to receive data from the pipe. // // Arguments: // pvReadBuffer: void* [OUT], The receiving buffer. // nBufferSize: int [IN], The size in bytes allocated for read at the // receive buffer. // // Return values: // GW6CM_UIS__NOERROR: Operation successful. // Any other value is an error. // // -------------------------------------------------------------------------- error_t PipeIO::Read( void* pvReadBuffer, const uint32_t nBufferSize, uint32_t& nRead ) { // Verify IPC handle. assert( m_Handle != INVALID_HANDLE_VALUE ); // Read from pipe. if( ReadFile( m_Handle, pvReadBuffer, (DWORD)nBufferSize, (DWORD*)(&nRead), NULL ) == 0 ) { return GW6CM_UIS_READPIPEFAILED; } // Operation successful. return GW6CM_UIS__NOERROR; } // -------------------------------------------------------------------------- // Function : Write // // Description: // Will attempt to write data to the pipe. // // Arguments: // pvData: void* [IN], The receiving buffer. // nDataSize: uint32_t [IN], The size in bytes to write. // nWritten: uint32_t [OUT], The number of bytes written. // // Return values: // GW6CM_UIS__NOERROR: Operation successful. // Any other value is an error. // // -------------------------------------------------------------------------- error_t PipeIO::Write( const void* pvData, const uint32_t nDataSize, uint32_t& nWritten ) { // Verify IPC handle. assert( m_Handle != INVALID_HANDLE_VALUE ); // Write to pipe. if( WriteFile( m_Handle, pvData, (DWORD)nDataSize, (DWORD*)(&nWritten), NULL ) == 0 ) { return GW6CM_UIS_WRITEPIPEFAILED; } // Operation successful. return GW6CM_UIS__NOERROR; } }
27.029557
91
0.531256
kevinmark
5e18e155b88423045bbb6456e5d6e6057c432eac
1,107
cpp
C++
AtCoder/ABC132/B.cpp
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
1
2018-11-25T04:15:45.000Z
2018-11-25T04:15:45.000Z
AtCoder/ABC132/B.cpp
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
null
null
null
AtCoder/ABC132/B.cpp
takaaki82/Java-Lessons
c4f11462bf84c091527dde5f25068498bfb2cc49
[ "MIT" ]
2
2018-08-08T13:01:14.000Z
2018-11-25T12:38:36.000Z
#include<iostream> #include<string> #include<cstdio> #include<vector> #include<cmath> #include<algorithm> #include<functional> #include<iomanip> #include<queue> #include<ciso646> #include<random> #include<map> #include<set> #include<complex> #include<bitset> #include<stack> #include<unordered_map> #include<utility> #include<cassert> using namespace std; const int MOD = 1000000007; typedef pair<int, int> P; typedef long long ll; #define rep(i, n) for(int i=0;i<n;i++) #define rep2(i, m, n) for(int i=m;i<n;i++) #define rrep(i, n, m) for(int i=n;i>=m;i--) using Graph = vector<vector<int>>; const int dx[4] = {1, 0, -1, 0}; const int dy[4] = {0, 1, 0, -1}; int main() { cin.tie(0); ios::sync_with_stdio(false); int n; cin >> n; vector<int> P; rep(i, n) { int p; cin >> p; P.push_back(p); } int ans; rep(i, n - 2) { int f = P[i]; int s = P[i + 1]; int t = P[i + 2]; if (f < s && s < t) { ans++; } if (t < s && s < f) { ans++; } } cout << ans << endl; }
18.45
43
0.539295
takaaki82
5e1aebe481561d2129791044d1187800e57398e6
1,285
cpp
C++
enduser/troubleshoot/tshoot/mutexowner.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
enduser/troubleshoot/tshoot/mutexowner.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
enduser/troubleshoot/tshoot/mutexowner.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// // MODULE: MutexOwner.cpp // // PURPOSE: strictly a utility class so we can properly construct & destruct a static mutex. // // COMPANY: Saltmine Creative, Inc. (206)-284-7511 support@saltmine.com // // AUTHOR: Oleg Kalosha, Joe Mabel // // ORIGINAL DATE: 11-04-98 // // NOTES: // // Version Date By Comments //-------------------------------------------------------------------- // V3.0 11-04-98 JM extracted from SafeTime // #include "stdafx.h" #include "MutexOwner.h" #include "BaseException.h" #include "Event.h" ////////////////////////////////////////////////////////////////////// //CMutexOwner ////////////////////////////////////////////////////////////////////// CMutexOwner::CMutexOwner(const CString & str) { m_hmutex = ::CreateMutex(NULL, FALSE, NULL); if (!m_hmutex) { // Shouldn't ever happen, so we're not coming up with any elaborate strategy, // but at least we log it. CBuildSrcFileLinenoStr SrcLoc( __FILE__, __LINE__ ); CEvent::ReportWFEvent( SrcLoc.GetSrcFileLineStr(), SrcLoc.GetSrcFileLineStr(), str, _T(""), EV_GTS_ERROR_MUTEX ); } } CMutexOwner::~CMutexOwner() { ::CloseHandle(m_hmutex); } HANDLE & CMutexOwner::Handle() { return m_hmutex; }
23.796296
93
0.535409
npocmaka
5e219979614a3a89bfe2ed0736b7e2962595a3bf
1,183
cpp
C++
qml_2048/src/main.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
qml_2048/src/main.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
qml_2048/src/main.cpp
codingpotato/clean-2048
70e3a7ae31c403195900db9a811985435365edf8
[ "MIT" ]
null
null
null
#include <QApplication> #include <QQmlApplicationEngine> #include "qt_view_model/BoardViewModel.h" #include "qt_view_model/Controller.h" #include "qt_view_model/GameOverViewModel.h" #include "qt_view_model/ScoreViewModel.h" #include "router/Router.h" #include "storage/Storage.h" int main(int argc, char *argv[]) { presenter::setRouter(std::make_unique<router::Router>()); use_case::setStorage(std::make_unique<storage::Storage>()); qmlRegisterType<qt_view_model::Controller>("Clean_2048.Controller", 1, 0, "Controller"); qmlRegisterType<qt_view_model::BoardViewModel>("Clean_2048.BoardViewModel", 1, 0, "BoardViewModel"); qmlRegisterType<qt_view_model::ScoreViewModel>("Clean_2048.ScoreViewModel", 1, 0, "ScoreViewModel"); qmlRegisterType<qt_view_model::GameOverViewModel>( "Clean_2048.GameOverViewModel", 1, 0, "GameOverViewModel"); QApplication app(argc, argv); app.setApplicationName("2048"); QQmlApplicationEngine engine; engine.load(QUrl(QStringLiteral("qrc:///qml/Main.qml"))); return app.exec(); }
36.96875
80
0.671175
codingpotato
5e22d170643be63031a58fb70f2f67444205f08d
6,317
cpp
C++
funcs/http_server_func/func.cpp
andersgjerdrum/diggi
c072911c439758b6f1bb1d9972c6fc32aa49d560
[ "Intel", "CC-BY-3.0", "MIT-CMU" ]
null
null
null
funcs/http_server_func/func.cpp
andersgjerdrum/diggi
c072911c439758b6f1bb1d9972c6fc32aa49d560
[ "Intel", "CC-BY-3.0", "MIT-CMU" ]
null
null
null
funcs/http_server_func/func.cpp
andersgjerdrum/diggi
c072911c439758b6f1bb1d9972c6fc32aa49d560
[ "Intel", "CC-BY-3.0", "MIT-CMU" ]
null
null
null
#include "runtime/func.h" #include "messaging/IMessageManager.h" #include "posix/stdio_stubs.h" #include <stdio.h> #include <inttypes.h> #include "runtime/DiggiAPI.h" #include "network/HTTP.h" #include "network/Connection.h" #include "posix/net_stubs.h" /*HTTP server func*/ static Connection *server_connection = nullptr; static SimpleTCP *api = nullptr; static DiggiAPI *a_con = nullptr; #define SERVER_PORT "7000" static size_t MaxDataSize = 1024 * 10; /*1mb max size*/ static std::map<string, zcstring> page_cache_map; typedef struct AsyncContext<int, DiggiAPI*, char*, size_t, char*, size_t, async_cb_t, http_request *> storage_context_t; void read_source_cb(void *ptr, int status); void open_source_cb(void * ptr, int status); void func_respond_done_cb(void *ptr, int status) { DIGGI_ASSERT(ptr); auto resp = (http_response *)ptr; a_con->GetLogObject()->Log("respond done: done sending HTTP response\n"); auto con = resp->GetConnection(); con->close(); delete con; delete resp; } void func_respond_ok(IConnection *connection, zcstring body) { ALIGNED_CONST_CHAR(8) http[] = "HTTP/1.1"; zcstring http_str(http); ALIGNED_CONST_CHAR(8) contenttype[] = "text/html"; zcstring cont_string(contenttype); ALIGNED_CONST_CHAR(8) type[] = "OK"; zcstring type_str(type); ALIGNED_CONST_CHAR(8) twohundred[] = "200"; zcstring twohundred_str(twohundred); auto re = new http_response(connection, a_con->GetLogObject()); re->set_response_type(type_str); re->set_status_code(twohundred_str); re->set_protocol_version(http_str); re->set_header("Content-Type", cont_string); re->body = body; re->Send(func_respond_done_cb, re); } void func_get_file(zcstring url, async_cb_t cb, http_request * context) { string path = url.tostring(); if (path.compare("/") == 0) { path = "index.html"; //standard site start } auto storg = a_con->GetStorageManager(); char *dat = (char*)malloc(MaxDataSize); auto resp_ctx = new storage_context_t(0, a_con, dat, MaxDataSize, dat, 0, cb, context); storg->async_open(path.c_str(), O_RDONLY, 0, open_source_cb, resp_ctx, false); } void func_respond_notfound(storage_context_t * ctx) { ALIGNED_CONST_CHAR(8) http[] = "HTTP/1.1"; zcstring http_str(http); ALIGNED_CONST_CHAR(8) contenttype[] = "text/html"; zcstring cont_string(contenttype); ALIGNED_CONST_CHAR(8) type[] = "Not Found"; zcstring type_str(type); ALIGNED_CONST_CHAR(8) twohundred[] = "404"; zcstring twohundred_str(twohundred); auto re = new http_response(ctx->item8->GetConnection(), a_con->GetLogObject()); re->set_response_type(type_str); re->set_status_code(twohundred_str); re->set_protocol_version(http_str); re->set_header("Content-Type", cont_string); re->Send(func_respond_done_cb, re); delete ctx->item8; delete ctx; } void open_source_cb(void * ptr, int status) { DIGGI_ASSERT(ptr); auto resp = (msg_async_response_t *)ptr; auto ctx = (storage_context_t*)resp->context; DIGGI_ASSERT(ctx); DIGGI_ASSERT(ctx->item2); auto a_context = ctx->item2; memcpy(&ctx->item1, resp->msg->data, sizeof(int)); DIGGI_ASSERT(resp->msg->size == (sizeof(msg_t) + sizeof(int))); memcpy(&ctx->item1, resp->msg->data, sizeof(int)); if (ctx->item1 == -1) { func_respond_notfound(ctx); return; } a_context->GetStorageManager()->async_read(ctx->item1, ctx->item3, ctx->item4, read_source_cb, ctx, false); } void read_source_cb(void *ptr, int status) { DIGGI_ASSERT(ptr); auto resp = (msg_async_response_t *)ptr; auto ctx = (storage_context_t*)resp->context; DIGGI_ASSERT(ctx); DIGGI_ASSERT(ctx->item2); DIGGI_ASSERT(ctx->item3); auto a_cont = ctx->item2; size_t chunk_size; memcpy(&chunk_size, resp->msg->data, sizeof(size_t)); DIGGI_ASSERT(chunk_size <= ctx->item4); ctx->item6 += chunk_size; /*Carrying an additional size for determining if buffer is empty*/ auto ptr_data = resp->msg->data + sizeof(size_t) + sizeof(off_t); memcpy(ctx->item3, ptr_data, chunk_size); if (chunk_size < ctx->item4) { //done with transfer ctx->item2->GetLogObject()->Log(LDEBUG, "done with transfer, chunk_size=%lu ....\n", chunk_size); DIGGI_DEBUG_BREAK(); a_cont->GetStorageManager()->async_close(ctx->item1, ctx->item7, ctx); } else { ctx->item4 -= chunk_size; ctx->item3 += chunk_size; /*May be more in file*/ open_source_cb(ctx, 1); } } void func_cache_page(void *ptr, int status) { DIGGI_ASSERT(ptr); auto resp = (msg_async_response_t *)ptr; auto ctx = (storage_context_t*)resp->context; DIGGI_ASSERT(ctx); DIGGI_ASSERT(ctx->item5); zcstring dat(ctx->item5, ctx->item6); http_request *req = ctx->item8; page_cache_map[req->url.tostring()] = dat; func_respond_ok(req->GetConnection(), dat); delete req; delete ctx; } void func_handle_get(http_request *req) { a_con->GetLogObject()->Log("Request path %s\n" ,req->url.tostring().c_str()); func_get_file(req->url, func_cache_page, req); } void func_handle_post(http_request *req) { } void func_http_incomming_cb(void *ptr, int status) { ALIGNED_CONST_CHAR(8) get_method[] = "GET"; ALIGNED_CONST_CHAR(8) post_method[] = "POST"; DIGGI_ASSERT(ptr); auto re = (http_request*)ptr; if (re->request_type.compare(get_method)) { func_handle_get(re); } else if (re->request_type.compare(post_method)) { func_handle_post(re); } else { DIGGI_ASSERT(false); /* Not supported http request type */ } //func_respond_ok(re->GetConnection()); } void func_incomming_http(void* ptr, int status) { DIGGI_ASSERT(ptr); auto con = (Connection*)ptr; auto re = new http_request(con, a_con->GetLogObject()); a_con->GetLogObject()->Log("Incomming http connection\n"); re->Get(func_http_incomming_cb, re); } void func_init(void * ctx, int status) { DIGGI_ASSERT(ctx); a_con = (DiggiAPI*)ctx; a_con->GetLogObject()->Log("func_init:http func\n"); api = new SimpleTCP(); server_connection = new Connection(a_con->GetThreadPool(), func_incomming_http, api, a_con->GetLogObject()); server_connection->InitializeServer(NULL, SERVER_PORT); //do nothing } void func_start(void *ctx, int status) { DIGGI_ASSERT(ctx); a_con->GetLogObject()->Log("func_start:http func\n"); } void func_stop(void *ctx, int status) { DIGGI_ASSERT(ctx); a_con->GetLogObject()->Log("func_stop:http func\n"); server_connection->close(); delete server_connection; delete api; }
26.211618
120
0.721862
andersgjerdrum
5e2fe59e43c6352ff716e678a91e1eca30072d45
720
hpp
C++
src/almost/primesieve-5.6.0/include/primesieve/PrimeGenerator.hpp
bgwines/project-euler
06c0dd8e4b2de2909bb8f48e9b02d181de7a19b0
[ "BSD-3-Clause" ]
null
null
null
src/almost/primesieve-5.6.0/include/primesieve/PrimeGenerator.hpp
bgwines/project-euler
06c0dd8e4b2de2909bb8f48e9b02d181de7a19b0
[ "BSD-3-Clause" ]
null
null
null
src/almost/primesieve-5.6.0/include/primesieve/PrimeGenerator.hpp
bgwines/project-euler
06c0dd8e4b2de2909bb8f48e9b02d181de7a19b0
[ "BSD-3-Clause" ]
null
null
null
/// /// @file PrimeGenerator.hpp /// /// Copyright (C) 2014 Kim Walisch, <kim.walisch@gmail.com> /// /// This file is distributed under the BSD License. See the COPYING /// file in the top level directory. /// #ifndef PRIMEGENERATOR_HPP #define PRIMEGENERATOR_HPP #include "config.hpp" #include "SieveOfEratosthenes.hpp" namespace primesieve { class PrimeFinder; class PrimeGenerator : public SieveOfEratosthenes { public: PrimeGenerator(PrimeFinder&); void doIt(); private: PrimeFinder& finder_; void segmentFinished(const byte_t*, uint_t); void generateSievingPrimes(const byte_t*, uint_t); void generateTinyPrimes(); DISALLOW_COPY_AND_ASSIGN(PrimeGenerator); }; } // namespace primesieve #endif
20.571429
67
0.748611
bgwines
5e34eb513c2b64479d3f73b97ccd486a633c8cf6
902
hpp
C++
libs/PhiCore/include/phi/compiler_support/nodiscard.hpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
3
2020-12-21T13:47:35.000Z
2022-03-16T23:53:21.000Z
libs/PhiCore/include/phi/compiler_support/nodiscard.hpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
53
2020-08-07T07:46:57.000Z
2022-02-12T11:07:08.000Z
libs/PhiCore/include/phi/compiler_support/nodiscard.hpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
1
2020-08-19T15:50:02.000Z
2020-08-19T15:50:02.000Z
#ifndef INCG_PHI_CORE_COMPILER_SUPPORT_NODISCARD_HPP #define INCG_PHI_CORE_COMPILER_SUPPORT_NODISCARD_HPP #include "phi/phi_config.hpp" #if PHI_HAS_EXTENSION_PRAGMA_ONCE() # pragma once #endif #include "phi/compiler_support/compiler.hpp" #include "phi/compiler_support/cpp_standard.hpp" #if PHI_HAS_FEATURE_NODISCARD() # define PHI_NODISCARD [[nodiscard]] # define PHI_NODISCARD_CLASS [[nodiscard]] #elif PHI_HAS_EXTENSION_ATTRIBUTE_WARN_UNUSED_RESULT() # define PHI_NODISCARD __attribute__((warn_unused_result)) # define PHI_NODISCARD_CLASS __attribute__((warn_unused_result)) #elif PHI_HAS_EXTENSION_CHECK_RETURN() # define PHI_NODISCARD _Check_return_ # define PHI_NODISCARD_CLASS /* Nothing */ #else # define PHI_NODISCARD /* Nothing */ # define PHI_NODISCARD_CLASS /* Nothing */ #endif #endif // INCG_PHI_CORE_COMPILER_SUPPORT_NODISCARD_HPP
32.214286
67
0.783814
AMS21
5e3501caa01b8de791dc1cedde034bd3a614aedf
13,846
hxx
C++
Components/Metrics/StatisticalShapePenalty/elxStatisticalShapePenalty.hxx
joasiee/elastix
c765ca8959fc288c19b0c7f75875b70f939581de
[ "Apache-2.0" ]
null
null
null
Components/Metrics/StatisticalShapePenalty/elxStatisticalShapePenalty.hxx
joasiee/elastix
c765ca8959fc288c19b0c7f75875b70f939581de
[ "Apache-2.0" ]
null
null
null
Components/Metrics/StatisticalShapePenalty/elxStatisticalShapePenalty.hxx
joasiee/elastix
c765ca8959fc288c19b0c7f75875b70f939581de
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright UMC Utrecht and contributors * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef elxStatisticalShapePenalty_hxx #define elxStatisticalShapePenalty_hxx #include "elxStatisticalShapePenalty.h" #include "itkTransformixInputPointFileReader.h" #include "itkPointSet.h" #include "itkDefaultStaticMeshTraits.h" #include "itkVTKPolyDataReader.h" #include "itkVTKPolyDataWriter.h" #include "itkTransformMeshFilter.h" #include <itkMesh.h> #include <fstream> #include <typeinfo> namespace elastix { /** * ******************* Initialize *********************** */ template <class TElastix> void StatisticalShapePenalty<TElastix>::Initialize() { itk::TimeProbe timer; timer.Start(); this->Superclass1::Initialize(); timer.Stop(); elxout << "Initialization of StatisticalShape metric took: " << static_cast<long>(timer.GetMean() * 1000) << " ms." << std::endl; } // end Initialize() /** * ***************** BeforeRegistration *********************** */ template <class TElastix> void StatisticalShapePenalty<TElastix>::BeforeRegistration() { /** Get and set NormalizedShapeModel. Default TRUE. */ bool normalizedShapeModel = true; this->GetConfiguration()->ReadParameter(normalizedShapeModel, "NormalizedShapeModel", 0, 0); this->SetNormalizedShapeModel(normalizedShapeModel); /** Get and set NormalizedShapeModel. Default TRUE. */ int shapeModelCalculation = 0; this->GetConfiguration()->ReadParameter(shapeModelCalculation, "ShapeModelCalculation", 0, 0); this->SetShapeModelCalculation(shapeModelCalculation); /** Read and set the fixed pointset. */ std::string fixedName = this->GetConfiguration()->GetCommandLineArgument("-fp"); typename PointSetType::Pointer fixedPointSet; // default-constructed (null) const typename ImageType::ConstPointer fixedImage = this->GetElastix()->GetFixedImage(); const unsigned int nrOfFixedPoints = this->ReadShape(fixedName, fixedPointSet, fixedImage); this->SetFixedPointSet(fixedPointSet); // itkCombinationImageToImageMetric.hxx checks if metric base class is ImageMetricType or PointSetMetricType. // This class is derived from SingleValuedPointSetToPointSetMetric which needs a moving pointset. this->SetMovingPointSet(fixedPointSet); // TODO: make itkCombinationImageToImageMetric check for a base class metric that doesn't use an image or moving // pointset. /** Read meanVector filename. */ std::string meanVectorName = this->GetConfiguration()->GetCommandLineArgument("-mean"); std::ifstream datafile; vnl_vector<double> * const meanVector = new vnl_vector<double>(); datafile.open(meanVectorName.c_str()); if (datafile.is_open()) { meanVector->read_ascii(datafile); datafile.close(); datafile.clear(); elxout << " meanVector " << meanVectorName << " read" << std::endl; } else { itkExceptionMacro(<< "Unable to open meanVector file: " << meanVectorName); } this->SetMeanVector(meanVector); /** Check. */ if (normalizedShapeModel) { if (nrOfFixedPoints * Self::FixedPointSetDimension != meanVector->size() - Self::FixedPointSetDimension - 1) { itkExceptionMacro(<< "ERROR: the number of elements in the meanVector (" << meanVector->size() << ") does not match the number of points of the fixed pointset (" << nrOfFixedPoints << ") times the point dimensionality (" << Self::FixedPointSetDimension << ") plus a Centroid of dimension " << Self::FixedPointSetDimension << " plus a size element"); } } else { if (nrOfFixedPoints * Self::FixedPointSetDimension != meanVector->size()) { itkExceptionMacro(<< "ERROR: the number of elements in the meanVector (" << meanVector->size() << ") does not match the number of points of the fixed pointset (" << nrOfFixedPoints << ") times the point dimensionality (" << Self::FixedPointSetDimension << ")"); } } /** Read covariance matrix filename. */ std::string covarianceMatrixName = this->GetConfiguration()->GetCommandLineArgument("-covariance"); vnl_matrix<double> * const covarianceMatrix = new vnl_matrix<double>(); datafile.open(covarianceMatrixName.c_str()); if (datafile.is_open()) { covarianceMatrix->read_ascii(datafile); datafile.close(); datafile.clear(); elxout << "covarianceMatrix " << covarianceMatrixName << " read" << std::endl; } else { itkExceptionMacro(<< "Unable to open covarianceMatrix file: " << covarianceMatrixName); } this->SetCovarianceMatrix(covarianceMatrix); /** Read eigenvector matrix filename. */ std::string eigenVectorsName = this->GetConfiguration()->GetCommandLineArgument("-evectors"); vnl_matrix<double> * const eigenVectors = new vnl_matrix<double>(); datafile.open(eigenVectorsName.c_str()); if (datafile.is_open()) { eigenVectors->read_ascii(datafile); datafile.close(); datafile.clear(); elxout << "eigenvectormatrix " << eigenVectorsName << " read" << std::endl; } else { // \todo: remove outcommented code: // itkExceptionMacro( << "Unable to open EigenVectors file: " << eigenVectorsName); } this->SetEigenVectors(eigenVectors); /** Read eigenvalue vector filename. */ std::string eigenValuesName = this->GetConfiguration()->GetCommandLineArgument("-evalues"); vnl_vector<double> * const eigenValues = new vnl_vector<double>(); datafile.open(eigenValuesName.c_str()); if (datafile.is_open()) { eigenValues->read_ascii(datafile); datafile.close(); datafile.clear(); elxout << "eigenvaluevector " << eigenValuesName << " read" << std::endl; } else { // itkExceptionMacro( << "Unable to open EigenValues file: " << eigenValuesName); } this->SetEigenValues(eigenValues); } // end BeforeRegistration() /** * ***************** BeforeEachResolution *********************** */ template <class TElastix> void StatisticalShapePenalty<TElastix>::BeforeEachResolution() { /** Get the current resolution level. */ unsigned int level = this->m_Registration->GetAsITKBaseType()->GetCurrentLevel(); /** Get and set ShrinkageIntensity. Default 0.5. */ double shrinkageIntensity = 0.5; this->GetConfiguration()->ReadParameter( shrinkageIntensity, "ShrinkageIntensity", this->GetComponentLabel(), level, 0); if (this->GetShrinkageIntensity() != shrinkageIntensity) { this->SetShrinkageIntensityNeedsUpdate(true); } this->SetShrinkageIntensity(shrinkageIntensity); /** Get and set BaseVariance. Default 1000. */ double baseVariance = 1000; this->GetConfiguration()->ReadParameter(baseVariance, "BaseVariance", this->GetComponentLabel(), level, 0); if (this->GetBaseVariance() != baseVariance) { this->SetBaseVarianceNeedsUpdate(true); } this->SetBaseVariance(baseVariance); /** Get and set CentroidXVariance. Default 10. */ double centroidXVariance = 10; this->GetConfiguration()->ReadParameter(centroidXVariance, "CentroidXVariance", this->GetComponentLabel(), level, 0); if (this->GetCentroidXVariance() != centroidXVariance) { this->SetVariancesNeedsUpdate(true); } this->SetCentroidXVariance(centroidXVariance); /** Get and set CentroidYVariance. Default 10. */ double centroidYVariance = 10; this->GetConfiguration()->ReadParameter(centroidYVariance, "CentroidYVariance", this->GetComponentLabel(), level, 0); if (this->GetCentroidYVariance() != centroidYVariance) { this->SetVariancesNeedsUpdate(true); } this->SetCentroidYVariance(centroidYVariance); /** Get and set CentroidZVariance. Default 10. */ double centroidZVariance = 10; this->GetConfiguration()->ReadParameter(centroidZVariance, "CentroidZVariance", this->GetComponentLabel(), level, 0); if (this->GetCentroidZVariance() != centroidZVariance) { this->SetVariancesNeedsUpdate(true); } this->SetCentroidZVariance(centroidZVariance); /** Get and set SizeVariance. Default 10. */ double sizeVariance = 10; this->GetConfiguration()->ReadParameter(sizeVariance, "SizeVariance", this->GetComponentLabel(), level, 0); if (this->GetSizeVariance() != sizeVariance) { this->SetVariancesNeedsUpdate(true); } this->SetSizeVariance(sizeVariance); /** Get and set CutOffValue. Default 0. */ double cutOffValue = 0; this->GetConfiguration()->ReadParameter(cutOffValue, "CutOffValue", this->GetComponentLabel(), level, 0); this->SetCutOffValue(cutOffValue); /** Get and set CutOffSharpness. Default 2. */ double cutOffSharpness = 2.0; this->GetConfiguration()->ReadParameter(cutOffSharpness, "CutOffSharpness", this->GetComponentLabel(), level, 0); this->SetCutOffSharpness(cutOffSharpness); } // end BeforeEachResolution() /** * ***************** ReadLandmarks *********************** */ template <class TElastix> unsigned int StatisticalShapePenalty<TElastix>::ReadLandmarks(const std::string & landmarkFileName, typename PointSetType::Pointer & pointSet, const typename ImageType::ConstPointer image) { /** Typedefs. */ using IndexType = typename ImageType::IndexType; using IndexValueType = typename ImageType::IndexValueType; using PointType = typename ImageType::PointType; using PointSetReaderType = itk::TransformixInputPointFileReader<PointSetType>; elxout << "Loading landmarks for " << this->GetComponentLabel() << ":" << this->elxGetClassName() << "." << std::endl; /** Read the landmarks. */ auto reader = PointSetReaderType::New(); reader->SetFileName(landmarkFileName.c_str()); elxout << " Reading landmark file: " << landmarkFileName << std::endl; try { reader->Update(); } catch (itk::ExceptionObject & err) { xl::xout["error"] << " Error while opening " << landmarkFileName << std::endl; xl::xout["error"] << err << std::endl; itkExceptionMacro(<< "ERROR: unable to configure " << this->GetComponentLabel()); } /** Some user-feedback. */ const unsigned int nrofpoints = reader->GetNumberOfPoints(); if (reader->GetPointsAreIndices()) { elxout << " Landmarks are specified as image indices." << std::endl; } else { elxout << " Landmarks are specified in world coordinates." << std::endl; } elxout << " Number of specified points: " << nrofpoints << std::endl; /** Get the pointset. */ pointSet = reader->GetOutput(); /** Convert from index to point if necessary */ pointSet->DisconnectPipeline(); if (reader->GetPointsAreIndices()) { /** Convert to world coordinates */ for (unsigned int j = 0; j < nrofpoints; ++j) { /** The landmarks from the pointSet are indices. We first cast to the * proper type, and then convert it to world coordinates. */ PointType point; IndexType index; pointSet->GetPoint(j, &point); for (unsigned int d = 0; d < FixedImageDimension; ++d) { index[d] = static_cast<IndexValueType>(vnl_math::rnd(point[d])); } /** Compute the input point in physical coordinates. */ image->TransformIndexToPhysicalPoint(index, point); pointSet->SetPoint(j, point); } // end for all points } // end for points are indices return nrofpoints; } // end ReadLandmarks() /** * ************** TransformPointsSomePointsVTK ********************* */ template <class TElastix> unsigned int StatisticalShapePenalty<TElastix>::ReadShape(const std::string & ShapeFileName, typename PointSetType::Pointer & pointSet, const typename ImageType::ConstPointer image) { /** Typedef's. \todo test DummyIPPPixelType=bool. */ using DummyIPPPixelType = double; using MeshTraitsType = DefaultStaticMeshTraits<DummyIPPPixelType, FixedImageDimension, FixedImageDimension, CoordRepType>; using MeshType = Mesh<DummyIPPPixelType, FixedImageDimension, MeshTraitsType>; using MeshReaderType = VTKPolyDataReader<MeshType>; /** Read the input points. */ auto meshReader = MeshReaderType::New(); meshReader->SetFileName(ShapeFileName.c_str()); elxout << " Reading input point file: " << ShapeFileName << std::endl; try { meshReader->Update(); } catch (ExceptionObject & err) { xl::xout["error"] << " Error while opening input point file." << std::endl; xl::xout["error"] << err << std::endl; } /** Some user-feedback. */ elxout << " Input points are specified in world coordinates." << std::endl; unsigned long nrofpoints = meshReader->GetOutput()->GetNumberOfPoints(); elxout << " Number of specified input points: " << nrofpoints << std::endl; typename MeshType::Pointer mesh = meshReader->GetOutput(); pointSet = PointSetType::New(); pointSet->SetPoints(mesh->GetPoints()); return nrofpoints; } // end ReadShape() } // end namespace elastix #endif // end #ifndef elxStatisticalShapePenalty_hxx
35.231552
120
0.669002
joasiee
5e37b8cc9172d77cb987b9143aa6861d46b6fb4d
664
cpp
C++
views/formview/emptyformwidget.cpp
DatabasesWorks/passiflora-symphytum-configurable-fields
6128d0391fe33438250efad4398d65c5982b005b
[ "BSD-2-Clause" ]
2
2017-10-01T07:59:54.000Z
2021-09-09T14:40:41.000Z
views/formview/emptyformwidget.cpp
DatabasesWorks/passiflora-symphytum-configurable-fields
6128d0391fe33438250efad4398d65c5982b005b
[ "BSD-2-Clause" ]
3
2017-11-01T15:42:46.000Z
2019-02-18T08:42:33.000Z
views/formview/emptyformwidget.cpp
DatabasesWorks/passiflora-symphytum-configurable-fields
6128d0391fe33438250efad4398d65c5982b005b
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2012 Giorgio Wicklein <giowckln@gmail.com> */ //----------------------------------------------------------------------------- // Hearders //----------------------------------------------------------------------------- #include "emptyformwidget.h" #include "ui_emptyformwidget.h" //----------------------------------------------------------------------------- // Public //----------------------------------------------------------------------------- EmptyFormWidget::EmptyFormWidget(QWidget *parent) : QWidget(parent), ui(new Ui::EmptyFormWidget) { ui->setupUi(this); } EmptyFormWidget::~EmptyFormWidget() { delete ui; }
23.714286
79
0.356928
DatabasesWorks
5e39b73f987ee318d848bae4454be807c3c02182
13,258
cpp
C++
src/AudioDevicesMacOS.cpp
fredemmott/AudioDeviceLib
01a2776440a4b570bbe18210d0a12858cd7de3b8
[ "MIT" ]
3
2021-06-05T12:14:27.000Z
2021-08-12T05:08:31.000Z
src/AudioDevicesMacOS.cpp
fredemmott/AudioDeviceLib
01a2776440a4b570bbe18210d0a12858cd7de3b8
[ "MIT" ]
null
null
null
src/AudioDevicesMacOS.cpp
fredemmott/AudioDeviceLib
01a2776440a4b570bbe18210d0a12858cd7de3b8
[ "MIT" ]
1
2021-11-17T15:00:51.000Z
2021-11-17T15:00:51.000Z
/* Copyright (c) 2019-present, Fred Emmott * * This source code is licensed under the MIT-style license found in the * LICENSE file. */ #include <CoreAudio/CoreAudio.h> #include "AudioDevices.h" namespace FredEmmott::Audio { namespace { std::string Utf8StringFromCFString(CFStringRef ref, size_t buf_size = 1024) { // Re-use the existing buffer if possible... auto ptr = CFStringGetCStringPtr(ref, kCFStringEncodingUTF8); if (ptr) { return ptr; } // ... but sometimes it isn't. Copy. char buf[buf_size]; CFStringGetCString(ref, buf, buf_size, kCFStringEncodingUTF8); return buf; } template <class T> T GetAudioObjectProperty( AudioObjectID id, const AudioObjectPropertyAddress& prop) { T value; UInt32 size = sizeof(value); const auto result = AudioObjectGetPropertyData(id, &prop, 0, nullptr, &size, &value); switch (result) { case kAudioHardwareBadDeviceError: case kAudioHardwareBadObjectError: throw device_not_available_error(); case kAudioHardwareUnsupportedOperationError: case kAudioHardwareUnknownPropertyError: throw operation_not_supported_error(); default: break; } return value; } template <> bool GetAudioObjectProperty<bool>( UInt32 id, const AudioObjectPropertyAddress& prop) { return GetAudioObjectProperty<UInt32>(id, prop); } template <> std::string GetAudioObjectProperty<std::string>( UInt32 id, const AudioObjectPropertyAddress& prop) { CFStringRef value = nullptr; UInt32 size = sizeof(value); AudioObjectGetPropertyData(id, &prop, 0, nullptr, &size, &value); if (!value) { return std::string(); } auto ret = Utf8StringFromCFString(value); CFRelease(value); return ret; } std::string MakeDeviceID(UInt32 id, AudioDeviceDirection dir) { const auto uid = GetAudioObjectProperty<std::string>( id, {kAudioDevicePropertyDeviceUID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}); char buf[1024]; snprintf( buf, sizeof(buf), "%s/%s", dir == AudioDeviceDirection::INPUT ? "input" : "output", uid.c_str() ); return std::string(buf); } std::tuple<UInt32, AudioDeviceDirection> ParseDeviceID(const std::string& id) { auto idx = id.find_first_of('/'); auto direction = id.substr(0, idx) == "input" ? AudioDeviceDirection::INPUT : AudioDeviceDirection::OUTPUT; CFStringRef uid = CFStringCreateWithCString( kCFAllocatorDefault, id.substr(idx + 1).c_str(), kCFStringEncodingUTF8); UInt32 device_id; AudioValueTranslation value{ &uid, sizeof(CFStringRef), &device_id, sizeof(device_id)}; AudioObjectPropertyAddress prop{ kAudioHardwarePropertyDeviceForUID, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}; UInt32 size = sizeof(value); AudioObjectGetPropertyData( kAudioObjectSystemObject, &prop, 0, nullptr, &size, &value); CFRelease(uid); return std::make_tuple(device_id, direction); } void SetAudioDeviceIsMuted(const std::string& id, bool muted) { const UInt32 value = muted; const auto [native_id, direction] = ParseDeviceID(id); AudioObjectPropertyAddress prop{ kAudioDevicePropertyMute, direction == AudioDeviceDirection::INPUT ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput, 0}; const auto result = AudioObjectSetPropertyData( native_id, &prop, 0, NULL, sizeof(value), &value); switch (result) { case kAudioHardwareNoError: break; case kAudioHardwareBadDeviceError: case kAudioHardwareBadObjectError: throw device_not_available_error(); case kAudioHardwareUnsupportedOperationError: case kAudioHardwareUnknownPropertyError: throw operation_not_supported_error(); default: break; } } }// namespace std::string GetDefaultAudioDeviceID( AudioDeviceDirection direction, AudioDeviceRole role) { if (role != AudioDeviceRole::DEFAULT) { return std::string(); } AudioDeviceID native_id = 0; UInt32 native_id_size = sizeof(native_id); AudioObjectPropertyAddress prop = { direction == AudioDeviceDirection::INPUT ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}; AudioObjectGetPropertyData( kAudioObjectSystemObject, &prop, 0, NULL, &native_id_size, &native_id); return MakeDeviceID(native_id, direction); } void SetDefaultAudioDeviceID( AudioDeviceDirection direction, AudioDeviceRole role, const std::string& deviceID) { if (role != AudioDeviceRole::DEFAULT) { return; } const auto [native_id, id_dir] = ParseDeviceID(deviceID); if (id_dir != direction) { return; } AudioObjectPropertyAddress prop = { direction == AudioDeviceDirection::INPUT ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}; AudioObjectSetPropertyData( kAudioObjectSystemObject, &prop, 0, NULL, sizeof(native_id), &native_id); } bool IsAudioDeviceMuted(const std::string& id) { const auto [native_id, direction] = ParseDeviceID(id); return GetAudioObjectProperty<UInt32>( native_id, {kAudioDevicePropertyMute, direction == AudioDeviceDirection::INPUT ? kAudioObjectPropertyScopeInput : kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMaster}); }; void MuteAudioDevice(const std::string& id) { SetAudioDeviceIsMuted(id, true); } void UnmuteAudioDevice(const std::string& id) { SetAudioDeviceIsMuted(id, false); } namespace { std::string GetDataSourceName( AudioDeviceID device_id, AudioObjectPropertyScope scope) { AudioObjectID data_source; try { data_source = GetAudioObjectProperty<AudioObjectID>( device_id, {kAudioDevicePropertyDataSource, scope, kAudioObjectPropertyElementMaster}); } catch (operation_not_supported_error) { return std::string(); } CFStringRef value = nullptr; AudioValueTranslation translate{ &data_source, sizeof(data_source), &value, sizeof(value)}; UInt32 size = sizeof(translate); const AudioObjectPropertyAddress prop{ kAudioDevicePropertyDataSourceNameForIDCFString, scope, kAudioObjectPropertyElementMaster}; AudioObjectGetPropertyData(device_id, &prop, 0, nullptr, &size, &translate); if (!value) { return std::string(); } auto ret = Utf8StringFromCFString(value); CFRelease(value); return ret; } }// namespace std::map<std::string, AudioDeviceInfo> GetAudioDeviceList( AudioDeviceDirection direction) { UInt32 size = 0; AudioObjectPropertyAddress prop = { kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}; AudioObjectGetPropertyDataSize( kAudioObjectSystemObject, &prop, 0, nullptr, &size); const auto count = size / sizeof(AudioDeviceID); AudioDeviceID ids[count]; AudioObjectGetPropertyData( kAudioObjectSystemObject, &prop, 0, nullptr, &size, ids); std::map<std::string, AudioDeviceInfo> out; // The array of devices will always contain both input and output, even if // we set the scope above; instead filter inside the loop const auto scope = direction == AudioDeviceDirection::INPUT ? kAudioObjectPropertyScopeInput : kAudioObjectPropertyScopeOutput; for (const auto id : ids) { const auto interface_name = GetAudioObjectProperty<std::string>( id, {kAudioObjectPropertyName, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}); // ... and we do that filtering by finding out how many channels there // are. No channels for a given direction? Not a valid device for that // direction. UInt32 size; prop = {kAudioDevicePropertyStreams, scope, kAudioObjectPropertyScopeGlobal}; AudioObjectGetPropertyDataSize(id, &prop, 0, nullptr, &size); if (size == 0) { continue; } AudioDeviceInfo info{ .id = MakeDeviceID(id, direction), .interfaceName = interface_name, .direction = direction}; info.state = GetAudioDeviceState(info.id); const auto data_source_name = GetDataSourceName(id, scope); if (data_source_name.empty()) { info.displayName = info.interfaceName; } else { info.displayName = data_source_name; } out.emplace(info.id, info); } return out; } AudioDeviceState GetAudioDeviceState(const std::string& id) { const auto [native_id, direction] = ParseDeviceID(id); if (!native_id) { return AudioDeviceState::DEVICE_NOT_PRESENT; } const auto scope = (direction == AudioDeviceDirection::INPUT) ? kAudioDevicePropertyScopeInput : kAudioObjectPropertyScopeOutput; const auto transport = GetAudioObjectProperty<UInt32>( native_id, {kAudioDevicePropertyTransportType, scope, kAudioObjectPropertyElementMaster}); // no jack: 'Internal Speakers' // jack: 'Headphones' // // Showing plugged/unplugged for these is just noise if (transport == kAudioDeviceTransportTypeBuiltIn) { return AudioDeviceState::CONNECTED; } const AudioObjectPropertyAddress prop = { kAudioDevicePropertyJackIsConnected, scope, kAudioObjectPropertyElementMaster}; const auto supports_jack = AudioObjectHasProperty(native_id, &prop); if (!supports_jack) { return AudioDeviceState::CONNECTED; } const auto is_plugged = GetAudioObjectProperty<bool>(native_id, prop); return is_plugged ? AudioDeviceState::CONNECTED : AudioDeviceState::DEVICE_PRESENT_NO_CONNECTION; } namespace { template <class TProp> struct BaseCallbackHandleImpl { typedef std::function<void(TProp value)> UserCallback; BaseCallbackHandleImpl( UserCallback callback, AudioDeviceID device, AudioObjectPropertyAddress prop) : mProp(prop), mDevice(device), mCallback(callback) { AudioObjectAddPropertyListener(mDevice, &mProp, &OSCallback, this); } virtual ~BaseCallbackHandleImpl() { AudioObjectRemovePropertyListener(mDevice, &mProp, &OSCallback, this); } private: const AudioObjectPropertyAddress mProp; AudioDeviceID mDevice; UserCallback mCallback; static OSStatus OSCallback( AudioDeviceID id, UInt32 _prop_count, const AudioObjectPropertyAddress* _props, void* data) { auto self = reinterpret_cast<BaseCallbackHandleImpl<TProp>*>(data); const auto value = GetAudioObjectProperty<TProp>(id, self->mProp); self->mCallback(value); return 0; } }; }// namespace struct MuteCallbackHandleImpl : BaseCallbackHandleImpl<bool> { MuteCallbackHandleImpl( UserCallback cb, AudioDeviceID device, AudioDeviceDirection direction) : BaseCallbackHandleImpl( cb, device, {kAudioDevicePropertyMute, direction == AudioDeviceDirection::INPUT ? kAudioObjectPropertyScopeInput : kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMaster}) { } }; MuteCallbackHandle::MuteCallbackHandle(MuteCallbackHandleImpl* impl) : AudioDeviceCallbackHandle(impl) { } MuteCallbackHandle::~MuteCallbackHandle() { } std::unique_ptr<MuteCallbackHandle> AddAudioDeviceMuteUnmuteCallback( const std::string& deviceID, std::function<void(bool isMuted)> cb) { const auto [id, direction] = ParseDeviceID(deviceID); return std::make_unique<MuteCallbackHandle>( new MuteCallbackHandleImpl(cb, id, direction)); } struct DefaultChangeCallbackHandleImpl { DefaultChangeCallbackHandleImpl( std::function< void(AudioDeviceDirection, AudioDeviceRole, const std::string&)> cb) : mInputImpl( [=](AudioDeviceID native_id) { const auto device = MakeDeviceID(native_id, AudioDeviceDirection::INPUT); cb(AudioDeviceDirection::INPUT, AudioDeviceRole::DEFAULT, device); }, kAudioObjectSystemObject, {kAudioHardwarePropertyDefaultInputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}), mOutputImpl( [=](AudioDeviceID native_id) { const auto device = MakeDeviceID(native_id, AudioDeviceDirection::OUTPUT); cb(AudioDeviceDirection::OUTPUT, AudioDeviceRole::DEFAULT, device); }, kAudioObjectSystemObject, {kAudioHardwarePropertyDefaultOutputDevice, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMaster}) { } private: BaseCallbackHandleImpl<AudioDeviceID> mInputImpl; BaseCallbackHandleImpl<AudioDeviceID> mOutputImpl; }; DefaultChangeCallbackHandle::DefaultChangeCallbackHandle( DefaultChangeCallbackHandleImpl* impl) : AudioDeviceCallbackHandle(impl) { } DefaultChangeCallbackHandle::~DefaultChangeCallbackHandle() { } std::unique_ptr<DefaultChangeCallbackHandle> AddDefaultAudioDeviceChangeCallback( std::function<void(AudioDeviceDirection, AudioDeviceRole, const std::string&)> cb) { return std::make_unique<DefaultChangeCallbackHandle>( new DefaultChangeCallbackHandleImpl(cb)); } }// namespace FredEmmott::Audio
31.417062
80
0.728843
fredemmott
5e39f466abe1b422f6c4b1f58274b14c8f9dd11c
11,808
cpp
C++
toolboxes/nfft/cpu/hoGriddingConvolution.cpp
roopchansinghv/gadgetron
fb6c56b643911152c27834a754a7b6ee2dd912da
[ "MIT" ]
1
2022-02-22T21:06:36.000Z
2022-02-22T21:06:36.000Z
toolboxes/nfft/cpu/hoGriddingConvolution.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
toolboxes/nfft/cpu/hoGriddingConvolution.cpp
apd47/gadgetron
073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2
[ "MIT" ]
null
null
null
#include "hoGriddingConvolution.h" #include "hoNDArray_elemwise.h" #include "NDArray_utils.h" #include "ConvolutionMatrix.h" namespace Gadgetron { template<class T, unsigned int D, template<class, unsigned int> class K> hoGriddingConvolution<T, D, K>::hoGriddingConvolution( const vector_td<size_t, D>& matrix_size, const vector_td<size_t, D>& matrix_size_os, const K<REAL, D>& kernel) : GriddingConvolutionBase<hoNDArray, T, D, K>( matrix_size, matrix_size_os, kernel) { } template<class T, unsigned int D, template<class, unsigned int> class K> hoGriddingConvolution<T, D, K>::hoGriddingConvolution( const vector_td<size_t, D>& matrix_size, const REAL os_factor, const K<REAL, D>& kernel) : GriddingConvolutionBase<hoNDArray, T, D, K>( matrix_size, os_factor, kernel) { } template<class T, unsigned int D, template<class, unsigned int> class K> hoGriddingConvolution<T, D, K>::~hoGriddingConvolution() { } template<class T, unsigned int D, template<class, unsigned int> class K> void hoGriddingConvolution<T, D, K>::preprocess( const hoNDArray<vector_td<REAL, D>> &trajectory, GriddingConvolutionPrepMode prep_mode) { GriddingConvolutionBase<hoNDArray, T, D, K>::preprocess( trajectory, prep_mode); auto scaled_trajectory = trajectory; auto matrix_size_os_real = vector_td<REAL,D>(this->matrix_size_os_); std::transform(scaled_trajectory.begin(), scaled_trajectory.end(), scaled_trajectory.begin(), [matrix_size_os_real](auto point) { return (point + REAL(0.5)) * matrix_size_os_real; }); conv_matrix_.reserve(this->num_frames_); conv_matrix_T_.reserve(this->num_frames_); for (auto traj : NDArrayViewRange<hoNDArray<vector_td<REAL,D>>>( scaled_trajectory, 0)) { conv_matrix_.push_back(ConvInternal::make_conv_matrix( traj, this->matrix_size_os_, this->kernel_)); if (prep_mode == GriddingConvolutionPrepMode::NC2C || prep_mode == GriddingConvolutionPrepMode::ALL) { conv_matrix_T_.push_back(ConvInternal::transpose(conv_matrix_.back())); } } } namespace { /** * \brief Matrix-vector multiplication. * * \tparam T Value type. Can be real or complex. * \param[in] matrix Convolution matrix. * \param[in] vector Vector. * \param[out] result Operation result. */ template<class T> void mvm( const ConvInternal::ConvolutionMatrix<realType_t<T>>& matrix, const T* vector, T* result) { for (size_t i = 0; i < matrix.n_cols; i++) { auto &row_indices = matrix.indices[i]; auto &weights = matrix.weights[i]; #ifndef WIN32 #pragma omp simd #endif // WIN32 for (size_t n = 0; n < row_indices.size(); n++) { result[i] += vector[row_indices[n]] * weights[n]; } } } } template<class T, unsigned int D, template<class, unsigned int> class K> void hoGriddingConvolution<T, D, K>::compute_C2NC( const hoNDArray<T> &image, hoNDArray<T> &samples, bool accumulate) { size_t nbatches = image.get_number_of_elements() / conv_matrix_.front().n_rows; assert(nbatches == samples.get_number_of_elements() / conv_matrix_.front().n_cols); if (!accumulate) clear(&samples); #pragma omp parallel for for (int b = 0; b < (int)nbatches; b++) { const T* image_view = image.get_data_ptr() + b * conv_matrix_.front().n_rows; T* samples_view = samples.get_data_ptr() + b * conv_matrix_.front().n_cols; size_t matrix_index = b % conv_matrix_.size(); mvm(conv_matrix_[matrix_index], image_view, samples_view); } } template<class T, unsigned int D, template<class, unsigned int> class K> void hoGriddingConvolution<T, D, K>::compute_NC2C( const hoNDArray<T> &samples, hoNDArray<T> &image, bool accumulate) { size_t nbatches = image.get_number_of_elements() / conv_matrix_.front().n_rows; assert(nbatches == samples.get_number_of_elements() / conv_matrix_.front().n_cols); if (!accumulate) clear(&image); #pragma omp parallel for for (int b = 0; b < (int)nbatches; b++) { T* image_view = image.get_data_ptr() + b * conv_matrix_.front().n_rows; const T* samples_view = samples.get_data_ptr() + b * conv_matrix_.front().n_cols; size_t matrix_index = b % conv_matrix_.size(); mvm(conv_matrix_T_[matrix_index], samples_view, image_view); } } } template class Gadgetron::hoGriddingConvolution<float, 1, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<float, 2, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<float, 3, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<float, 4, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<double, 1, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<double, 2, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<double, 3, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<double, 4, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<float>, 1, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<float>, 2, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<float>, 3, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<float>, 4, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<double>, 1, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<double>, 2, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<double>, 3, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<double>, 4, Gadgetron::KaiserKernel>; template class Gadgetron::hoGriddingConvolution<float, 1, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<float, 2, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<float, 3, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<float, 4, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<double, 1, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<double, 2, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<double, 3, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<double, 4, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<float>, 1, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<float>, 2, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<float>, 3, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<float>, 4, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<double>, 1, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<double>, 2, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<double>, 3, Gadgetron::JincKernel>; template class Gadgetron::hoGriddingConvolution<Gadgetron::complext<double>, 4, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, float, 1, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, float, 2, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, float, 3, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, float, 4, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, double, 1, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, double, 2, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, double, 3, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, double, 4, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<float>, 1, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<float>, 2, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<float>, 3, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<float>, 4, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<double>, 1, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<double>, 2, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<double>, 3, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<double>, 4, Gadgetron::KaiserKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, float, 1, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, float, 2, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, float, 3, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, float, 4, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, double, 1, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, double, 2, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, double, 3, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, double, 4, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<float>, 1, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<float>, 2, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<float>, 3, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<float>, 4, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<double>, 1, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<double>, 2, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<double>, 3, Gadgetron::JincKernel>; template class Gadgetron::GriddingConvolution<Gadgetron::hoNDArray, Gadgetron::complext<double>, 4, Gadgetron::JincKernel>;
50.896552
125
0.721545
roopchansinghv
5e3a956d9ab6f24c2ed4434cdeb62f26069e7902
3,104
hpp
C++
include/codegen/include/UnityEngine/ProBuilder/BezierShape.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/ProBuilder/BezierShape.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/ProBuilder/BezierShape.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:20 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" // Including type: UnityEngine.ProBuilder.BezierPoint #include "UnityEngine/ProBuilder/BezierPoint.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: UnityEngine::ProBuilder namespace UnityEngine::ProBuilder { // Forward declaring type: ProBuilderMesh class ProBuilderMesh; } // Completed forward declares // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Autogenerated type: UnityEngine.ProBuilder.BezierShape class BezierShape : public UnityEngine::MonoBehaviour { public: // public System.Collections.Generic.List`1<UnityEngine.ProBuilder.BezierPoint> points // Offset: 0x18 System::Collections::Generic::List_1<UnityEngine::ProBuilder::BezierPoint>* points; // public System.Boolean closeLoop // Offset: 0x20 bool closeLoop; // public System.Single radius // Offset: 0x24 float radius; // public System.Int32 rows // Offset: 0x28 int rows; // public System.Int32 columns // Offset: 0x2C int columns; // public System.Boolean smooth // Offset: 0x30 bool smooth; // private System.Boolean m_IsEditing // Offset: 0x31 bool m_IsEditing; // private UnityEngine.ProBuilder.ProBuilderMesh m_Mesh // Offset: 0x38 UnityEngine::ProBuilder::ProBuilderMesh* m_Mesh; // public System.Boolean get_isEditing() // Offset: 0x15146F4 bool get_isEditing(); // public System.Void set_isEditing(System.Boolean value) // Offset: 0x15146FC void set_isEditing(bool value); // public UnityEngine.ProBuilder.ProBuilderMesh get_mesh() // Offset: 0x1514708 UnityEngine::ProBuilder::ProBuilderMesh* get_mesh(); // public System.Void set_mesh(UnityEngine.ProBuilder.ProBuilderMesh value) // Offset: 0x15147B4 void set_mesh(UnityEngine::ProBuilder::ProBuilderMesh* value); // public System.Void Init() // Offset: 0x15147BC void Init(); // public System.Void Refresh() // Offset: 0x15149F0 void Refresh(); // public System.Void .ctor() // Offset: 0x1514AC0 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static BezierShape* New_ctor(); }; // UnityEngine.ProBuilder.BezierShape } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::ProBuilder::BezierShape*, "UnityEngine.ProBuilder", "BezierShape"); #pragma pack(pop)
36.093023
103
0.70232
Futuremappermydud
5e3d2cc60a2c5c1696708cda7276b63940e92e2d
357
cpp
C++
oopAsgn3/prob4.cpp
debargham14/Object-Oriented-Programming-Assignment
25d7c87803e957c16188cac563eb238654c5a87b
[ "MIT" ]
null
null
null
oopAsgn3/prob4.cpp
debargham14/Object-Oriented-Programming-Assignment
25d7c87803e957c16188cac563eb238654c5a87b
[ "MIT" ]
null
null
null
oopAsgn3/prob4.cpp
debargham14/Object-Oriented-Programming-Assignment
25d7c87803e957c16188cac563eb238654c5a87b
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; //max function to return the pointer as the argument int max(int &a, int &b) { return (a > b ? a : b); } int main() { int first, second; cout << "Enter the first and the second numbers respectively :- "; cin >> first >> second; int c = max(first, second); cout << "The max out of two numbers is :- " << c; }
21
67
0.635854
debargham14
1e0f92c808d63ebae42b78adb83637f0551918cf
8,682
cc
C++
extensions/browser/computed_hashes_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
extensions/browser/computed_hashes_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
extensions/browser/computed_hashes_unittest.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "extensions/browser/computed_hashes.h" #include "base/base64.h" #include "base/files/file_path.h" #include "base/files/scoped_temp_dir.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" #include "crypto/sha2.h" #include "extensions/browser/content_verifier/content_verifier_utils.h" #include "extensions/common/constants.h" #include "testing/gtest/include/gtest/gtest.h" namespace { constexpr bool kIsDotSpaceSuffixIgnored = extensions::content_verifier_utils::IsDotSpaceFilenameSuffixIgnored(); constexpr bool kIsFileAccessCaseInsensitive = !extensions::content_verifier_utils::IsFileAccessCaseSensitive(); // Helper to return base64 encode result by value. std::string Base64Encode(const std::string& data) { std::string result; base::Base64Encode(data, &result); return result; } struct HashInfo { base::FilePath path; int block_size; std::vector<std::string> hashes; }; testing::AssertionResult WriteThenReadComputedHashes( const std::vector<HashInfo>& hash_infos, extensions::ComputedHashes* result) { base::ScopedTempDir scoped_dir; if (!scoped_dir.CreateUniqueTempDir()) return testing::AssertionFailure() << "Failed to create temp dir."; base::FilePath computed_hashes_path = scoped_dir.GetPath().AppendASCII("computed_hashes.json"); extensions::ComputedHashes::Data computed_hashes_data; for (const auto& info : hash_infos) computed_hashes_data.Add(info.path, info.block_size, info.hashes); if (!extensions::ComputedHashes(std::move(computed_hashes_data)) .WriteToFile(computed_hashes_path)) { return testing::AssertionFailure() << "Failed to write computed_hashes.json"; } extensions::ComputedHashes::Status computed_hashes_status; absl::optional<extensions::ComputedHashes> computed_hashes = extensions::ComputedHashes::CreateFromFile(computed_hashes_path, &computed_hashes_status); if (!computed_hashes) return testing::AssertionFailure() << "Failed to read computed_hashes.json (status: " << static_cast<int>(computed_hashes_status) << ")"; *result = std::move(computed_hashes.value()); return testing::AssertionSuccess(); } } // namespace namespace extensions { TEST(ComputedHashesTest, ComputedHashes) { // We'll add hashes for 2 files, one of which uses a subdirectory // path. The first file will have a list of 1 block hash, and the // second file will have 2 block hashes. base::FilePath path1(FILE_PATH_LITERAL("foo.txt")); base::FilePath path2 = base::FilePath(FILE_PATH_LITERAL("foo")).AppendASCII("bar.txt"); std::vector<std::string> hashes1 = {crypto::SHA256HashString("first")}; std::vector<std::string> hashes2 = {crypto::SHA256HashString("second"), crypto::SHA256HashString("third")}; const int kBlockSize1 = 4096; const int kBlockSize2 = 2048; ComputedHashes computed_hashes{ComputedHashes::Data()}; ASSERT_TRUE(WriteThenReadComputedHashes( {{path1, kBlockSize1, hashes1}, {path2, kBlockSize2, hashes2}}, &computed_hashes)); // After reading hashes back assert that we got what we wrote. std::vector<std::string> read_hashes1; std::vector<std::string> read_hashes2; int block_size = 0; EXPECT_TRUE(computed_hashes.GetHashes(path1, &block_size, &read_hashes1)); EXPECT_EQ(block_size, 4096); block_size = 0; EXPECT_TRUE(computed_hashes.GetHashes(path2, &block_size, &read_hashes2)); EXPECT_EQ(block_size, 2048); EXPECT_EQ(hashes1, read_hashes1); EXPECT_EQ(hashes2, read_hashes2); // Make sure we can lookup hashes for a file using incorrect case base::FilePath path1_badcase(FILE_PATH_LITERAL("FoO.txt")); std::vector<std::string> read_hashes1_badcase; EXPECT_EQ(kIsFileAccessCaseInsensitive, computed_hashes.GetHashes(path1_badcase, &block_size, &read_hashes1_badcase)); if (kIsFileAccessCaseInsensitive) { EXPECT_EQ(4096, block_size); EXPECT_EQ(hashes1, read_hashes1_badcase); } // Finally make sure that we can retrieve the hashes for the subdir // path even when that path contains forward slashes (on windows). base::FilePath path2_fwd_slashes = base::FilePath::FromUTF8Unsafe("foo/bar.txt"); block_size = 0; EXPECT_TRUE( computed_hashes.GetHashes(path2_fwd_slashes, &block_size, &read_hashes2)); EXPECT_EQ(hashes2, read_hashes2); } // Note: the expected hashes used in this test were generated using linux // command line tools. E.g., from a bash prompt: // $ printf "hello world" | openssl dgst -sha256 -binary | base64 // // The file with multiple-blocks expectations were generated by doing: // $ for i in `seq 500 ; do printf "hello world" ; done > hello.txt // $ dd if=hello.txt bs=4096 count=1 | openssl dgst -sha256 -binary | base64 // $ dd if=hello.txt skip=1 bs=4096 count=1 | // openssl dgst -sha256 -binary | base64 TEST(ComputedHashesTest, GetHashesForContent) { const int block_size = 4096; // Simple short input. std::string content1 = "hello world"; std::string content1_expected_hash = "uU0nuZNNPgilLlLX2n2r+sSE7+N6U4DukIj3rOLvzek="; std::vector<std::string> hashes1 = ComputedHashes::GetHashesForContent(content1, block_size); ASSERT_EQ(1u, hashes1.size()); EXPECT_EQ(content1_expected_hash, Base64Encode(hashes1[0])); // Multiple blocks input. std::string content2; for (int i = 0; i < 500; i++) content2 += "hello world"; const char* content2_expected_hashes[] = { "bvtt5hXo8xvHrlzGAhhoqPL/r+4zJXHx+6wAvkv15V8=", "lTD45F7P6I/HOdi8u7FLRA4qzAYL+7xSNVeusG6MJI0="}; std::vector<std::string> hashes2 = ComputedHashes::GetHashesForContent(content2, block_size); ASSERT_EQ(2u, hashes2.size()); EXPECT_EQ(content2_expected_hashes[0], Base64Encode(hashes2[0])); EXPECT_EQ(content2_expected_hashes[1], Base64Encode(hashes2[1])); // Now an empty input. std::string content3; std::vector<std::string> hashes3 = ComputedHashes::GetHashesForContent(content3, block_size); ASSERT_EQ(1u, hashes3.size()); ASSERT_EQ(std::string("47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU="), Base64Encode(hashes3[0])); } // Tests that dot/space path suffixes are treated correctly in // ComputedHashes::InitFromFile. // // Regression test for https://crbug.com/696208. TEST(ComputedHashesTest, DotSpaceSuffix) { const std::string hash_value = crypto::SHA256HashString("test"); ComputedHashes computed_hashes{ComputedHashes::Data()}; // Add hashes for "foo.html" to computed_hashes.json. ASSERT_TRUE(WriteThenReadComputedHashes( { {base::FilePath(FILE_PATH_LITERAL("foo.html")), extension_misc::kContentVerificationDefaultBlockSize, {hash_value}}, }, &computed_hashes)); struct TestCase { const char* path; bool expect_hash; std::string ToString() const { return base::StringPrintf("path = %s, expect_hash = %d", path, expect_hash); } } test_cases[] = { // Sanity check: existing file. {"foo.html", true}, // Sanity check: non existent file. {"notfound.html", false}, // Path with "." suffix, along with incorrect case for the same. {"foo.html.", kIsDotSpaceSuffixIgnored}, {"fOo.html.", kIsDotSpaceSuffixIgnored}, // Path with " " suffix, along with incorrect case for the same. {"foo.html ", kIsDotSpaceSuffixIgnored}, {"fOo.html ", kIsDotSpaceSuffixIgnored}, // Path with ". " suffix, along with incorrect case for the same. {"foo.html. ", kIsDotSpaceSuffixIgnored}, {"fOo.html. ", kIsDotSpaceSuffixIgnored}, // Path with " ." suffix, along with incorrect case for the same. {"foo.html .", kIsDotSpaceSuffixIgnored}, {"fOo.html .", kIsDotSpaceSuffixIgnored}, }; for (const auto& test_case : test_cases) { SCOPED_TRACE(test_case.ToString()); int block_size = 0; std::vector<std::string> read_hashes; EXPECT_EQ( test_case.expect_hash, computed_hashes.GetHashes(base::FilePath().AppendASCII(test_case.path), &block_size, &read_hashes)); if (test_case.expect_hash) { EXPECT_EQ(block_size, extension_misc::kContentVerificationDefaultBlockSize); ASSERT_EQ(1u, read_hashes.size()); EXPECT_EQ(hash_value, read_hashes[0]); } } } } // namespace extensions
37.912664
80
0.702373
zealoussnow
1e13b659bc9bb9a101b1e3e4aaab70c4c2c45449
1,237
hpp
C++
src/coapp/coapp.hpp
JoachimDuquesne/lely
cc6bad10ba57e380386622211e603006eeee0fff
[ "Apache-2.0" ]
null
null
null
src/coapp/coapp.hpp
JoachimDuquesne/lely
cc6bad10ba57e380386622211e603006eeee0fff
[ "Apache-2.0" ]
null
null
null
src/coapp/coapp.hpp
JoachimDuquesne/lely
cc6bad10ba57e380386622211e603006eeee0fff
[ "Apache-2.0" ]
null
null
null
/**@file * This is the internal header file of the C++ CANopen application library. * * @copyright 2018-2019 Lely Industries N.V. * * @author J. S. Seldenthuis <jseldenthuis@lely.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef LELY_COAPP_INTERN_COAPP_HPP_ #define LELY_COAPP_INTERN_COAPP_HPP_ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <lely/features.h> namespace lely { /// The namespace for the C++ CANopen application library. namespace canopen { /** * The namespace for implementation details of the C++ CANopen application * library. */ namespace detail {} } // namespace canopen } // namespace lely LELY_INGORE_EMPTY_TRANSLATION_UNIT #endif // LELY_COAPP_INTERN_COAPP_HPP_
28.113636
75
0.747777
JoachimDuquesne
1e1415ff66e766405f7012c6d081305b47977a5c
3,463
cpp
C++
cpp-htp/standard/ch12solutions/Ex12_10/ex12_10.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
75
2020-03-23T11:00:31.000Z
2022-02-20T05:22:53.000Z
cpp-htp/standard/ch12solutions/Ex12_10/ex12_10.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
null
null
null
cpp-htp/standard/ch12solutions/Ex12_10/ex12_10.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
39
2020-04-03T23:47:24.000Z
2022-01-19T05:06:39.000Z
// Exercise 12.10 Solution: ex12_10.cpp // Test program for Account hierarchy. #include <iostream> #include <iomanip> #include "Account.h" // Account class definition #include "SavingsAccount.h" // SavingsAccount class definition #include "CheckingAccount.h" // CheckingAccount class definition using namespace std; int main() { Account account1( 50.0 ); // create Account object SavingsAccount account2( 25.0, .03 ); // create SavingsAccount object CheckingAccount account3( 80.0, 1.0 ); // create CheckingAccount object cout << fixed << setprecision( 2 ); // display initial balance of each object cout << "account1 balance: $" << account1.getBalance() << endl; cout << "account2 balance: $" << account2.getBalance() << endl; cout << "account3 balance: $" << account3.getBalance() << endl; cout << "\nAttempting to debit $25.00 from account1." << endl; account1.debit( 25.0 ); // try to debit $25.00 from account1 cout << "\nAttempting to debit $30.00 from account2." << endl; account2.debit( 30.0 ); // try to debit $30.00 from account2 cout << "\nAttempting to debit $40.00 from account3." << endl; account3.debit( 40.0 ); // try to debit $40.00 from account3 // display balances cout << "\naccount1 balance: $" << account1.getBalance() << endl; cout << "account2 balance: $" << account2.getBalance() << endl; cout << "account3 balance: $" << account3.getBalance() << endl; cout << "\nCrediting $40.00 to account1." << endl; account1.credit( 40.0 ); // credit $40.00 to account1 cout << "\nCrediting $65.00 to account2." << endl; account2.credit( 65.0 ); // credit $65.00 to account2 cout << "\nCrediting $20.00 to account3." << endl; account3.credit( 20.0 ); // credit $20.00 to account3 // display balances cout << "\naccount1 balance: $" << account1.getBalance() << endl; cout << "account2 balance: $" << account2.getBalance() << endl; cout << "account3 balance: $" << account3.getBalance() << endl; // add interest to SavingsAccount object account2 double interestEarned = account2.calculateInterest(); cout << "\nAdding $" << interestEarned << " interest to account2." << endl; account2.credit( interestEarned ); cout << "\nNew account2 balance: $" << account2.getBalance() << endl; } // end main /************************************************************************** * (C) Copyright 1992-2008 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * **************************************************************************/
48.097222
80
0.600347
yanshengjia
1e14211c6d6d10936884843f06432493915fce7e
3,935
hpp
C++
sferes/sferes/stat/pareto_front.hpp
Evolving-AI-Lab/innovation-engine
58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba
[ "MIT" ]
31
2015-09-20T03:03:29.000Z
2022-01-25T06:50:20.000Z
sferes/sferes/stat/pareto_front.hpp
Evolving-AI-Lab/innovation-engine
58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba
[ "MIT" ]
1
2016-08-11T07:24:50.000Z
2016-08-17T01:19:57.000Z
sferes/sferes/stat/pareto_front.hpp
Evolving-AI-Lab/innovation-engine
58c7fcc3cbe3d6f8f59f87d95bdb5f2302f425ba
[ "MIT" ]
10
2015-11-15T01:52:25.000Z
2018-06-11T23:42:58.000Z
//| This file is a part of the sferes2 framework. //| Copyright 2009, ISIR / Universite Pierre et Marie Curie (UPMC) //| Main contributor(s): Jean-Baptiste Mouret, mouret@isir.fr //| //| This software is a computer program whose purpose is to facilitate //| experiments in evolutionary computation and evolutionary robotics. //| //| This software is governed by the CeCILL license under French law //| and abiding by the rules of distribution of free software. You //| can use, modify and/ or redistribute the software under the terms //| of the CeCILL license as circulated by CEA, CNRS and INRIA at the //| following URL "http://www.cecill.info". //| //| As a counterpart to the access to the source code and rights to //| copy, modify and redistribute granted by the license, users are //| provided only with a limited warranty and the software's author, //| the holder of the economic rights, and the successive licensors //| have only limited liability. //| //| In this respect, the user's attention is drawn to the risks //| associated with loading, using, modifying and/or developing or //| reproducing the software by the user in light of its specific //| status of free software, that may mean that it is complicated to //| manipulate, and that also therefore means that it is reserved for //| developers and experienced professionals having in-depth computer //| knowledge. Users are therefore encouraged to load and test the //| software's suitability as regards their requirements in conditions //| enabling the security of their systems and/or data to be ensured //| and, more generally, to use and operate it in the same conditions //| as regards security. //| //| The fact that you are presently reading this means that you have //| had knowledge of the CeCILL license and that you accept its terms. #ifndef PARETO_FRONT_HPP_ #define PARETO_FRONT_HPP_ #include <boost/serialization/shared_ptr.hpp> #include <boost/serialization/nvp.hpp> #include <sferes/stc.hpp> #include <sferes/parallel.hpp> #include <sferes/fit/fitness.hpp> #include <sferes/stat/stat.hpp> namespace sferes { namespace stat { SFERES_STAT(ParetoFront, Stat) { public: typedef std::vector<boost::shared_ptr<Phen> > pareto_t; // asume a ea.pareto_front() method template<typename E> void refresh(const E& ea) { _pareto_front = ea.pareto_front(); parallel::sort(_pareto_front.begin(), _pareto_front.end(), fit::compare_objs_lex()); this->_create_log_file(ea, "pareto.dat"); if (ea.dump_enabled()) show_all(*(this->_log_file), ea.gen()); //this->_log_file->close(); } void show(std::ostream& os, size_t k) const { os<<"log format : gen id obj_1 ... obj_n"<<std::endl; show_all(os, 0); _pareto_front[k]->develop(); _pareto_front[k]->show(os); _pareto_front[k]->fit().set_mode(fit::mode::view); _pareto_front[k]->fit().eval(*_pareto_front[k]); os << "=> displaying individual " << k << std::endl; os << "fit:"; for (size_t i =0; i < _pareto_front[k]->fit().objs().size(); ++i) os << _pareto_front[k]->fit().obj(i) << " "; os << std::endl; assert(k < _pareto_front.size()); } const pareto_t& pareto_front() const { return _pareto_front; } template<class Archive> void serialize(Archive & ar, const unsigned int version) { ar & BOOST_SERIALIZATION_NVP(_pareto_front); } void show_all(std::ostream& os, size_t gen = 0) const { for (unsigned i = 0; i < _pareto_front.size(); ++i) { os << gen << " " << i << " "; for (unsigned j = 0; j < _pareto_front[i]->fit().objs().size(); ++j) os << _pareto_front[i]->fit().obj(j) << " "; os << std::endl;; } } protected: pareto_t _pareto_front; }; } } #endif
38.960396
78
0.655654
Evolving-AI-Lab
1e15cb7c065d514b823a305720a5202910558246
6,975
cxx
C++
Seismic/Widgets/qColadaH5SeisModel.cxx
tierra-colada/ColadaSeismic
3a0b6cdcac0650e49c07d2845caab0a929f72d1a
[ "MIT" ]
null
null
null
Seismic/Widgets/qColadaH5SeisModel.cxx
tierra-colada/ColadaSeismic
3a0b6cdcac0650e49c07d2845caab0a929f72d1a
[ "MIT" ]
null
null
null
Seismic/Widgets/qColadaH5SeisModel.cxx
tierra-colada/ColadaSeismic
3a0b6cdcac0650e49c07d2845caab0a929f72d1a
[ "MIT" ]
null
null
null
// Colada includes #include "qColadaH5SeisModel.h" #include "qColadaH5SeisModel_p.h" // Qt includes #include <QIcon> #include <QDebug> // MRML includes #include <vtkMRMLScene.h> #include <vtkMRMLSeisVolumeNode.h> #include <vtkMRMLSeisModelNode.h> // h5gt includes #include <h5gt/H5File.hpp> #include <h5gt/H5Group.hpp> // h5geo includes #include <h5geo/h5points.h> #include <h5geo/h5seis.h> #include <h5geo/h5seiscontainer.h> #include <filesystem> namespace fs = std::filesystem; qColadaH5SeisModelPrivate::qColadaH5SeisModelPrivate(qColadaH5SeisModel &q) : Superclass(q) {} //----------------------------------------------------------------------------- qColadaH5SeisModelPrivate::~qColadaH5SeisModelPrivate() {} void qColadaH5SeisModelPrivate::init(const QString &title) { this->Superclass::init(title); } qColadaH5SeisModel::qColadaH5SeisModel(QObject *parent) : Superclass(new qColadaH5SeisModelPrivate(*this), parent) { Q_D(qColadaH5SeisModel); d->init(""); } qColadaH5SeisModel::qColadaH5SeisModel(const QString &title, QObject *parent) : Superclass(new qColadaH5SeisModelPrivate(*this), parent) { Q_D(qColadaH5SeisModel); d->init(title); } qColadaH5SeisModel::qColadaH5SeisModel(qColadaH5SeisModelPrivate *pimpl, QObject *parent) : Superclass(pimpl, parent) { // init() is called by derived class. } qColadaH5SeisModel::~qColadaH5SeisModel() {} QVariant qColadaH5SeisModel::data(const QModelIndex &index, int role) const { if (!index.isValid()) return QVariant(); qColadaH5Item* item = itemFromIndex(index); if (!item) return QVariant(); if (role == Qt::CheckStateRole){ if (static_cast<h5geo::ObjectType>(item->getH5GeoObjectType()) == h5geo::ObjectType::SEISMIC) return item->checkState(); } else if (role == Qt::DecorationRole){ if (static_cast<h5geo::ObjectType>(item->getH5GeoObjectType()) == h5geo::ObjectType::SEISMIC) return QIcon(":/Icons/seismic-12.png"); } return Superclass::data(index, role); } bool qColadaH5SeisModel::hasChildren(const QModelIndex &parent) const { qColadaH5Item *parentItem = itemFromIndex(parent); if (!parentItem) return false; auto objType = static_cast<h5geo::ObjectType>(parentItem->getH5GeoObjectType()); if (objType == h5geo::ObjectType::SEISMIC) return false; return Superclass::hasChildren(parent); } void qColadaH5SeisModel::fetchMore(const QModelIndex &parent) { qColadaH5Item *parentItem = itemFromIndex(parent); if (!parentItem || static_cast<h5geo::ObjectType>(parentItem->getH5GeoObjectType()) == h5geo::ObjectType::POINTS_1 || static_cast<h5geo::ObjectType>(parentItem->getH5GeoObjectType()) == h5geo::ObjectType::POINTS_2 || static_cast<h5geo::ObjectType>(parentItem->getH5GeoObjectType()) == h5geo::ObjectType::POINTS_3 || static_cast<h5geo::ObjectType>(parentItem->getH5GeoObjectType()) == h5geo::ObjectType::POINTS_4 || static_cast<h5geo::ObjectType>(parentItem->getH5GeoObjectType()) == h5geo::ObjectType::SEISMIC) return; if (!parentItem->isRoot()) removeRows(0, parentItem->childCount(), parentItem); auto objG = parentItem->getObjG(); if (!objG.has_value()) return; std::vector<std::string> childrenNameList = objG->listObjectNames(); // update parent in case of refetch while the objects in file has been updated parentItem->setChildCountInGroup(childrenNameList.size()); QVector<qColadaH5Item *> childItems; childItems.reserve(childrenNameList.size()); for (const auto& name : childrenNameList) { if (!objG->hasObject(name, h5gt::ObjectType::Group)) continue; h5gt::Group group = objG->getGroup(name); h5geo::ObjectType objType = h5geo::getGeoObjectType(group); qColadaH5Item* item = new qColadaH5Item(QString::fromStdString(name), parentItem); item->setH5GtObjectType(static_cast<int>(h5gt::ObjectType::Group)); item->setH5GeoObjectType(static_cast<unsigned>(objType)); item->setLinkType(objG->getLinkType(name)); item->setChildCountInGroup(group.getNumberObjects()); initItemToBeInserted(item); childItems.push_back(item); } // important to set mapped even if the childItems is empty (in case of moving items and refetching) parentItem->setMapped(true); childItems.shrink_to_fit(); if (childItems.isEmpty()) return; // init checkstate in case there are already GeoNodes on the scene updateItemsCheckState(childItems); beginInsertRows(parent, 0, childItems.count() - 1); parentItem->setChildren(childItems); endInsertRows(); } void qColadaH5SeisModel::initItemToBeInserted(qColadaH5Item* item) const { if (!item) return; Qt::ItemFlags flags = Qt::ItemIsSelectable | Qt::ItemIsEnabled | Qt::ItemIsEditable | Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled; unsigned objType = item->getH5GeoObjectType(); auto objTypeEnum = static_cast<h5geo::ObjectType>(objType); if (objTypeEnum == h5geo::ObjectType::POINTS_3 || objTypeEnum == h5geo::ObjectType::POINTS_4 || objTypeEnum == h5geo::ObjectType::SEISMIC){ flags |= Qt::ItemIsUserCheckable; } item->setFlags(flags); } bool qColadaH5SeisModel::canAddH5File(const h5gt::File& file) const { if (h5geo::isGeoContainerByType(file, h5geo::ContainerType::SEISMIC)) return Superclass::canAddH5File(file); return false; } H5Seis *qColadaH5SeisModel::openSeisFromItem(qColadaH5Item *item) const { if (!item) return nullptr; auto opt = item->getObjG(); if (!opt.has_value()) return nullptr; return h5geo::openSeis(opt.value()); } H5SeisContainer * qColadaH5SeisModel::openSeisCntFromItem(qColadaH5Item *item) const { if (!item || !item->isContainer()) return nullptr; auto opt = item->getH5File(); if (!opt.has_value()) return nullptr; return h5geo::openSeisContainer(opt.value()); } bool qColadaH5SeisModel::canDropMimeData( const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const { if (action == Qt::IgnoreAction) return true; qColadaH5Item* parentItem = nullptr; qColadaH5Item* item = nullptr; if (!const_cast<qColadaH5SeisModel*>(this)->canDropMimeDataAndPrepare( data, row, column, parent, parentItem, item)) return false; // forbid drag objects that are within H5Seis auto objG = item->getObjG(); if (objG.has_value() && !h5geo::isSeis(objG.value())){ qColadaH5Item *ip = item->getParent(); while (ip) { auto opt = ip->getObjG(); if (opt.has_value() && h5geo::isSeis(objG.value())) return false; ip = ip->getParent(); } } // forbid drop objects to H5Seis qColadaH5Item *pp = parentItem; while (pp) { auto opt = pp->getObjG(); if (opt.has_value() && h5geo::isSeis(objG.value())) return false; pp = pp->getParent(); } return Superclass::canDropMimeData(data, action, row, column, parent); }
30.592105
104
0.699498
tierra-colada
1e185f7208af4f6b8b050f2475cab05db595533d
18,162
cpp
C++
test/test_concat.in.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
test/test_concat.in.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
test/test_concat.in.cpp
kthur/he-transformer
5d3294473edba10f2789197043b8d8704409719e
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2018-2019 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. //***************************************************************************** #include "he_op_annotations.hpp" #include "ngraph/ngraph.hpp" #include "seal/he_seal_backend.hpp" #include "test_util.hpp" #include "util/all_close.hpp" #include "util/ndarray.hpp" #include "util/test_control.hpp" #include "util/test_tools.hpp" static std::string s_manifest = "${MANIFEST}"; auto concat_test = [](const ngraph::Shape& shape_a, const ngraph::Shape& shape_b, const ngraph::Shape& shape_c, size_t concat_axis, const std::vector<float>& input_a, const std::vector<float>& input_b, const std::vector<float>& input_c, const std::vector<float>& output, const bool arg1_encrypted, const bool complex_packing, const bool packed) { auto backend = ngraph::runtime::Backend::create("${BACKEND_NAME}"); auto he_backend = static_cast<ngraph::he::HESealBackend*>(backend.get()); if (complex_packing) { he_backend->update_encryption_parameters( ngraph::he::HESealEncryptionParameters:: default_complex_packing_parms()); } auto a = std::make_shared<ngraph::op::Parameter>(ngraph::element::f32, shape_a); auto b = std::make_shared<ngraph::op::Parameter>(ngraph::element::f32, shape_b); auto c = std::make_shared<ngraph::op::Parameter>(ngraph::element::f32, shape_c); auto t = std::make_shared<ngraph::op::Concat>(ngraph::NodeVector{a, b, c}, concat_axis); auto f = std::make_shared<ngraph::Function>(t, ngraph::ParameterVector{a, b, c}); a->set_op_annotations( ngraph::test::he::annotation_from_flags(false, arg1_encrypted, packed)); b->set_op_annotations( ngraph::test::he::annotation_from_flags(false, arg1_encrypted, packed)); c->set_op_annotations( ngraph::test::he::annotation_from_flags(false, arg1_encrypted, packed)); auto t_a = ngraph::test::he::tensor_from_flags(*he_backend, shape_a, arg1_encrypted, packed); auto t_b = ngraph::test::he::tensor_from_flags(*he_backend, shape_b, arg1_encrypted, packed); auto t_c = ngraph::test::he::tensor_from_flags(*he_backend, shape_c, arg1_encrypted, packed); auto t_result = ngraph::test::he::tensor_from_flags( *he_backend, t->get_shape(), arg1_encrypted, packed); copy_data(t_a, input_a); copy_data(t_b, input_b); copy_data(t_c, input_c); auto handle = backend->compile(f); handle->call_with_validate({t_result}, {t_a, t_b, t_c}); EXPECT_TRUE( ngraph::test::he::all_close(read_vector<float>(t_result), output, 1e-3f)); }; NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise_plain_real_unpacked) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{2, 3}, ngraph::Shape{2, 3}, 1, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}, false, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise_plain_real_packed) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{2, 3}, ngraph::Shape{2, 3}, 1, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}, false, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise_plain_complex_unpacked) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{2, 3}, ngraph::Shape{2, 3}, 1, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}, false, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise_plain_complex_packed) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{2, 3}, ngraph::Shape{2, 3}, 1, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}, false, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise_cipher_real_unpacked) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{2, 3}, ngraph::Shape{2, 3}, 1, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}, true, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise_cipher_real_packed) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{2, 3}, ngraph::Shape{2, 3}, 1, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}, false, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise_cipher_complex_unpacked) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{2, 3}, ngraph::Shape{2, 3}, 1, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}, true, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_colwise_cipher_complex_packed) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{2, 3}, ngraph::Shape{2, 3}, 1, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 1, 2, 4, 2, 3, 5, 8, 16, 8, 16, 32, 7, 11, 13}, true, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowise_plain_real_unpacked) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{3, 2}, ngraph::Shape{3, 2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}, false, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowise_plain_real_packed) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{3, 2}, ngraph::Shape{3, 2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}, false, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowise_plain_complex_unpacked) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{3, 2}, ngraph::Shape{3, 2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}, false, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowise_plain_complex_packed) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{3, 2}, ngraph::Shape{3, 2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}, false, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowise_cipher_real_unpacked) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{3, 2}, ngraph::Shape{3, 2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}, true, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowise_cipher_real_packed) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{3, 2}, ngraph::Shape{3, 2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}, true, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowise_cipher_complex_unpacked) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{3, 2}, ngraph::Shape{3, 2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}, true, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_matrix_rowise_cipher_complex_packed) { concat_test( ngraph::Shape{2, 2}, ngraph::Shape{3, 2}, ngraph::Shape{3, 2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{2, 3, 5, 7, 11, 13}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 2, 3, 5, 7, 11, 13}, true, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_vector_plain_real_unpacked) { concat_test(ngraph::Shape{4}, ngraph::Shape{6}, ngraph::Shape{2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{18, 19}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}, false, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_vector_plain_real_packed) { concat_test(ngraph::Shape{4}, ngraph::Shape{6}, ngraph::Shape{2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{18, 19}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}, false, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_vector_plain_complex_unpacked) { concat_test(ngraph::Shape{4}, ngraph::Shape{6}, ngraph::Shape{2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{18, 19}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}, false, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_vector_plain_complex_packed) { concat_test(ngraph::Shape{4}, ngraph::Shape{6}, ngraph::Shape{2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{18, 19}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}, false, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_vector_cipher_real_unpacked) { concat_test(ngraph::Shape{4}, ngraph::Shape{6}, ngraph::Shape{2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{18, 19}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}, true, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_vector_cipher_real_packed) { concat_test(ngraph::Shape{4}, ngraph::Shape{6}, ngraph::Shape{2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{18, 19}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}, true, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_vector_cipher_complex_unpacked) { concat_test(ngraph::Shape{4}, ngraph::Shape{6}, ngraph::Shape{2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{18, 19}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}, true, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_vector_cipher_complex_packed) { concat_test(ngraph::Shape{4}, ngraph::Shape{6}, ngraph::Shape{2}, 0, std::vector<float>{2, 4, 8, 16}, std::vector<float>{1, 2, 4, 8, 16, 32}, std::vector<float>{18, 19}, std::vector<float>{2, 4, 8, 16, 1, 2, 4, 8, 16, 32, 18, 19}, true, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor_plain_real_unpacked) { concat_test(ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, false, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor_plain_real_packed) { concat_test(ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, false, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor_plain_complex_unpacked) { concat_test(ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, false, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor_plain_complex_packed) { concat_test(ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, false, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor_cipher_real_unpacked) { concat_test(ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, true, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor_cipher_real_packed) { concat_test(ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, true, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor_cipher_complex_unpacked) { concat_test(ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, true, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_4d_tensor_cipher_complex_packed) { concat_test(ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, ngraph::Shape{1, 1, 1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, true, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor_plain_real_unpacked) { concat_test(ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, false, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor_plain_real_packed) { concat_test(ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, false, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor_plain_complex_unpacked) { concat_test(ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, false, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor_plain_complex_packed) { concat_test(ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, false, true, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor_cipher_real_unpacked) { concat_test(ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, true, false, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor_cipher_real_packed) { concat_test(ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, true, false, true); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor_cipher_complex_unpacked) { concat_test(ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, true, true, false); } NGRAPH_TEST(${BACKEND_NAME}, concat_2d_tensor_cipher_complex_packed) { concat_test(ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, ngraph::Shape{1, 1}, 0, std::vector<float>{1}, std::vector<float>{2}, std::vector<float>{3}, std::vector<float>{1, 2, 3}, true, true, true); }
44.297561
80
0.578846
kthur
1e18d1c01af8e32f561a60976063a2660baeeb12
16,110
cc
C++
upscaler.cc
pps83/pik
9747f8dbe9c10079b7473966fc974e4b3bcef034
[ "Apache-2.0" ]
null
null
null
upscaler.cc
pps83/pik
9747f8dbe9c10079b7473966fc974e4b3bcef034
[ "Apache-2.0" ]
null
null
null
upscaler.cc
pps83/pik
9747f8dbe9c10079b7473966fc974e4b3bcef034
[ "Apache-2.0" ]
null
null
null
// This file implements a ppm to (dc-ppm, ac-ppm) mapping that allows // us to experiment in different ways to compose the image into // (4x4) pseudo-dc and respective ac components. #include "upscaler.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <cmath> #include <vector> #include "butteraugli_distance.h" #include "gamma_correct.h" #include "image.h" #include "image_io.h" #include "resample.h" #define BUTTERAUGLI_RESTRICT __restrict__ namespace pik { namespace { std::vector<float> ComputeKernel(float sigma) { // Filtering becomes slower, but more Gaussian when m is increased. // More Gaussian doesn't mean necessarily better results altogether. const float m = 2.5; const float scaler = -1.0 / (2 * sigma * sigma); const int diff = std::max<int>(1, m * fabs(sigma)); std::vector<float> kernel(2 * diff + 1); for (int i = -diff; i <= diff; ++i) { kernel[i + diff] = exp(scaler * i * i); } return kernel; } void ConvolveBorderColumn(const ImageF& in, const std::vector<float>& kernel, const float weight_no_border, const float border_ratio, const size_t x, float* const BUTTERAUGLI_RESTRICT row_out) { const int offset = kernel.size() / 2; int minx = x < offset ? 0 : x - offset; int maxx = std::min<int>(in.xsize() - 1, x + offset); float weight = 0.0f; for (int j = minx; j <= maxx; ++j) { weight += kernel[j - x + offset]; } // Interpolate linearly between the no-border scaling and border scaling. weight = (1.0f - border_ratio) * weight + border_ratio * weight_no_border; float scale = 1.0f / weight; for (size_t y = 0; y < in.ysize(); ++y) { const float* const BUTTERAUGLI_RESTRICT row_in = in.Row(y); float sum = 0.0f; for (int j = minx; j <= maxx; ++j) { sum += row_in[j] * kernel[j - x + offset]; } row_out[y] = sum * scale; } } // Computes a horizontal convolution and transposes the result. ImageF Convolution(const ImageF& in, const std::vector<float>& kernel, const float border_ratio) { ImageF out(in.ysize(), in.xsize()); const int len = kernel.size(); const int offset = kernel.size() / 2; float weight_no_border = 0.0f; for (int j = 0; j < len; ++j) { weight_no_border += kernel[j]; } float scale_no_border = 1.0f / weight_no_border; const int border1 = in.xsize() <= offset ? in.xsize() : offset; const int border2 = in.xsize() - offset; int x = 0; // left border for (; x < border1; ++x) { ConvolveBorderColumn(in, kernel, weight_no_border, border_ratio, x, out.Row(x)); } // middle for (; x < border2; ++x) { float* const BUTTERAUGLI_RESTRICT row_out = out.Row(x); for (size_t y = 0; y < in.ysize(); ++y) { const float* const BUTTERAUGLI_RESTRICT row_in = &in.Row(y)[x - offset]; float sum = 0.0f; for (int j = 0; j < len; ++j) { sum += row_in[j] * kernel[j]; } row_out[y] = sum * scale_no_border; } } // right border for (; x < in.xsize(); ++x) { ConvolveBorderColumn(in, kernel, weight_no_border, border_ratio, x, out.Row(x)); } return out; } // A blur somewhat similar to a 2D Gaussian blur. // See: https://en.wikipedia.org/wiki/Gaussian_blur ImageF Blur(const ImageF& in, float sigma, float border_ratio) { std::vector<float> kernel = ComputeKernel(sigma); return Convolution(Convolution(in, kernel, border_ratio), kernel, border_ratio); } Image3F Blur(const Image3F& image, float sigma) { float border = 0.0; return Image3F(Blur(image.plane(0), sigma, border), Blur(image.plane(1), sigma, border), Blur(image.plane(2), sigma, border)); } // DoGBlur is an approximate of difference of Gaussians. We use it to // approximate LoG (Laplacian of Gaussians). // See: https://en.wikipedia.org/wiki/Difference_of_Gaussians // For motivation see: // https://en.wikipedia.org/wiki/Pyramid_(image_processing)#Laplacian_pyramid ImageF DoGBlur(const ImageF& in, float sigma, float border_ratio) { ImageF blur1 = Blur(in, sigma, border_ratio); ImageF blur2 = Blur(in, sigma * 2.0f, border_ratio); static const float mix = 0.25; ImageF out(in.xsize(), in.ysize()); for (size_t y = 0; y < in.ysize(); ++y) { const float* const BUTTERAUGLI_RESTRICT row1 = blur1.Row(y); const float* const BUTTERAUGLI_RESTRICT row2 = blur2.Row(y); float* const BUTTERAUGLI_RESTRICT row_out = out.Row(y); for (size_t x = 0; x < in.xsize(); ++x) { row_out[x] = (1.0f + mix) * row1[x] - mix * row2[x]; } } return out; } Image3F DoGBlur(const Image3F& image, float sigma) { float border = 0.0; return Image3F(DoGBlur(image.plane(0), sigma, border), DoGBlur(image.plane(1), sigma, border), DoGBlur(image.plane(2), sigma, border)); } void SelectiveBlur(Image3F& image, float sigma, float select) { Image3F copy = Blur(image, sigma); float select2 = select * 2; float ramp = 0.8f; float onePerSelect = ramp / select; float onePerSelect2 = ramp / select2; for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < image.ysize(); ++y) { const float* PIK_RESTRICT row_copy = copy.ConstPlaneRow(c, y); float* PIK_RESTRICT row = image.PlaneRow(c, y); for (size_t x = 0; x < image.xsize(); ++x) { float dist = fabs(row_copy[x] - row[x]); float w = 0.0f; if ((x & 7) == 0 || (x & 7) == 7 || (y & 7) == 0 || (y & 7) == 7) { if (dist < select2) { w = ramp - dist * onePerSelect2; if (w > 1.0f) w = 1.0f; } } else if (dist < select) { w = ramp - dist * onePerSelect; if (w > 1.0f) w = 1.0f; } row[x] = w * row_copy[x] + (1.0 - w) * row[x]; } } } } void SelectiveBlur8x8(Image3F& image, Image3F& ac, float sigma, float select_mod) { Image3F copy = Blur(image, sigma); float ramp = 1.0f; for (int c = 0; c < 3; ++c) { for (size_t wy = 0; wy < image.ysize(); wy += 8) { for (size_t wx = 0; wx < image.xsize(); wx += 8) { // Find maxdiff double max = 0; for (int dy = 0; dy < 6; ++dy) { for (int dx = 0; dx < 6; ++dx) { int y = wy + dy; int x = wx + dx; if (y >= image.ysize() || x >= image.xsize()) { break; } // Look at the criss-cross of diffs between two pixels. // Scale the smoothing within the block of the amplitude // of such local change. const float* PIK_RESTRICT row_ac0 = ac.PlaneRow(c, y); const float* PIK_RESTRICT row_ac2 = ac.PlaneRow(c, y + 2); float dist = fabs(row_ac0[x] - row_ac0[x + 2]); if (max < dist) max = dist; dist = fabs(row_ac0[x] - row_ac2[x]); if (max < dist) max = dist; dist = fabs(row_ac0[x] - row_ac2[x + 2]); if (max < dist) max = dist; dist = fabs(row_ac0[x + 2] - row_ac2[x]); if (max < dist) max = dist; } } float select = select_mod * max; float select2 = 2.0 * select; float onePerSelect = ramp / select; float onePerSelect2 = ramp / select2; for (int dy = 0; dy < 8; ++dy) { for (int dx = 0; dx < 8; ++dx) { int y = wy + dy; int x = wx + dx; if (y >= image.ysize() || x >= image.xsize()) { break; } const float* PIK_RESTRICT row_copy = copy.PlaneRow(c, y); float* PIK_RESTRICT row = image.PlaneRow(c, y); float dist = fabs(row_copy[x] - row[x]); float w = 0.0f; if ((x & 7) == 0 || (x & 7) == 7 || (y & 7) == 0 || (y & 7) == 7) { if (dist < select2) { w = ramp - dist * onePerSelect2; if (w > 1.0f) w = 1.0f; } } else if (dist < select) { w = ramp - dist * onePerSelect; if (w > 1.0f) w = 1.0f; } row[x] = w * row_copy[x] + (1.0 - w) * row[x]; } } } } } } Image3F SubSampleSimple8x8(const Image3F& image) { const size_t nxs = (image.xsize() + 7) >> 3; const size_t nys = (image.ysize() + 7) >> 3; Image3F retval(nxs, nys, 0.0f); float mul = 1 / 64.0; for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < image.ysize(); ++y) { const float* PIK_RESTRICT row_in = image.PlaneRow(c, y); float* PIK_RESTRICT row_out = retval.PlaneRow(c, y >> 3); for (size_t x = 0; x < image.xsize(); ++x) { row_out[x >> 3] += mul * row_in[x]; } } } if ((image.xsize() & 7) != 0) { const float last_column_mul = 8.0 / (image.xsize() & 7); for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < nys; ++y) { retval.PlaneRow(c, y)[nxs - 1] *= last_column_mul; } } } if ((image.ysize() & 7) != 0) { const float last_row_mul = 8.0 / (image.ysize() & 7); for (int c = 0; c < 3; ++c) { for (size_t x = 0; x < nxs; ++x) { retval.PlaneRow(c, nys - 1)[x] *= last_row_mul; } } } return retval; } Image3F SubSampleSimple4x4(const Image3F& image) { const size_t nxs = (image.xsize() + 3) >> 2; const size_t nys = (image.ysize() + 3) >> 2; Image3F retval(nxs, nys, 0.0f); float mul = 1 / 16.0; for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < image.ysize(); ++y) { const float* PIK_RESTRICT row_in = image.PlaneRow(c, y); float* PIK_RESTRICT row_out = retval.PlaneRow(c, y >> 2); for (size_t x = 0; x < image.xsize(); ++x) { row_out[x >> 2] += mul * row_in[x]; } } } if ((image.xsize() & 3) != 0) { const float last_column_mul = 4.0 / (image.xsize() & 3); for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < nys; ++y) { retval.PlaneRow(c, y)[nxs - 1] *= last_column_mul; } } } if ((image.ysize() & 3) != 0) { const float last_row_mul = 4.0 / (image.ysize() & 3); for (int c = 0; c < 3; ++c) { for (size_t x = 0; x < nxs; ++x) { retval.PlaneRow(c, nys - 1)[x] *= last_row_mul; } } } return retval; } Image3F SuperSample2x2(const Image3F& image) { size_t nxs = image.xsize() << 1; size_t nys = image.ysize() << 1; Image3F retval(nxs, nys); for (int c = 0; c < 3; ++c) { for (size_t ny = 0; ny < nys; ++ny) { const float* PIK_RESTRICT row_in = image.PlaneRow(c, ny >> 1); float* PIK_RESTRICT row_out = retval.PlaneRow(c, ny); for (size_t nx = 0; nx < nxs; ++nx) { row_out[nx] = row_in[nx >> 1]; } } } return retval; } Image3F SuperSample4x4(const Image3F& image) { size_t nxs = image.xsize() << 2; size_t nys = image.ysize() << 2; Image3F retval(nxs, nys); for (int c = 0; c < 3; ++c) { for (size_t ny = 0; ny < nys; ++ny) { const float* PIK_RESTRICT row_in = image.PlaneRow(c, ny >> 2); float* PIK_RESTRICT row_out = retval.PlaneRow(c, ny); for (size_t nx = 0; nx < nxs; ++nx) { row_out[nx] = row_in[nx >> 2]; } } } return retval; } Image3F SuperSample8x8(const Image3F& image) { size_t nxs = image.xsize() << 3; size_t nys = image.ysize() << 3; Image3F retval(nxs, nys); for (int c = 0; c < 3; ++c) { for (size_t ny = 0; ny < nys; ++ny) { const float* PIK_RESTRICT row_in = image.PlaneRow(c, ny >> 3); float* PIK_RESTRICT row_out = retval.PlaneRow(c, ny); for (size_t nx = 0; nx < nxs; ++nx) { row_out[nx] = row_in[nx >> 3]; } } } return retval; } void Smooth4x4Corners(Image3F& ima) { static const float overshoot = 3.5; static const float m = 1.0 / (4.0 - overshoot); for (int y = 3; y + 3 < ima.ysize(); y += 4) { for (int x = 3; x + 3 < ima.xsize(); x += 4) { float ave[3] = {0}; for (int c = 0; c < 3; ++c) { ave[c] += ima.PlaneRow(c, y)[x]; ave[c] += ima.PlaneRow(c, y)[x + 1]; ave[c] += ima.PlaneRow(c, y + 1)[x]; ave[c] += ima.PlaneRow(c, y + 1)[x + 1]; } const int off = 2; for (int c = 0; c < 3; ++c) { float others = (ave[c] - overshoot * ima.PlaneRow(c, y)[x]) * m; ima.PlaneRow(c, y - off)[x - off] -= (others - ima.PlaneRow(c, y)[x]); ima.PlaneRow(c, y)[x] = others; } for (int c = 0; c < 3; ++c) { float others = (ave[c] - overshoot * ima.PlaneRow(c, y)[x + 1]) * m; ima.PlaneRow(c, y - off)[x + off + 1] -= (others - ima.PlaneRow(c, y)[x + 1]); ima.PlaneRow(c, y)[x + 1] = others; } for (int c = 0; c < 3; ++c) { float others = (ave[c] - overshoot * ima.PlaneRow(c, y + 1)[x]) * m; ima.PlaneRow(c, y + off + 1)[x - off] -= (others - ima.PlaneRow(c, y + 1)[x]); ima.PlaneRow(c, y + 1)[x] = others; } for (int c = 0; c < 3; ++c) { float others = (ave[c] - overshoot * ima.PlaneRow(c, y + 1)[x + 1]) * m; ima.PlaneRow(c, y + off + 1)[x + off + 1] -= (others - ima.PlaneRow(c, y + 1)[x + 1]); ima.PlaneRow(c, y + 1)[x + 1] = others; } } } } void Subtract(Image3F& a, const Image3F& b) { for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < a.ysize(); ++y) { const float* PIK_RESTRICT row_b = b.PlaneRow(c, y); float* PIK_RESTRICT row_a = a.PlaneRow(c, y); for (size_t x = 0; x < a.xsize(); ++x) { row_a[x] -= row_b[x]; } } } } void Add(Image3F& a, const Image3F& b) { for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < a.ysize(); ++y) { const float* PIK_RESTRICT row_b = b.PlaneRow(c, y); float* PIK_RESTRICT row_a = a.PlaneRow(c, y); for (size_t x = 0; x < a.xsize(); ++x) { row_a[x] += row_b[x]; } } } } // Clamps pixel values to 0, 255. Image3F Crop(const Image3F& image, int newxsize, int newysize) { Image3F retval(newxsize, newysize); for (int c = 0; c < 3; ++c) { for (int y = 0; y < newysize; ++y) { const float* PIK_RESTRICT row_in = image.PlaneRow(c, y); float* PIK_RESTRICT row_out = retval.PlaneRow(c, y); for (int x = 0; x < newxsize; ++x) { float v = row_in[x]; if (v < 0) { v = 0; } if (v > 255) { v = 255; } row_out[x] = v; } } } return retval; } Image3F ToLinear(const Image3F& image) { Image3F out(image.xsize(), image.ysize()); for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < image.ysize(); ++y) { const float* PIK_RESTRICT row_in = image.PlaneRow(c, y); float* PIK_RESTRICT row_out = out.PlaneRow(c, y); for (size_t x = 0; x < image.xsize(); ++x) { row_out[x] = Srgb8ToLinearDirect(row_in[x]); } } } return out; } Image3F EncodePseudoDC(const Image3F& in) { Image3F goal = CopyImage(in); Image3F image8x8sub; static const int kIters = 2; for (int ii = 0; ii < kIters; ++ii) { if (ii != 0) { Image3F normal = UpscalerReconstruct(image8x8sub); // adjust the image by diff of normal and image. for (int c = 0; c < 3; ++c) { for (size_t y = 0; y < in.ysize(); ++y) { const float* PIK_RESTRICT row_normal = normal.PlaneRow(c, y); const float* PIK_RESTRICT row_in = in.PlaneRow(c, y); float* PIK_RESTRICT row_goal = goal.PlaneRow(c, y); for (size_t x = 0; x < in.xsize(); ++x) { row_goal[x] -= 0.1 * (row_normal[x] - row_in[x]); } } } } image8x8sub = SubSampleSimple8x8(goal); } // Encode pseudo dc. return image8x8sub; } } // namespace Image3F UpscalerReconstruct(const Image3F& in) { Image3F out1 = SuperSample4x4(in); Smooth4x4Corners(out1); out1 = Blur(out1, 2.5); Image3F out(out1.xsize() * 2, out1.ysize() * 2); Upsample<slow::Upsampler>(ExecutorLoop(), out1, kernel::CatmullRom(), &out); return out; } } // namespace pik
32.944785
80
0.537803
pps83
1e1a0d85f71ca57102048498466f0bfbf3d81021
845
cpp
C++
src/sword_to_offer/sword_q05.cpp
jielyu/leetcode
ce5327f5e5ceaa867ea2ddd58a93bfb02b427810
[ "MIT" ]
9
2020-04-09T12:37:50.000Z
2021-04-01T14:01:14.000Z
src/sword_to_offer/sword_q05.cpp
jielyu/leetcode
ce5327f5e5ceaa867ea2ddd58a93bfb02b427810
[ "MIT" ]
3
2020-05-05T02:43:54.000Z
2020-05-20T11:12:16.000Z
src/sword_to_offer/sword_q05.cpp
jielyu/leetcode
ce5327f5e5ceaa867ea2ddd58a93bfb02b427810
[ "MIT" ]
5
2020-04-17T02:32:10.000Z
2020-05-20T10:12:26.000Z
/* #剑指Offer# Q05 从尾到头打印链表 */ #include "leetcode.h" namespace sword_q05 { template<typename T> bool run_testcases() { T slt; { vector<int> input {1,2,3,4,5}, ret {5,4,3,2,1}; auto head = create_list(input); auto check = comp_vector(ret, slt.printFromTail(head)); delete_list(head); CHECK_RET(check); } return true; } class Solution{ private: void _print(ListNode * head, vector<int> & ret) { if (head) { if (head->next) { _print(head->next, ret); } ret.push_back(head->val); } } public: vector<int> printFromTail(ListNode * head) { vector<int> ret; _print(head, ret); return ret; } }; TEST(SwordQ05, Solution) {EXPECT_TRUE(run_testcases<Solution>());} } // namespace sword_q05
19.651163
66
0.559763
jielyu
1e1afb2e8e01b12b46f84d7c7688dde898413081
2,328
cpp
C++
interview_questions/google_interview_1.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
1
2020-05-05T13:06:51.000Z
2020-05-05T13:06:51.000Z
interview_questions/google_interview_1.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
interview_questions/google_interview_1.cpp
bvbasavaraju/competitive_programming
a82ffc1b639588a84f4273b44285d57cdc2f4b11
[ "Apache-2.0" ]
null
null
null
/* A[], {2, 1, 0,0,0,0,0,0, 7, 1} K l - k till 0 + k => Max Sum 10, k = 3 7 to 3 size => k * 2 copying => entries from the ends of the given array calculate MaxSubArraySum of window size k */ #include <iostream> #include <vector> #include <stdint.h> using namespace std; class Solution_t { int MaxSubArraySum(vector<int> a, int k) { int al = a.size(); //Construct the SubArray => O(2*k) vector<int> subArray; for (int i = al - k; i < al; i++) { subArray.push_back(a[i]); } for (int i = 0; i < k; i++) { subArray.push_back(a[i]); } //Calculate the MaxSum of SubArray of windows size k => O(k * k + 2k) int retVal = INT32_MIN; // minimum int int cl = k * 2; //SubArray => {0, 7, 1, 2, 1, 0} for (int i = 0; i < (cl - (k - 1)); i++) { int windowSum = 0; //ws for (int j = i; j < (i + k); j++) { windowSum += subArray[i + j]; } retVal = max(windowSum, retVal); // it1 => ws = 8, retVal = 8 // it2 => ws = 10, retVal = 10 // it3 => ws = 4, retVal = 10 // it4 => ws = 3, retVal = 10; } return retVal; } }; /* Face to Face interview question! + Design a system to to flash a driver update for software to specific driver. Ex: In a mobile, let say Snapdragon SOC is there, and there is another module from Broadcom. Broadcom released an update to its hardware. Now, how do you flash that update in mobile device + Applying filter to an image Lets say, you have image of 2D matrix, and you have an filter (again 2D matrix), apply this filter to matrix such that m[i][j] = (m[i][j] * f[0][0]) + (m[i][j+1] * f[0][1]) + (m[i][j+2] * f[0][2]) + ....... + (m[i+1][j] * f[1][0]) + m[i+1][j+1] * f[1][1] + .......... + (m[i+f_row][j+f_col] * f[f_row][f_col]) + Given a linked list, and list of pointers. give a solution to check if the pointers are pointing to the nodes in the list. Pointers can be in any order. Note: My solution was in O(nlogn). but expected was O(n). I got to know after interview got over!! :( + Design a class to providing the User access to specific memroy location/buffer. */
31.890411
194
0.53823
bvbasavaraju
1e1baafd7ebc907d1cfd55d4372fcb084046ccfd
1,363
cpp
C++
Acepta_El_Reto/problema_342.cpp
paulamlago/EDA-1
201e247f1dfb85bffbe61cce39af244e220152ee
[ "WTFPL" ]
null
null
null
Acepta_El_Reto/problema_342.cpp
paulamlago/EDA-1
201e247f1dfb85bffbe61cce39af244e220152ee
[ "WTFPL" ]
null
null
null
Acepta_El_Reto/problema_342.cpp
paulamlago/EDA-1
201e247f1dfb85bffbe61cce39af244e220152ee
[ "WTFPL" ]
4
2018-10-26T10:01:11.000Z
2021-12-14T09:51:57.000Z
#include <iostream>; // Comentar para AER #define getchar_unlocked getchar #define putchar_unlocked putchar using namespace std; inline void in(int &n) { n = 0; int ch = getchar_unlocked(); int sign = 1; while (ch < '0' || ch > '9') { if (ch == '-')sign = -1; ch = getchar_unlocked(); } while (ch >= '0' && ch <= '9') n = (n << 3) + (n << 1) + ch - '0', ch = getchar_unlocked(); n = n * sign; } int main() { int ini, fin, n; int k, x; int i; in(ini); in(fin); in(n); while (ini && fin && n) { in(k); i = 0; while (i < k) { in(x); if (x < ini) {} else if (x > fin) {} else if (n < x) fin = x - 1; else ini = x; ++i; } if (ini == fin) { putchar_unlocked('L'); putchar_unlocked('O'); putchar_unlocked(' '); putchar_unlocked('S'); putchar_unlocked('A'); putchar_unlocked('B'); putchar_unlocked('E'); putchar_unlocked('\n'); } else { putchar_unlocked('N'); putchar_unlocked('O'); putchar_unlocked(' '); putchar_unlocked('L'); putchar_unlocked('O'); putchar_unlocked(' '); putchar_unlocked('S'); putchar_unlocked('A'); putchar_unlocked('B'); putchar_unlocked('E'); putchar_unlocked('\n'); } in(ini); in(fin); in(n); } return 0; }
15.144444
84
0.505503
paulamlago
1e1d3d52e4526c0368c13fd892e37eeb1cced86e
4,457
cpp
C++
cg/src/debug/AnimatedAlgorithm.cpp
MachSilva/Ds
a7da3d4ca3b00b19884bc64d9d7baefea809cb3d
[ "Zlib" ]
2
2021-11-23T18:36:51.000Z
2021-11-24T19:38:25.000Z
cg/src/debug/AnimatedAlgorithm.cpp
MachSilva/Ds
a7da3d4ca3b00b19884bc64d9d7baefea809cb3d
[ "Zlib" ]
1
2022-02-12T20:47:59.000Z
2022-03-17T02:03:25.000Z
cg/src/debug/AnimatedAlgorithm.cpp
MachSilva/Ds
a7da3d4ca3b00b19884bc64d9d7baefea809cb3d
[ "Zlib" ]
1
2022-02-12T22:31:50.000Z
2022-02-12T22:31:50.000Z
//[]---------------------------------------------------------------[] //| | //| Copyright (C) 2016, 2019 Paulo Pagliosa. | //| | //| This software is provided 'as-is', without any express or | //| implied warranty. In no event will the authors be held liable | //| for any damages arising from the use of this software. | //| | //| Permission is granted to anyone to use this software for any | //| purpose, including commercial applications, and to alter it and | //| redistribute it freely, subject to the following restrictions: | //| | //| 1. The origin of this software must not be misrepresented; you | //| must not claim that you wrote the original software. If you use | //| this software in a product, an acknowledgment in the product | //| documentation would be appreciated but is not required. | //| | //| 2. Altered source versions must be plainly marked as such, and | //| must not be misrepresented as being the original software. | //| | //| 3. This notice may not be removed or altered from any source | //| distribution. | //| | //[]---------------------------------------------------------------[] // // OVERVIEW: AnimatedAlgorithm.cpp // ======== // Source file for animated algorithm. // // Author: Paulo Pagliosa // Last revision: 12/02/2019 #include "debug/AnimatedAlgorithm.h" #include <cstdarg> #include <stdexcept> namespace cg { // begin namespace cg #ifdef _DRAW_ALG // TODO: fix the draw function namespace this_algorithm { // begin namespace this_algorithm class AbortException: public std::runtime_error { public: AbortException(): std::runtime_error("aborted") { // do nothing } }; // AbortException void draw(bool stop, const char* fmt, ...) { if (auto a = AnimatedAlgorithm::_current) { if (a->_state == AnimatedAlgorithm::State::CANCEL) throw AbortException{}; if (!GUI::isPoolingEvents()) return; if (fmt != nullptr) { const size_t maxLen{1024}; char msg[maxLen]; va_list args; va_start(args, fmt); vsnprintf(msg, maxLen, fmt, args); a->_stepLog = msg; } a->wait(a->runMode == AnimatedAlgorithm::RunMode::STEP || stop); } } } // end namespace this_algorithm #endif ///////////////////////////////////////////////////////////////////// // // AnimatedAlgoritm implementation // ================ AnimatedAlgorithm* AnimatedAlgorithm::_current; inline void AnimatedAlgorithm::wait(bool stop) { std::unique_lock<std::mutex> lock{_lockDrawing}; _stopped = stop; _canDraw = !(_notified = false); _state = State::SLEEPING; _drawing.wait(lock, [this]() { return _notified; }); } void AnimatedAlgorithm::wake(bool force) { if ((!_notified && !_stopped) || force) { _canDraw = !(_notified = true); if (_state != State::CANCEL) _state = State::RUNNING; _drawing.notify_one(); } } void AnimatedAlgorithm::launch() { _thread = ThreadPtr{new std::thread{[this]() { _state = State::RUNNING; wait(true); try { if (_state != State::CANCEL) run(); } catch (...) { // do nothing } _canDraw = true; _stepLog.clear(); _state = State::RUN; }}}; } void AnimatedAlgorithm::start() { if (_state != State::CREATED && _state != State::TERMINATED) return; _current = this; // Initialize this algorithm. initialize(); // Run this algorithm in a new thread. launch(); } void AnimatedAlgorithm::join() { if (_state != State::RUN) _state = State::CANCEL; // Wait for thread termination. wake(true); _thread->join(); _thread = nullptr; // Terminate this algorithm. _state = State::TERMINATED; terminate(); _current = nullptr; } void AnimatedAlgorithm::cancel() { if (_state == State::RUNNING) _state = State::CANCEL; else if (_state == State::SLEEPING) { _state = State::CANCEL; wake(true); } } } // end namespace cg
25.180791
69
0.534889
MachSilva
1e1e0fab26da5f72c84dfcf45c9bf020ea99752c
7,190
cpp
C++
src/esp32ModbusTCP.cpp
bertmelis/esp32ModbusTCP
4e60c5622b3c4d66b0b9c678a8c1073adf57a82f
[ "MIT" ]
58
2018-11-27T01:38:30.000Z
2022-03-20T14:19:38.000Z
src/esp32ModbusTCP.cpp
bertmelis/esp32Modbus
4e60c5622b3c4d66b0b9c678a8c1073adf57a82f
[ "MIT" ]
18
2019-04-29T06:56:14.000Z
2020-08-16T11:12:48.000Z
src/esp32ModbusTCP.cpp
bertmelis/esp32Modbus
4e60c5622b3c4d66b0b9c678a8c1073adf57a82f
[ "MIT" ]
27
2018-11-27T01:38:31.000Z
2022-01-13T18:15:59.000Z
/* esp32ModbusTCP Copyright 2018 Bert Melis 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 <Arduino.h> #include <esp32-hal.h> #include "esp32ModbusTCP.h" esp32ModbusTCP::esp32ModbusTCP(uint8_t serverID, IPAddress addr, uint16_t port) : _client(), _lastMillis(0), _state(NOTCONNECTED), _serverID(serverID), _addr(addr), _port(port), _onDataHandler(nullptr), _onErrorHandler(nullptr), _queue() { _client.onConnect(_onConnected, this); _client.onDisconnect(_onDisconnected, this); _client.onError(_onError, this); _client.onTimeout(_onTimeout, this); _client.onPoll(_onPoll, this); _client.onData(_onData, this); _client.setNoDelay(true); _client.setAckTimeout(5000); _queue = xQueueCreate(MB_NUMBER_QUEUE_ITEMS, sizeof(esp32ModbusTCPInternals::ModbusRequest*)); } esp32ModbusTCP::~esp32ModbusTCP() { esp32ModbusTCPInternals::ModbusRequest* req = nullptr; while (xQueueReceive(_queue, &(req), (TickType_t)20)) { delete req; } vQueueDelete(_queue); } void esp32ModbusTCP::onData(esp32Modbus::MBTCPOnData handler) { _onDataHandler = handler; } void esp32ModbusTCP::onError(esp32Modbus::MBTCPOnError handler) { _onErrorHandler = handler; } uint16_t esp32ModbusTCP::readDiscreteInputs(uint16_t address, uint16_t numberInputs) { esp32ModbusTCPInternals::ModbusRequest* request = new esp32ModbusTCPInternals::ModbusRequest02(_serverID, address, numberInputs); return _addToQueue(request); } uint16_t esp32ModbusTCP::readHoldingRegisters(uint16_t address, uint16_t numberRegisters) { esp32ModbusTCPInternals::ModbusRequest* request = new esp32ModbusTCPInternals::ModbusRequest03(_serverID, address, numberRegisters); return _addToQueue(request); } uint16_t esp32ModbusTCP::readInputRegisters(uint16_t address, uint16_t numberRegisters) { esp32ModbusTCPInternals::ModbusRequest* request = new esp32ModbusTCPInternals::ModbusRequest04(_serverID, address, numberRegisters); return _addToQueue(request); } uint16_t esp32ModbusTCP::_addToQueue(esp32ModbusTCPInternals::ModbusRequest* request) { if (uxQueueSpacesAvailable(_queue) > 0) { if (xQueueSend(_queue, &request, (TickType_t) 10) == pdPASS) { _processQueue(); return request->getId(); } } delete request; return 0; } /************************ TCP Handling *******************************/ void esp32ModbusTCP::_connect() { if (_state > NOTCONNECTED) { log_i("already connected"); return; } log_v("connecting"); _client.connect(_addr, _port); _state = CONNECTING; } void esp32ModbusTCP::_disconnect(bool now) { log_v("disconnecting"); _state = DISCONNECTING; _client.close(now); } void esp32ModbusTCP::_onConnected(void* mb, AsyncClient* client) { log_v("connected"); esp32ModbusTCP* o = reinterpret_cast<esp32ModbusTCP*>(mb); o->_state = IDLE; o->_lastMillis = millis(); o->_processQueue(); } void esp32ModbusTCP::_onDisconnected(void* mb, AsyncClient* client) { log_v("disconnected"); esp32ModbusTCP* o = reinterpret_cast<esp32ModbusTCP*>(mb); o->_state = NOTCONNECTED; o->_lastMillis = millis(); o->_processQueue(); } void esp32ModbusTCP::_onError(void* mb, AsyncClient* client, int8_t error) { esp32ModbusTCP* o = reinterpret_cast<esp32ModbusTCP*>(mb); if (o->_state == IDLE || o->_state == DISCONNECTING) { log_w("unexpected tcp error"); return; } o->_tryError(esp32Modbus::COMM_ERROR); } void esp32ModbusTCP::_onTimeout(void* mb, AsyncClient* client, uint32_t time) { esp32ModbusTCP* o = reinterpret_cast<esp32ModbusTCP*>(mb); if (o->_state < WAITING) { log_w("unexpected tcp timeout"); return; } o->_tryError(esp32Modbus::TIMEOUT); } void esp32ModbusTCP::_onData(void* mb, AsyncClient* client, void* data, size_t length) { /* It is assumed that a Modbus message completely fits in one TCP packet. So when soon _onData is called, the complete processing can be done. As we're communication in a sequential way, the message is corresponding to the request at the queue front. */ log_v("data"); esp32ModbusTCP* o = reinterpret_cast<esp32ModbusTCP*>(mb); esp32ModbusTCPInternals::ModbusRequest* req = nullptr; xQueuePeek(o->_queue, &req, (TickType_t)10); esp32ModbusTCPInternals::ModbusResponse resp(reinterpret_cast<uint8_t*>(data), length, req); if (resp.isComplete()) { if (resp.isSucces()) { // all OK o->_tryData(&resp); } else { // message not correct o->_tryError(resp.getError()); } } else { // message not complete o->_tryError(esp32Modbus::COMM_ERROR); } } void esp32ModbusTCP::_onPoll(void* mb, AsyncClient* client) { esp32ModbusTCP* o = static_cast<esp32ModbusTCP*>(mb); if (millis() - o->_lastMillis > MB_IDLE_DICONNECT_TIME) { log_v("idle time disconnecting"); o->_disconnect(); } } void esp32ModbusTCP::_processQueue() { if (_state == NOTCONNECTED && uxQueueMessagesWaiting(_queue) > 0) { _connect(); return; } if (_state == CONNECTING || _state == WAITING || _state == DISCONNECTING || uxQueueSpacesAvailable(_queue) == 0 || !_client.canSend()) { return; } esp32ModbusTCPInternals::ModbusRequest* req = nullptr; if (xQueuePeek(_queue, &req, (TickType_t)20)) { _state = WAITING; log_v("send"); _client.add(reinterpret_cast<char*>(req->getMessage()), req->getSize()); _client.send(); _lastMillis = millis(); } } void esp32ModbusTCP::_tryError(esp32Modbus::Error error) { esp32ModbusTCPInternals::ModbusRequest* req = nullptr; if (xQueuePeek(_queue, &req, (TickType_t)10)) { if (_onErrorHandler) _onErrorHandler(req->getId(), error); } _next(); } void esp32ModbusTCP::_tryData(esp32ModbusTCPInternals::ModbusResponse* response) { if (_onDataHandler) _onDataHandler( response->getId(), response->getSlaveAddress(), response->getFunctionCode(), response->getData(), response->getByteCount()); _next(); } void esp32ModbusTCP::_next() { esp32ModbusTCPInternals::ModbusRequest* req = nullptr; if (xQueueReceive(_queue, &req, (TickType_t)20)) { delete req; } _lastMillis = millis(); _state = IDLE; _processQueue(); }
31.955556
98
0.720584
bertmelis
1e1fa50753ad0b5aba2449c6ab62c37e1bb3ac4f
1,245
cpp
C++
src/tray.cpp
AhhNuts/30047W
54bfb5770a9ad08d853395c2b6d659dca27177f6
[ "MIT" ]
null
null
null
src/tray.cpp
AhhNuts/30047W
54bfb5770a9ad08d853395c2b6d659dca27177f6
[ "MIT" ]
null
null
null
src/tray.cpp
AhhNuts/30047W
54bfb5770a9ad08d853395c2b6d659dca27177f6
[ "MIT" ]
null
null
null
#include "tray.h" #include "vex.h" #include "button.h" Button lb; void tray(){ //if both button hold then max speed down if(Controller1.ButtonDown.pressing()){ TRAY.resetPosition(); } else if(Controller1.ButtonR1.pressing() && Controller1.ButtonR2.pressing()){ //Tray Lift Faster Down TRAY.spin(reverse,90,pct); } else if(Controller1.ButtonR1.pressing()){ //Button to hold to go up fast then depending on the position if(TRAY.position(deg) > 1000){ //it will go slower (Semi-Automatic) TRAY.spin(forward,30,pct); } else if(TRAY.position(deg) > 600){ TRAY.spin(forward,50,pct); }else{ TRAY.spin(forward,100,pct); } } else if(Controller1.ButtonR2.pressing()){ //Button R2 to go down slow TRAY.spin(reverse,50,pct); } else if (TRAY.rotation(deg) < 350){ TRAY.stop(coast); //Going against the rubber banding causing motor to overheat significantly changing it to coast at that //position helped the proble } else if(TRAY.rotation(deg) < -3){ TRAY.resetPosition(); //Solve issue with going to fast because the motor position goes negative }else{ TRAY.stop(hold); } }
34.583333
128
0.628916
AhhNuts
1e2047c81d9753e18aedcb38899c961a9ab6bba0
10,010
cpp
C++
source/de/hackcraft/proc/Facade.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
23
2015-12-08T19:29:10.000Z
2021-09-22T04:13:31.000Z
source/de/hackcraft/proc/Facade.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
7
2018-04-30T13:05:57.000Z
2021-08-25T03:58:07.000Z
source/de/hackcraft/proc/Facade.cpp
DMJC/linwarrior
50cd46660c11e58cc6fbc431a150cf55ce0dd682
[ "Apache-2.0" ]
4
2018-01-25T03:05:19.000Z
2021-08-25T03:30:15.000Z
#include "Facade.h" #include "Noise.h" #include "Distortion.h" #include "de/hackcraft/psi3d/ctrl.h" #include "de/hackcraft/psi3d/math3d.h" void Facade::getVStrings(float x, float y, float* color4f, unsigned char seed) { float x_ = fmod(x, 1.0f); float sinx = Noise::simplex3(((x_ < 0.5f) ? (x_) : (1.0f - x_))*16.0, 0, 0, seed); float sx = 0.8 + 0.2 * sinx; sx *= sx; float grain = 0.9f + 0.1f * (0.5f + 0.5f * Noise::simplex3(x * 256.0f, y * 256.0f, 0, seed)); color4f[0] = color4f[1] = color4f[2] = grain * sx; color4f[3] = 1.0f; } void Facade::getHStrings(float x, float y, float* color4f, unsigned char seed) { float y_ = fmod(y, 1.0f); float siny = Noise::simplex3(0, y_ * 8.0f, 0, seed); float sy = 0.8 + 0.2 * siny; sy *= sy; float grain = 0.9f + 0.1f * (0.5f + 0.5f * Noise::simplex3(x * 256.0f, y * 256.0f, 0, seed)); color4f[0] = color4f[1] = color4f[2] = grain * sy; color4f[3] = 1.0f; } void Facade::getInterrior(float x, float y, float* color4fv, unsigned char seed) { float x_ = fmod(x, 1.0f); float y_ = fmod(y, 1.0f); bool bk = (x_ > 0.3f) && (x_ < 0.7f) && (y_ > 0.3f) && (y_ < 0.7f); bool d1 = x_ > y_; bool d2 = (1-x_) > y_; float t = (d1 && d2 && !bk) ? 1.0f : 0.0f; float r = (d1 && !d2 && !bk) ? 1.0f : 0.0f; float b = (!d1 && !d2 && !bk) ? 1.0f : 0.0f; float l = (!d1 && d2 && !bk) ? 1.0f : 0.0f; float f = t * 0.8 + (l + r) * 0.7 + b * 0.5 + bk * 0.9; float alpha = 0.3f + 0.7f * (0.5f + 0.5f * Noise::samplex3(x * 63, y * 63, 0, seed)); alpha *= f; float dark[] = {0.05f, 0.05f, 0.05f, 1.0f}; float lite[] = {0.99f, 0.99f, 0.70f, 1.0f}; Distortion::fade4(alpha, dark, lite, color4fv); } void getInterriorLight(float x, float y, float* color4fv, unsigned char seed = 121) { float zero[] = { 0.99f, 0.99f, 0.70f, 1.0f }; float one[] = { 0.60f, 0.40f, 0.20f, 1.0f }; float alpha = sqrt(1.0f - fabs(sin(0.80f * y * M_PI))); Distortion::fade4(alpha, zero, one, color4fv); } void getBlinds(float x, float y, float* color4fv, unsigned char seed) { float y_ = fmod(y, 1.0f); unsigned char h = (3*((unsigned char)(x))) + (7*((unsigned char)(y))); unsigned char n = Noise::LFSR8(seed + h) ^ h; n &= 0x0F; float y__ = y_ * 16; float f = fmod(y__, 1.0f); f = (y__ > n) ? 0 : f; float alpha = 1.0f - (1.0f - f) * (1.0f - f); float dark[] = {0.2f, 0.2f, 0.0f, 1.0f}; float lite[] = {0.99f, 0.99f, 0.99f, 1.0f}; Distortion::fade4(alpha, dark, lite, color4fv); color4fv[3] = (f <= 0.0) ? 0 : color4fv[3]; } void Facade::getExterrior(float x, float y, float* color4fv, unsigned char seed) { float alpha = 0.3f + 0.7f * (0.5f + 0.5f * Noise::simplex3(x, y, 0, seed)); float dark[] = {0.30f, 0.30f, 0.40f, 1.0f}; float lite[] = {0.50f, 0.50f, 0.70f, 1.0f}; Distortion::fade4(alpha, dark, lite, color4fv); } void Facade::getConcrete(float x, float y, float z, float* color4fv, unsigned char seed) { float grain = 0.15f + 0.15f * (0.5f + 0.5f * Noise::simplex3(x, y, z, seed)); color4fv[0] = color4fv[1] = color4fv[2] = grain; color4fv[3] = 1.0f; } unsigned char Facade::generateFrame(float* dims4x4, float (*sums5)[4], unsigned char seed) { enum Levels { MARGIN, BORDER, PADDING, CONTENT, MAX_LEVELS }; float* dims = dims4x4; float (*sum)[4] = sums5; // Get the random numbers rolling... unsigned char r = Noise::LFSR8(seed); r = Noise::LFSR8(r); r = Noise::LFSR8(r); r = Noise::LFSR8(r); r = Noise::LFSR8(r); const float inv256 = 0.003906f; float* margin = &dims[0]; { r = Noise::LFSR8(r); margin[0] = 0.20f * r * inv256 + 0.006f; margin[2] = margin[0]; r = Noise::LFSR8(r); margin[1] = 0.14f * r * inv256 + 0.006f; // should be related r = Noise::LFSR8(r); margin[3] = 0.36f * r * inv256 + 0.006f; } float* border = &dims[4]; { float w = 1.0f - (margin[2] + margin[0]); float h = 1.0f - (margin[3] + margin[1]); r = Noise::LFSR8(r); border[0] = r * 0.0002f * w + 0.0002f * w; border[2] = border[0]; r = Noise::LFSR8(r); border[1] = r * 0.0002f * h + 0.0002f * h; border[3] = border[1]; } float* padding = &dims[8]; { float w = 1.0f - (margin[2] + border[2] + margin[0] + border[0]); float h = 1.0f - (margin[3] + border[3] + margin[1] + border[1]); r = Noise::LFSR8(r); padding[0] = r * 0.0002f * w + 0.0002f * w; padding[2] = padding[0]; r = Noise::LFSR8(r); padding[1] = r * 0.0002f * h + 0.0002f * h; padding[3] = padding[1]; } float* content = &dims[12]; { float w = 1.0f - (margin[2] + border[2] + padding[2] + margin[0] + border[0] + padding[0]); float h = 1.0f - (margin[3] + border[3] + padding[3] + margin[1] + border[1] + padding[1]); r = Noise::LFSR8(r); content[0] = r * 0.0002f * w + 0.0002f * w; content[2] = content[0]; r = Noise::LFSR8(r); content[1] = r * 0.0001f * h + 0.0001f * h; r = Noise::LFSR8(r); content[3] = r * 0.0001f * h + 0.0001f * h; } sum[0][0] = 0; sum[0][1] = 0; sum[0][2] = 0; sum[0][3] = 0; loopi(MAX_LEVELS) { sum[i + 1][0] = sum[i][0] + dims[4 * i + 0]; sum[i + 1][1] = sum[i][1] + dims[4 * i + 1]; sum[i + 1][2] = sum[i][2] + dims[4 * i + 2]; sum[i + 1][3] = sum[i][3] + dims[4 * i + 3]; } // Row major if result is even. return Noise::LFSR8(r); } void Facade::getFacade(float x, float y, int gx, int gy, float age, float* c3f, unsigned char seed) { // Border Levels from outside to inside. enum Levels { MARGIN, BORDER, PADDING, CONTENT, MAX_LEVELS }; float dims[4 * MAX_LEVELS]; float sum[MAX_LEVELS + 1][4]; unsigned char r = generateFrame(dims, sum, seed); bool rowmajor = (r & 1) == 0; float* margin = &dims[0]; //float* border = &dims[4]; //float* padding = &dims[8]; //float* content = &dims[12]; const float inv256 = 0.003906f; float pyr[MAX_LEVELS + 1]; loopi(MAX_LEVELS + 1) { pyr[i] = Distortion::rampPyramid(sum[i][0], sum[i][1], 1.0f - sum[i][2], 1.0f - sum[i][3], x, y); } float inside[MAX_LEVELS + 1]; loopi(MAX_LEVELS + 1) { inside[i] = (pyr[i] >= 0) ? 1.0f : 0.0f; } rgba colors[] = { { 1, 0, 0, 1}, { 0, 1, 0, 1}, { 0, 0, 1, 1}, { 0, 1, 1, 1}, { 1, 1, 1, 1}, }; loopi(MAX_LEVELS + 1) { if (pyr[i] >= 0) { c3f[0] = colors[i][0]; c3f[1] = colors[i][1]; c3f[2] = colors[i][2]; } } float chma = 2.0f * 0.1f; chma *= rowmajor ? 0.1f : 1.0f; float cr = r = Noise::LFSR8(r); float cg = r = Noise::LFSR8(r); float cb = r = Noise::LFSR8(r); float cl = r = Noise::LFSR8(r); cl = 0.6f + 0.4f * inv256*cl; cl *= (1.0f - chma); chma *= inv256; float c0[] = {cl + chma*cr, cl + chma*cg, cl + chma*cb, 1.0f}; chma = 2.0f * 0.1f; chma *= rowmajor ? 1.0f : 0.1f; cr = r = Noise::LFSR8(r); cg = r = Noise::LFSR8(r); cb = r = Noise::LFSR8(r); cl = r = Noise::LFSR8(r); cl = 0.6f + 0.4f * inv256*cl; cl *= (1.0f - chma); chma *= inv256; float c1[] = {cl + chma*cr, cl + chma*cg, cl + chma*cb, 1.0f}; //return; // Vertical Column Pattern. float col[4]; getVStrings(x, y, col, seed + 21); loopi(4) { col[i] *= c0[i]; } // Horizontal Row Pattern. float row[4]; getHStrings(x, y, row, seed + 11); loopi(4) { row[i] *= c1[i]; } // Glass distortion float dx = 0.02f * Noise::simplex3((gx + x)*27, (gy + y)*27, 0, seed + 43); float dy = 0.02f * Noise::simplex3((gx + x)*27, (gy + y)*27, 0, seed + 31); // Interrior Room Pattern. float interrior[4]; getInterrior(gx + x + dx, gy + y + dy, interrior); // Interrior Lighting. float interriorLight[4]; getInterriorLight(x + 3*dx, y + 3*dy, interriorLight); Distortion::fade4(0.7, interrior, interriorLight, interrior); // Blinds float blinds[4]; getBlinds(gx + x + 0.0*dy, gy + y + 0.0*dy, blinds, r); Distortion::fade4(blinds[3], interrior, blinds, interrior); // Exterrior Scene Reflection Pattern. float exterrior[4]; getExterrior(gx + x + 2 * dx, gy + y + 2 * dy, exterrior); // Light smearing float smear = 0.8 + 0.2f * Noise::simplex3((gx + x)*8 + (gy + y)*8, (gx + x)*1 - (gy + y)*1, 0, seed + 41); //float glass[] = { 0.90f, 0.90f, 0.99f, 1.0f }; //float window[] = { 0.3f, 0.35f, 0.3f, 1.0f }; int u = (x < margin[0]) ? 0 : ((x < 1.0f - margin[2]) ? 1 : 2); int v = (y < margin[1]) ? 0 : ((y < 1.0f - margin[3]) ? 1 : 2); int colpart = ((!rowmajor || v == 1) && u != 1) ? 1 : 0; int rowpart = ((rowmajor || u == 1) && v != 1) ? 1 : 0; float mirror = 0.7f; mirror *= smear; float shade[4]; Distortion::fade4(mirror, interrior, exterrior, shade); Distortion::mix3(0.56f * colpart, col, 0.60f * rowpart, row, c3f); int winpart = inside[BORDER + 1]; Distortion::mix3(1.0f - winpart, c3f, winpart, shade, c3f); //return; /* float dirt[] = {0.3, 0.3, 0.25, 1.0f}; float dirtf = 1.0f + pyr[BORDER + 1]; dirtf = (dirtf > 1.0f) ? 0.0f : dirtf; dirtf *= 0.99f; Distortion::mix3(1.0f - dirtf, c3f, dirtf, dirt, c3f); */ float windowf = -cos((x - 0.5) * 6.0 * M_PI); //float windowf = cos((x - 0.5) * 4.0 * M_PI); windowf = fmax(windowf, cos((y - 0.5) * 12.0 * M_PI)); windowf = ((windowf < 0.98) || !winpart) ? 0.0 : windowf; float wframe[] = { 0, 0, 0, 1 }; Distortion::mix3(1.0f - windowf, c3f, windowf, wframe, c3f); }
30.705521
111
0.50959
DMJC
1e2179add4a3e17da484980b4c8374c14b4f4e38
763
hpp
C++
problem/pascaltriangle2.hpp
cloudyfsail/LeetCode
89b341828ec452997d3e05e06b08bfba95216f41
[ "MIT" ]
null
null
null
problem/pascaltriangle2.hpp
cloudyfsail/LeetCode
89b341828ec452997d3e05e06b08bfba95216f41
[ "MIT" ]
null
null
null
problem/pascaltriangle2.hpp
cloudyfsail/LeetCode
89b341828ec452997d3e05e06b08bfba95216f41
[ "MIT" ]
null
null
null
#ifndef _PASCAL_TRIANGLE2_H_ #define _PASCAL_TRIANGLE2_H_ #include <vector> #include "stdint.h" #include <ostream> using std::vector; namespace LeetCode { class Solution { public: vector<int> getRow(int rowIndex) { if(rowIndex < 0) return vector<int>(0); vector<int> row(rowIndex + 1); uint64_t num = 1; uint64_t den = 1; for(int i = 0;i <= rowIndex;++i) { if(i == 0 || i == rowIndex) { row[i] = 1; continue; } std::cout << row.at(i - 1) << " * " << (rowIndex - i + 1) << std::endl; row[i] = row.at(i - 1) / i * (rowIndex - i + 1) ; } return row; } }; } #endif
19.564103
83
0.461337
cloudyfsail
1e21ef80b6ad93a1aad95da2aa7c4ba7b7d25d72
1,522
cpp
C++
ema-tools/palate-contour/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
null
null
null
ema-tools/palate-contour/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
2
2017-05-29T09:43:01.000Z
2017-05-29T09:50:05.000Z
ema-tools/palate-contour/src/bin/main.cpp
ahewer/mri-shape-tools
4268499948f1330b983ffcdb43df62e38ca45079
[ "MIT" ]
4
2017-05-17T11:56:02.000Z
2022-03-05T09:12:24.000Z
#include "mesh/MeshIO.h" #include "ema/Ema.h" #include "ema-modify/ApplyModifications.h" #include "PalateContour.h" #include "visualize/ProjectMesh.h" #include "settings.h" int main(int argc, char* argv[]) { Settings settings(argc, argv); Ema ema; std::vector<arma::vec> points; for(const std::string& fileName: settings.input) { ema.read().from(fileName); if(settings.applyModifications == true) { emaModify::ApplyModifications(ema).apply(settings.emaModifications); } for(const std::string& channel: settings.channels) { ema.coil(channel).transform().scale(settings.scale); for(int i = 0; i < ema.info().sample_amount(); ++i) { points.push_back(ema.coil(channel).access().position(i)); } } } PalateContour contour(points, settings.axisAccess); Mesh result; result.set_vertices(contour.get_boundary(settings.spacing)); MeshIO::write(result, settings.output); if(settings.outputImage == true) { arma::vec min, max; result.get_bounding_box(min, max) ; const int originX = min(0); const int originY = min(1); const int originZ = min(2); Image image; image.create() .with_dimension(max(0) - min(0), max(1) - min(1), max(2) - min(2)) .with_grid_spacing(1, 1, 1) .with_origin(originX, originY, originZ) .empty_image(); ProjectMesh projection(result, image, 5); image = projection.get_projected_mesh(); image.write().to(settings.imageOutput); } return 0; }
20.026316
74
0.653745
ahewer
1e228ea9477628f70f77e6e834b622cf2b694906
2,861
hpp
C++
dakota-6.3.0.Windows.x86/include/LegendreOrthogPolynomial.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/LegendreOrthogPolynomial.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
null
null
null
dakota-6.3.0.Windows.x86/include/LegendreOrthogPolynomial.hpp
seakers/ExtUtils
b0186098063c39bd410d9decc2a765f24d631b25
[ "BSD-2-Clause" ]
1
2022-03-18T14:13:14.000Z
2022-03-18T14:13:14.000Z
/* _______________________________________________________________________ PECOS: Parallel Environment for Creation Of Stochastics Copyright (c) 2011, Sandia National Laboratories. This software is distributed under the GNU Lesser General Public License. For more information, see the README file in the top Pecos directory. _______________________________________________________________________ */ //- Class: LegendreOrthogPolynomial //- Description: Class for Legendre Orthogonal Polynomial //- //- Owner: Mike Eldred, Sandia National Laboratories #ifndef LEGENDRE_ORTHOG_POLYNOMIAL_HPP #define LEGENDRE_ORTHOG_POLYNOMIAL_HPP #include "OrthogonalPolynomial.hpp" namespace Pecos { /// Derived orthogonal polynomial class for Legendre polynomials /** The LegendreOrthogPolynomial class evaluates a univariate Legendre polynomial of a particular order. These polynomials are orthogonal with respect to the weight function 1 when integrated over the support range of [-1,+1]. This corresponds to the probability density function f(x) = 1/(U-L) = 1/2 for the uniform distribution for [L,U]=[-1,1]. It enables (mixed) multidimensional orthogonal polynomial basis functions within OrthogPolyApproximation. Legendre polynomials are a special case (alpha = beta = 0) of the more general Jacobi polynomials (implemented separately) which correspond to the beta distribution. */ class LegendreOrthogPolynomial: public OrthogonalPolynomial { public: // //- Heading: Constructor and destructor // LegendreOrthogPolynomial(short colloc_rule); ///< extended constructor LegendreOrthogPolynomial(); ///< default constructor ~LegendreOrthogPolynomial(); ///< destructor protected: // //- Heading: Virtual function redefinitions // Real type1_value(Real x, unsigned short order); Real type1_gradient(Real x, unsigned short order); Real type1_hessian(Real x, unsigned short order); Real norm_squared(unsigned short order); const RealArray& collocation_points(unsigned short order); const RealArray& type1_collocation_weights(unsigned short order); Real length_scale() const; private: // //- Heading: Data // }; // collocRule may be GAUSS_LEGENDRE (default), GAUSS_PATTERSON, // CLENSHAW_CURTIS, or FEJER2 inline LegendreOrthogPolynomial::LegendreOrthogPolynomial(short colloc_rule) { collocRule = colloc_rule; wtFactor = 0.5; } inline LegendreOrthogPolynomial::LegendreOrthogPolynomial() { collocRule = GAUSS_LEGENDRE; wtFactor = 0.5; } inline LegendreOrthogPolynomial::~LegendreOrthogPolynomial() { } /** [-1,1]: mean is zero; return std deviation = 2/sqrt(12). */ inline Real LegendreOrthogPolynomial::length_scale() const { return std::pow(3., -0.5); } } // namespace Pecos #endif
31.097826
78
0.74834
seakers
1e26392b6ad6d77798f57ab019b1a55a6575eeb8
393
cpp
C++
maketutorial/animals/main.cpp
keelimepi/CS225
a98871095cc2d488c646a72acd2c28aceb2b3ae7
[ "AFL-1.1" ]
4
2018-09-23T00:00:13.000Z
2018-11-02T22:56:35.000Z
maketutorial/animals/main.cpp
keelimepi/CS225
a98871095cc2d488c646a72acd2c28aceb2b3ae7
[ "AFL-1.1" ]
null
null
null
maketutorial/animals/main.cpp
keelimepi/CS225
a98871095cc2d488c646a72acd2c28aceb2b3ae7
[ "AFL-1.1" ]
null
null
null
/** * @file main.cpp * @author Lisa Sproat */ #include "dog.hpp" #include <iostream> #include <utility> // std::pair int main(){ Dog my_dog = Dog("Skye"); my_dog.bark(); my_dog.run(30, 10); my_dog.read_tag(); std::pair<int, int> loc = my_dog.radio_collar(); std::cout << "[Main] Location: (" << loc.first << ", " << loc.second << ")" << std::endl; }
20.684211
58
0.541985
keelimepi
1e27526cf94dab43e14065c22570953c28b562a2
191
cpp
C++
src/Step/7. Basic Math 1/1712.cpp
ljh15952/Baekjoon
fd85e5fef0f9fea382628e0c60f4f97dcdc3ec74
[ "MIT" ]
null
null
null
src/Step/7. Basic Math 1/1712.cpp
ljh15952/Baekjoon
fd85e5fef0f9fea382628e0c60f4f97dcdc3ec74
[ "MIT" ]
null
null
null
src/Step/7. Basic Math 1/1712.cpp
ljh15952/Baekjoon
fd85e5fef0f9fea382628e0c60f4f97dcdc3ec74
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int a,b,c; cin >> a >> b >> c; int sum = (b > c) ? -1 : (c - b ==0) ? -1 : (a / (c - b) + 1); cout << sum << endl; return 0; }
13.642857
63
0.450262
ljh15952
1e281b3cfd887c10e284dce2d6965d8013c82b64
35,358
cc
C++
unittest/mysqlshdk/libs/config/config_file_t.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
119
2016-04-14T14:16:22.000Z
2022-03-08T20:24:38.000Z
unittest/mysqlshdk/libs/config/config_file_t.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
9
2017-04-26T20:48:42.000Z
2021-09-07T01:52:44.000Z
unittest/mysqlshdk/libs/config/config_file_t.cc
mueller/mysql-shell
29bafc5692bd536a12c4e41c54cb587375fe52cf
[ "Apache-2.0" ]
51
2016-07-20T05:06:48.000Z
2022-03-09T01:20:53.000Z
/* * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, as * designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License, version 2.0, for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifdef _WIN32 #include <Windows.h> #endif #include "my_config.h" #include "mysqlshdk/libs/config/config_file.h" #include "mysqlshdk/libs/utils/nullable.h" #include "mysqlshdk/libs/utils/utils_file.h" #include "mysqlshdk/libs/utils/utils_path.h" #include "mysqlshdk/libs/utils/utils_string.h" #include "unittest/test_utils.h" #include "unittest/test_utils/mocks/gmock_clean.h" using mysqlshdk::config::Config_file; using mysqlshdk::utils::nullable; extern "C" const char *g_test_home; namespace testing { class ConfigFileTest : public tests::Shell_base_test { protected: std::string m_option_files_basedir; std::string m_tmpdir; void SetUp() { tests::Shell_base_test::SetUp(); m_option_files_basedir = shcore::path::join_path(g_test_home, "data", "config"); m_tmpdir = getenv("TMPDIR"); } void TearDown() { tests::Shell_base_test::TearDown(); } }; /** * Verify all the expected data in the Config_file object. * * @param expected_data map with the expected groups and option/values. * @param cfg Config_file object to check. */ void check_config_file_data( const std::map<std::string, std::map<std::string, nullable<std::string>>> &expected_data, const Config_file &cfg) { // Make sure the number of groups is the same, i.e. that there are no // additional groups in the Config_file object. EXPECT_EQ(cfg.groups().size(), expected_data.size()); for (const auto &grp_pair : expected_data) { std::string grp = grp_pair.first; // Make sure the number of option for each group is the same, i.e., there // are no additional options in the Config_file object. EXPECT_EQ(cfg.options(grp).size(), grp_pair.second.size()); for (const auto &opt_pair : grp_pair.second) { std::string opt = opt_pair.first; nullable<std::string> expected_val = opt_pair.second; nullable<std::string> value = cfg.get(grp, opt); std::string str_expected_val = expected_val.is_null() ? "NULL" : "'" + (*expected_val) + "'"; std::string str_value = value.is_null() ? "NULL" : "'" + (*value) + "'"; // Verify that the value for each option in all groups matches what is // expected. EXPECT_EQ(expected_val, value) << "Value for group '" << grp.c_str() << "' and option '" << opt.c_str() << "' does not match. Expected: " << str_expected_val.c_str() << ", Got: " << str_value.c_str() << "."; } } } TEST_F(ConfigFileTest, test_read) { // Test reading a sample MySQL option file (my.cnf). Config_file cfg = Config_file(); std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my.cnf"); std::map<std::string, std::map<std::string, nullable<std::string>>> data = { {"default", {{"password", nullable<std::string>("54321")}, {"repeated_value", nullable<std::string>("what")}}}, {"client", {{"password", nullable<std::string>("12345")}, {"port", nullable<std::string>("1000")}, {"socket", nullable<std::string>("/var/run/mysqld/mysqld.sock")}, {"ssl-ca", nullable<std::string>("dummyCA")}, {"ssl-cert", nullable<std::string>("dummyCert")}, {"ssl-key", nullable<std::string>("dummyKey")}, {"ssl-cipher", nullable<std::string>("AES256-SHA:CAMELLIA256-SHA")}, {"CaseSensitiveOptions", nullable<std::string>("Yes")}, {"option_to_delete_with_value", nullable<std::string>("20")}, {"option_to_delete_without_value", nullable<std::string>()}}}, {"mysqld_safe", {{"socket", nullable<std::string>("/var/run/mysqld/mysqld1.sock")}, {"nice", nullable<std::string>("0")}, {"valid_v1", nullable<std::string>("include comment ( #) symbol")}, {"valid_v2", nullable<std::string>("include comment ( #) symbol")}}}, {"mysqld", {{"option_to_delete_with_value", nullable<std::string>("20")}, {"option_to_delete_without_value", nullable<std::string>()}, {"master-info-repository", nullable<std::string>("FILE")}, {"user", nullable<std::string>("mysql")}, {"pid-file", nullable<std::string>("/var/run/mysqld/mysqld.pid")}, {"socket", nullable<std::string>("/var/run/mysqld/mysqld2.sock")}, {"port", nullable<std::string>("1001")}, {"basedir", nullable<std::string>("/usr")}, {"datadir", nullable<std::string>("/var/lib/mysql")}, {"tmpdir", nullable<std::string>("/tmp")}, {"to_override", nullable<std::string>()}, {"to_override_with_value", nullable<std::string>("old_val")}, {"no_comment_no_value", nullable<std::string>()}, {"lc-messages-dir", nullable<std::string>("/usr/share/mysql")}, {"skip-external-locking", nullable<std::string>()}, {"binlog", nullable<std::string>("True")}, {"multivalue", nullable<std::string>("Noooooooooooooooo")}, {"semi-colon", nullable<std::string>(";")}, {"bind-address", nullable<std::string>("127.0.0.1")}, {"log_error", nullable<std::string>("/var/log/mysql/error.log")}}}, {"delete_section", {{"option_to_drop_with_no_value", nullable<std::string>()}, {"option_to_drop_with_value", nullable<std::string>("value")}, {"option_to_drop_with_value2", nullable<std::string>("value")}}}, {"escape_sequences", {{"backspace", nullable<std::string>("\b")}, {"tab", nullable<std::string>("\t")}, {"newline", nullable<std::string>("\n")}, {"carriage-return", nullable<std::string>("\r")}, {"backslash", nullable<std::string>("\\")}, {"space", nullable<std::string>(" ")}, {"not_esc_seq_char", nullable<std::string>("\\S")}}}, {"path_options", {{"win_path_no_esc_seq_char1", nullable<std::string>("C:\\Program Files\\MySQL\\MySQL Server 5.7")}, {"win_path_no_esc_seq_char2", nullable<std::string>("C:\\Program Files\\MySQL\\MySQL Server 5.7")}, {"win_path_esc_seq_char", nullable<std::string>("C:\\Program Files\\MySQL\\MySQL Server 5.7")}, {"win_path_with_posix_sep", nullable<std::string>("C:/Program Files/MySQL/MySQL Server 5.7")}}}, {"empty section", {}}, {"delete_section2", {{"option_to_drop_with_no_value", nullable<std::string>()}, {"option_to_drop_with_value", nullable<std::string>("value")}, {"option_to_drop_with_value2", nullable<std::string>("value")}}}}; { SCOPED_TRACE("Test read of file: my.cnf"); cfg.read(cfg_path); check_config_file_data(data, cfg); } { // Test re-reading the same sample file again (no error) // Reset existing configurations with the new read values. SCOPED_TRACE("Test re-read of file: my.cnf"); cfg.read(cfg_path); check_config_file_data(data, cfg); } { // Test Error reading a file that does not exists. SCOPED_TRACE("Test read of file: not_exist.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "not_exist.cnf"); EXPECT_THROW_LIKE(cfg.read(cfg_path), std::runtime_error, "Cannot open file: "); } { // Test error reading a file with no group. SCOPED_TRACE("Test read of file: my_error_no_grp.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_error_no_grp.cnf"); EXPECT_THROW_LIKE(cfg.read(cfg_path), std::runtime_error, "Group missing before option at line 24 of file '"); } { // In case of error, previous state cannot be changed. SCOPED_TRACE("Test state not changed in case of error"); check_config_file_data(data, cfg); } { // No error reading file with duplicated groups. SCOPED_TRACE("Test read of file: my_duplicated_grp.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_duplicated_grp.cnf"); cfg.read(cfg_path); data = {{"client", {{"password", nullable<std::string>("0000")}, {"port", nullable<std::string>("1000")}}}}; check_config_file_data(data, cfg); } { // Read file with !include directives. SCOPED_TRACE("Test read of file: my_include.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_include.cnf"); cfg.read(cfg_path); data = {{"group1", {{"option1", nullable<std::string>("153")}, {"option2", nullable<std::string>("20")}}}, {"group2", {{"option11", nullable<std::string>("11")}, {"option1", nullable<std::string>("203")}, {"option2", nullable<std::string>("303")}, {"option22", nullable<std::string>("22")}}}, {"group3", {{"option3", nullable<std::string>("33")}}}, {"group4", {{"option3", nullable<std::string>("200")}}}, {"mysql", {{"user", nullable<std::string>("myuser")}}}, {"client", {{"user", nullable<std::string>("spam")}}}}; check_config_file_data(data, cfg); } { // Read file with !include and !includedir directives. SCOPED_TRACE("Test read of file: my_include_all.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_include_all.cnf"); cfg.read(cfg_path); data = {{"group1", {{"option1", nullable<std::string>("15")}, {"option2", nullable<std::string>("20")}, {"option3", nullable<std::string>("0")}}}, {"group2", {{"option1", nullable<std::string>("20")}, {"option2", nullable<std::string>("30")}, {"option3", nullable<std::string>("3")}, {"option22", nullable<std::string>("22")}}}, {"group3", {{"option3", nullable<std::string>("3")}}}, {"group4", {{"option3", nullable<std::string>("200")}}}, {"mysql", {{"user", nullable<std::string>("dam")}}}, {"client", {{"user", nullable<std::string>("spam")}}}}; check_config_file_data(data, cfg); } { // Test reading include with loop SCOPED_TRACE("Test read of file: my_include_loopA.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_include_loopA.cnf"); cfg.read(cfg_path); data = {{"group1", {{"option1", nullable<std::string>("11")}, {"option2", nullable<std::string>("13")}}}, {"group2", {{"option1", nullable<std::string>("21")}, {"option2", nullable<std::string>("22")}}}, {"group4", {{"option3", nullable<std::string>("200")}}}, {"mysql", {{"user", nullable<std::string>("myuserB")}}}}; check_config_file_data(data, cfg); } { // Test error including file that does not exist. SCOPED_TRACE("Test read of file: my_include_error3.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_include_error3.cnf"); EXPECT_THROW_LIKE(cfg.read(cfg_path), std::runtime_error, "Cannot open file: "); } { // Test error including file with an invalid format (parsing error). SCOPED_TRACE("Test read of file: my_include_error2.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_include_error2.cnf"); EXPECT_THROW_LIKE(cfg.read(cfg_path), std::runtime_error, "Group missing before option at line 24 of file '"); } { // Test error reading invalid directive SCOPED_TRACE("Test read of file: my_error_invalid_directive.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_error_invalid_directive.cnf"); EXPECT_THROW_LIKE(cfg.read(cfg_path), std::runtime_error, "Invalid directive at line 25 of file '"); } { // Test error reading malformed group SCOPED_TRACE("Test read of file: my_error_malformed_group.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_error_malformed_group.cnf"); EXPECT_THROW_LIKE( cfg.read(cfg_path), std::runtime_error, "Invalid group, not ending with ']', at line 32 of file '"); } { // Test error reading invalid group SCOPED_TRACE("Test read of file: my_error_invalid_group.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_error_invalid_group.cnf"); EXPECT_THROW_LIKE(cfg.read(cfg_path), std::runtime_error, "Invalid group at line 32 of file '"); } { // Test error missing closing quotes SCOPED_TRACE("Test read of file: my_error_quotes_no_match.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_error_quotes_no_match.cnf"); EXPECT_THROW_LIKE( cfg.read(cfg_path), std::runtime_error, "Invalid option, missing closing quote for option value at " "line 25 of file '"); } { // Test error invalid text after quotes SCOPED_TRACE("Test read of file: my_error_quotes_invalid_char.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_error_quotes_invalid_char.cnf"); EXPECT_THROW_LIKE(cfg.read(cfg_path), std::runtime_error, "Invalid option, only comments (started with #) are " "allowed after a quoted value at line 25 of file '"); } { // Test error invalid text after quotes SCOPED_TRACE( "Test read of file: my_error_quotes_single_quote_not_escaped.cnf"); cfg_path = shcore::path::join_path( m_option_files_basedir, "my_error_quotes_single_quote_not_escaped.cnf"); EXPECT_THROW_LIKE( cfg.read(cfg_path), std::runtime_error, "Invalid option, missing closing quote for option value at " "line 25 of file '"); } { // Test error invalid line start SCOPED_TRACE("Test read of file: my_error_invalid_line_start.cnf"); cfg_path = shcore::path::join_path(m_option_files_basedir, "my_error_invalid_line_start.cnf"); EXPECT_THROW_LIKE(cfg.read(cfg_path), std::runtime_error, "Line 31 starts with invalid character in file '"); } { // Test clear (remove all elements) of the Config_file SCOPED_TRACE("Test clear()"); cfg.clear(); data = {}; check_config_file_data(data, cfg); } } TEST_F(ConfigFileTest, test_write) { // Test write to a new file (does not exist) without any changes. { SCOPED_TRACE("Test write to new file (no changes): my_write_test.cnf"); std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my.cnf"); std::string res_cfg_path = shcore::path::join_path(m_tmpdir, "my_write_test.cnf"); std::string cfg_path_tmp = res_cfg_path + ".tmp"; // Simulate that a backup file already exists to test the random file name // creation shcore::create_file(cfg_path_tmp, ""); Config_file cfg = Config_file(); cfg.read(cfg_path); EXPECT_NO_THROW(cfg.write(res_cfg_path)); Config_file cfg_res = Config_file(); cfg_res.read(res_cfg_path); EXPECT_EQ(cfg, cfg_res); // Delete test files at the end. shcore::delete_file(res_cfg_path, true); shcore::delete_file(cfg_path_tmp, true); } // Test write to a new file (does not exist) from the scratch (no read()). { SCOPED_TRACE("Test write to new file (no read): my_no_read_test.cnf"); std::string res_cfg_path = shcore::path::join_path(m_tmpdir, "my_no_read_test.cnf"); Config_file cfg = Config_file(); cfg.add_group("mysqld"); cfg.set("mysqld", "test_option", nullable<std::string>("test_value")); EXPECT_NO_THROW(cfg.write(res_cfg_path)); Config_file cfg_res = Config_file(); cfg_res.read(res_cfg_path); EXPECT_EQ(cfg, cfg_res); // Delete test files at the end. shcore::delete_file(res_cfg_path, true); } // Test write to a file without write permissions. { SCOPED_TRACE( "Test write to a file without write permissions.: " "no_perm_write_test.cnf"); std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my.cnf"); std::string no_write_perm_cfg_path = shcore::path::join_path(m_tmpdir, "no_perm_write_test.cnf"); // Create file to write to and make it read only shcore::create_file(no_write_perm_cfg_path, ""); shcore::make_file_readonly(no_write_perm_cfg_path); Config_file cfg = Config_file(); cfg.read(cfg_path); EXPECT_THROW(cfg.write(no_write_perm_cfg_path), std::runtime_error); #ifdef _WIN32 // NOTE: On Windows, read-only attribute (previously set) must be removed // before deleting the file, otherwise an Access is denied error is // issued. const auto wide_no_write_perm_cfg_path = shcore::utf8_to_wide(no_write_perm_cfg_path); auto attributes = GetFileAttributesW(wide_no_write_perm_cfg_path.c_str()); // Remove (reset) read-only attribute from the file SetFileAttributesW(wide_no_write_perm_cfg_path.c_str(), attributes & ~FILE_ATTRIBUTE_READONLY); #endif // Delete test file at the end. shcore::delete_file(no_write_perm_cfg_path, true); } // Test write to an existing file without any sections { SCOPED_TRACE( "Test write to an existing file without any sections: " "my_write_test.cnf"); std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my.cnf"); std::string res_cfg_path = shcore::path::join_path(m_tmpdir, "my_write_test.cnf"); // simulate that a backup file already exists to test the random file name // creation shcore::create_file(res_cfg_path, "key=value\n"); Config_file cfg = Config_file(); cfg.read(cfg_path); EXPECT_THROW_LIKE(cfg.write(res_cfg_path), std::runtime_error, "Group missing before option at line 1 of file ") // Delete test file at the end. shcore::delete_file(res_cfg_path, true); } // Test write to the same file without any changes. { SCOPED_TRACE("Test write to same file (no changes): my_write_test.cnf"); // Create a copy of the original test file to always keep it unchanged. std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my.cnf"); std::string res_cfg_path = shcore::path::join_path(m_tmpdir, "my_write_test.cnf"); shcore::copy_file(cfg_path, res_cfg_path); Config_file cfg = Config_file(); cfg.read(res_cfg_path); EXPECT_NO_THROW(cfg.write(res_cfg_path)); Config_file cfg_res = Config_file(); cfg_res.read(res_cfg_path); EXPECT_EQ(cfg, cfg_res); // Delete test file at the end. shcore::delete_file(res_cfg_path, true); } // Test write to the same file with changes to the configuration. { SCOPED_TRACE("Test write to same file (with changes): my_write_test.cnf"); // Create a copy of the original test file to always keep it unchanged. std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my.cnf"); std::string res_cfg_path = shcore::path::join_path(m_tmpdir, "my_write_test.cnf"); shcore::copy_file(cfg_path, res_cfg_path); Config_file cfg = Config_file(); cfg.read(res_cfg_path); cfg.set("default", "new_option", nullable<std::string>("with value")); cfg.set("default", "new_option_no_value", nullable<std::string>()); cfg.set("default", "new_option_empty_value", nullable<std::string>("")); cfg.remove_option("client", "option_to_delete-with_value"); cfg.remove_option("client", "option_to_delete-without_value"); cfg.set("client", "MyNameIs", nullable<std::string>("007")); cfg.remove_option("mysqld", "loose_option_to_delete_with_value"); cfg.remove_option("MySQLd", "loose-option_to_delete_without_value"); cfg.set("mysqld", "to_override", nullable<std::string>("True")); cfg.set("MySQLd", "to_override_with_value", nullable<std::string>("new_val")); cfg.set("mysqld", "binlog", nullable<std::string>()); cfg.remove_option("mysqld", "master-info-repository"); cfg.remove_group("delete_section"); cfg.remove_group("delete_section2"); cfg.add_group("IAmNew"); cfg.set("iamnew", "loose_option-with-prefix", nullable<std::string>("need_quote_with_#_symbol")); cfg.set("iamnew", "new_option1", nullable<std::string>("need_quote_different_from_'_with_#_symbol")); cfg.set("iamnew", "new_option2", nullable<std::string>("still need \" ' quote with space")); cfg.set("iamnew", "new_option_no-value", nullable<std::string>()); cfg.set("empty section", "new_option_no-value", nullable<std::string>()); cfg.set("empty section", "new_option_value", nullable<std::string>("value")); EXPECT_NO_THROW(cfg.write(res_cfg_path)); Config_file cfg_res = Config_file(); cfg_res.read(res_cfg_path); EXPECT_EQ(cfg, cfg_res); // Verify that updated options keep their inline comment. std::ifstream cfg_file(res_cfg_path); std::string line; while (std::getline(cfg_file, line)) { if (line.empty()) continue; if (shcore::str_beginswith(line, "to_override=")) { EXPECT_STREQ( "to_override = True # this option is going to be overridden", line.c_str()); } else if (shcore::str_beginswith(line, "to_override_with_value")) { EXPECT_STREQ( "to_override_with_value = new_val # this is also to be " "overridden", line.c_str()); } else if (shcore::str_beginswith(line, "binlog")) { EXPECT_STREQ("binlog # ignore this comment", line.c_str()); } } cfg_file.close(); // Delete test file at the end. shcore::delete_file(res_cfg_path, true); } // Test write to the same file with !include directives. { SCOPED_TRACE( "Test write to file with !include directives: " "my_write_include_test.cnf"); // Create a copy of the original test files to keep them unchanged. std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my_include.cnf"); std::string res_cfg_path = shcore::path::join_path(m_tmpdir, "my_write_include_test.cnf"); shcore::copy_file(cfg_path, res_cfg_path); std::string include_dir = shcore::path::join_path(m_option_files_basedir, "include_files"); std::string tmp_include_dir = shcore::path::join_path(m_tmpdir, "include_files"); shcore::create_directory(tmp_include_dir, false); std::string include_2_cnf = shcore::path::join_path(include_dir, "2.cnf"); std::string include_3_txt = shcore::path::join_path(include_dir, "3.txt"); std::string tmp_include_2_cnf = shcore::path::join_path(tmp_include_dir, "2.cnf"); std::string tmp_include_3_txt = shcore::path::join_path(tmp_include_dir, "3.txt"); shcore::copy_file(include_2_cnf, tmp_include_2_cnf); shcore::copy_file(include_3_txt, tmp_include_3_txt); Config_file cfg = Config_file(); cfg.read(res_cfg_path); EXPECT_NO_THROW(cfg.write(res_cfg_path)); Config_file cfg_res = Config_file(); cfg_res.read(res_cfg_path); EXPECT_EQ(cfg, cfg_res); // Delete all test files at the end. shcore::delete_file(res_cfg_path, true); shcore::remove_directory(tmp_include_dir, true); } // Test write to the same file with !include and !includedir directives. { SCOPED_TRACE( "Test write to file with !include and !includedir directives: " "my_write_include_all_test.cnf"); // Create a copy of the original test files to keep them unchanged. std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my_include_all.cnf"); std::string res_cfg_path = shcore::path::join_path(m_tmpdir, "my_write_include_all_test.cnf"); shcore::copy_file(cfg_path, res_cfg_path); std::string include_dir = shcore::path::join_path(m_option_files_basedir, "include_files"); std::string tmp_include_dir = shcore::path::join_path(m_tmpdir, "include_files"); shcore::create_directory(tmp_include_dir, false); std::string include_1_cnf = shcore::path::join_path(include_dir, "1.cnf"); std::string include_1_txt = shcore::path::join_path(include_dir, "1.txt"); std::string include_2_cnf = shcore::path::join_path(include_dir, "2.cnf"); std::string include_3_txt = shcore::path::join_path(include_dir, "3.txt"); std::string tmp_include_1_cnf = shcore::path::join_path(tmp_include_dir, "1.cnf"); std::string tmp_include_1_txt = shcore::path::join_path(tmp_include_dir, "1.txt"); std::string tmp_include_2_cnf = shcore::path::join_path(tmp_include_dir, "2.cnf"); std::string tmp_include_3_txt = shcore::path::join_path(tmp_include_dir, "3.txt"); shcore::copy_file(include_1_cnf, tmp_include_1_cnf); shcore::copy_file(include_1_txt, tmp_include_1_txt); shcore::copy_file(include_2_cnf, tmp_include_2_cnf); shcore::copy_file(include_3_txt, tmp_include_3_txt); Config_file cfg = Config_file(); cfg.read(res_cfg_path); EXPECT_NO_THROW(cfg.write(res_cfg_path)); Config_file cfg_res = Config_file(); cfg_res.read(res_cfg_path); EXPECT_EQ(cfg, cfg_res); // Delete all test files at the end. shcore::delete_file(res_cfg_path, true); shcore::remove_directory(tmp_include_dir, true); } } TEST_F(ConfigFileTest, test_groups_case_insensitive) { // Test config file with no groups Config_file cfg = Config_file(); EXPECT_FALSE(cfg.has_group("test_group")); // Add new group and verify it was added. EXPECT_TRUE(cfg.add_group("Test_Group")); EXPECT_TRUE(cfg.has_group("tesT_grouP")); std::vector<std::string> groups = cfg.groups(); EXPECT_EQ(groups.size(), 1); EXPECT_THAT(groups, UnorderedElementsAre("Test_Group")); // Adding a group with the same name does nothing (false returned). EXPECT_FALSE(cfg.add_group("TEST_group")); groups = cfg.groups(); EXPECT_EQ(groups.size(), 1); // Removing a non existing group (false returned). EXPECT_FALSE(cfg.remove_group("not_exist")); groups = cfg.groups(); EXPECT_EQ(groups.size(), 1); // Removing an existing group (true returned). EXPECT_TRUE(cfg.remove_group("test_GROUP")); groups = cfg.groups(); EXPECT_EQ(groups.size(), 0); } TEST_F(ConfigFileTest, test_groups_case_sensitive) { // Test config file with no groups Config_file cfg = Config_file(mysqlshdk::config::Case::SENSITIVE); EXPECT_FALSE(cfg.has_group("test_group")); // Add new group and verify it was added. EXPECT_TRUE(cfg.add_group("Test_Group")); EXPECT_TRUE(cfg.has_group("Test_Group")); EXPECT_FALSE(cfg.has_group("tesT_grouP")); std::vector<std::string> groups = cfg.groups(); EXPECT_EQ(groups.size(), 1); EXPECT_THAT(groups, UnorderedElementsAre("Test_Group")); // Adding a group with the same name and different case. EXPECT_TRUE(cfg.add_group("TEST_group")); groups = cfg.groups(); EXPECT_EQ(groups.size(), 2); EXPECT_THAT(groups, UnorderedElementsAre("Test_Group", "TEST_group")); // Removing a non existing group (false returned). EXPECT_FALSE(cfg.remove_group("not_exist")); groups = cfg.groups(); EXPECT_EQ(groups.size(), 2); // Removing an existing group (true returned). EXPECT_TRUE(cfg.remove_group("TEST_group")); groups = cfg.groups(); EXPECT_EQ(groups.size(), 1); // Removing a non existing group (false returned). EXPECT_FALSE(cfg.remove_group("TEST_group")); groups = cfg.groups(); EXPECT_EQ(groups.size(), 1); EXPECT_THAT(groups, UnorderedElementsAre("Test_Group")); } TEST_F(ConfigFileTest, test_options) { // Test config file with a group and no options Config_file cfg = Config_file(); cfg.add_group("test_group"); EXPECT_FALSE(cfg.has_option("test_group", "test_option")); // Setting a new option to a non-existing group throws an exception. mysqlshdk::utils::nullable<std::string> value("test value"); EXPECT_THROW(cfg.set("no_group", "test_option", value), std::out_of_range); // Adding (set) new options (with and without value) to an existing group. // NOTE: Options can use '-' and '_' interchangeably, and have the 'loose_' // prefix, but they are case sensitive. cfg.set("Test_Group", "test-option", value); EXPECT_TRUE(cfg.has_option("tesT_grouP", "test_option")); EXPECT_TRUE(cfg.has_option("tesT_grouP", "test-option")); EXPECT_TRUE(cfg.has_option("tesT_grouP", "loose-test-option")); EXPECT_TRUE(cfg.has_option("tesT_grouP", "loose_test_option")); cfg.set("test_group", "loose_no_value_option", mysqlshdk::utils::nullable<std::string>()); EXPECT_TRUE(cfg.has_option("test_group", "no_value_option")); EXPECT_TRUE(cfg.has_option("test_group", "no-value_option")); EXPECT_TRUE(cfg.has_option("test_group", "loose-no_value_option")); EXPECT_TRUE(cfg.has_option("test_group", "loose_no-value-option")); // The option name that was first set for the option is returned by // options() std::vector<std::string> options = cfg.options("test_group"); EXPECT_EQ(options.size(), 2); EXPECT_THAT(options, UnorderedElementsAre("test-option", "loose_no_value_option")); // Getting the value for a non existing option or group throws an exception. EXPECT_THROW(cfg.get("test_group", "no_option"), std::out_of_range); EXPECT_THROW(cfg.get("no_group", "test-option"), std::out_of_range); // Get value of added options. // NOTE: Options can use '-' and '_' interchangeably, and have the 'loose_' // prefix, but they are case sensitive. mysqlshdk::utils::nullable<std::string> ret_value = cfg.get("test_group", "test-option"); EXPECT_FALSE(ret_value.is_null()); EXPECT_EQ(*value, *ret_value); ret_value = cfg.get("test_group", "loose-test_option"); EXPECT_FALSE(ret_value.is_null()); EXPECT_EQ(*value, *ret_value); ret_value = cfg.get("test_group", "loose_no_value_option"); EXPECT_TRUE(ret_value.is_null()); ret_value = cfg.get("test_group", "no-value-option"); EXPECT_TRUE(ret_value.is_null()); // Changing (set) existing options (with and without value), // Switch value of previously set options. // NOTE: Options can use '-' and '_' interchangeably, and have the 'loose_' // prefix, but they are case sensitive. cfg.set("test_group", "loose-test_option", mysqlshdk::utils::nullable<std::string>()); EXPECT_TRUE(cfg.has_option("test_group", "test-option")); cfg.set("test_group", "no-value-option", value); EXPECT_TRUE(cfg.has_option("test_group", "loose_no_value_option")); options = cfg.options("test_group"); EXPECT_EQ(options.size(), 2); EXPECT_THAT(options, UnorderedElementsAre("test-option", "loose_no_value_option")); // Get value of changed options. // NOTE: Options can use '-' and '_' interchangeably, and have the 'loose_' // prefix, but they are case sensitive. ret_value = cfg.get("test_group", "test-option"); EXPECT_TRUE(ret_value.is_null()); ret_value = cfg.get("test_group", "loose-test_option"); EXPECT_TRUE(ret_value.is_null()); ret_value = cfg.get("test_group", "loose_no_value_option"); EXPECT_FALSE(ret_value.is_null()); EXPECT_EQ(*value, *ret_value); ret_value = cfg.get("test_group", "no-value-option"); EXPECT_FALSE(ret_value.is_null()); EXPECT_EQ(*value, *ret_value); // Removing an option from a non existing group throws an exception. EXPECT_THROW(cfg.remove_option("no_group", "test-option"), std::out_of_range); // Removing a non existing option (false returned). EXPECT_FALSE(cfg.remove_option("test_group", "not_exist")); options = cfg.options("test_group"); EXPECT_EQ(options.size(), 2); // Removing an existing option (true returned). // NOTE: Options can use '-' and '_' interchangeably, and have the 'loose_' // prefix, but they are case sensitive. EXPECT_TRUE(cfg.remove_option("test_group", "loose_test-option")); options = cfg.options("test_group"); EXPECT_EQ(options.size(), 1); EXPECT_TRUE(cfg.remove_option("test_group", "no-value-option")); options = cfg.options("test_group"); EXPECT_EQ(options.size(), 0); // Getting the options from a non existing group should throw exception EXPECT_THROW(cfg.options("does_not_exist"), std::out_of_range); } TEST_F(ConfigFileTest, test_constructor) { // Test default (no parameters) constructor, no groups (thus no options) Config_file cfg1 = Config_file(); EXPECT_TRUE(cfg1.groups().empty()); // Test constructor with same object as parameter (copy) Config_file cfg = Config_file(); std::string cfg_path = shcore::path::join_path(m_option_files_basedir, "my.cnf"); cfg.read(cfg_path); Config_file cfg_copy = Config_file(cfg); EXPECT_TRUE(cfg_copy.groups() == cfg.groups()); } TEST_F(ConfigFileTest, get_default_config_paths) { using mysqlshdk::config::get_default_config_paths; using shcore::OperatingSystem; // BUG#30171324 : mysql shell does not know about my.cnf default location // Test default path include /etc/my.cnf and /etc/mysql/my.cnf for all // unix and unix-like systems. auto test_unix_defaults = [](shcore::OperatingSystem os) { SCOPED_TRACE("Test mandatory default paths for '" + to_string(os) + "'"); std::vector<std::string> res = get_default_config_paths(os); std::string sysconfdir; #ifdef DEFAULT_SYSCONFDIR sysconfdir = std::string(DEFAULT_SYSCONFDIR); #endif EXPECT_THAT(res, Contains("/etc/my.cnf")); EXPECT_THAT(res, Contains("/etc/mysql/my.cnf")); if (!sysconfdir.empty()) { EXPECT_THAT(res, Contains(sysconfdir + "/my.cnf")); } }; std::vector<shcore::OperatingSystem> unix_os_list{ shcore::OperatingSystem::DEBIAN, shcore::OperatingSystem::REDHAT, shcore::OperatingSystem::SOLARIS, shcore::OperatingSystem::LINUX, shcore::OperatingSystem::MACOS}; for (const auto &unix_os : unix_os_list) { test_unix_defaults(unix_os); } } } // namespace testing
42.395683
80
0.663669
mueller
1e29151475f2ba6e7d204d9813dc77e2134372e4
6,988
cpp
C++
module07/EX01/IFT3100H22_Lighting/src/renderer.cpp
philvoyer/IFT3100H20
17b5c260b7bff2b2df4ed4c61fb078a5841f5c67
[ "MIT" ]
13
2020-01-22T20:17:26.000Z
2020-08-31T01:02:18.000Z
module07/EX01/IFT3100H22_Lighting/src/renderer.cpp
philvoyer/IFT3100H22
17b5c260b7bff2b2df4ed4c61fb078a5841f5c67
[ "MIT" ]
null
null
null
module07/EX01/IFT3100H22_Lighting/src/renderer.cpp
philvoyer/IFT3100H22
17b5c260b7bff2b2df4ed4c61fb078a5841f5c67
[ "MIT" ]
1
2022-01-11T22:05:37.000Z
2022-01-11T22:05:37.000Z
// IFT3100H22_Lighting/renderer.cpp // Classe responsable du rendu de l'application. #include "renderer.h" Renderer::Renderer(){} void Renderer::setup() { ofSetFrameRate(60); ofEnableDepthTest(); ofSetSphereResolution(32); // paramètres camera_offset = 350.0f; speed_motion = 150.0f; oscillation_frequency = 7500.0f; oscillation_amplitude = 45.0; initial_x = 0.0f; initial_z = -100.0f; scale_cube = 100.0f; scale_sphere = 80.0f; scale_teapot = 0.618f; // chargement du modèle 3D teapot.loadModel("teapot.obj"); // initialisation de la scène reset(); } void Renderer::reset() { // initialisation des variables offset_x = initial_x; offset_z = initial_z; delta_x = speed_motion; delta_z = speed_motion; use_smooth_lighting = true; is_active_ligh_ambient = true; is_active_light_directional = true; is_active_light_point = true; is_active_light_spot = true; // centre du framebuffer center_x = ofGetWidth() / 2.0f; center_y = ofGetHeight() / 2.0f; // déterminer la position des géométries position_cube.set(-ofGetWidth() * (1.0f / 4.0f), 0.0f, 0.0f); position_sphere.set(0.0f, 0.0f, 0.0f); position_teapot.set(ofGetWidth() * (1.0f / 4.0f), 50.0f, 0.0f); // configurer le matériau du cube material_cube.setAmbientColor(ofColor(63, 63, 63)); material_cube.setDiffuseColor(ofColor(127, 0, 0)); material_cube.setEmissiveColor(ofColor( 31, 0, 0)); material_cube.setSpecularColor(ofColor(127, 127, 127)); material_cube.setShininess(16.0f); // configurer le matériau de la sphère material_sphere.setAmbientColor(ofColor(63, 63, 63)); material_sphere.setDiffuseColor(ofColor(191, 63, 0)); material_sphere.setEmissiveColor(ofColor(0, 31, 0)); material_sphere.setSpecularColor(ofColor(255, 255, 64)); material_sphere.setShininess(8.0f); // configurer le matériau du teapot material_teapot.setAmbientColor(ofColor(63, 63, 63)); material_teapot.setDiffuseColor(ofColor(63, 0, 63)); material_teapot.setEmissiveColor(ofColor(0, 0, 31)); material_teapot.setSpecularColor(ofColor(191, 191, 191)); material_teapot.setShininess(8.0f); // configurer la lumière ambiante light_ambient.set(127, 127, 127); // configurer la lumière directionnelle light_directional.setDiffuseColor(ofColor(31, 255, 31)); light_directional.setSpecularColor(ofColor(191, 191, 191)); light_directional.setOrientation(ofVec3f(0.0f, 0.0f, 0.0f)); light_directional.setDirectional(); // configurer la lumière ponctuelle light_point.setDiffuseColor(ofColor(255, 255, 255)); light_point.setSpecularColor(ofColor(191, 191, 191)); light_point.setPointLight(); // configurer la lumière projecteur light_spot.setDiffuseColor(ofColor(191, 191, 191)); light_spot.setSpecularColor(ofColor(191, 191, 191)); light_spot.setOrientation(ofVec3f(0.0f, 0.0f, 0.0f)); light_spot.setSpotConcentration(2); light_spot.setSpotlightCutOff(30); light_spot.setSpotlight(); ofLog() << "<reset>"; } void Renderer::update() { ofPushMatrix(); if (is_active_light_directional) { // transformer la lumière directionnelle orientation_directional.makeRotate(int(ofGetElapsedTimeMillis() * 0.1f) % 360, 0, 1, 0); light_directional.setPosition(center_x, center_y + 60, camera_offset * 0.75f); light_directional.setOrientation(orientation_directional); } if (is_active_light_point) { // transformer la lumière ponctuelle light_point.setPosition(ofGetMouseX(), ofGetMouseY(), camera_offset * 0.75f); } if (is_active_light_spot) { // transformer la lumière projecteur oscillation = oscillate(ofGetElapsedTimeMillis(), oscillation_frequency, oscillation_amplitude); orientation_spot.makeRotate(30.0f, ofVec3f(1, 0, 0), oscillation, ofVec3f(0, 1, 0), 0.0f, ofVec3f(0, 0, 1)); light_spot.setOrientation(orientation_spot); light_spot.setPosition (center_x, center_y - 75.0f, camera_offset * 0.75f); } ofPopMatrix(); } void Renderer::draw() { ofBackground(0); ofPushMatrix(); // afficher un repère visuel pour les lumières if (is_active_light_point) light_point.draw(); if (is_active_light_directional) light_directional.draw(); if (is_active_light_spot) light_spot.draw(); ofPopMatrix(); // activer l'éclairage dynamique ofEnableLighting(); // activer les lumières lighting_on(); ofPushMatrix(); // transformer l'origine de la scène au milieu de la fenêtre d'affichage ofTranslate(center_x + offset_x, center_y, offset_z); // légère rotation de la scène ofRotateDeg(ofGetFrameNum() * 0.25f, 0, 1, 0); ofPushMatrix(); // position ofTranslate( position_cube.x, position_cube.y, position_cube.z); // rotation locale ofRotateDeg(ofGetFrameNum() * 1.0f, 0, 1, 0); // activer le matériau material_cube.begin(); // dessiner un cube ofDrawBox(0, 0, 0, scale_cube); // désactiver le matériau material_cube.end(); ofPopMatrix(); ofPushMatrix(); // position ofTranslate( position_sphere.x, position_sphere.y, position_sphere.z); // rotation locale ofRotateDeg(ofGetFrameNum() * 1.0f, 0, 1, 0); // activer le matériau material_sphere.begin(); // dessiner une sphère ofDrawSphere(0, 0, 0, scale_sphere); // désactiver le matériau material_sphere.end(); ofPopMatrix(); ofPushMatrix(); // position teapot.setPosition( position_teapot.x, position_teapot.y + 15, position_teapot.z); // rotation locale teapot.setRotation(0, ofGetFrameNum() * -1.0f, 0, 1, 0); // dimension teapot.setScale( scale_teapot, scale_teapot, scale_teapot); // désactiver le matériau par défaut du modèle teapot.disableMaterials(); // activer le matériau material_teapot.begin(); // dessiner un teapot teapot.draw(OF_MESH_FILL); // désactiver le matériau material_teapot.end(); ofPopMatrix(); ofPopMatrix(); // désactiver les lumières lighting_off(); // désactiver l'éclairage dynamique ofDisableLighting(); } // désactivation des lumières dynamiques void Renderer::lighting_on() { if (is_active_ligh_ambient) ofSetGlobalAmbientColor(light_ambient); else ofSetGlobalAmbientColor(ofColor(0, 0, 0)); if (is_active_light_directional) light_directional.enable(); if (is_active_light_point) light_point.enable(); if (is_active_light_spot) light_spot.enable(); } // activation des lumières dynamiques void Renderer::lighting_off() { ofSetGlobalAmbientColor(ofColor(0, 0, 0)); light_directional.disable(); light_point.disable(); light_spot.disable(); } // fonction d'oscillation float Renderer::oscillate(float time, float frequency, float amplitude) { return sinf(time * 2.0f * PI / frequency) * amplitude; }
24.780142
112
0.694476
philvoyer
1e2a66133bb9ec462c1d844cfa5d294fb39071c1
4,884
cpp
C++
conformance_tests/core/test_ipc/src/test_ipc_event.cpp
oneapi-src/level-zero-tests
aff26cb658dbe0991566a62716be00dde390e793
[ "MIT" ]
32
2020-03-05T19:26:02.000Z
2022-02-21T13:13:52.000Z
conformance_tests/core/test_ipc/src/test_ipc_event.cpp
oneapi-src/level-zero-tests
aff26cb658dbe0991566a62716be00dde390e793
[ "MIT" ]
9
2020-05-04T20:15:09.000Z
2021-12-19T07:17:50.000Z
conformance_tests/core/test_ipc/src/test_ipc_event.cpp
oneapi-src/level-zero-tests
aff26cb658dbe0991566a62716be00dde390e793
[ "MIT" ]
19
2020-04-07T16:00:48.000Z
2022-01-19T00:19:49.000Z
/* * * Copyright (C) 2019 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "gtest/gtest.h" #include "utils/utils.hpp" #include "test_harness/test_harness.hpp" #include "logging/logging.hpp" #include "test_ipc_event.hpp" #include "test_ipc_comm.hpp" #include <boost/interprocess/shared_memory_object.hpp> #include <boost/interprocess/mapped_region.hpp> #include <boost/process.hpp> #include <level_zero/ze_api.h> namespace lzt = level_zero_tests; namespace bipc = boost::interprocess; namespace { static const ze_event_desc_t defaultEventDesc = { ZE_STRUCTURE_TYPE_EVENT_DESC, nullptr, 5, 0, ZE_EVENT_SCOPE_FLAG_HOST // ensure memory coherency across device // and Host after event signalled }; ze_event_pool_desc_t defaultEventPoolDesc = { ZE_STRUCTURE_TYPE_EVENT_POOL_DESC, nullptr, (ZE_EVENT_POOL_FLAG_HOST_VISIBLE | ZE_EVENT_POOL_FLAG_IPC), 10}; static lzt::zeEventPool get_event_pool(bool multi_device) { lzt::zeEventPool ep; if (multi_device) { auto devices = lzt::get_devices(lzt::get_default_driver()); ep.InitEventPool(defaultEventPoolDesc, devices); } else { ze_device_handle_t device = lzt::get_default_device(lzt::get_default_driver()); ep.InitEventPool(defaultEventPoolDesc); } return ep; } static void parent_host_signals(ze_event_handle_t hEvent) { lzt::signal_event_from_host(hEvent); } static void parent_device_signals(ze_event_handle_t hEvent) { auto cmdlist = lzt::create_command_list(); auto cmdqueue = lzt::create_command_queue(); lzt::append_signal_event(cmdlist, hEvent); lzt::close_command_list(cmdlist); lzt::execute_command_lists(cmdqueue, 1, &cmdlist, nullptr); lzt::synchronize(cmdqueue, UINT64_MAX); // cleanup lzt::destroy_command_list(cmdlist); lzt::destroy_command_queue(cmdqueue); } static void run_ipc_event_test(parent_test_t parent_test, child_test_t child_test, bool multi_device) { #ifdef __linux__ auto ep = get_event_pool(multi_device); ze_ipc_event_pool_handle_t hIpcEventPool; ep.get_ipc_handle(&hIpcEventPool); if (testing::Test::HasFatalFailure()) return; // Abort test if IPC Event handle failed ze_event_handle_t hEvent; ep.create_event(hEvent, defaultEventDesc); shared_data_t test_data = {parent_test, child_test, multi_device}; bipc::shared_memory_object::remove("ipc_event_test"); bipc::shared_memory_object shm(bipc::create_only, "ipc_event_test", bipc::read_write); shm.truncate(sizeof(shared_data_t)); bipc::mapped_region region(shm, bipc::read_write); std::memcpy(region.get_address(), &test_data, sizeof(shared_data_t)); // launch child boost::process::child c("./ipc/test_ipc_event_helper"); lzt::send_ipc_handle(hIpcEventPool); switch (parent_test) { case PARENT_TEST_HOST_SIGNALS: parent_host_signals(hEvent); break; case PARENT_TEST_DEVICE_SIGNALS: parent_device_signals(hEvent); break; default: FAIL() << "Fatal test error"; } c.wait(); // wait for the process to exit ASSERT_EQ(c.exit_code(), 0); // cleanup bipc::shared_memory_object::remove("ipc_event_test"); ep.destroy_event(hEvent); #endif // linux } TEST( zeIPCEventTests, GivenTwoProcessesWhenEventSignaledByHostInParentThenEventSetinChildFromHostPerspective) { run_ipc_event_test(PARENT_TEST_HOST_SIGNALS, CHILD_TEST_HOST_READS, false); } TEST( zeIPCEventTests, GivenTwoProcessesWhenEventSignaledByDeviceInParentThenEventSetinChildFromHostPerspective) { run_ipc_event_test(PARENT_TEST_DEVICE_SIGNALS, CHILD_TEST_HOST_READS, false); } TEST( zeIPCEventTests, GivenTwoProcessesWhenEventSignaledByDeviceInParentThenEventSetinChildFromDevicePerspective) { run_ipc_event_test(PARENT_TEST_DEVICE_SIGNALS, CHILD_TEST_DEVICE_READS, false); } TEST( zeIPCEventTests, GivenTwoProcessesWhenEventSignaledByHostInParentThenEventSetinChildFromDevicePerspective) { run_ipc_event_test(PARENT_TEST_HOST_SIGNALS, CHILD_TEST_DEVICE_READS, false); } TEST( zeIPCEventMultiDeviceTests, GivenTwoProcessesWhenEventSignaledByDeviceInParentThenEventSetinChildFromSecondDevicePerspective) { if (lzt::get_ze_device_count() < 2) { SUCCEED(); LOG_INFO << "WARNING: Exiting as multiple devices do not exist"; return; } run_ipc_event_test(PARENT_TEST_DEVICE_SIGNALS, CHILD_TEST_DEVICE2_READS, true); } TEST( zeIPCEventMultiDeviceTests, GivenTwoProcessesWhenEventSignaledByHostInParentThenEventSetinChildFromMultipleDevicePerspective) { if (lzt::get_ze_device_count() < 2) { SUCCEED(); LOG_INFO << "WARNING: Exiting as multiple devices do not exist"; return; } run_ipc_event_test(PARENT_TEST_HOST_SIGNALS, CHILD_TEST_MULTI_DEVICE_READS, true); } } // namespace
30.716981
103
0.753071
oneapi-src
1e2ac827524f4e4ce531fb752d5de85ede74c238
175
cpp
C++
src/bounce/event/destroy/run.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
src/bounce/event/destroy/run.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
src/bounce/event/destroy/run.cpp
cbosoft/bounce
f63e5ad1aabe201debf7a9a73525e93973c34932
[ "MIT" ]
null
null
null
#include <bounce/physics/engine/engine.hpp> #include <bounce/event/destroy/destroy.hpp> void TransformDestroyEvent::run(Game *game) { this->_to_be_destroyed->destroy(); }
25
43
0.76
cbosoft
1e2bb53bc07b2db5c4f1bcab3ecc603ed609e37b
7,578
cpp
C++
OpenSim/Common/Logger.cpp
tnamayeshi/opensim-core
acbedd604909980293776da3d54b9611732964bf
[ "Apache-2.0" ]
null
null
null
OpenSim/Common/Logger.cpp
tnamayeshi/opensim-core
acbedd604909980293776da3d54b9611732964bf
[ "Apache-2.0" ]
1
2022-03-19T14:24:11.000Z
2022-03-19T14:24:11.000Z
OpenSim/Common/Logger.cpp
tnamayeshi/opensim-core
acbedd604909980293776da3d54b9611732964bf
[ "Apache-2.0" ]
null
null
null
/* -------------------------------------------------------------------------- * * OpenSim: Logger.cpp * * -------------------------------------------------------------------------- * * The OpenSim API is a toolkit for musculoskeletal modeling and simulation. * * See http://opensim.stanford.edu and the NOTICE file for more information. * * OpenSim is developed at Stanford University and supported by the US * * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA * * through the Warrior Web program. * * * * Copyright (c) 2005-2019 Stanford University and the 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 "Logger.h" #include "Exception.h" #include "IO.h" #include "LogSink.h" #include "spdlog/sinks/stdout_color_sinks.h" using namespace OpenSim; std::shared_ptr<spdlog::logger> Logger::m_cout_logger = spdlog::stdout_color_mt("cout"); std::shared_ptr<spdlog::sinks::basic_file_sink_mt> Logger::m_filesink = {}; std::shared_ptr<spdlog::logger> Logger::m_default_logger; // Force creation of the Logger instane to initialize spdlog::loggers std::shared_ptr<OpenSim::Logger> Logger::m_osimLogger = Logger::getInstance(); Logger::Logger() { m_default_logger = spdlog::default_logger(); m_default_logger->set_level(spdlog::level::info); m_default_logger->set_pattern("[%l] %v"); m_cout_logger->set_level(spdlog::level::info); m_cout_logger->set_pattern("%v"); // This ensures log files are updated regularly, instead of only when the // program shuts down. spdlog::flush_on(spdlog::level::info); } void Logger::setLevel(Level level) { switch (level) { case Level::Off: spdlog::set_level(spdlog::level::off); break; case Level::Critical: spdlog::set_level(spdlog::level::critical); break; case Level::Error: spdlog::set_level(spdlog::level::err); break; case Level::Warn: spdlog::set_level(spdlog::level::warn); break; case Level::Info: spdlog::set_level(spdlog::level::info); break; case Level::Debug: spdlog::set_level(spdlog::level::debug); break; case Level::Trace: spdlog::set_level(spdlog::level::trace); break; default: OPENSIM_THROW(Exception, "Internal error."); } Logger::info("Set log level to {}.", getLevelString()); } Logger::Level Logger::getLevel() { const auto level = m_default_logger->level(); switch (level) { case spdlog::level::off: return Level::Off; case spdlog::level::critical: return Level::Critical; case spdlog::level::err: return Level::Error; case spdlog::level::warn: return Level::Warn; case spdlog::level::info: return Level::Info; case spdlog::level::debug: return Level::Debug; case spdlog::level::trace: return Level::Trace; default: OPENSIM_THROW(Exception, "Internal error."); } } void Logger::setLevelString(std::string str) { Level level; str = IO::Lowercase(str); if (str == "off") level = Level::Off; else if (str == "critical") level = Level::Critical; else if (str == "error") level = Level::Error; else if (str == "warn") level = Level::Warn; else if (str == "info") level = Level::Info; else if (str == "debug") level = Level::Debug; else if (str == "trace") level = Level::Trace; else { OPENSIM_THROW(Exception, "Expected log level to be Off, Critical, Error, " "Warn, Info, Debug, or Trace; got {}.", str); } setLevel(level); } std::string Logger::getLevelString() { const auto level = getLevel(); switch (level) { case Level::Off: return "Off"; case Level::Critical: return "Critical"; case Level::Error: return "Error"; case Level::Warn: return "Warn"; case Level::Info: return "Info"; case Level::Debug: return "Debug"; case Level::Trace: return "Trace"; default: OPENSIM_THROW(Exception, "Internal error."); } } bool Logger::shouldLog(Level level) { spdlog::level::level_enum spdlogLevel; switch (level) { case Level::Off: spdlogLevel = spdlog::level::off; break; case Level::Critical: spdlogLevel = spdlog::level::critical; break; case Level::Error: spdlogLevel = spdlog::level::err; break; case Level::Warn: spdlogLevel = spdlog::level::warn; break; case Level::Info: spdlogLevel = spdlog::level::info; break; case Level::Debug: spdlogLevel = spdlog::level::debug; break; case Level::Trace: spdlogLevel = spdlog::level::trace; break; default: OPENSIM_THROW(Exception, "Internal error."); } return m_default_logger->should_log(spdlogLevel); } void Logger::addFileSink(const std::string& filepath) { if (m_filesink) { warn("Already logging to file '{}'; log file not added. Call " "removeFileSink() first.", m_filesink->filename()); return; } // check if file can be opened at the specified path if not return meaningful // warning rather than bubble the exception up. try { m_filesink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filepath); } catch (...) { warn("Can't open file '{}' for writing. Log file will not be created. " "Check that you have write permissions to the specified path.", filepath); return; } addSinkInternal(m_filesink); } void Logger::removeFileSink() { removeSinkInternal( std::static_pointer_cast<spdlog::sinks::sink>(m_filesink)); m_filesink.reset(); } void Logger::addSink(const std::shared_ptr<LogSink> sink) { addSinkInternal(std::static_pointer_cast<spdlog::sinks::sink>(sink)); } void Logger::removeSink(const std::shared_ptr<LogSink> sink) { removeSinkInternal(std::static_pointer_cast<spdlog::sinks::sink>(sink)); } void Logger::addSinkInternal(std::shared_ptr<spdlog::sinks::sink> sink) { m_default_logger->sinks().push_back(sink); m_cout_logger->sinks().push_back(sink); } void Logger::removeSinkInternal(const std::shared_ptr<spdlog::sinks::sink> sink) { { auto& sinks = m_default_logger->sinks(); auto to_erase = std::find(sinks.cbegin(), sinks.cend(), sink); if (to_erase != sinks.cend()) sinks.erase(to_erase); } { auto& sinks = m_cout_logger->sinks(); auto to_erase = std::find(sinks.cbegin(), sinks.cend(), sink); if (to_erase != sinks.cend()) sinks.erase(to_erase); } }
37.514851
81
0.598179
tnamayeshi
1e2bfb745beb3e219c8623aaa009f9a221eed121
3,848
hpp
C++
openstudiocore/src/model/LifeCycleCost_Impl.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
4
2015-05-02T21:04:15.000Z
2015-10-28T09:47:22.000Z
openstudiocore/src/model/LifeCycleCost_Impl.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
null
null
null
openstudiocore/src/model/LifeCycleCost_Impl.hpp
BIMDataHub/OpenStudio-1
13ec115b00aa6a2af1426ceb26446f05014c8c8d
[ "blessing" ]
1
2020-11-12T21:52:36.000Z
2020-11-12T21:52:36.000Z
/********************************************************************** * Copyright (c) 2008-2015, Alliance for Sustainable Energy. * 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.1 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 **********************************************************************/ #ifndef MODEL_LIFECYCLECOST_IMPL_HPP #define MODEL_LIFECYCLECOST_IMPL_HPP #include "ParentObject_Impl.hpp" #include "LifeCycleCost.hpp" #include "../utilities/core/Optional.hpp" namespace openstudio { namespace model { class SpaceLoadDefinition; namespace detail { class MODEL_API LifeCycleCost_Impl : public ModelObject_Impl { Q_OBJECT; Q_PROPERTY(const std::string& itemType READ itemType); Q_PROPERTY(double cost READ cost WRITE setCost); Q_PROPERTY(std::string costUnits READ costUnits WRITE setCostUnits); public: // constructor LifeCycleCost_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle); // construct from workspace LifeCycleCost_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle); // clone copy constructor LifeCycleCost_Impl(const LifeCycleCost_Impl& other,Model_Impl* model,bool keepHandle); // virtual destructor virtual ~LifeCycleCost_Impl(){} virtual IddObjectType iddObjectType() const override {return LifeCycleCost::iddObjectType();} virtual const std::vector<std::string>& outputVariableNames() const override; /** @name Getters */ //@{ std::string category() const; std::string itemType() const; ModelObject item() const; double cost() const; std::vector<std::string> validCostUnitsValues() const; std::string costUnits() const; int yearsFromStart() const; bool isYearsFromStartDefaulted() const; int monthsFromStart() const; bool isMonthsFromStartDefaulted() const; int repeatPeriodYears() const; bool isRepeatPeriodYearsDefaulted() const; int repeatPeriodMonths() const; bool isRepeatPeriodMonthsDefaulted() const; //@} /** @name Setters */ //@{ bool setCategory(const std::string& category); bool setCost(double cost); bool setCostUnits(const std::string& costUnits); bool setYearsFromStart(int yearsFromStart); void resetYearsFromStart(); bool setMonthsFromStart(int monthsFromStart); void resetMonthsFromStart(); bool setRepeatPeriodYears(int repeatPeriodYears); void resetRepeatPeriodYears(); bool setRepeatPeriodMonths(int repeatPeriodMonths); void resetRepeatPeriodMonths(); //@} double totalCost() const; bool convertToCostPerEach(); boost::optional<int> costedQuantity() const; boost::optional<double> costedArea() const; boost::optional<int> costedThermalZones() const; private: REGISTER_LOGGER("openstudio.model.LifeCycleCost"); //double getArea(const SpaceLoadInstance& spaceLoadInstance) const; //double getArea(const SpaceLoadDefinition& spaceLoadDefinition) const; }; } // detail } // model } // openstudio #endif // MODEL_LIFECYCLECOST_IMPL_HPP
29.829457
96
0.695166
BIMDataHub
1e2d66959e32676a9103fdfec190eaf20ffb5a54
20,375
cpp
C++
Source/Primative.cpp
findux/ToolKit
3caa97441318d19fe0a6e3d13d88dfbdb60afb44
[ "MIT" ]
32
2020-10-16T00:17:14.000Z
2022-03-02T18:25:58.000Z
Source/Primative.cpp
findux/ToolKit
3caa97441318d19fe0a6e3d13d88dfbdb60afb44
[ "MIT" ]
1
2021-09-19T12:18:17.000Z
2022-02-23T06:53:30.000Z
Source/Primative.cpp
findux/ToolKit
3caa97441318d19fe0a6e3d13d88dfbdb60afb44
[ "MIT" ]
5
2020-09-18T09:04:40.000Z
2022-02-11T12:44:55.000Z
#include "stdafx.h" #include "Primative.h" #include "Mesh.h" #include "ToolKit.h" #include "MathUtil.h" #include "Directional.h" #include "Node.h" #include "DebugNew.h" namespace ToolKit { Billboard::Billboard(const Settings& settings) : m_settings(settings) { } void Billboard::LookAt(Camera* cam, float windowHeight) { Camera::CamData data = cam->GetData(); // Billboard placement. if (m_settings.distanceToCamera > 0.0f) { if (cam->IsOrtographic()) { m_node->SetTranslation(m_worldLocation, TransformationSpace::TS_WORLD); if (m_settings.heightInScreenSpace > 0.0f) { float distToCenter = glm::distance(Vec3(), data.pos); float dCompansate = distToCenter * 4.0f / 500.0f; float hCompansate = m_settings.heightInScreenSpace / windowHeight; m_node->SetScale(Vec3(dCompansate * hCompansate)); // Compensate shrinkage due to height changes. } } else { Vec3 cdir = cam->GetDir(); Vec3 camWorldPos = cam->m_node->GetTranslation(TransformationSpace::TS_WORLD); Vec3 dir = glm::normalize(m_worldLocation - camWorldPos); float radialToPlanarDistance = 1.0f / glm::dot(cdir, dir); // Always place at the same distance from the near plane. if (radialToPlanarDistance < 0) { return; } Vec3 billWorldPos = camWorldPos + dir * m_settings.distanceToCamera * radialToPlanarDistance; m_node->SetTranslation(billWorldPos, TransformationSpace::TS_WORLD); if (m_settings.heightInScreenSpace > 0.0f) { m_node->SetScale(Vec3(m_settings.heightInScreenSpace / data.height)); // Compensate shrinkage due to height changes. } } if (m_settings.lookAtCamera) { Quaternion camOrientation = cam->m_node->GetOrientation(TransformationSpace::TS_WORLD); m_node->SetOrientation(camOrientation, TransformationSpace::TS_WORLD); } } } Entity* Billboard::GetCopy(Entity* copyTo) const { Drawable::GetCopy(copyTo); Billboard* ntt = static_cast<Billboard*> (copyTo); ntt->m_settings = m_settings; ntt->m_worldLocation = m_worldLocation; return ntt; } Entity* Billboard::GetInstance(Entity* copyTo) const { Drawable::GetInstance(copyTo); Billboard* instance = static_cast<Billboard*> (copyTo); instance->m_settings = m_settings; instance->m_worldLocation = m_worldLocation; return nullptr; } EntityType Billboard::GetType() const { return EntityType::Entity_Billboard; } Cube::Cube(bool genDef) { if (genDef) { Generate(); } } Cube::Cube(const Params& params) : m_params(params) { Generate(); } Entity* Cube::GetCopy(Entity* copyTo) const { return Drawable::GetCopy(copyTo); } EntityType Cube::GetType() const { return EntityType::Entity_Cube; } void Cube::Serialize(XmlDocument* doc, XmlNode* parent) const { Entity::Serialize(doc, parent); m_params.Serialize(doc, parent->last_node()); } void Cube::DeSerialize(XmlDocument* doc, XmlNode* parent) { Entity::DeSerialize(doc, parent); m_params.DeSerialize(doc, parent); Generate(); } Entity* Cube::GetInstance(Entity* copyTo) const { Drawable::GetInstance(copyTo); Cube* instance = static_cast<Cube*> (copyTo); instance->m_params = m_params; return instance; } void Cube::Generate() { VertexArray vertices; vertices.resize(36); const Vec3& scale = m_params.m_variants[0].GetVar<Vec3>(); Vec3 corners[8] { Vec3(-0.5f, 0.5f, 0.5f) * scale, // FTL. Vec3(-0.5f, -0.5f, 0.5f) * scale, // FBL. Vec3(0.5f, -0.5f, 0.5f) * scale, // FBR. Vec3(0.5f, 0.5f, 0.5f) * scale, // FTR. Vec3(-0.5f, 0.5f, -0.5f) * scale, // BTL. Vec3(-0.5f, -0.5f, -0.5f) * scale, // BBL. Vec3(0.5f, -0.5f, -0.5f) * scale, // BBR. Vec3(0.5f, 0.5f, -0.5f) * scale, // BTR. }; // Front vertices[0].pos = corners[0]; vertices[0].tex = Vec2(0.0f, 1.0f); vertices[0].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[1].pos = corners[1]; vertices[1].tex = Vec2(0.0f, 0.0f); vertices[1].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[2].pos = corners[2]; vertices[2].tex = Vec2(1.0f, 0.0f); vertices[2].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[3].pos = corners[0]; vertices[3].tex = Vec2(0.0f, 1.0f); vertices[3].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[4].pos = corners[2]; vertices[4].tex = Vec2(1.0f, 0.0f); vertices[4].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[5].pos = corners[3]; vertices[5].tex = Vec2(1.0f, 1.0f); vertices[5].norm = Vec3(0.0f, 0.0f, 1.0f); // Right vertices[6].pos = corners[3]; vertices[6].tex = Vec2(0.0f, 1.0f); vertices[6].norm = Vec3(1.0f, 0.0f, 0.0f); vertices[7].pos = corners[2]; vertices[7].tex = Vec2(0.0f, 0.0f); vertices[7].norm = Vec3(1.0f, 0.0f, 0.0f); vertices[8].pos = corners[6]; vertices[8].tex = Vec2(1.0f, 0.0f); vertices[8].norm = Vec3(1.0f, 0.0f, 0.0f); vertices[9].pos = corners[3]; vertices[9].tex = Vec2(0.0f, 1.0f); vertices[9].norm = Vec3(1.0f, 0.0f, 0.0f); vertices[10].pos = corners[6]; vertices[10].tex = Vec2(1.0f, 0.0f); vertices[10].norm = Vec3(1.0f, 0.0f, 0.0f); vertices[11].pos = corners[7]; vertices[11].tex = Vec2(1.0f, 1.0f); vertices[11].norm = Vec3(1.0f, 0.0f, 0.0f); // Top vertices[12].pos = corners[0]; vertices[12].tex = Vec2(0.0f, 0.0f); vertices[12].norm = Vec3(0.0f, 1.0f, 0.0f); vertices[13].pos = corners[3]; vertices[13].tex = Vec2(1.0f, 0.0f); vertices[13].norm = Vec3(0.0f, 1.0f, 0.0f); vertices[14].pos = corners[7]; vertices[14].tex = Vec2(1.0f, 1.0f); vertices[14].norm = Vec3(0.0f, 1.0f, 0.0f); vertices[15].pos = corners[0]; vertices[15].tex = Vec2(0.0f, 0.0f); vertices[15].norm = Vec3(0.0f, 1.0f, 0.0f); vertices[16].pos = corners[7]; vertices[16].tex = Vec2(1.0f, 1.0f); vertices[16].norm = Vec3(0.0f, 1.0f, 0.0f); vertices[17].pos = corners[4]; vertices[17].tex = Vec2(0.0f, 1.0f); vertices[17].norm = Vec3(0.0f, 1.0f, 0.0f); // Back vertices[18].pos = corners[4]; vertices[18].tex = Vec2(0.0f, 1.0f); vertices[18].norm = Vec3(0.0f, 0.0f, -1.0f); vertices[19].pos = corners[6]; vertices[19].tex = Vec2(1.0f, 0.0f); vertices[19].norm = Vec3(0.0f, 0.0f, -1.0f); vertices[20].pos = corners[5]; vertices[20].tex = Vec2(0.0f, 0.0f); vertices[20].norm = Vec3(0.0f, 0.0f, -1.0f); vertices[21].pos = corners[4]; vertices[21].tex = Vec2(0.0f, 1.0f); vertices[21].norm = Vec3(0.0f, 0.0f, -1.0f); vertices[22].pos = corners[7]; vertices[22].tex = Vec2(1.0f, 1.0f); vertices[22].norm = Vec3(0.0f, 0.0f, -1.0f); vertices[23].pos = corners[6]; vertices[23].tex = Vec2(1.0f, 0.0f); vertices[23].norm = Vec3(0.0f, 0.0f, -1.0f); // Left vertices[24].pos = corners[0]; vertices[24].tex = Vec2(0.0f, 1.0f); vertices[24].norm = Vec3(-1.0f, 0.0f, 0.0f); vertices[25].pos = corners[5]; vertices[25].tex = Vec2(1.0f, 0.0f); vertices[25].norm = Vec3(-1.0f, 0.0f, 0.0f); vertices[26].pos = corners[1]; vertices[26].tex = Vec2(0.0f, 0.0f); vertices[26].norm = Vec3(-1.0f, 0.0f, 0.0f); vertices[27].pos = corners[0]; vertices[27].tex = Vec2(0.0f, 1.0f); vertices[27].norm = Vec3(-1.0f, 0.0f, 0.0f); vertices[28].pos = corners[4]; vertices[28].tex = Vec2(1.0f, 1.0f); vertices[28].norm = Vec3(-1.0f, 0.0f, 0.0f); vertices[29].pos = corners[5]; vertices[29].tex = Vec2(1.0f, 0.0f); vertices[29].norm = Vec3(-1.0f, 0.0f, 0.0f); // Bottom vertices[30].pos = corners[1]; vertices[30].tex = Vec2(0.0f, 1.0f); vertices[30].norm = Vec3(0.0f, -1.0f, 0.0f); vertices[31].pos = corners[6]; vertices[31].tex = Vec2(1.0f, 0.0f); vertices[31].norm = Vec3(0.0f, -1.0f, 0.0f); vertices[32].pos = corners[2]; vertices[32].tex = Vec2(0.0f, 0.0f); vertices[32].norm = Vec3(0.0f, -1.0f, 0.0f); vertices[33].pos = corners[1]; vertices[33].tex = Vec2(0.0f, 1.0f); vertices[33].norm = Vec3(0.0f, -1.0f, 0.0f); vertices[34].pos = corners[5]; vertices[34].tex = Vec2(1.0f, 1.0f); vertices[34].norm = Vec3(0.0f, -1.0f, 0.0f); vertices[35].pos = corners[6]; vertices[35].tex = Vec2(1.0f, 0.0f); vertices[35].norm = Vec3(0.0f, -1.0f, 0.0f); m_mesh->m_vertexCount = (uint)vertices.size(); m_mesh->m_clientSideVertices = vertices; m_mesh->m_clientSideIndices = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35 }; m_mesh->m_indexCount = (uint)m_mesh->m_clientSideIndices.size(); m_mesh->m_material = GetMaterialManager()->GetCopyOfDefaultMaterial(); m_mesh->CalculateAABB(); m_mesh->ConstructFaces(); } Quad::Quad(bool genDef) { if (genDef) { Generate(); } } Entity* Quad::GetCopy(Entity* copyTo) const { return Drawable::GetCopy(copyTo); } EntityType Quad::GetType() const { return EntityType::Entity_Quad; } Entity* Quad::GetInstance(Entity* copyTo) const { Drawable::GetInstance(copyTo); Quad* instance = static_cast<Quad*> (copyTo); return instance; } void Quad::Generate() { VertexArray vertices; vertices.resize(4); // Front vertices[0].pos = Vec3(-0.5f, 0.5f, 0.0f); vertices[0].tex = Vec2(0.0f, 1.0f); vertices[0].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[0].btan = Vec3(0.0f, 1.0f, 0.0f); vertices[1].pos = Vec3(-0.5f, -0.5f, 0.0f); vertices[1].tex = Vec2(0.0f, 0.0f); vertices[1].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[1].btan = Vec3(0.0f, 1.0f, 0.0f); vertices[2].pos = Vec3(0.5f, -0.5f, 0.0f); vertices[2].tex = Vec2(1.0f, 0.0f); vertices[2].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[2].btan = Vec3(0.0f, 1.0f, 0.0f); vertices[3].pos = Vec3(0.5f, 0.5f, 0.0f); vertices[3].tex = Vec2(1.0f, 1.0f); vertices[3].norm = Vec3(0.0f, 0.0f, 1.0f); vertices[3].btan = Vec3(0.0f, 1.0f, 0.0f); m_mesh->m_vertexCount = (uint)vertices.size(); m_mesh->m_clientSideVertices = vertices; m_mesh->m_indexCount = 6; m_mesh->m_clientSideIndices = { 0,1,2,0,2,3 }; m_mesh->m_material = GetMaterialManager()->GetCopyOfDefaultMaterial(); m_mesh->CalculateAABB(); m_mesh->ConstructFaces(); } Sphere::Sphere(bool genDef) { if (genDef) { Generate(); } } Sphere::Sphere(const Params& params) : m_params(params) { Generate(); } Entity* Sphere::GetCopy(Entity* copyTo) const { Drawable::GetCopy(copyTo); Sphere* ntt = static_cast<Sphere*> (copyTo); ntt->m_params = m_params; return ntt; } EntityType Sphere::GetType() const { return EntityType::Entity_Sphere; } void Sphere::Generate() { const float r = m_params[0].GetVar<float>(); const int nRings = 32; const int nSegments = 32; VertexArray vertices; std::vector<uint> indices; constexpr float fDeltaRingAngle = (glm::pi<float>() / nRings); constexpr float fDeltaSegAngle = (glm::two_pi<float>() / nSegments); unsigned short wVerticeIndex = 0; // Generate the group of rings for the sphere for (int ring = 0; ring <= nRings; ring++) { float r0 = r * sinf(ring * fDeltaRingAngle); float y0 = r * cosf(ring * fDeltaRingAngle); // Generate the group of segments for the current ring for (int seg = 0; seg <= nSegments; seg++) { float x0 = r0 * sinf(seg * fDeltaSegAngle); float z0 = r0 * cosf(seg * fDeltaSegAngle); // Add one vertex to the strip which makes up the sphere Vertex v; v.pos = Vec3(x0, y0, z0); v.norm = Vec3(x0, y0, z0); v.tex = Vec2((float)seg / (float)nSegments, (float)ring / (float)nRings); float r2, zenith, azimuth; ToSpherical(v.pos, r2, zenith, azimuth); v.btan = Vec3(r * glm::cos(zenith) * glm::sin(azimuth), -r * glm::sin(zenith), r * glm::cos(zenith) * glm::cos(azimuth)); vertices.push_back(v); if (ring != nRings) { // each vertex (except the last) has six indices pointing to it indices.push_back(wVerticeIndex + nSegments + 1); indices.push_back(wVerticeIndex); indices.push_back(wVerticeIndex + nSegments); indices.push_back(wVerticeIndex + nSegments + 1); indices.push_back(wVerticeIndex + 1); indices.push_back(wVerticeIndex); wVerticeIndex++; } } // end for seg } // end for ring m_mesh->m_vertexCount = (uint)vertices.size(); m_mesh->m_clientSideVertices = vertices; m_mesh->m_indexCount = (uint)indices.size(); m_mesh->m_clientSideIndices = indices; m_mesh->m_material = GetMaterialManager()->GetCopyOfDefaultMaterial(); m_mesh->CalculateAABB(); m_mesh->ConstructFaces(); } void Sphere::Serialize(XmlDocument* doc, XmlNode* parent) const { Entity::Serialize(doc, parent); m_params.Serialize(doc, parent->last_node()); } void Sphere::DeSerialize(XmlDocument* doc, XmlNode* parent) { Entity::DeSerialize(doc, parent); m_params.DeSerialize(doc, parent); Generate(); } Entity* Sphere::GetInstance(Entity* copyTo) const { Drawable::GetInstance(copyTo); Sphere* instance = static_cast<Sphere*> (copyTo); instance->m_params = m_params; return instance; } Cone::Cone(bool genDef) { if (genDef) { Generate(); } } Cone::Cone(const Params& params) : m_params(params) { Generate(); } // https://github.com/OGRECave/ogre-procedural/blob/master/library/src/ProceduralConeGenerator.cpp void Cone::Generate() { VertexArray vertices; std::vector<uint> indices; float height = m_params[0].GetVar<float>(); float radius = m_params[1].GetVar<float>(); int nSegBase = m_params[2].GetVar<int>(); int nSegHeight = m_params[3].GetVar<int>(); float deltaAngle = (glm::two_pi<float>() / nSegBase); float deltaHeight = height / nSegHeight; int offset = 0; Vec3 refNormal = glm::normalize(Vec3(radius, height, 0.0f)); Quaternion q; for (int i = 0; i <= nSegHeight; i++) { float r0 = radius * (1 - i / (float)nSegHeight); for (int j = 0; j <= nSegBase; j++) { float x0 = r0 * glm::cos(j * deltaAngle); float z0 = r0 * glm::sin(j * deltaAngle); q = glm::angleAxis(glm::radians(-deltaAngle * j), Y_AXIS); Vertex v { Vec3(x0, i * deltaHeight, z0), q * refNormal, Vec2(j / (float)nSegBase, i / (float)nSegHeight), Vec3() // btan missing. }; vertices.push_back(v); if (i != nSegHeight && j != nSegBase) { indices.push_back(offset + nSegBase + 2); indices.push_back(offset); indices.push_back(offset + nSegBase + 1); indices.push_back(offset + nSegBase + +2); // Is this valid "nSegBase + +2" ?? indices.push_back(offset + 1); indices.push_back(offset); } offset++; } } //low cap int centerIndex = offset; Vertex v { Vec3(), -Y_AXIS, Y_AXIS, Vec3() // btan missing. }; vertices.push_back(v); offset++; for (int j = 0; j <= nSegBase; j++) { float x0 = radius * glm::cos(j * deltaAngle); float z0 = radius * glm::sin(j * deltaAngle); Vertex v { Vec3(x0, 0.0f, z0), -Y_AXIS, Vec2(j / (float)nSegBase, 0.0f), Vec3() // btan missing. }; vertices.push_back(v); if (j != nSegBase) { indices.push_back(centerIndex); indices.push_back(offset); indices.push_back(offset + 1); } offset++; } m_mesh->m_vertexCount = (uint)vertices.size(); m_mesh->m_clientSideVertices = vertices; m_mesh->m_indexCount = (uint)indices.size(); m_mesh->m_clientSideIndices = indices; m_mesh->m_material = GetMaterialManager()->GetCopyOfDefaultMaterial(); m_mesh->CalculateAABB(); m_mesh->ConstructFaces(); } Cone* Cone::GetCopy() const { Cone* cpy = new Cone(false); GetCopy(cpy); return cpy; } Entity* Cone::GetCopy(Entity* copyTo) const { Drawable::GetCopy(copyTo); Cone* ntt = static_cast<Cone*> (copyTo); ntt->m_params = m_params; return ntt; } EntityType Cone::GetType() const { return EntityType::Entity_Cone; } void Cone::Serialize(XmlDocument* doc, XmlNode* parent) const { Entity::Serialize(doc, parent); m_params.Serialize(doc, parent->last_node()); } void Cone::DeSerialize(XmlDocument* doc, XmlNode* parent) { Entity::DeSerialize(doc, parent); m_params.DeSerialize(doc, parent); Generate(); } Entity* Cone::GetInstance(Entity* copyTo) const { Drawable::GetInstance(copyTo); Cone* instance = static_cast<Cone*> (copyTo); instance->m_params = m_params; return instance; } Arrow2d::Arrow2d(bool genDef) { m_label = AxisLabel::X; if (genDef) { Generate(); } } Arrow2d::Arrow2d(AxisLabel label) : m_label(label) { Generate(); } Entity* Arrow2d::GetCopy(Entity* copyTo) const { Drawable::GetCopy(copyTo); Arrow2d* ntt = static_cast<Arrow2d*> (copyTo); ntt->m_label = m_label; return ntt; } Entity* Arrow2d::GetInstance(Entity* copyTo) const { Drawable::GetInstance(copyTo); Arrow2d* instance = static_cast<Arrow2d*> (copyTo); instance->m_label = m_label; return instance; } EntityType Arrow2d::GetType() const { return EntityType::Etity_Arrow; } void Arrow2d::Generate() { VertexArray vertices; vertices.resize(8); // Line vertices[0].pos = Vec3(0.0f, 0.0f, 0.0f); vertices[1].pos = Vec3(0.8f, 0.0f, 0.0f); // Triangle vertices[2].pos = Vec3(0.8f, -0.2f, 0.0f); vertices[3].pos = Vec3(0.8f, 0.2f, 0.0f); vertices[4].pos = Vec3(0.8f, 0.2f, 0.0f); vertices[5].pos = Vec3(1.0f, 0.0f, 0.0f); vertices[6].pos = Vec3(1.0f, 0.0f, 0.0f); vertices[7].pos = Vec3(0.8f, -0.2f, 0.0f); MaterialPtr newMaterial = GetMaterialManager()->GetCopyOfUnlitColorMaterial(); newMaterial->GetRenderState()->drawType = DrawType::Line; newMaterial->m_color = Vec3(0.89f, 0.239f, 0.341f); Quaternion rotation; if (m_label == AxisLabel::Y) { newMaterial->m_color = Vec3(0.537f, 0.831f, 0.07f); rotation = glm::angleAxis(glm::half_pi<float>(), Z_AXIS); } if (m_label == AxisLabel::Z) { newMaterial->m_color = Vec3(0.196f, 0.541f, 0.905f); rotation = glm::angleAxis(-glm::half_pi<float>(), Y_AXIS); } for (size_t i = 0; i < vertices.size(); i++) { vertices[i].pos = rotation * vertices[i].pos; } m_mesh->m_vertexCount = (uint)vertices.size(); m_mesh->m_clientSideVertices = vertices; m_mesh->m_material = newMaterial; m_mesh->CalculateAABB(); m_mesh->ConstructFaces(); } LineBatch::LineBatch(const Vec3Array& linePnts, const Vec3& color, DrawType t, float lineWidth) { MaterialPtr newMaterial = GetMaterialManager()->GetCopyOfUnlitColorMaterial(); newMaterial->GetRenderState()->drawType = t; m_mesh->m_material = newMaterial; Generate(linePnts, color, t, lineWidth); } LineBatch::LineBatch() { } Entity* LineBatch::GetCopy(Entity* copyTo) const { return Drawable::GetCopy(copyTo); } EntityType LineBatch::GetType() const { return EntityType::Entity_LineBatch; } void LineBatch::Generate(const Vec3Array& linePnts, const Vec3& color, DrawType t, float lineWidth) { VertexArray vertices; vertices.resize(linePnts.size()); m_mesh->UnInit(); for (size_t i = 0; i < linePnts.size(); i++) { vertices[i].pos = linePnts[i]; } m_mesh->m_vertexCount = (uint)vertices.size(); m_mesh->m_clientSideVertices = vertices; m_mesh->m_material->m_color = color; m_mesh->m_material->GetRenderState()->lineWidth = lineWidth; m_mesh->CalculateAABB(); } }
27.422611
136
0.603337
findux
1e38d528542dffeed2c014b79aa8aaca1f307e44
197
cpp
C++
Baekjoon/Problem_1005/Problem_1005.cpp
ShinYoung-hwan/Problem_Solving
3f181b0b978ed22f1bbca102d41d45679cfb288f
[ "MIT" ]
null
null
null
Baekjoon/Problem_1005/Problem_1005.cpp
ShinYoung-hwan/Problem_Solving
3f181b0b978ed22f1bbca102d41d45679cfb288f
[ "MIT" ]
null
null
null
Baekjoon/Problem_1005/Problem_1005.cpp
ShinYoung-hwan/Problem_Solving
3f181b0b978ed22f1bbca102d41d45679cfb288f
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(void) { int Testcase; cin >> Testcase; for(int i = 0; i < Testcase; i++) { int N, K; cin >> N >> K; } return 0; }
11.588235
37
0.507614
ShinYoung-hwan
1e3a7b79774b0beab098cf02618d62aa5e70d5dd
840
cc
C++
test/core/test2.7-2/test.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
63
2018-06-21T14:11:59.000Z
2022-03-30T11:24:36.000Z
test/core/test2.7-2/test.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
5
2018-09-22T14:01:53.000Z
2021-12-27T16:11:05.000Z
test/core/test2.7-2/test.cc
XpressAI/frovedis
bda0f2c688fb832671c5b542dd8df1c9657642ff
[ "BSD-2-Clause" ]
12
2018-08-23T15:59:44.000Z
2022-02-20T06:47:22.000Z
#include <frovedis.hpp> #define BOOST_TEST_MODULE FrovedisTest #include <boost/test/unit_test.hpp> using namespace frovedis; using namespace std; std::vector<int> two_times(const std::vector<int>& v) { std::vector<int> r(v.size()); for(size_t i = 0; i < v.size(); i++) r[i] = v[i] * 2; return r; } BOOST_AUTO_TEST_CASE( frovedis_test ) { int argc = 1; char** argv = NULL; use_frovedis use(argc, argv); // filling sample input/output vectors std::vector<int> v, ref; for(size_t i = 1; i <= 8; i++) v.push_back(i); for(size_t i = 1; i <= 8; i++) ref.push_back(i*2); auto d1 = frovedis::make_dvector_scatter(v); auto d2 = d1.as_node_local().map(two_times).moveto_dvector<int>(); auto d3 = d1.map_partitions(two_times); auto r1 = d2.gather(); auto r2 = d3.gather(); BOOST_CHECK(r1 == ref && r2 == ref); }
24.705882
68
0.652381
XpressAI
1e3b7fbf559f330b42a3455f17d84e8a9259c950
11,605
hpp
C++
include/exces/collection.hpp
matus-chochlik/exces
50b57ce4c9f6c41ab2eacfae054529cbbe6164c0
[ "BSL-1.0" ]
1
2018-03-26T20:51:36.000Z
2018-03-26T20:51:36.000Z
include/exces/collection.hpp
matus-chochlik/exces
50b57ce4c9f6c41ab2eacfae054529cbbe6164c0
[ "BSL-1.0" ]
null
null
null
include/exces/collection.hpp
matus-chochlik/exces
50b57ce4c9f6c41ab2eacfae054529cbbe6164c0
[ "BSL-1.0" ]
null
null
null
/** * @file exces/collection.hpp * @brief Entity collections and classifications * * Copyright 2012-2014 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef EXCES_COLLECTION_1304231127_HPP #define EXCES_COLLECTION_1304231127_HPP #include <exces/group.hpp> #include <exces/entity_range.hpp> #include <exces/entity_key_set.hpp> #include <exces/entity_filters.hpp> #include <exces/iter_info.hpp> #include <map> #include <functional> namespace exces { template <typename Group> class manager; /// Implementation of basic entity collection traversal functions template <typename Group> class collect_entity_range { private: typedef typename manager<Group>::entity_key entity_key; typedef typename std::vector<entity_key>::const_iterator _iter; _iter _i; const _iter _e; public: collect_entity_range(_iter i, _iter e) : _i(i) , _e(e) { } /// Indicates that the range is empty (the traversal is done) bool empty(void) const { return _i == _e; } /// Returns the current front element of the range entity_key front(void) const { assert(!empty()); return *_i; } /// Moves the front of the range one element ahead void next(void) { assert(!empty()); ++_i; } }; /// Base interface for entity collections and classifications /** * @note do not use directly, use the derived classes instead. */ template <typename Group> class collection_intf { private: friend class manager<Group>; manager<Group>* _pmanager; typedef typename manager<Group>::entity_key entity_key; typedef std::size_t update_key; update_key _cur_uk; virtual void insert(entity_key key) = 0; virtual void remove(entity_key key) = 0; virtual update_key begin_update(entity_key key) = 0; virtual void finish_update(entity_key ekey, update_key) = 0; protected: update_key _next_update_key(void); manager<Group>& _manager(void) const; void _register(void); collection_intf(manager<Group>& parent_manager) : _pmanager(&parent_manager) , _cur_uk(0) { } public: collection_intf(const collection_intf&) = delete; collection_intf(collection_intf&& tmp); virtual ~collection_intf(void); }; /// Entity collection /** Entity collection stores references to a subset of entities managed by * a manager, satisfying some predicate. For example all entities having * a specified set of components, etc. * * @see classification */ template <typename Group = default_group> class collection : public collection_intf<Group> { private: typedef collection_intf<Group> _base; std::function< bool ( manager<Group>&, typename manager<Group>::entity_key ) > _filter_entity; typedef entity_key_set<Group> _entity_key_set; _entity_key_set _entities; typedef typename manager<Group>::entity_key entity_key; typedef std::size_t update_key; void insert(entity_key key); void remove(entity_key key); update_key begin_update(entity_key key); void finish_update(entity_key ekey, update_key); template <typename Component, typename MemFnRV> struct _call_comp_mem_fn { MemFnRV (Component::*_mem_fn_ptr)(void) const; _call_comp_mem_fn( MemFnRV (Component::*mem_fn_ptr)(void) const ): _mem_fn_ptr(mem_fn_ptr) { } bool operator ()( manager<Group>& mgr, typename manager<Group>::entity_key ekey ) { assert(mgr.template has<Component>(ekey)); return bool( (mgr.template rw<Component>(ekey) .*_mem_fn_ptr)() ); } }; public: static void _instantiate(void); /// Constructs a new collection /** The @p parent_manager must not be destroyed during the whole * lifetime of the newly constructed collection. */ collection( manager<Group>& parent_manager, const std::function< bool (manager<Group>&, entity_key) >& entity_filter ): _base(parent_manager) , _filter_entity(entity_filter) { this->_register(); } template <typename Component, typename MemFnRV> collection( manager<Group>& parent_manager, MemFnRV (Component::*mem_fn_ptr)(void) const ): _base(parent_manager) , _filter_entity(_call_comp_mem_fn<Component, MemFnRV>(mem_fn_ptr)) { this->_register(); } /// Collections are non-copyable collection(const collection&) = delete; /// Collections are movable collection(collection&& tmp) : _base(static_cast<_base&&>(tmp)) , _filter_entity(std::move(tmp._filter_entity)) , _entities(std::move(tmp._entities)) { } /// Execute a @p function on each entity in the collection. void for_each( const std::function<bool( const iter_info&, manager<Group>&, typename manager<Group>::entity_key )>& function ) const; }; /// A template for entity classifications /** A classification stores references to entities managed by a manager * and divides them into disjunct subsets by their 'class' which is a value * assigned to the entities by a 'classifier' function. The second function * called 'class filter' determines which classes are stored and which are not. * There is also a third function called the entity filter that determines * if an entity should be even considered for classification. * If the entity filter is present and returns true then the entity is * classified. Then if the class filter returns true for a class (value) * then entities being of that class are stored in the classification, * entities having classes for which the class filter returns false are * not stored by the classification. * * A classification allows to enumerate entities belonging to a particular * class. * * @see collection * * @tparam Class the type that is used to classify entities. * @tparam Group the component group. */ template <typename Class, typename Group = default_group> class classification : public collection_intf<Group> { private: typedef collection_intf<Group> _base; std::function< bool ( manager<Group>&, typename manager<Group>::entity_key ) > _filter_entity; std::function< Class ( manager<Group>&, typename manager<Group>::entity_key ) > _classify; std::function<bool (Class)> _filter_class; typedef entity_key_set<Group> _entity_key_set; typedef std::map<Class, _entity_key_set> _class_map; _class_map _classes; typedef typename manager<Group>::entity_key entity_key; typedef std::size_t update_key; typedef std::map<update_key, typename _class_map::iterator> _update_map; _update_map _updates; void insert(entity_key key, Class entity_class); void insert(entity_key key); void remove(entity_key key, Class entity_class); void remove(entity_key key); update_key begin_update(entity_key key); void finish_update(entity_key ekey, update_key ukey); template <typename Component> static bool _has_component( manager<Group>& mgr, typename manager<Group>::entity_key ekey ) { return mgr.template has<Component>(ekey); } template <typename Component, typename MemVarType> struct _get_comp_mem_var { MemVarType Component::* _mem_var_ptr; _get_comp_mem_var( MemVarType Component::* mem_var_ptr ): _mem_var_ptr(mem_var_ptr) { } Class operator ()( manager<Group>& mgr, typename manager<Group>::entity_key ekey ) { assert(mgr.template has<Component>(ekey)); return Class( mgr.template rw<Component>(ekey) .*_mem_var_ptr ); } }; template <typename Component, typename MemFnRV> struct _call_comp_mem_fn { MemFnRV (Component::*_mem_fn_ptr)(void) const; _call_comp_mem_fn( MemFnRV (Component::*mem_fn_ptr)(void) const ): _mem_fn_ptr(mem_fn_ptr) { } Class operator ()( manager<Group>& mgr, typename manager<Group>::entity_key ekey ) { assert(mgr.template has<Component>(ekey)); return Class( (mgr.template rw<Component>(ekey) .*_mem_fn_ptr)() ); } }; public: static void _instantiate(void); /// Constructs a new classification /** The @p parent_manager must not be destroyed during the whole * lifetime of the newly constructed classification. The classifier * is used to divide entities of the manager into classes there is * no class filter so all classes are stored. */ classification( manager<Group>& parent_manager, const std::function< bool (manager<Group>&, entity_key) >& entity_filter, const std::function< Class (manager<Group>&, entity_key) >& classifier ): _base(parent_manager) , _filter_entity(entity_filter) , _classify(classifier) , _filter_class() { this->_register(); } /// Constructs a new classification /** The @p parent_manager must not be destroyed during the whole * lifetime of the newly constructed classification. The classifier * is used to divide entities of the manager into classes and filter * determines the classes that are stored by the classification. */ classification( manager<Group>& parent_manager, const std::function< bool (manager<Group>&, entity_key) >& entity_filter, const std::function< Class (manager<Group>&, entity_key) >& classifier, const std::function<bool (Class)>& class_filter ): _base(parent_manager) , _filter_entity(entity_filter) , _classify(classifier) , _filter_class(class_filter) { this->_register(); } template <typename Component, typename MemVarType> classification( manager<Group>& parent_manager, MemVarType Component::* mem_var_ptr ): _base(parent_manager) , _filter_entity(&_has_component<Component>) , _classify(_get_comp_mem_var<Component, MemVarType>(mem_var_ptr)) , _filter_class() { this->_register(); } template <typename Component, typename MemVarType> classification( manager<Group>& parent_manager, MemVarType Component::* mem_var_ptr, const std::function<bool (Class)>& class_filter ): _base(parent_manager) , _filter_entity(&_has_component<Component>) , _classify(_get_comp_mem_var<Component, MemVarType>(mem_var_ptr)) , _filter_class(class_filter) { this->_register(); } template <typename Component, typename MemFnRV> classification( manager<Group>& parent_manager, MemFnRV (Component::*mem_fn_ptr)(void) const ): _base(parent_manager) , _filter_entity(&_has_component<Component>) , _classify(_call_comp_mem_fn<Component, MemFnRV>(mem_fn_ptr)) , _filter_class() { this->_register(); } template <typename Component, typename MemFnRV> classification( manager<Group>& parent_manager, MemFnRV (Component::*mem_fn_ptr)(void) const, const std::function<bool (Class)>& class_filter ): _base(parent_manager) , _filter_entity(&_has_component<Component>) , _classify(_call_comp_mem_fn<Component, MemFnRV>(mem_fn_ptr)) , _filter_class(class_filter) { this->_register(); } /// Classifications are not copyable classification(const classification&) = delete; /// Classifications are movable classification(classification&& tmp) : _base(static_cast<_base&&>(tmp)) , _filter_entity(std::move(tmp._filter_entity)) , _classify(std::move(tmp._classify)) , _filter_class(std::move(tmp._filter_class)) , _classes(std::move(tmp._classes)) , _updates(std::move(tmp._updates)) { } /// Returns the number of different classes std::size_t class_count(void) const; /// Returns the number of entities of the specified class std::size_t cardinality(const Class& entity_class) const; /// Execute a @p function on each entity in the specified entity_class. void for_each( const Class& entity_class, const std::function<bool( const iter_info&, manager<Group>&, typename manager<Group>::entity_key )>& function ) const; }; } // namespace exces #endif //include guard
25.505495
81
0.734856
matus-chochlik
1e3d47053a7917cf34ba4c07e4dd42cf4b22bf39
118
cpp
C++
gxx/print/src/impl/print_cout.cpp
Mirmik/gxx
986e4de50a5652ce7d82c01fcf4ff87daa18904a
[ "MIT" ]
null
null
null
gxx/print/src/impl/print_cout.cpp
Mirmik/gxx
986e4de50a5652ce7d82c01fcf4ff87daa18904a
[ "MIT" ]
null
null
null
gxx/print/src/impl/print_cout.cpp
Mirmik/gxx
986e4de50a5652ce7d82c01fcf4ff87daa18904a
[ "MIT" ]
null
null
null
#include <gxx/print.h> #include <gxx/io/std.h> namespace gxx { gxx::io::ostream* standart_output = &gxx::io::cout; }
19.666667
52
0.677966
Mirmik
1e43bf5c02a3f4c4fdec95b8cf4eefe0c92bb8cb
11,919
cc
C++
util/buildWeissPalette.cc
MartinezTorres/Edelweiss
ef7eeaa1b8262e85f708c672fbb3310a6912be0c
[ "MIT" ]
2
2021-01-20T13:12:31.000Z
2021-02-24T17:00:36.000Z
util/buildWeissPalette.cc
MartinezTorres/sdcc_msx_interlacedScrollMSX1
69b5463c67c822e6a272acbfdadb6bee81cdbdf7
[ "MIT" ]
1
2021-04-07T20:19:37.000Z
2021-04-07T20:19:37.000Z
util/buildWeissPalette.cc
MartinezTorres/sdcc_msx_interlacedScrollMSX1
69b5463c67c822e6a272acbfdadb6bee81cdbdf7
[ "MIT" ]
1
2021-02-24T17:00:43.000Z
2021-02-24T17:00:43.000Z
//////////////////////////////////////////////////////////////////////// // Build MSX1 palette // // Manuel Martinez (salutte@gmail.com) // // FLAGS: -std=gnu++14 -g `pkg-config opencv --cflags --libs` -Ofast -lpthread -fopenmp -lgomp -Wno-format-nonliteral #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <iostream> #include <fstream> #include <vector> #include <deque> #include <map> #include <thread> #include <chrono> #include <functional> using namespace std::chrono_literals; struct Colorspace { std::array<float, 256> TsRGB2lin; std::array<uint8_t,4096> Tlin2sRGB; Colorspace() { for (size_t i=0; i<256; i++) { double srgb = (i+0.5)/255.999; double lin = 0; if (srgb <= 0.0405) { lin = srgb/12.92; } else { lin = std::pow((srgb+0.055)/(1.055),2.4); } TsRGB2lin[i]=lin; } for (size_t i=0; i<4096; i++) { double lin = (i+0.5)/4095.999; double srgb = 0; if (lin <= 0.0031308) { srgb = lin*12.92; } else { srgb = 1.055*std::pow(lin,1/2.4)-0.055; } Tlin2sRGB[i]=srgb*255.999999999; } } cv::Vec3f sRGB2Lin(cv::Vec3b a) const { return { TsRGB2lin[a[0]], TsRGB2lin[a[1]], TsRGB2lin[a[2]] }; } cv::Vec3b lin2sRGB(cv::Vec3f a) const { auto cap = [](float f){ int i = std::round(f*4095.999+0.5); return std::min(std::max(i,0),4095); }; return { Tlin2sRGB[cap(a[0])], Tlin2sRGB[cap(a[1])], Tlin2sRGB[cap(a[2])], }; } cv::Mat3f sRGB2Lin(cv::Mat3b a) const { cv::Mat3f ret(a.rows, a.cols); for (int i=0; i<a.rows; i++) for (int j=0; j<a.cols; j++) ret(i,j) = sRGB2Lin(a(i,j)); return ret; } cv::Mat3b lin2sRGB(cv::Mat3f a) const { cv::Mat3b ret(a.rows, a.cols); for (int i=0; i<a.rows; i++) for (int j=0; j<a.cols; j++) ret(i,j) = lin2sRGB(a(i,j)); return ret; } static float Y(cv::Vec3b a) { return a[0]*0.2126 + a[1]*0.7152 + a[2]*0.0722; } static float perceptualCompare(cv::Vec3b rgb1, cv::Vec3b rgb2) { const int YR = 19595, YG = 38470, YB = 7471, CB_R = -11059, CB_G = -21709, CB_B = 32767, CR_R = 32767, CR_G = -27439, CR_B = -5329; cv::Vec3b ycc1, ycc2; { const int r = rgb1[0], g = rgb1[1], b = rgb1[2]; ycc1[0] = (r * YR + g * YG + b * YB + 32767) >> 16; ycc1[1] = 128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16); ycc1[2] = 128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16); } { const int r = rgb2[0], g = rgb2[1], b = rgb2[2]; ycc2[0] = (r * YR + g * YG + b * YB + 32767) >> 16; ycc2[1] = 128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16); ycc2[2] = 128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16); } float Ydiff = 4.f * std::pow(std::abs(ycc1[0]-ycc2[0]), 1); float C1diff = 1.f * std::pow(std::abs(ycc1[1]-ycc2[1]), 1); float C2diff = 1.f * std::pow(std::abs(ycc1[2]-ycc2[2]), 1); return Ydiff + C1diff + C2diff; } }; static Colorspace CS; struct Tpalette { std::map<std::string, std::vector<cv::Vec3b>> allColors = { // Note, those are RGB { "HW-MSX", {//https://paulwratt.github.io/programmers-palettes/HW-MSX/HW-MSX-palettes.html { 0, 0, 0}, // transparent { 1, 1, 1}, // black { 62, 184, 73}, // medium green { 116, 208, 125}, // light green { 89, 85, 224}, // dark blue { 128, 118, 241}, // light blue { 185, 94, 81}, // dark red { 101, 219, 239}, // cyan { 219, 101, 89}, // medium red { 255, 137, 125}, // light red { 204, 195, 94}, // dark yellow { 222, 208, 135}, // light yellow { 58, 162, 65}, // dark green { 183, 102, 181}, // magenta { 204, 204, 204}, // gray { 255, 255, 255} // white } }, { "Toshiba Palette", { { 0, 0, 0 }, // transparent, { 0, 0, 0 }, // black, { 102, 204, 102 }, // medium green, { 136, 238, 136 }, // light green, { 68, 68, 221 }, // dark blue, { 119, 119, 255 }, // light blue, { 187, 85, 85 }, // dark red, { 119, 221, 221 }, // cyan, { 221, 102, 102 }, // medium red, { 255, 119, 119 }, // light red, { 204, 204, 85 }, // dark yellow, { 238, 238, 136 }, // light yellow, { 85, 170, 85 }, // dark green, { 187, 85, 187 }, // magenta, { 204, 204, 204 }, // gray, { 238, 238, 238 } // white, } }, { "TMS9918A (NTSC)", { { 0, 0, 0 }, // transparent, { 0, 0, 0 }, // black, { 71, 183, 62 }, // medium green, { 124, 208, 108 }, // light green, { 99, 91, 169 }, // dark blue, { 127, 113, 255 }, // light blue, { 183, 98, 73 }, // dark red, { 92, 199, 239 }, // cyan, { 217, 107, 72 }, // medium red, { 253, 142, 108 }, // light red, { 195, 206, 66 }, // dark yellow, { 211, 219, 117 }, // light yellow, { 61, 160, 47 }, // dark green, { 183, 99, 199 }, // magenta, { 205, 205, 205 }, // gray, { 255, 255, 255 } // white, } }, { "TMS9929A (PAL)", { { 0, 0, 0 }, // transparent, { 0, 0, 0 }, // black, { 81, 202, 92 }, // medium green, { 133, 223, 141 }, // light green, { 108, 103, 240 }, // dark blue, { 146, 137, 255 }, // light blue, { 213, 100, 113 }, // dark red, { 102, 219, 239 }, // cyan, { 231, 118, 131 }, // medium red, { 255, 152, 164 }, // light red, { 215, 207, 97 }, // dark yellow, { 230, 222, 112 }, // light yellow, { 74, 177, 81 }, // dark green, { 200, 121, 200 }, // magenta, { 205, 205, 205 }, // gray, { 255, 255, 255 } // white, } }, { "TMS9929A (PAL, alternate GAMMA)", { { 0, 0, 0 }, // transparent, { 0, 0, 0 }, // black, { 72, 178, 81 }, // medium green, { 117, 196, 125 }, // light green, { 95, 91, 212 }, // dark blue, { 129, 121, 224 }, // light blue, { 187, 89, 99 }, // dark red, { 90, 193, 210 }, // cyan, { 203, 104, 115 }, // medium red, { 224, 134, 145 }, // light red, { 189, 182, 86 }, // dark yellow, { 203, 196, 99 }, // light yellow, { 66, 156, 72 }, // dark green, { 176, 108, 175 }, // magenta, { 180, 180, 180 }, // gray, { 255, 255, 255 } // white, } } }; typedef std::pair<std::array<cv::Vec3b, 4>, std::array<size_t, 2>> Palette4; std::vector<Palette4> allPalettes; cv::Mat3b colorMatrix; Tpalette(std::string name = "TMS9929A (PAL)") { auto colors = allColors.find(name)->second; colorMatrix = cv::Mat3b(14,14); for (size_t j=1; j<colors.size(); j++) for (size_t k=1; k<colors.size(); k++) colorMatrix((j>8?j-2:j-1),(k>8?k-2:k-1)) = CS.lin2sRGB((CS.sRGB2Lin(colors[j]) + CS.sRGB2Lin(colors[k]))*0.5); std::vector<Palette4> tentativePalettes; //for (size_t i=1; i<colors.size(); i++) { // I is the background color, which is common to both tiles. size_t i = 1; { //On a better though, let's fix the background to black so we can perfilate everything. for (size_t j=1; j<colors.size(); j++) { // J is the first foreground color if (j==i) continue; if (j==8) continue; for (size_t k=j; k<colors.size(); k++) { // K is the second foreground color if (k==i) continue; if (k==8) continue; Palette4 p4 = { { colors[i], CS.lin2sRGB((CS.sRGB2Lin(colors[i]) + CS.sRGB2Lin(colors[j]))*0.5), CS.lin2sRGB((CS.sRGB2Lin(colors[i]) + CS.sRGB2Lin(colors[k]))*0.5), CS.lin2sRGB((CS.sRGB2Lin(colors[j]) + CS.sRGB2Lin(colors[k]))*0.5), }, {j, k} }; if (j==k) { // allPalettes.push_back(p4); } else { tentativePalettes.push_back(p4); } } } } std::random_shuffle(tentativePalettes.begin(), tentativePalettes.end()); for (auto &tp : tentativePalettes) { auto &t = tp.first; float minD = 1e10; for (auto &pp : allPalettes) { auto &p = pp.first; float d = 0.f; auto perceptualCompare = Colorspace::perceptualCompare; d += std::min(std::min(std::min(perceptualCompare(t[0],p[0]), perceptualCompare(t[0],p[1])), perceptualCompare(t[0],p[2])), perceptualCompare(t[0],p[3])); d += std::min(std::min(std::min(perceptualCompare(t[1],p[0]), perceptualCompare(t[1],p[1])), perceptualCompare(t[1],p[2])), perceptualCompare(t[1],p[3])); d += std::min(std::min(std::min(perceptualCompare(t[2],p[0]), perceptualCompare(t[2],p[1])), perceptualCompare(t[2],p[2])), perceptualCompare(t[2],p[3])); d += std::min(std::min(std::min(perceptualCompare(t[3],p[0]), perceptualCompare(t[3],p[1])), perceptualCompare(t[3],p[2])), perceptualCompare(t[3],p[3])); minD = std::min(minD, d); } //std::cout << minD << std::endl; if (minD>75) allPalettes.push_back(tp); } std::sort(allPalettes.begin(), allPalettes.end(), [](const Palette4 &a, const Palette4 &b){ if (a.second[0]!=b.second[0]) return a.second[0]<b.second[0]; return a.second[1]<b.second[1]; }); } }; int main() { Tpalette P = Tpalette("TMS9918A (NTSC)"); // Tpalette P = Tpalette("TMS9929A (PAL, alternate GAMMA)"); // Tpalette P = Tpalette("TMS9929A (PAL)"); std::cout << P.allPalettes.size() << std::endl; cv::Mat3b paletteImage( P.allPalettes.size() * 16, 4*32 ); for (size_t i=0; i<P.allPalettes.size(); i++) { paletteImage(cv::Rect(0*32,i*16,32,16)) = P.allPalettes[i].first[0]; paletteImage(cv::Rect(1*32,i*16,32,16)) = P.allPalettes[i].first[1]; paletteImage(cv::Rect(2*32,i*16,32,16)) = P.allPalettes[i].first[2]; paletteImage(cv::Rect(3*32,i*16,32,16)) = P.allPalettes[i].first[3]; std::cout << " { " << P.allPalettes[i].second[0] << ", " << P.allPalettes[i].second[1] << " }, "; } std::cout << std::endl; for (auto &p : paletteImage) std::swap(p[0],p[2]); cv::imshow("palette", paletteImage); cv::Mat3b colorMatrix = P.colorMatrix; { std::ofstream off("msx_extended.gpl"); off << "GIMP Palette" << std::endl; off << "Name: MSX extended" << std::endl << std::endl; for (auto &c : colorMatrix) off << int(c[0]) << " " << int(c[1]) << " " << int(c[2]) << " noNamed" << std::endl; } cv::resize(colorMatrix, colorMatrix, cv::Size(),50,50, cv::INTER_NEAREST); for (auto &p : colorMatrix) std::swap(p[0],p[2]); cv::imshow("colorMatrix", colorMatrix); cv::waitKey(0); }
35.055882
170
0.461784
MartinezTorres
1e464bfa0b9f58f7e86ca7ab23d3cc7ca71f31b9
4,315
hpp
C++
src/arrangement/arrangement.hpp
cbosoft/rlp
21adacbb514f3ff68a77577c2d097fcaaaeffe25
[ "MIT" ]
1
2020-03-28T15:53:08.000Z
2020-03-28T15:53:08.000Z
src/arrangement/arrangement.hpp
cbosoft/rlp
21adacbb514f3ff68a77577c2d097fcaaaeffe25
[ "MIT" ]
null
null
null
src/arrangement/arrangement.hpp
cbosoft/rlp
21adacbb514f3ff68a77577c2d097fcaaaeffe25
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include "../util/vec.hpp" #include "../particle/particle.hpp" #include "../util/exception.hpp" class ParticleArrangement { protected: bool get_two_particle_frictional_interaction(const Particle *settling, const Particle *settled, double &time, Vec3 &final_position) const { Vec3 dV = Vec3({0, 0, 1}); Vec3 dP = settled->get_position() - settling->get_position(); double A = dV.dot(dV); double B = 2.0*dV.dot(dP); double C = dP.dot(dP) - settled->get_radius() - settling->get_radius(); double discriminant = (B*B) - (4.0*A*C); if (discriminant > 0.0) { double discriminant_root = std::pow(discriminant, 0.5); double bigsol = (-B + discriminant_root) / (2.0 * A); double lilsol = (-B - discriminant_root) / (2.0 * A); if ((bigsol > 1e-7) or (lilsol > 1e-7)) { // if results are not both approximately zero... if (lilsol < 0.0) { if (bigsol > 0.0) { time = bigsol; } } else { if (bigsol < 0.0) { time = lilsol; } else { time = lilsol; if (bigsol < lilsol) { time = bigsol; } } } } final_position = settling->get_position() + (Vec3({0, 0, -1})*time); return true; } return false; } public: ParticleArrangement() {} virtual ~ParticleArrangement() {}; virtual bool check_interacts_with(const Particle *p) =0; virtual Vec3 get_interaction_result(const Particle *p) =0; virtual Vec3 get_frictional_interaction_result(const Particle *p) =0; virtual double get_sort_distance(const Particle *p) =0; virtual double get_z_position() =0; virtual double get_max_distance(const Particle *p) =0; virtual double get_min_distance(const Particle *p) =0; virtual bool covers(ParticleArrangement *arr) =0; virtual std::vector<Vec3> get_extents() =0; virtual std::string repr() =0; virtual Vec3 get_centre() const =0; virtual bool is_final() =0; virtual std::string get_type() =0; virtual int get_complexity() = 0; }; class ArrangementComparator { private: const Particle *p; public: ArrangementComparator(const Particle *p) { this->p = p; } bool operator()(ParticleArrangement *l, ParticleArrangement *r) { return l->get_sort_distance(this->p) < r->get_sort_distance(this->p); } }; class ArrangementByComplexityComparator { public: bool operator()(ParticleArrangement *l, ParticleArrangement *r) { return l->get_complexity() < r->get_complexity(); } }; class ArrangementByZPositionComparator { public: bool operator()(ParticleArrangement *l, ParticleArrangement *r) { return l->get_z_position() < r->get_z_position(); } }; class ArrangementByMaxDistanceComparator { private: const Particle *p; public: ArrangementByMaxDistanceComparator(const Particle *p) { this->p = p; } bool operator()(ParticleArrangement *l, ParticleArrangement *r) { return l->get_max_distance(this->p) < r->get_max_distance(this->p); } }; class ArrangementByMinDistanceComparator { private: const Particle *p; public: ArrangementByMinDistanceComparator(const Particle *p) { this->p = p; } bool operator()(ParticleArrangement *l, ParticleArrangement *r) { return l->get_min_distance(this->p) < r->get_min_distance(this->p); } }; class ArrangementByNameComparator { public: int arrnameindex(ParticleArrangement *p) { int pi; std::string t = p->get_type(); const char *c = t.c_str(); if (strcmp(c, "Vertex") == 0) { pi = 0; } else if (strcmp(c, "Line") == 0) { pi = 1; } else if (strcmp(c, "Triangle") == 0) { pi = 2; } else { throw TypeError(Formatter() << "Unknown arrangement type: " << t << "."); } return pi; } bool operator()(ParticleArrangement *l, ParticleArrangement *r) { int li = this->arrnameindex(l), ri = this->arrnameindex(r); return li<ri; } };
22.710526
141
0.588644
cbosoft
1e4a5478604c5d95ed891603ccbb364a68cfddfa
1,179
cpp
C++
gpu/examples/binarization.cpp
DasudaRunner/CUDA-CV
4dca7e80e403b978b3b9ef4dc4d8bc962b4380e3
[ "MIT" ]
146
2018-11-15T13:20:23.000Z
2022-03-30T01:47:37.000Z
gpu/examples/binarization.cpp
layyyang/DeltaCV
4dca7e80e403b978b3b9ef4dc4d8bc962b4380e3
[ "MIT" ]
1
2018-12-05T04:44:39.000Z
2020-07-07T01:20:22.000Z
gpu/examples/binarization.cpp
layyyang/DeltaCV
4dca7e80e403b978b3b9ef4dc4d8bc962b4380e3
[ "MIT" ]
8
2019-07-19T07:23:38.000Z
2021-09-26T15:36:27.000Z
#include <iostream> #include "opencv2/core.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include <opencv2/opencv.hpp> #include <cuda_runtime.h> #include "deltaCV/gpu/cudaImg.cuh" #include "deltaCV/gpu/cudaUtils.hpp" #include <time.h> #include <algorithm> #include "deltaCV/gpu/cu_wrapper.hpp" using namespace std; #define IMAGE_ROWS 480 #define IMAGE_COLS 640 int main() { if(!getGPUConfig()) { return 0; } cv::Mat dst; deltaCV::binarization binar(IMAGE_COLS,IMAGE_ROWS); deltaCV::colorSpace color(IMAGE_COLS,IMAGE_ROWS); cv::Mat frame = cv::imread("***.jpg"); cv::Mat gray,opencv_ostu; while(true) { color.imgToGPU(frame); color.toGRAY(); color.getMat(gray,0); //get cv::mat from gpu, taking a lot of time cv::threshold(gray, opencv_ostu, 0, 255, CV_THRESH_OTSU); binar.setGpuPtr(color.getGpuPtr_GRAY()); binar.ostu(); binar.getMat(dst); cv::imshow("frame",frame); cv::imshow("gray_cuda",dst); cv::imshow("opencv_ostu",opencv_ostu); if(cv::waitKey(3)>0) { break; } } }
19.65
74
0.620865
DasudaRunner
1e4afd6cf260b5d2cea2853dafc16527eb765c58
15,066
cpp
C++
src/replication/replication_manager.cpp
tpan496/terrier
671a55b7036af005359411ecef980e7d6d0313c9
[ "MIT" ]
null
null
null
src/replication/replication_manager.cpp
tpan496/terrier
671a55b7036af005359411ecef980e7d6d0313c9
[ "MIT" ]
null
null
null
src/replication/replication_manager.cpp
tpan496/terrier
671a55b7036af005359411ecef980e7d6d0313c9
[ "MIT" ]
null
null
null
#include "replication/replication_manager.h" #include <chrono> // NOLINT #include <fstream> #include <optional> #include "common/error/exception.h" #include "common/json.h" #include "loggers/replication_logger.h" #include "network/network_io_utils.h" #include "storage/recovery/replication_log_provider.h" #include "storage/write_ahead_log/log_io.h" namespace { /** @return True if left > right. False otherwise. */ bool CompareMessages(const noisepage::replication::ReplicateBufferMessage &left, const noisepage::replication::ReplicateBufferMessage &right) { return left.GetMessageId() > right.GetMessageId(); } } // namespace namespace noisepage::replication { Replica::Replica(common::ManagedPointer<messenger::Messenger> messenger, const std::string &replica_name, const std::string &hostname, uint16_t port) : replica_info_(messenger::ConnectionDestination::MakeTCP(replica_name, hostname, port)), connection_(messenger->MakeConnection(replica_info_)), last_heartbeat_(0) {} const char *ReplicateBufferMessage::key_buf_id = "buf_id"; const char *ReplicateBufferMessage::key_content = "content"; ReplicateBufferMessage ReplicateBufferMessage::FromMessage(const messenger::ZmqMessage &msg) { // TODO(WAN): Sanity-check the received message. common::json message = nlohmann::json::parse(msg.GetMessage()); uint64_t source_callback_id = msg.GetSourceCallbackId(); uint64_t buffer_id = message.at(key_buf_id); std::string contents = nlohmann::json::from_cbor(message[key_content].get<std::vector<uint8_t>>()); return ReplicateBufferMessage(buffer_id, std::move(contents), source_callback_id); } common::json ReplicateBufferMessage::ToJson() { common::json json; json[key_buf_id] = buffer_id_; json[key_content] = nlohmann::json::to_cbor(contents_); // TODO(WAN): Add a size and checksum to message. return json; } ReplicationManager::ReplicationManager( common::ManagedPointer<messenger::Messenger> messenger, const std::string &network_identity, uint16_t port, const std::string &replication_hosts_path, common::ManagedPointer<common::ConcurrentBlockingQueue<storage::BufferedLogWriter *>> empty_buffer_queue) : messenger_(messenger), identity_(network_identity), port_(port), empty_buffer_queue_(empty_buffer_queue) { auto listen_destination = messenger::ConnectionDestination::MakeTCP("", "127.0.0.1", port); messenger_->ListenForConnection(listen_destination, network_identity, [this](common::ManagedPointer<messenger::Messenger> messenger, const messenger::ZmqMessage &msg) { EventLoop(messenger, msg); }); BuildReplicaList(replication_hosts_path); } const char *ReplicationManager::key_message_type = "message_type"; ReplicationManager::~ReplicationManager() = default; void ReplicationManager::EnableReplication() { REPLICATION_LOG_TRACE(fmt::format("[PID={}] Replication enabled.", ::getpid())); replication_enabled_ = true; } void ReplicationManager::DisableReplication() { REPLICATION_LOG_TRACE(fmt::format("[PID={}] Replication disabled.", ::getpid())); replication_enabled_ = false; } void ReplicationManager::BuildReplicaList(const std::string &replication_hosts_path) { // The replication.config file is expected to have the following format: // IGNORED LINE (can be used for comments) // REPLICA NAME // REPLICA HOSTNAME // REPLICA PORT // Repeated and separated by newlines. std::ifstream hosts_file(replication_hosts_path); if (!hosts_file.is_open()) { throw REPLICATION_EXCEPTION(fmt::format("Unable to open file: {}", replication_hosts_path)); } std::string line; std::string replica_name; std::string replica_hostname; uint16_t replica_port; for (int ctr = 0; std::getline(hosts_file, line); ctr = (ctr + 1) % 4) { switch (ctr) { case 0: // Ignored line. break; case 1: replica_name = line; break; case 2: replica_hostname = line; break; case 3: replica_port = std::stoi(line); // All information parsed. if (identity_ == replica_name) { // For our specific identity, check that the port is right. NOISEPAGE_ASSERT(replica_port == port_, "Mismatch of identity/port combo in replica config."); } else { // Connect to the replica. ReplicaConnect(replica_name, replica_hostname, replica_port); } break; default: NOISEPAGE_ASSERT(false, "Impossible."); break; } } hosts_file.close(); } void ReplicationManager::ReplicaConnect(const std::string &replica_name, const std::string &hostname, uint16_t port) { replicas_.try_emplace(replica_name, messenger_, replica_name, hostname, port); } void ReplicationManager::ReplicaAck(const std::string &replica_name, const uint64_t callback_id, const bool block) { ReplicaSendInternal(replica_name, MessageType::ACK, common::json{}, callback_id, block); } void ReplicationManager::ReplicaSend(const std::string &replica_name, common::json msg, const bool block) { ReplicaSendInternal(replica_name, MessageType::REPLICATE_BUFFER, std::move(msg), static_cast<uint64_t>(messenger::Messenger::BuiltinCallback::NOOP), block); } void ReplicationManager::ReplicaSendInternal(const std::string &replica_name, const MessageType msg_type, common::json msg_json, const uint64_t remote_cb_id, const bool block) { if (!replication_enabled_) { REPLICATION_LOG_WARN(fmt::format("Skipping send -> {} as replication is disabled.")); return; } msg_json[key_message_type] = static_cast<uint8_t>(msg_type); auto msg = msg_json.dump(); REPLICATION_LOG_TRACE(fmt::format("Send -> {} (block {}): msg size {} preview {}", replica_name, block, msg.size(), msg.substr(0, MESSAGE_PREVIEW_LEN))); bool completed = false; try { messenger_->SendMessage( GetReplicaConnection(replica_name), msg, [this, block, &completed](common::ManagedPointer<messenger::Messenger> messenger, const messenger::ZmqMessage &msg) { if (block) { // If this isn't a blocking send, then completed will fall out of scope. completed = true; blocking_send_cvar_.notify_all(); } }, remote_cb_id); if (block) { std::unique_lock<std::mutex> lock(blocking_send_mutex_); // If the caller requested to block until the operation was completed, the thread waits. if (!blocking_send_cvar_.wait_for(lock, REPLICATION_MAX_BLOCKING_WAIT_TIME, [&completed] { return completed; })) { // TODO(WAN): Additionally, this is hackily a messenger exception so that it gets handled by the catch. throw MESSENGER_EXCEPTION("TODO(WAN): Handle a replica dying in synchronous replication."); } } } catch (const MessengerException &e) { // TODO(WAN): This assumes that the replica has died. If the replica has in fact not died, and somehow the message // just crapped out and failed to send, this will hang the replica since the replica expects messages to be // received in order and we don't try to resend the message. REPLICATION_LOG_WARN(fmt::format("[FAILED] Send -> {} (block {}): msg size {} preview {}", replica_name, block, msg.size(), msg.substr(0, MESSAGE_PREVIEW_LEN))); } } void ReplicationManager::EventLoop(common::ManagedPointer<messenger::Messenger> messenger, const messenger::ZmqMessage &msg) { common::json json = nlohmann::json::parse(msg.GetMessage()); switch (static_cast<MessageType>(json.at(key_message_type))) { case MessageType::ACK: { REPLICATION_LOG_TRACE(fmt::format("ACK: {}", json.dump())); break; } case MessageType::HEARTBEAT: { REPLICATION_LOG_TRACE(fmt::format("Heartbeat from: {}", msg.GetRoutingId())); break; } default: break; } } void ReplicationManager::ReplicaHeartbeat(const std::string &replica_name) { Replica &replica = replicas_.at(replica_name); // If the replica's heartbeat time has not been initialized yet, set the heartbeat time to the current time. { auto epoch_now = std::chrono::system_clock::now().time_since_epoch(); auto epoch_now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(epoch_now); if (0 == replica.last_heartbeat_) { replica.last_heartbeat_ = epoch_now_ms.count(); REPLICATION_LOG_TRACE( fmt::format("Replica {}: heartbeat initialized at {}.", replica_name, replica.last_heartbeat_)); } } REPLICATION_LOG_TRACE(fmt::format("Replica {}: heartbeat start.", replica_name)); try { messenger_->SendMessage( GetReplicaConnection(replica_name), "", [&](common::ManagedPointer<messenger::Messenger> messenger, const messenger::ZmqMessage &msg) { auto epoch_now = std::chrono::system_clock::now().time_since_epoch(); auto epoch_now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(epoch_now); replica.last_heartbeat_ = epoch_now_ms.count(); REPLICATION_LOG_TRACE(fmt::format("Replica {}: last heartbeat {}, heartbeat {} OK.", replica_name, replica.last_heartbeat_, epoch_now_ms.count())); }, static_cast<uint64_t>(messenger::Messenger::BuiltinCallback::NOOP)); } catch (const MessengerException &e) { REPLICATION_LOG_TRACE( fmt::format("Replica {}: last heartbeat {}, heartbeat failed.", replica_name, replica.last_heartbeat_)); } auto epoch_now = std::chrono::system_clock::now().time_since_epoch(); auto epoch_now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(epoch_now); if (epoch_now_ms.count() - replica.last_heartbeat_ >= REPLICATION_CARDIAC_ARREST_MS) { REPLICATION_LOG_WARN(fmt::format("Replica {}: last heartbeat {}, declared dead {}.", replica_name, replica.last_heartbeat_, epoch_now_ms.count())); } REPLICATION_LOG_TRACE(fmt::format("Replica {}: heartbeat end.", replica_name)); } common::ManagedPointer<messenger::ConnectionId> ReplicationManager::GetReplicaConnection( const std::string &replica_name) { return replicas_.at(replica_name).GetConnectionId(); } common::ManagedPointer<PrimaryReplicationManager> ReplicationManager::GetAsPrimary() { NOISEPAGE_ASSERT(IsPrimary(), "This should only be called from the primary node!"); return common::ManagedPointer(this).CastManagedPointerTo<PrimaryReplicationManager>(); } common::ManagedPointer<ReplicaReplicationManager> ReplicationManager::GetAsReplica() { NOISEPAGE_ASSERT(IsReplica(), "This should only be called from a replica node!"); return common::ManagedPointer(this).CastManagedPointerTo<ReplicaReplicationManager>(); } PrimaryReplicationManager::PrimaryReplicationManager( common::ManagedPointer<messenger::Messenger> messenger, const std::string &network_identity, uint16_t port, const std::string &replication_hosts_path, common::ManagedPointer<common::ConcurrentBlockingQueue<storage::BufferedLogWriter *>> empty_buffer_queue) : ReplicationManager(messenger, network_identity, port, replication_hosts_path, empty_buffer_queue) {} PrimaryReplicationManager::~PrimaryReplicationManager() = default; void PrimaryReplicationManager::ReplicateBuffer(storage::BufferedLogWriter *buffer) { if (!replication_enabled_) { REPLICATION_LOG_WARN(fmt::format("Skipping replicate buffer as replication is disabled.")); return; } NOISEPAGE_ASSERT(buffer != nullptr, "Don't try to replicate null buffers. That's pointless." "You might plausibly want to track statistics at some point, but that should not happen here."); ReplicateBufferMessage msg{next_buffer_sent_id_++, std::string(buffer->buffer_, buffer->buffer_size_)}; for (const auto &replica : replicas_) { // TODO(WAN): many things break when block is flipped from true to false. ReplicaSend(replica.first, msg.ToJson(), true); } if (buffer->MarkSerialized()) { empty_buffer_queue_->Enqueue(buffer); } } ReplicaReplicationManager::ReplicaReplicationManager( common::ManagedPointer<messenger::Messenger> messenger, const std::string &network_identity, uint16_t port, const std::string &replication_hosts_path, common::ManagedPointer<common::ConcurrentBlockingQueue<storage::BufferedLogWriter *>> empty_buffer_queue) : ReplicationManager(messenger, network_identity, port, replication_hosts_path, empty_buffer_queue), provider_(std::make_unique<storage::ReplicationLogProvider>(std::chrono::seconds(1))), received_message_queue_(CompareMessages) {} ReplicaReplicationManager::~ReplicaReplicationManager() = default; void ReplicaReplicationManager::HandleReplicatedBuffer(const messenger::ZmqMessage &msg) { auto rb_msg = ReplicateBufferMessage::FromMessage(msg); REPLICATION_LOG_TRACE(fmt::format("ReplicateBuffer from: {} {}", msg.GetRoutingId(), rb_msg.GetMessageId())); // Check if the message needs to be buffered. if (rb_msg.GetMessageId() > last_record_received_id_ + 1) { // The message should be buffered if there are gaps in between the last seen buffer. received_message_queue_.push(rb_msg); } else { // Otherwise, pull out the log record from the message and hand the record to the replication log provider. provider_->AddBufferFromMessage(rb_msg.GetSourceCallbackId(), rb_msg.GetContents()); last_record_received_id_ = rb_msg.GetMessageId(); // This may unleash the rest of the buffered messages. while (!received_message_queue_.empty()) { auto &top = received_message_queue_.top(); // Stop once you're missing a buffer. if (top.GetMessageId() > last_record_received_id_ + 1) { break; } // Otherwise, send the top buffer's contents along. received_message_queue_.pop(); NOISEPAGE_ASSERT(top.GetMessageId() == last_record_received_id_ + 1, "Duplicate buffer? Old buffer?"); provider_->AddBufferFromMessage(top.GetSourceCallbackId(), top.GetContents()); last_record_received_id_ = top.GetMessageId(); } } } void ReplicaReplicationManager::EventLoop(common::ManagedPointer<messenger::Messenger> messenger, const messenger::ZmqMessage &msg) { // TODO(WAN): This is inefficient because the JSON is parsed again. auto json = nlohmann::json::parse(msg.GetMessage()); switch (static_cast<MessageType>(json.at(ReplicationManager::key_message_type))) { case MessageType::REPLICATE_BUFFER: { HandleReplicatedBuffer(msg); break; } default: { // Delegate to the common ReplicationManager event loop. ReplicationManager::EventLoop(messenger, msg); break; } } } } // namespace noisepage::replication
44.973134
120
0.707222
tpan496
1e4e7c537a8b0dced7a39d4deea38baed0fb402e
555
cpp
C++
BOCA/CD/src/ac.cpp
Raquel29/PC1-IFB-CC
36b55e95373a5f022651545248d8cb66bac1cd3f
[ "MIT" ]
1
2020-05-24T02:22:13.000Z
2020-05-24T02:22:13.000Z
BOCA/CD/src/ac.cpp
danielsaad/PC1-IFB-CC
36b55e95373a5f022651545248d8cb66bac1cd3f
[ "MIT" ]
null
null
null
BOCA/CD/src/ac.cpp
danielsaad/PC1-IFB-CC
36b55e95373a5f022651545248d8cb66bac1cd3f
[ "MIT" ]
4
2019-05-15T10:55:57.000Z
2019-10-26T13:46:48.000Z
#include <bits/stdc++.h> using namespace std; using ii = pair<int, int>; ii solve(int N, int M, const vector<string>& A) { for (int i = 0; i < N; ++i) for (int j = 0; j < M; ++j) if (A[i][j] == 'W') return ii(i + 1, j + 1); return ii(0, 0); } int main() { ios::sync_with_stdio(false); int N, M; cin >> N >> M; vector<string> A(N); for (int i = 0; i < N; ++i) cin >> A[i]; auto pos = solve(N, M, A); cout << pos.first << ' ' << pos.second << '\n'; return 0; }
15.857143
51
0.445045
Raquel29
1e509b2624970c8e21ea4dd1b744bc24c91f4bce
1,974
cpp
C++
Renderer/VertexCache.cpp
TywyllSoftware/TywRenderer
2da2ea2076d4311488b8ddb39c2fec896c98378a
[ "Unlicense" ]
11
2016-11-15T20:06:19.000Z
2021-03-31T01:04:01.000Z
Renderer/VertexCache.cpp
TywyllSoftware/TywRenderer
2da2ea2076d4311488b8ddb39c2fec896c98378a
[ "Unlicense" ]
1
2016-11-06T23:53:05.000Z
2016-11-07T08:06:07.000Z
Renderer/VertexCache.cpp
TywyllSoftware/TywRenderer
2da2ea2076d4311488b8ddb39c2fec896c98378a
[ "Unlicense" ]
2
2017-09-03T11:18:46.000Z
2019-03-10T06:27:49.000Z
/* * Copyright 2015-2016 Tomas Mikalauskas. All rights reserved. * GitHub repository - https://github.com/TywyllSoftware/TywRenderer * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <RendererPch\stdafx.h> //Renderer Includes #include "VertexCache.h" VertexCache vertexCache; /* ============== ClearGeoBufferSet ============== */ static void ClearGeoBufferSet(geoBufferSet_t &gbs) { gbs.allocations = 0; } /* ============== AllocGeoBufferSet ============== */ static void AllocGeoBufferSet(geoBufferSet_t &gbs, const size_t vertexBytes,const size_t indexByes) { //gbs.vertexBuffer.AllocateBufferObject(nullptr, vertexBytes, 0); //gbs.indexBuffer.AllocateBufferObject(nullptr, indexByes, 1); } void VertexCache::Init() { currentFrame = 0; drawListNum = 0; listNum = 0; for (int i = 0; i < VERTCACHE_NUM_FRAMES; i++) { AllocGeoBufferSet(frameData[i], VERTCACHE_VERTEX_MEMORY_PER_FRAME, VERTCACHE_INDEX_MEMORY_PER_FRAME); } AllocGeoBufferSet(staticData, STATIC_VERTEX_MEMORY, STATIC_INDEX_MEMORY); } /* ============== ActuallyAlloc ============== */ void VertexCache::ActuallyAlloc(geoBufferSet_t & vcs, const void * data, size_t bytes, cacheType_t type) { //data transfer to GPU if (data != nullptr) { if (type == cacheType_t::CACHE_VERTEX) { // vcs.vertexBuffer.AllocateBufferObject(data, bytes, 0); } else if (type == cacheType_t::CACHE_INDEX) { //vcs.vertexBuffer.AllocateBufferObject(data, bytes, 1); } vcs.allocations++; } else { if (type == cacheType_t::CACHE_VERTEX) { //vcs.vertexBuffer.AllocateBufferObject(data, bytes, 0); } else if (type == cacheType_t::CACHE_INDEX) { //vcs.vertexBuffer.AllocateBufferObject(data, bytes, 1); } //vcs.vertexBuffer.AllocateBufferObject(data, bytes, 0); } } /* ==================== Shutdown ==================== */ void VertexCache::Shutdown() { //This is not finished //staticData.vertexBuffer.FreeBufferObject(); }
23.5
106
0.68693
TywyllSoftware
1e51a2a5ba3f41f3bc13ef96d1338fd3983d8255
515
cpp
C++
Arrays/KthRowPascalTriangle.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
Arrays/KthRowPascalTriangle.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
Arrays/KthRowPascalTriangle.cpp
aviral243/interviewbit-solutions-1
7b4bda68b2ff2916263493f40304b20fade16c9a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define mod 1000003; using namespace std; long long int fact(long long int A) { return A <= 1 ? 1 : (A * (fact(A - 1))); } vector<int> getRow(int A) { int n = A, r = 0; vector<int> B; int fN = fact(n); for (int i = 0; i <= A; i++) { long long int val = fN / (fact(i) * fact(A - i)); B.push_back(val); } return B; } int main() { int v1 = 3; vector<int> v2 = getRow(v1); for (auto i = 0; i < v2.size(); i++) { cout << v2[i] << " "; } return 0; }
14.305556
53
0.502913
aviral243
1e5260e1815b2c39538defcb9ea0fe52c102ebdb
362
cpp
C++
p14TimePlus15Minutes/TimePlus15Minutes.cpp
RadoslavEvgeniev/CPlusPlus-Simple-Conditional-Statements
afc3bb8f2b8562c9dc3f2a00d378d92088c7da13
[ "MIT" ]
null
null
null
p14TimePlus15Minutes/TimePlus15Minutes.cpp
RadoslavEvgeniev/CPlusPlus-Simple-Conditional-Statements
afc3bb8f2b8562c9dc3f2a00d378d92088c7da13
[ "MIT" ]
null
null
null
p14TimePlus15Minutes/TimePlus15Minutes.cpp
RadoslavEvgeniev/CPlusPlus-Simple-Conditional-Statements
afc3bb8f2b8562c9dc3f2a00d378d92088c7da13
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> using namespace std; int main() { int hours; int minutes; cin >> hours >> minutes; minutes = minutes + (hours * 60) + 15; hours = minutes / 60; minutes %= 60; hours %= 24; stringstream ss; ss << hours << ":"; if (minutes < 10) { ss << 0 << minutes; } else { ss << minutes; } cout << ss.str() << endl; }
15.083333
39
0.571823
RadoslavEvgeniev
1e56396e2202753f532533525d93618640102b91
456
hh
C++
include/tr064/serialize/Serializer.hh
awidegreen/tr064
da738c3d3ecc1bf5990d746a49feb6efb7166e1a
[ "BSD-2-Clause" ]
15
2015-03-20T17:05:23.000Z
2021-04-22T14:14:47.000Z
include/tr064/serialize/Serializer.hh
awidegreen/tr064
da738c3d3ecc1bf5990d746a49feb6efb7166e1a
[ "BSD-2-Clause" ]
6
2015-06-01T12:08:28.000Z
2018-04-05T15:49:09.000Z
include/tr064/serialize/Serializer.hh
awidegreen/tr064
da738c3d3ecc1bf5990d746a49feb6efb7166e1a
[ "BSD-2-Clause" ]
4
2016-04-15T18:20:28.000Z
2019-10-21T21:01:18.000Z
#ifndef SERIALIZER_HH #define SERIALIZER_HH #include "Serializable.hh" // stl #include <ostream> #include <istream> namespace tr064 { namespace serialize { class Serializer { public: virtual ~Serializer() { } virtual void serialize(std::ostream& out, const Serializeable& root) const = 0; virtual void deserialize(std::istream& in, Serializeable& root) const = 0; protected: Serializer() { } }; } // ns } // ns #endif /* SERIALIZER_HH */
13.818182
81
0.699561
awidegreen
1e5cc5e4086da84b0346526f7177a30b65b025e2
4,596
hpp
C++
include/signal/controllers/motorcontroller.hpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/signal/controllers/motorcontroller.hpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/signal/controllers/motorcontroller.hpp
Bormachine-Learning/embedded
165daf847fe9c2a7bcc17c7aee4c5e28b3cf4055
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/** Copyright 2019 Bosch Engineering Center Cluj and BFMC organizers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ****************************************************************************** * @file Controller.hpp * @author RBRO/PJ-IU * @version V1.0.0 * @date day-month-year * @brief This file contains the class declaration for the controller * functionality. ****************************************************************************** */ /* Include guard */ #ifndef CONTROLLER_HPP #define CONTROLLER_HPP #include<cmath> #include<signal/controllers/sisocontrollers.hpp> #include <hardware/encoders/encoderinterfaces.hpp> #include <signal/controllers/converters.hpp> #include <mbed.h> namespace signal { namespace controllers { /** * @brief It implements a controller with a single input and a single output. It needs an encoder getter interface to get the measured values, a controller to calculate the control signal. It can be completed with a converter to convert the measaurment unit of the control signal. * */ class CMotorController { /* PID controller declaration*/ template <class T> using ControllerType=siso::IController<T>; public: /* Construnctor */ CMotorController(hardware::encoders::IEncoderGetter& f_encoder ,ControllerType<double>& f_pid ,signal::controllers::IConverter* f_converter=NULL ,float f_inf_ref = -225 ,float f_sup_ref = 225); /* Set controller reference value */ void setRef(double f_RefRps); /* Get controller reference value */ double getRef(); /* Get control value */ double get(); /* Get error */ double getError(); /* Clear PID parameters */ void clear(); /* Control action */ int8_t control(); bool inRange(double f_RefRps); private: /* PWM onverter */ double converter(double f_u); /* Enconder object reference */ hardware::encoders::IEncoderGetter& m_encoder; /* PID object reference */ ControllerType<double>& m_pid; /* Controller reference */ double m_RefRps; /* Control value */ double m_u; /* Error */ double m_error; /* Converter */ signal::controllers::IConverter* m_converter; uint8_t m_nrHighPwm; /* Maximum High PWM Signal */ const uint8_t m_maxNrHighPwm; /* Scaled PWM control signal limits */ const float m_control_sup; const float m_control_inf; /* Absolute inferior limit of reference to inactivate the controller in the case low reference and observation value. */ const float m_ref_abs_inf; /* Absolute inferior limits of measured speed to inactivate the controller in the case low reference and observation value. */ const float m_mes_abs_inf; /* Superior limits of measured speed to deactivate the controller for avoid over accelerating. */ const float m_mes_abs_sup; /* Reference allowed limits */ const float m_inf_ref; const float m_sup_ref; }; }; // namespace controllers }; // namespace signal #endif
39.965217
284
0.520017
Bormachine-Learning