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
109
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
48.5k
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
64761fb25e33e1481807347cd7fe9d1ac6810106
1,304
hpp
C++
src/phase_field/PFBaseClass.hpp
flowzario/mesoBasic
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
[ "MIT" ]
null
null
null
src/phase_field/PFBaseClass.hpp
flowzario/mesoBasic
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
[ "MIT" ]
null
null
null
src/phase_field/PFBaseClass.hpp
flowzario/mesoBasic
0a86c98e784a7446a7b6f03b48eef4c9dbfe5940
[ "MIT" ]
null
null
null
# ifndef PFBASECLASS_H # define PFBASECLASS_H # include "../utils/CommonParams.h" # include "../utils/GetPot" using namespace std; // --------------------------------------------------------------------- // This is the base class for phase-field classes in the PF App. // This class serves as an interface, and contains a factory method. // --------------------------------------------------------------------- class PFBaseClass { public: // ------------------------------------------------------------------- // Factory method that creates objects of sub-classes: // ------------------------------------------------------------------- static PFBaseClass* PFFactory(const CommonParams&, const GetPot&); // ------------------------------------------------------------------- // pure virtual functions: // ------------------------------------------------------------------- virtual void initPhaseField() = 0; virtual void updatePhaseField() = 0; virtual void outputPhaseField() = 0; virtual void setTimeStep(int) = 0; // ------------------------------------------------------------------- // virtual destructor: // ------------------------------------------------------------------- virtual ~PFBaseClass() { } }; # endif // PFBASECLASS_H
29.636364
73
0.382669
flowzario
64783d070f0a46328f1073e894c7afb53ce20bbd
6,222
cpp
C++
src/core/utility.cpp
Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3
d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20
[ "MIT" ]
1
2020-11-29T18:04:31.000Z
2020-11-29T18:04:31.000Z
src/core/utility.cpp
Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3
d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20
[ "MIT" ]
1
2020-09-27T14:53:34.000Z
2020-09-27T14:53:34.000Z
src/core/utility.cpp
Sundancer78/Marlin-2.0.4_SKR_14_turbo_ender3
d9dbef52e6fb4e110908a6d09d0af00fc0ac9b20
[ "MIT" ]
null
null
null
/** * Marlin 3D Printer Firmware * Copyright (c) 2020 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (c) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ #include "utility.h" #include "../MarlinCore.h" #include "../module/temperature.h" void safe_delay(millis_t ms) { while (ms > 50) { ms -= 50; delay(50); thermalManager.manage_heater(); } delay(ms); thermalManager.manage_heater(); // This keeps us safe if too many small safe_delay() calls are made } // A delay to provide brittle hosts time to receive bytes #if ENABLED(SERIAL_OVERRUN_PROTECTION) #include "../gcode/gcode.h" // for set_autoreport_paused void serial_delay(const millis_t ms) { const bool was = gcode.set_autoreport_paused(true); safe_delay(ms); gcode.set_autoreport_paused(was); } #endif #if ENABLED(DEBUG_LEVELING_FEATURE) #include "../module/probe.h" #include "../module/motion.h" #include "../module/stepper.h" #include "../libs/numtostr.h" #include "../feature/bedlevel/bedlevel.h" void log_machine_info() { SERIAL_ECHOLNPGM("Machine Type: " #if ENABLED(DELTA) "Delta" #elif IS_SCARA "SCARA" #elif IS_CORE "Core" #else "Cartesian" #endif ); SERIAL_ECHOLNPGM("Probe: " #if ENABLED(PROBE_MANUALLY) "PROBE_MANUALLY" #elif ENABLED(NOZZLE_AS_PROBE) "NOZZLE_AS_PROBE" #elif ENABLED(FIX_MOUNTED_PROBE) "FIX_MOUNTED_PROBE" #elif ENABLED(BLTOUCH) "BLTOUCH" #elif HAS_Z_SERVO_PROBE "SERVO PROBE" #elif ENABLED(TOUCH_MI_PROBE) "TOUCH_MI_PROBE" #elif ENABLED(Z_PROBE_SLED) "Z_PROBE_SLED" #elif ENABLED(Z_PROBE_ALLEN_KEY) "Z_PROBE_ALLEN_KEY" #elif ENABLED(SOLENOID_PROBE) "SOLENOID_PROBE" #else "NONE" #endif ); #if HAS_BED_PROBE #if !HAS_PROBE_XY_OFFSET SERIAL_ECHOPAIR("Probe Offset X0 Y0 Z", probe.offset.z, " ("); #else SERIAL_ECHOPAIR_P(PSTR("Probe Offset X"), probe.offset_xy.x, SP_Y_STR, probe.offset_xy.y, SP_Z_STR, probe.offset.z); if (probe.offset_xy.x > 0) SERIAL_ECHOPGM(" (Right"); else if (probe.offset_xy.x < 0) SERIAL_ECHOPGM(" (Left"); else if (probe.offset_xy.y != 0) SERIAL_ECHOPGM(" (Middle"); else SERIAL_ECHOPGM(" (Aligned With"); if (probe.offset_xy.y > 0) { #if IS_SCARA SERIAL_ECHOPGM("-Distal"); #else SERIAL_ECHOPGM("-Back"); #endif } else if (probe.offset_xy.y < 0) { #if IS_SCARA SERIAL_ECHOPGM("-Proximal"); #else SERIAL_ECHOPGM("-Front"); #endif } else if (probe.offset_xy.x != 0) SERIAL_ECHOPGM("-Center"); SERIAL_ECHOPGM(" & "); #endif if (probe.offset.z < 0) SERIAL_ECHOPGM("Below"); else if (probe.offset.z > 0) SERIAL_ECHOPGM("Above"); else SERIAL_ECHOPGM("Same Z as"); SERIAL_ECHOLNPGM(" Nozzle)"); #endif #if HAS_ABL_OR_UBL SERIAL_ECHOLNPGM("Auto Bed Leveling: " #if ENABLED(AUTO_BED_LEVELING_LINEAR) "LINEAR" #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) "BILINEAR" #elif ENABLED(AUTO_BED_LEVELING_3POINT) "3POINT" #elif ENABLED(AUTO_BED_LEVELING_UBL) "UBL" #endif ); if (planner.leveling_active) { SERIAL_ECHOLNPGM(" (enabled)"); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) SERIAL_ECHOLNPAIR("Z Fade: ", planner.z_fade_height); #endif #if ABL_PLANAR SERIAL_ECHOPGM("ABL Adjustment X"); LOOP_XYZ(a) { float v = planner.get_axis_position_mm(AxisEnum(a)) - current_position[a]; SERIAL_CHAR(' ', 'X' + char(a)); if (v > 0) SERIAL_CHAR('+'); SERIAL_ECHO(v); } #else #if ENABLED(AUTO_BED_LEVELING_UBL) SERIAL_ECHOPGM("UBL Adjustment Z"); const float rz = ubl.get_z_correction(current_position); #elif ENABLED(AUTO_BED_LEVELING_BILINEAR) SERIAL_ECHOPGM("ABL Adjustment Z"); const float rz = bilinear_z_offset(current_position); #endif SERIAL_ECHO(ftostr43sign(rz, '+')); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) { SERIAL_ECHOPAIR(" (", ftostr43sign(rz * planner.fade_scaling_factor_for_z(current_position.z), '+')); SERIAL_CHAR(')'); } #endif #endif } else SERIAL_ECHOLNPGM(" (disabled)"); SERIAL_EOL(); #elif ENABLED(MESH_BED_LEVELING) SERIAL_ECHOPGM("Mesh Bed Leveling"); if (planner.leveling_active) { SERIAL_ECHOLNPGM(" (enabled)"); SERIAL_ECHOPAIR("MBL Adjustment Z", ftostr43sign(mbl.get_z(current_position), '+')); #if ENABLED(ENABLE_LEVELING_FADE_HEIGHT) if (planner.z_fade_height) { SERIAL_ECHOPAIR(" (", ftostr43sign( mbl.get_z(current_position, planner.fade_scaling_factor_for_z(current_position.z)), '+' )); SERIAL_CHAR(')'); } #endif } else SERIAL_ECHOPGM(" (disabled)"); SERIAL_EOL(); #endif // MESH_BED_LEVELING } #endif // DEBUG_LEVELING_FEATURE
29.211268
124
0.605754
Sundancer78
647b799e3c4f615e86414b398073408f20771b30
476
cpp
C++
Hashing/colorful.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Hashing/colorful.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Hashing/colorful.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int colorful(int A) { vector<int> digits; while(A) { digits.push_back(A % 10); A /= 10; } reverse(digits.begin(), digits.end()); unordered_set<int> seen; for(int i = 0; i < digits.size(); ++i) { int prd = 1; for(int j = i; j < digits.size(); ++j) { prd *= digits[j]; if(seen.find(prd) != seen.end()) { return 0; } else { seen.insert(prd); } } } return 1; } int main(void) { }
14.424242
42
0.537815
aneesh001
647beafa61b468ae327ee06d91311e250936812c
445
hpp
C++
include/ncurses++/widget.hpp
lukaszgemborowski/ncursesplusplus
e104281812dfe47720a8185fe1351393cf66e366
[ "MIT" ]
3
2019-12-07T19:54:15.000Z
2021-01-10T18:38:20.000Z
include/ncurses++/widget.hpp
lukaszgemborowski/ncursesplusplus
e104281812dfe47720a8185fe1351393cf66e366
[ "MIT" ]
16
2019-12-10T13:46:59.000Z
2019-12-15T00:39:05.000Z
include/ncurses++/widget.hpp
lukaszgemborowski/ncursesplusplus
e104281812dfe47720a8185fe1351393cf66e366
[ "MIT" ]
null
null
null
#ifndef NCURSESPP_WIDGET_HPP #define NCURSESPP_WIDGET_HPP #include <ncurses++/rect.hpp> namespace ncursespp { template<class Base> class widget { public: widget() = default; void resize(rect_i r) { static_cast<Base *>(this)->do_resize (r); size_ = r; } constexpr auto size() const { return size_; } private: rect_i size_; }; } // namespace ncursespp #endif // NCURSESPP_WIDGET_HPP
13.484848
49
0.638202
lukaszgemborowski
6481578a08d372f27bd4a5df8390b6eb516a4e2c
1,906
cpp
C++
libv8/ruby/1.9.1/gems/therubyracer-0.9.4/ext/v8/v8_try_catch.cpp
tcmaker/ConOnRails
97656120dbc9a5bf773538e021b768d0515ae333
[ "Apache-2.0" ]
1
2021-02-07T21:33:42.000Z
2021-02-07T21:33:42.000Z
libv8/ruby/1.9.1/gems/therubyracer-0.9.4/ext/v8/v8_try_catch.cpp
tcmaker/ConOnRails
97656120dbc9a5bf773538e021b768d0515ae333
[ "Apache-2.0" ]
null
null
null
libv8/ruby/1.9.1/gems/therubyracer-0.9.4/ext/v8/v8_try_catch.cpp
tcmaker/ConOnRails
97656120dbc9a5bf773538e021b768d0515ae333
[ "Apache-2.0" ]
null
null
null
#include "rr.h" #include "v8_try_catch.h" #include "v8_message.h" using namespace v8; namespace { VALUE TryCatchClass; TryCatch *unwrap(VALUE self) { TryCatch *tc = 0; Data_Get_Struct(self, class TryCatch, tc); if (RTEST(rb_iv_get(self, "dead"))) { rb_raise(rb_eScriptError, "out of scope access of %s", RSTRING_PTR(rb_inspect(self))); return false; } else { return tc; } } VALUE Try(int argc, VALUE *argv, VALUE self) { if (rb_block_given_p()) { HandleScope scope; TryCatch tc; VALUE try_catch = Data_Wrap_Struct(TryCatchClass, 0, 0, &tc); rb_iv_set(try_catch, "dead", Qfalse); VALUE result = rb_yield(try_catch); rb_iv_set(try_catch, "dead", Qtrue); tc.Reset(); return result; } else { return Qnil; } } VALUE HasCaught(VALUE self) { TryCatch *tc = unwrap(self); return tc ? rr_v82rb(tc->HasCaught()) : Qnil; } VALUE _Exception(VALUE self) { TryCatch *tc = unwrap(self); return tc ? rr_v82rb(tc->Exception()) : Qnil; } VALUE _StackTrace(VALUE self) { TryCatch *tc = unwrap(self); return tc ? rr_v82rb(tc->StackTrace()) : Qnil; } VALUE _Message(VALUE self) { TryCatch *tc = unwrap(self); return tc ? rr_v82rb(tc->Message()) : Qnil; } VALUE CanContinue(VALUE self) { TryCatch *tc = unwrap(self); return tc ? rr_v82rb(tc->CanContinue()) : Qnil; } } void rr_init_v8_try_catch() { TryCatchClass = rr_define_class("TryCatch"); rr_define_singleton_method(TryCatchClass, "try", Try, -1); rr_define_method(TryCatchClass, "HasCaught", HasCaught, 0); rr_define_method(TryCatchClass, "Exception", _Exception, 0); rr_define_method(TryCatchClass, "StackTrace", _StackTrace, 0); rr_define_method(TryCatchClass, "Message", _Message, 0); rr_define_method(TryCatchClass, "CanContinue", CanContinue, 0); }
26.84507
92
0.650052
tcmaker
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
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
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
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
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
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
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
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
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
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
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 ([email protected]), 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
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
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
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
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
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 <[email protected]> */ //----------------------------------------------------------------------------- // 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
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
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 <[email protected]> * * 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
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, [email protected] //| //| 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
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
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
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
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
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
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
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 ([email protected]) // // 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
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
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
1e5d7e0819ba54ac813ffee97c00328c93c74c35
3,953
hpp
C++
modules/gui/src/MetaObject/params/ui/Qt/Containers.hpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
2
2017-10-26T04:41:49.000Z
2018-02-09T05:12:19.000Z
modules/gui/src/MetaObject/params/ui/Qt/Containers.hpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
null
null
null
modules/gui/src/MetaObject/params/ui/Qt/Containers.hpp
dtmoodie/MetaObject
8238d143d578ff9c0c6506e7e627eca15e42369e
[ "MIT" ]
3
2017-01-08T21:09:48.000Z
2018-02-10T04:27:32.000Z
#pragma once #include "IHandler.hpp" #include "POD.hpp" #include <MetaObject/thread/fiber_include.hpp> namespace mo { namespace UI { namespace qt { struct UiUpdateListener; template <class T, typename Enable> class THandler; // ********************************************************************************** // *************************** std::pair ******************************************** // ********************************************************************************** template <typename T1, typename T2> class THandler<std::pair<T1, T2>> : public UiUpdateHandler { THandler<T1> _handler1; THandler<T2> _handler2; public: THandler(IParamProxy& parent) : UiUpdateHandler(parent) , _handler1(parent) , _handler2(parent) { } void updateUi(const std::pair<T1, T2>& data) { _handler1.UpdateUi(data.first); _handler2.UpdateUi(data.second); } void updateParam(std::pair<T1, T2>& data) { _handler1(data.first); _handler2(data.second); } std::vector<QWidget*> getUiWidgets(QWidget* parent) { auto out1 = _handler1.getUiWidgets(parent); auto out2 = _handler2.getUiWidgets(parent); out2.insert(out2.end(), out1.begin(), out1.end()); return out2; } }; // ********************************************************************************** // *************************** std::vector ****************************************** // ********************************************************************************** template <typename T> class THandler<std::vector<T>, void> : public UiUpdateHandler { QSpinBox* index; THandler<T, void> _data_handler; public: THandler(IParamProxy& parent) : index(new QSpinBox()) , UiUpdateHandler(parent) , _data_handler(parent) { index->setMinimum(0); } void updateUi(const std::vector<T>& data) { if (data.size()) { index->setMaximum(static_cast<int>(data.size())); if (index->value() < data.size()) _data_handler.updateUi(data[index->value()]); } } void updateParam(std::vector<T>& data) { auto idx = index->value(); if (idx < data.size()) { _data_handler.updateParam(data[idx]); } else if (idx == data.size()) { T append_data; _data_handler.updateParam(append_data); data.push_back(append_data); } } std::vector<QWidget*> getUiWidgets(QWidget* parent) { auto output = _data_handler.getUiWidgets(parent); index->setParent(parent); index->setMinimum(0); IHandler::proxy->connect(index, SIGNAL(valueChanged(int)), IHandler::proxy, SLOT(on_update(int))); output.push_back(index); return output; } }; } } }
36.943925
118
0.362762
dtmoodie
1e5e5f604ac9cf7c701e5f595e85395deb0983bb
1,044
hpp
C++
headers/Core/VertexBuffer.hpp
Gilqamesh/GameEngineDemo
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
[ "MIT" ]
null
null
null
headers/Core/VertexBuffer.hpp
Gilqamesh/GameEngineDemo
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
[ "MIT" ]
null
null
null
headers/Core/VertexBuffer.hpp
Gilqamesh/GameEngineDemo
796bb107df5c01b875c2ae73fcfd44e7c07e3a87
[ "MIT" ]
null
null
null
#ifndef VERTEXBUFFER_HPP # define VERTEXBUFFER_HPP # include "pch.hpp" namespace NAMESPACE { class VertexBuffer { GLuint GL_ID; public: VertexBuffer(); /* * Static version * Cannot be modified */ VertexBuffer(const void *data, GLuint size); /* * Dynamic version * Initialize it later and possibly multiple times */ VertexBuffer(GLuint size); ~VertexBuffer(); // to avoid destruction of OpenGL context VertexBuffer(const VertexBuffer &other) = delete; VertexBuffer &operator=(const VertexBuffer &other) = delete; VertexBuffer(VertexBuffer &&other); VertexBuffer &operator=(VertexBuffer &&other); /* * Caller responsibility: * - VBO has to be dynamically initialized * - call bind() before calling 'update' */ void update(const void *data, GLuint size); /* * Delete IndexBuffer from the OpenGL context * Reset the object's state */ void release(); void bind(); void unbind(); }; } #endif
19.698113
64
0.636015
Gilqamesh
1e604e910458d9be0caa061f2cb698ed395f3af4
1,198
hpp
C++
src/Utilities/TypeTraits/ArraySize.hpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/Utilities/TypeTraits/ArraySize.hpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/Utilities/TypeTraits/ArraySize.hpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <array> #include <cstddef> #include <type_traits> namespace tt { namespace TypeTraits_detail { template <typename T, std::size_t N> std::integral_constant<std::size_t, N> array_size_impl( const std::array<T, N>& /*array*/); } // namespace TypeTraits_detail /// @{ /// \ingroup TypeTraitsGroup /// \brief Get the size of a std::array as a std::integral_constant /// /// \details /// Given a std::array, `Array`, returns a std::integral_constant that has the /// size of the array as its value /// /// \usage /// For a std::array `T` /// \code /// using result = tt::array_size<T>; /// \endcode /// /// \metareturns /// std::integral_constant<std::size_t> /// /// \semantics /// For a type `T`, /// \code /// using tt::array_size<std::array<T, N>> = std::integral_constant<std::size_t, /// N>; /// \endcode /// /// \example /// \snippet Test_ArraySize.cpp array_size_example /// \tparam Array the whose size should be stored in value of array_size template <typename Array> using array_size = decltype(TypeTraits_detail::array_size_impl(std::declval<const Array&>())); /// @} } // namespace tt
24.44898
80
0.676962
nilsvu
1e61d8c2c5e2e4fb2d876dc729f8371efa3e8b9c
4,548
hh
C++
include/sdf/Mesh.hh
scpeters-test/sdformat
4668d7857e1d18d8d9b68b40537f77d540353448
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
include/sdf/Mesh.hh
scpeters-test/sdformat
4668d7857e1d18d8d9b68b40537f77d540353448
[ "ECL-2.0", "Apache-2.0" ]
3
2020-10-30T19:22:51.000Z
2020-12-03T20:57:20.000Z
include/sdf/Mesh.hh
scpeters-test/sdformat
4668d7857e1d18d8d9b68b40537f77d540353448
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Open Source Robotics Foundation * * 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 SDF_MESH_HH_ #define SDF_MESH_HH_ #include <string> #include <ignition/math/Vector3.hh> #include <sdf/Element.hh> #include <sdf/Error.hh> #include <sdf/sdf_config.h> namespace sdf { // Inline bracket to help doxygen filtering. inline namespace SDF_VERSION_NAMESPACE { // // Forward declare private data class. class MeshPrivate; /// \brief Mesh represents a mesh shape, and is usually accessed through a /// Geometry. class SDFORMAT_VISIBLE Mesh { /// \brief Constructor public: Mesh(); /// \brief Copy constructor /// \param[in] _mesh Mesh to copy. public: Mesh(const Mesh &_mesh); /// \brief Move constructor /// \param[in] _mesh Mesh to move. public: Mesh(Mesh &&_mesh) noexcept; /// \brief Destructor public: virtual ~Mesh(); /// \brief Move assignment operator. /// \param[in] _mesh Mesh to move. /// \return Reference to this. public: Mesh &operator=(Mesh &&_mesh); /// \brief Copy Assignment operator. /// \param[in] _mesh The mesh to set values from. /// \return *this public: Mesh &operator=(const Mesh &_mesh); /// \brief Load the mesh geometry based on a element pointer. /// This is *not* the usual entry point. Typical usage of the SDF DOM is /// through the Root object. /// \param[in] _sdf The SDF Element pointer /// \return Errors, which is a vector of Error objects. Each Error includes /// an error code and message. An empty vector indicates no error. public: Errors Load(ElementPtr _sdf); /// \brief Get the mesh's URI. /// \return The URI of the mesh data. public: std::string Uri() const; /// \brief Set the mesh's URI. /// \param[in] _uri The URI of the mesh. public: void SetUri(const std::string &_uri); /// \brief The path to the file where this element was loaded from. /// \return Full path to the file on disk. public: const std::string &FilePath() const; /// \brief Set the path to the file where this element was loaded from. /// \paramp[in] _filePath Full path to the file on disk. public: void SetFilePath(const std::string &_filePath); /// \brief Get the mesh's scale factor. /// \return The mesh's scale factor. public: ignition::math::Vector3d Scale() const; /// \brief Set the mesh's scale factor. /// \return The mesh's scale factor. public: void SetScale(const ignition::math::Vector3d &_scale); /// \brief A submesh, contained with the mesh at the specified URI, may /// optionally be specified. If specified, this submesh should be used /// instead of the entire mesh. /// \return The name of the submesh within the mesh at the specified URI. public: std::string Submesh() const; /// \brief Set the mesh's submesh. See Submesh() for more information. /// \param[in] _submesh Name of the submesh. The name should match a submesh /// within the mesh at the specified URI. public: void SetSubmesh(const std::string &_submesh); /// \brief Get whether the submesh should be centered at 0,0,0. This will /// effectively remove any transformations on the submesh before the poses /// from parent links and models are applied. The return value is only /// applicable if a SubMesh has been specified. /// \return True if the submesh should be centered. public: bool CenterSubmesh() const; /// \brief Set whether the submesh should be centered. See CenterSubmesh() /// for more information. /// \param[in] _center True to center the submesh. public: void SetCenterSubmesh(const bool _center); /// \brief Get a pointer to the SDF element that was used during load. /// \return SDF element pointer. The value will be nullptr if Load has /// not been called. public: sdf::ElementPtr Element() const; /// \brief Private data pointer. private: MeshPrivate *dataPtr; }; } } #endif
35.255814
80
0.679639
scpeters-test
1e623ef13e1deeb8e6529b0e43f8400820d9ad21
218
cpp
C++
atcoder.jp/abc079/abc079_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc079/abc079_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
atcoder.jp/abc079/abc079_b/Main.cpp
shikij1/AtCoder
7ae2946efdceaea3cc8725e99a2b9c137598e2f8
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int N; long long L[87]; int main() { cin >> N; L[0] = 2, L[1] = 1; for (int i = 2; i <= N; i++) L[i] = L[i - 2] + L[i - 1]; cout << L[N] << endl; }
16.769231
35
0.431193
shikij1
1e6272cc6b091f11b2b8ec7df3139e3c63b3c2d6
3,234
cpp
C++
Code en C++ de Mage War Online/VikingHammer.cpp
Drakandes/Portfolio_NicolasPaulBonneau
c8115d5ecd6c284113766d64d0f907c074315cff
[ "MIT" ]
null
null
null
Code en C++ de Mage War Online/VikingHammer.cpp
Drakandes/Portfolio_NicolasPaulBonneau
c8115d5ecd6c284113766d64d0f907c074315cff
[ "MIT" ]
null
null
null
Code en C++ de Mage War Online/VikingHammer.cpp
Drakandes/Portfolio_NicolasPaulBonneau
c8115d5ecd6c284113766d64d0f907c074315cff
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "VikingHammer.h" VikingHammer::VikingHammer() { texture_projectile.loadFromFile("VikingHammer.png"); shadow_texture.loadFromFile("VikingHammerShadow.png"); } VikingHammer::~VikingHammer() { } void VikingHammer::Init(sf::Vector2f &position_initial, float damage_received, float direction_projectile_received, int id_caster, float speed, bool can_affect_player, bool can_affect_monster) { id_parent = id_caster; direction_projectile = direction_projectile_received; damage_initial = damage_received; damage = damage_received; position_origin = position_initial; range_projectile = 800; this->can_affect_player = can_affect_player; this->can_affect_monster = can_affect_monster; size_projectile = sf::Vector2f(100, 60); shadow_size = size_projectile; speed_projectile = speed; projectile = GlobalFunction::CreateSprite(position_initial, size_projectile, texture_projectile); projectile.setTextureRect(sf::IntRect(0, 0, size_projectile.x, size_projectile.y)); projectile.setRotation(direction_projectile); shadow = GlobalFunction::CreateSprite(sf::Vector2f(0, 0), shadow_size, shadow_texture); shadow.setRotation(direction_projectile); } void VikingHammer::CuttingSprite() { if (clock_animation.getElapsedTime().asSeconds() >= 0.01) { projectile.setTextureRect(sf::IntRect(size_projectile.x*source_x, 0, size_projectile.x, size_projectile.y)); shadow.setTextureRect(sf::IntRect(size_projectile.x*source_x, 0, size_projectile.x, size_projectile.y)); source_x++; if (source_x == 20) { source_x = 0; } clock_animation.restart(); } } void VikingHammer::Update(float DELTATIME, sf::Vector2f player_position) { MovementGestion(DELTATIME); CuttingSprite(); } float VikingHammer::GetDamage() { return damage; } void VikingHammer::DealWithCollision(std::shared_ptr<CollisionalObject> object_collided) { int id_object = object_collided->GetId(); int type_object = object_collided->GetTypeCollisionalObject(); sf::Vector2f position_self = GetCurrentPosition(); sf::Vector2f position_objet = object_collided->GetCurrentPosition(); sf::Vector2f size_object = object_collided->GetSize(); float armor_penetration = 0; if (type_object == Player_E) { if (CanAffectPlayer()) { is_to_delete = true; float damage_dealt = object_collided->GotDamaged(GetDamage(), id_parent, 0); if (CanStun()) { object_collided->ChangeStunTime(GetStunTime()); } if (CanChangeObjectStat()) { for (int i = 0; i < GetNumberObjectStatChange(); i++) { object_collided->GivePlayerChangeStat(GetObjectStatChanging(i), GetObjectStatChangeDuration(i), GetObjectStatChangValue(i)); } } } } if (type_object == Monster_E) { if (CanAffectMonster()) { is_to_delete = true; float damage_dealt = object_collided->GotDamaged(GetDamage(), id_parent, armor_penetration); TextGenerator::instance()->GenerateOneTextForBlob(position_objet, damage_dealt, size_object, object_collided); } } if (type_object == NatureObject_E) { if (!object_collided->CheckIfProjectileDisable()) { is_to_delete = true; } } }
28.368421
193
0.730674
Drakandes
1e663f6fc641ee122299408e6b4a32059a899e9c
380
hpp
C++
BrainfuckCompiler/Assert.hpp
addrianyy/BrainfuckCompiler
4e47cb9fc926aeae567556e5c75e095c304ae7f5
[ "MIT" ]
3
2020-05-28T21:05:44.000Z
2020-06-23T10:03:19.000Z
BrainfuckCompiler/Assert.hpp
addrianyy/BrainfuckCompiler
4e47cb9fc926aeae567556e5c75e095c304ae7f5
[ "MIT" ]
null
null
null
BrainfuckCompiler/Assert.hpp
addrianyy/BrainfuckCompiler
4e47cb9fc926aeae567556e5c75e095c304ae7f5
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> // Assert working on release builds. void AssertInternal(bool condition, const char* conditionText, const char* filename, uint32_t lineNumer); #define MAKE_STRING(s) MAKE_STRING_1(s) #define MAKE_STRING_1(s) #s #define Assert(x) AssertInternal((x), MAKE_STRING(x), __FILE__, __LINE__)
27.142857
73
0.652632
addrianyy
1e6aa11097025c50662746292dd67ea5d487998c
2,419
cpp
C++
Engine/code/IA_Controller_Task.cpp
miguelangelgil/FirstEngine
3177cffa3663c9f75bc37fe67ac52d6780acfeec
[ "MIT" ]
null
null
null
Engine/code/IA_Controller_Task.cpp
miguelangelgil/FirstEngine
3177cffa3663c9f75bc37fe67ac52d6780acfeec
[ "MIT" ]
null
null
null
Engine/code/IA_Controller_Task.cpp
miguelangelgil/FirstEngine
3177cffa3663c9f75bc37fe67ac52d6780acfeec
[ "MIT" ]
null
null
null
#include "headers\IA_Controller_Task.hpp" #include <Scene.hpp> #include <IA_Component.hpp> #include <Transform_Component.hpp> namespace engine { engine::IA_Controller_Task::IA_Controller_Task(Scene* scene, int priority) : Task(scene, priority) { } bool engine::IA_Controller_Task::initialize() { scan_entities(); active = true; return true; } bool engine::IA_Controller_Task::finalize() { active = false; return true; } bool engine::IA_Controller_Task::step(double time) { for (auto&& entity : entities) { glm::vec3 target = dynamic_cast<IA_Component*>(entity->get_component("ia").get())->get_current_target_position(); Transform_Component* transform = dynamic_cast<Transform_Component*>(entity->get_component("transform").get()); glm::vec3 current_position = *transform->get_position(); glm::vec3 translation(0.f,0.f,0.f); if (target.x > current_position.x) { translation.x = 1.f * 0.003f; } else if (target.x < current_position.x) { translation.x = - 1.f *0.003f; } if (target.y > current_position.y) { translation.y = 1.f * 0.003f; } else if (target.y < current_position.y) { translation.y = -1.f * 0.003f; } transform->set_traslate(translation); } return true; } void engine::IA_Controller_Task::scan_entities() { typedef shared_ptr<Component> component_ptr; map<string, component_ptr> ::iterator iterator_components; map<ID, Entity*>* scene_entities = scene->get_entities(); map<ID, Entity*> ::iterator iterator_entities = scene_entities->begin(); for (; iterator_entities != scene_entities->end(); iterator_entities++) { iterator_components = iterator_entities->second->get_components()->begin(); for (; iterator_components != iterator_entities->second->get_components()->end(); iterator_components++) { if (iterator_components->second->get_type_component() == "ia") { entities.push_back(iterator_entities->second); } } } } }
31.415584
125
0.567177
miguelangelgil
1e6efa3b812a95d652142334d9d0b69311c8034a
861
cpp
C++
src/expression/operation/optime.cpp
ellery85/sparselizard
7d09e97e9443a436d74cbd241b8466527edb9e2f
[ "MIT" ]
null
null
null
src/expression/operation/optime.cpp
ellery85/sparselizard
7d09e97e9443a436d74cbd241b8466527edb9e2f
[ "MIT" ]
null
null
null
src/expression/operation/optime.cpp
ellery85/sparselizard
7d09e97e9443a436d74cbd241b8466527edb9e2f
[ "MIT" ]
null
null
null
#include "optime.h" std::vector<std::vector<densematrix>> optime::interpolate(elementselector& elemselect, std::vector<double>& evaluationcoordinates, expression* meshdeform) { densematrix output(elemselect.countinselection(), evaluationcoordinates.size()/3, universe::currenttimestep); // This can only be on the cos0 harmonic: return {{},{output}}; } densematrix optime::multiharmonicinterpolate(int numtimeevals, elementselector& elemselect, std::vector<double>& evaluationcoordinates, expression* meshdeform) { std::cout << "Error in 'optime' object: time variable 't' is not supported (non-periodic)" << std::endl; abort(); } std::shared_ptr<operation> optime::copy(void) { std::shared_ptr<optime> op(new optime); *op = *this; op->reuse = false; return op; } void optime::print(void) { std::cout << "t"; }
28.7
159
0.704994
ellery85
1e723aadb187589d5b96e1fb6f6a9d4160106403
8,148
hpp
C++
src/main/cpp/Balau/Concurrent/Fork.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
6
2018-12-30T15:09:26.000Z
2020-04-20T09:27:59.000Z
src/main/cpp/Balau/Concurrent/Fork.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
null
null
null
src/main/cpp/Balau/Concurrent/Fork.hpp
borasoftware/balau
8bb82e9cbf7aa8193880eda1de5cbca4db1e1c14
[ "Apache-2.0" ]
2
2019-11-12T08:07:16.000Z
2019-11-29T11:19:47.000Z
// @formatter:off // // Balau core C++ library // // Copyright (C) 2008 Bora Software ([email protected]) // // 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 Fork.hpp /// /// Convenience wrapper for forking processes. /// #ifndef COM_BORA_SOFTWARE__BALAU_CONCURRENT__FORK #define COM_BORA_SOFTWARE__BALAU_CONCURRENT__FORK #include <Balau/Exception/SystemExceptions.hpp> #include <Balau/Dev/Assert.hpp> #include <boost/predef.h> #include <sys/wait.h> namespace Balau::Concurrent { /// /// Convenience wrapper for forking processes. /// class Fork { /// /// Determine whether forking is support on this platform. /// public: static bool forkSupported() { #pragma clang diagnostic push #pragma ide diagnostic ignored "OCSimplifyInspection" #pragma ide diagnostic ignored "OCDFAInspection" return BOOST_OS_UNIX; #pragma clang diagnostic pop } /// /// Perform a fork operator and run the supplied function for the child. /// /// The child process will exit when the function returns if exitChild is set /// to true. Otherwise, the child will return and the caller will need to /// handle child termination. /// /// @param function the function to run in the child process /// @param exitChild if set to true, _Exit(int) is called with the the exit state of the function /// @return the child pid for the parent process, the exit state of the function for the child process if it returns /// @throw ForkException if the fork call failed /// public: static int performFork(const std::function<int ()> & function, bool exitChild) { Assert::assertion(forkSupported(), "fork() called for platform that does not support it."); const int pid = ::fork(); if (pid == 0) { const int status = function(); if (exitChild) { _Exit(status); } else { return status; } } else if (pid > 0) { return pid; } else { ThrowBalauException(Exception::ForkException, errno, "Failed to fork process."); } } /// /// Perform a fork operator and run the supplied function for the child. /// /// The child will return when the function has completed and the caller will /// need to handle child termination. /// /// This version does not require a function that returns an integer. /// /// @param function the function to run in the child process /// @return the child pid for the parent process and zero for the child process /// @throw ForkException if the fork call failed /// public: static int performFork(const std::function<int ()> & function) { Assert::assertion(forkSupported(), "fork() called for platform that does not support it."); const int pid = ::fork(); if (pid == 0) { function(); return 0; } else if (pid > 0) { return pid; } else { ThrowBalauException(Exception::ForkException, errno, "Failed to fork process."); } } /// /// A termination report, returned by wait methods. /// /// Instances of this structure are returned from the pid checking functions /// in this class, in order to communicate the status code of the process. /// public: struct TerminationReport { /// /// The PID of the process. /// int pid; /// /// The signal code. /// int code; /// /// The exit status. /// int exitStatus; TerminationReport() : pid(0), code(0), exitStatus(0) {} TerminationReport(int pid_, int code_, int exitStatus_) : pid(pid_), code(code_), exitStatus(exitStatus_) {} TerminationReport(const TerminationReport & copy) = default; TerminationReport(TerminationReport && rhs) noexcept : pid(rhs.pid), code(rhs.code), exitStatus(rhs.exitStatus) {} TerminationReport & operator = (const TerminationReport & copy) = default; TerminationReport & operator = (TerminationReport && rhs) noexcept { pid = rhs.pid; code = rhs.code; exitStatus = rhs.exitStatus; return *this; } }; /// /// Wait on a process until the process terminates. /// /// If the pid is invalid, an empty termination report is returned. /// /// @param pid the process id /// @return a termination report /// @throw WaitException if the waitid call failed /// public: static TerminationReport waitOnProcess(int pid) { if (pid <= 0) { return TerminationReport(); } siginfo_t infop; int options = WEXITED; memset(&infop, 0, sizeof(siginfo_t)); if (waitid(P_PID, (unsigned int) pid, &infop, options) == -1) { ThrowBalauException(Exception::WaitException, errno); } else if (infop.si_pid) { return TerminationReport(pid, infop.si_code, infop.si_status); } // TODO what else may happen here? return TerminationReport(); } /// /// Check the process for termination without blocking. /// /// If the pid is invalid, an empty termination report is returned. /// /// If the process with the specified id has not terminated, an empty /// termination report is returned. /// /// @param pid the process id /// @return a termination report /// @throw WaitException if the waitid call failed /// public: static TerminationReport checkForTermination(int pid) { if (pid <= 0) { return TerminationReport(); } siginfo_t infop; int options = WEXITED | WNOHANG; memset(&infop, 0, sizeof(siginfo_t)); if (waitid(P_PID, (unsigned int) pid, &infop, options) == -1) { ThrowBalauException(Exception::WaitException, errno); } else if (infop.si_pid) { switch (infop.si_code) { case CLD_EXITED: case CLD_KILLED: case CLD_DUMPED: { return TerminationReport(pid, infop.si_code, infop.si_status); } default: { break; } } } return TerminationReport(); } /// /// Check without blocking the supplied processes for termination. /// /// @param pids the process ids /// @return a vector of termination reports for the pids that terminated. /// @throw WaitException if the waitid call failed /// public: static std::vector<TerminationReport> checkForTermination(const std::vector<int> & pids) { std::vector<TerminationReport> reports; siginfo_t infop; int options = WEXITED | WNOHANG; // NOLINT for (int pid : pids) { if (pid <= 0) { continue; } memset(&infop, 0, sizeof(siginfo_t)); if (waitid(P_PID, (unsigned int) pid, &infop, options) == -1) { ThrowBalauException(Exception::WaitException, errno); } else if (infop.si_pid) { switch (infop.si_code) { case CLD_EXITED: case CLD_KILLED: case CLD_DUMPED: { reports.emplace_back(pid, infop.si_code, infop.si_status); } default: { break; } } } } return reports; } /// /// Terminate the child process if it is running. /// /// If the process has not terminated, terminate it and return an empty termination report. /// If the pid is invalid, an empty termination report is returned. /// /// @param pid the process id /// @return a termination report /// @throw WaitException if the waitid call failed /// public: static TerminationReport terminateProcess(int pid) { if (pid <= 0) { return TerminationReport(); } siginfo_t infop; int options = WEXITED | WNOHANG; // NOLINT memset(&infop, 0, sizeof(siginfo_t)); if (waitid(P_PID, (unsigned int) pid, &infop, options) == -1) { ThrowBalauException(Exception::WaitException, errno); } else if (infop.si_pid) { switch (infop.si_code) { case CLD_EXITED: case CLD_KILLED: case CLD_DUMPED: { return TerminationReport(pid, infop.si_code, infop.si_status); } default: { kill(pid, SIGKILL); break; } } } return TerminationReport(); } }; } // namespace Balau::Concurrent #endif // COM_BORA_SOFTWARE__BALAU_CONCURRENT__FORK
26.627451
117
0.681885
borasoftware
1e84a9fb8a076b8210e8cb9a5712d21d6f77b173
1,198
cpp
C++
example/concepts.cpp
boost-ext/te
f18e0a3462575b5159c43d5a54023ea72461f4bc
[ "BSL-1.0" ]
72
2020-07-01T17:01:35.000Z
2022-03-22T10:37:18.000Z
example/concepts.cpp
boost-ext/te
f18e0a3462575b5159c43d5a54023ea72461f4bc
[ "BSL-1.0" ]
4
2021-05-08T13:36:27.000Z
2022-02-07T18:46:57.000Z
example/concepts.cpp
boost-ext/te
f18e0a3462575b5159c43d5a54023ea72461f4bc
[ "BSL-1.0" ]
8
2020-07-10T08:04:38.000Z
2022-03-22T11:40:01.000Z
// // Copyright (c) 2018-2019 Kris Jusiak (kris at jusiak dot net) // // 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) // #if defined(__cpp_concepts) #include <iostream> #include "boost/te.hpp" namespace te = boost::te; struct Drawable { void draw(std::ostream &out) const { te::call([](auto const &self, auto &out) -> decltype(self.draw(out)) { self.draw(out); }, *this, out); } }; struct Square { void draw(std::ostream &out) const { out << "Square"; } }; struct Circle { void draw(std::ostream &out) const { out << "Circle"; } }; template <te::conceptify<Drawable> TDrawable> void draw(TDrawable const &drawable) { drawable.draw(std::cout); } int main() { { te::var<Drawable> drawable = Square{}; drawable.draw(std::cout); // prints Square } { te::var<Drawable> drawable = Circle{}; drawable.draw(std::cout); // prints Circle } { auto drawable = Square{}; draw(drawable); // prints Square } { auto drawable = Circle{}; draw(drawable); // prints Circle } } #else int main() {} #endif
19.966667
75
0.6202
boost-ext
1e8537ac60c9fa2ce327a86213842d3101e3c95c
8,241
cpp
C++
Ray.cpp
selinnilesy/Ray-Tracing
4b1ac770902ed35560f0bc774ac42cb118f3789a
[ "MIT" ]
null
null
null
Ray.cpp
selinnilesy/Ray-Tracing
4b1ac770902ed35560f0bc774ac42cb118f3789a
[ "MIT" ]
null
null
null
Ray.cpp
selinnilesy/Ray-Tracing
4b1ac770902ed35560f0bc774ac42cb118f3789a
[ "MIT" ]
null
null
null
#include "Ray.h" #include "Algebra.h" #include "math.h" #include <limits> using namespace std; using namespace parser; Ray::Ray() { } Ray::Ray(const Vec3f& e_, const Vec3f& d_):e(e_),d(d_),recursion(parser::scene.max_recursion_depth) { //selincikkk:D normalize(d); } inline Vec3f Ray::positionT(float t) { return e+d*t; } /* return -1 if does not intersect. * */ float Ray::intersect(const Sphere& s) { Vec3f diff = this->e - s.center_vertex; // o - c float B = dotProduct(this->d, diff ); // d.(o-c) float A = dotProduct(this->d , this->d ); // d.d float C = dotProduct(diff, diff ) - s.radius*s.radius; // (o-c).(o-c) - R^2 float discriminant = B*B - A*C; if(discriminant < -1 * epsilon ) return -1; float t1 = (-B + sqrt(discriminant) ) / (A) ; float t2 = (-B - sqrt(discriminant) ) / (A) ; return t1<t2 ? t1 : t2; } /* returns -1 if the plane and the ray are perpendicular. * to eachother. */ float Ray::intersect(const Face& f) { //Vec3f normd(d); //normalize(normd); float product = dotProduct( f.normal, this->d); if( product < epsilon && product > -1*epsilon ) { //LOG_ERR("perpendicular face and normal") ; return -1; } Vec3f a = scene.vertex_data[f.v0_id - 1 ]; Vec3f b = scene.vertex_data[f.v1_id - 1 ]; Vec3f c = scene.vertex_data[f.v2_id - 1 ]; float t = (dotProduct((a - this->e),f.normal)) / product; // TO DO: check if the intersection is inside triangle. Vec3f point = e+d*t; // check vertex c and point on the same direction of ab Vec3f vp = crossProduct(point-b , a-b); Vec3f vc = crossProduct(c-b, a-b); if(dotProduct(vp, vc) + epsilon> 0){ // check vertex a and point on the same direction of bc Vec3f vp_2 = crossProduct(point-c , b-c); Vec3f va_2 = crossProduct(a-c, b-c); if(dotProduct(vp_2, va_2) +epsilon > 0){ // check vertex b and point on the same direction of ca Vec3f vp_3 = crossProduct(point-a , c-a); Vec3f vb_3 = crossProduct(b-a, c-a); if(dotProduct(vp_3, vb_3) +epsilon > 0){ return t; } } } return -1; } float Ray::intersect(const Vec3f& position) { return (e.x - position.x)/d.x; } /* * verify intersection of the ray in the proper range. */ bool Ray::checkObstacle(float minDistance, float maxDistance) { float t ; //= std::numeric_limits<float>::max(); for (Sphere& s : parser::scene.spheres) { t = intersect(s); if (t > minDistance && t < maxDistance) { return true; } } for (Triangle& tr : parser::scene.triangles) { Face& f = tr.indices; t = intersect(f); if (t > minDistance && t < maxDistance) { return true; } } for (Mesh& m : parser::scene.meshes) { for (Face& f : m.faces) { t = intersect(f); Vec3f p = e + d * t; if (t > minDistance && t < maxDistance) { float dp = dotProduct(d,f.normal ); return true; } } } return false; } Vec3f Ray::calculateColor(const Vec3f& intersection, const Vec3f& normal, const Material& material) { Vec3f ambient = hadamardProduct(scene.ambient_light, material.ambient); Vec3f spec = { 0,0,0 }, diffuse = { 0,0,0 }, specAdd = { 0,0,0 }, diffuseAdd = { 0,0,0 },half; float cos, cosNormal; for (PointLight& l : scene.point_lights) { float distance = calculateDistance(l.position, intersection); Ray r(intersection, l.position - intersection); if (!r.checkObstacle(scene.shadow_ray_epsilon, distance)) { cos = max((float)0.0, dotProduct(r.d, normal)); diffuseAdd = (cos / (distance * distance)) * l.intensity; //diffuseAdd = hadamardProduct(diffuseAdd, material.diffuse); //limitColorRange(diffuseAdd); diffuse = diffuse + diffuseAdd; if (cos == 0) { continue; } half = r.d - d; normalize(half); cos = max((float)0.0, dotProduct(normal, half)); specAdd = (pow(cos, material.phong_exponent) / (distance * distance)) * l.intensity; //specAdd = hadamardProduct(specAdd, material.specular); //limitColorRange(specAdd); spec = spec +specAdd ; } } diffuse = hadamardProduct(diffuse, material.diffuse); spec = hadamardProduct(spec, material.specular); //Vec3f total = ambient + spec + diffuse; //limitColorRange(total); if(this->recursion == scene.max_recursion_depth) return ambient + spec + diffuse; else return diffuse + spec; } /* minDistance = epsilon * for recursion level 1, minDistance = distance of scene */ Vec3f Ray::calculateColor(float minDistance) { float t = std::numeric_limits<float>::max(), tmpt = 0; Vec3f color,normal,intersection; color.x = scene.background_color.x; color.y = scene.background_color.y; color.z = scene.background_color.z; if (recursion == -1) return color; Ray newRay; Sphere* sphere = nullptr; Triangle* triange = nullptr; Mesh* mesh = nullptr; Face* face = nullptr; Material* material; bool intersected = false; for (Sphere& s : parser::scene.spheres) { tmpt = intersect(s); if (tmpt > minDistance && tmpt < t) { t = tmpt; sphere = &s; material = &s.material; intersection = positionT(t); normal = (intersection - sphere->center_vertex)/sphere->radius; intersected = true; } } for (Triangle& tr : parser::scene.triangles) { Face& f = tr.indices; tmpt = intersect(f); if (tmpt > minDistance && tmpt < t) { t = tmpt; face = &f; material = &tr.material; normal = face->normal; intersected = true; } } for (Mesh& m : parser::scene.meshes) { for (Face& f : m.faces) { tmpt = intersect(f); if (tmpt > minDistance && tmpt < t) { t = tmpt; face = &f; material = &m.material; normal = face->normal; intersected = true; } } } if (intersected == false) { color.x = scene.background_color.x; color.y = scene.background_color.y; color.z = scene.background_color.z; return color; } intersection = positionT(t); color = calculateColor(intersection, normal, *material); if (recursion != 0 && material->is_mirror ) { newRay = generateReflection(intersection, normal); Vec3f reflectionColor = newRay.calculateColor(parser::scene.shadow_ray_epsilon); return color + hadamardProduct(reflectionColor, material->mirror); } else return color; } Vec3f Ray::calculateDiffuse(const Vec3f& intersection, const Vec3f& normal, const Material& material) { float cos; Vec3f diffuse; diffuse.x = 0; diffuse.y = 0; diffuse.z = 0; Vec3f diffuseAdd(diffuse); for (PointLight& l : scene.point_lights) { float distance = calculateDistance(l.position, intersection); Ray r(intersection, l.position - intersection); if (!r.checkObstacle(scene.shadow_ray_epsilon, distance)) { cos = max((float)0.0, dotProduct(r.d, normal)); if (cos > 1 || cos < -1 * epsilon) { int bp = 0; } diffuseAdd = (cos / (distance * distance)) * l.intensity; //diffuseAdd = hadamardProduct(diffuseAdd, material.diffuse); //limitColorRange(diffuseAdd); diffuse = diffuse + diffuseAdd; } } diffuse = hadamardProduct(diffuse, material.diffuse); //limitColorRange(diffuse); return diffuse; } Vec3f Ray::calculateSpecular(const Vec3f& intersection, const Vec3f& normal, const Material& material) { float cos; Vec3f spec, half; spec.x = 0; spec.y = 0; spec.z = 0; Vec3f specAdd(spec); for (PointLight& l : scene.point_lights) { float distance = calculateDistance(l.position, intersection); Ray r(intersection, (l.position - intersection) / distance); if (!r.checkObstacle(scene.shadow_ray_epsilon, distance)) { half = r.d - d; half = normalize(half); cos = max((float)0.0, dotProduct(normal, half)); float cosNormal = dotProduct(normal, r.d); if (cosNormal < -1 * epsilon) { continue; } specAdd = (pow(cos,material.phong_exponent) / (distance * distance)) * l.intensity; //specAdd = hadamardProduct(specAdd, material.specular); //limitColorRange(specAdd); spec = spec + specAdd; } } spec = hadamardProduct(spec, material.specular); //limitColorRange(spec); return spec; } Ray Ray::generateReflection(const Vec3f& position, const Vec3f& normal) { Vec3f d_reflection; float cos = dotProduct(normal, -1 * d); Ray r(position, d + 2 * cos* normal ); r.recursion = recursion - 1; return r; }
28.915789
103
0.649193
selinnilesy
1e86c52f38707156cbb2a7ed3a8cb9a5aeafac0b
2,892
cpp
C++
McQuickBoot/src/Controller/McResult.cpp
mrcao20/McQuickBoot
187a16ea9459fa5e2b3477b5280302a9090e8ccf
[ "MIT" ]
3
2020-03-29T18:41:42.000Z
2020-09-23T01:46:25.000Z
McQuickBoot/src/Controller/McResult.cpp
mrcao20/McQuickBoot
187a16ea9459fa5e2b3477b5280302a9090e8ccf
[ "MIT" ]
3
2020-11-26T03:37:31.000Z
2020-12-21T02:17:17.000Z
McQuickBoot/src/Controller/McResult.cpp
mrcao20/McQuickBoot
187a16ea9459fa5e2b3477b5280302a9090e8ccf
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2021 mrcao20 * * 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 "McBoot/Controller/impl/McResult.h" #include <QDebug> #include <QJsonDocument> #include <QJsonObject> MC_DECL_PRIVATE_DATA(McResult) bool isInternalError{false}; bool isSuccess{false}; QString errMsg; QVariant result; MC_DECL_PRIVATE_DATA_END MC_INIT(McResult) MC_REGISTER_BEAN_FACTORY(McResult); MC_INIT_END McResult::McResult(QObject *parent) : QObject(parent) { MC_NEW_PRIVATE_DATA(McResult) } McResult::~McResult() { } bool McResult::isSuccess() const noexcept { return d->isSuccess; } void McResult::setSuccess(bool val) noexcept { d->isSuccess = val; } QString McResult::errMsg() const noexcept { return d->errMsg; } void McResult::setErrMsg(const QString &val) noexcept { d->errMsg = val; } QVariant McResult::result() const noexcept { return d->result; } void McResult::setResult(const QVariant &val) noexcept { d->result = val; } QDebug operator<<(QDebug dbg, McResult *r) { QDebugStateSaver saver(dbg); QJsonObject jsonObj; jsonObj.insert("isSuccess", r->isSuccess()); jsonObj.insert("result", QJsonValue::fromVariant(r->result())); jsonObj.insert("errMsg", r->errMsg()); dbg.noquote() << QJsonDocument(jsonObj).toJson(); return dbg; } QDebug operator<<(QDebug dbg, const QSharedPointer<McResult> &r) { QDebugStateSaver saver(dbg); QJsonObject jsonObj; jsonObj.insert("isSuccess", r->isSuccess()); jsonObj.insert("result", QJsonValue::fromVariant(r->result())); jsonObj.insert("errMsg", r->errMsg()); dbg.noquote() << QJsonDocument(jsonObj).toJson(); return dbg; } bool McResult::isInternalError() const noexcept { return d->isInternalError; } void McResult::setInternalError(bool val) noexcept { d->isInternalError = val; }
25.821429
81
0.727178
mrcao20
1e948963b99808defb6948eed9bbe07f81adf80b
9,171
cpp
C++
core/Instances.cpp
sudarsun/c48
4ffd0825380eacd0b120b42cfd0b24182bf9fb8e
[ "Unlicense" ]
null
null
null
core/Instances.cpp
sudarsun/c48
4ffd0825380eacd0b120b42cfd0b24182bf9fb8e
[ "Unlicense" ]
null
null
null
core/Instances.cpp
sudarsun/c48
4ffd0825380eacd0b120b42cfd0b24182bf9fb8e
[ "Unlicense" ]
null
null
null
#include "Instances.h" #include "Instance.h" #include "Consts.h" #include "Utils.h" #include <iostream> #include <unordered_set> #include <exception> #include <stdexcept> Instances::Instances(const string &name, std::vector<Attribute*> &attInfo, const int capacity) { // check whether the attribute names are unique std::unordered_set<string> attr_names; string nonUniqueNames = ""; for (auto att : attInfo) { if (std::find(attr_names.begin(), attr_names.end(), att->name()) != attr_names.end()) { nonUniqueNames.append(string("'") + att->name() + string("' ")); } attr_names.insert(att->name()); } if (attr_names.size() != attInfo.size()) { throw std::invalid_argument(string("Attribute names are not unique!") + string(" Causes: ") + nonUniqueNames); } attr_names.clear(); mRelationName = name; mClassIndex = -1; mAttributes = attInfo; mNamesToAttributeIndices = std::unordered_map<string, int>(static_cast<int>(numAttributes() / 0.75)); for (int i = 0; i < numAttributes(); i++) { attribute(i).setIndex(i); mNamesToAttributeIndices[(attribute(i)).name()] = i; } mInstances = std::vector<Instance*>(capacity); } Instances::Instances(Instances *dataset) :Instances(dataset, 0) { this->copyInstances(0, *dataset, dataset->numInstances()); } Instances::Instances(Instances *dataset, const int capacity) { initialize(*dataset, capacity); } Attribute &Instances::attribute(const int index) const { return *mAttributes[index]; } Attribute &Instances::attribute(const string &name) { int index = mNamesToAttributeIndices[name]; if (index != -1) { return attribute(index); } return *(new Attribute(nullptr)); } int Instances::numAttributes() const { return (int)mAttributes.size(); } int Instances::classIndex() const { return mClassIndex; } void Instances::setClassIndex(const int classIndex) { if (classIndex >= numAttributes()) { throw string("Invalid class index: ") + std::to_string(classIndex); } mClassIndex = classIndex; } bool Instances::add(Instance &instance) { Instance *newInstance = static_cast<Instance*>(&instance); newInstance->setDataset(const_cast<Instances*>(this)); mInstances.push_back(&instance); return true; } void Instances::add(const int index, Instance &instance) { Instance *newInstance = static_cast<Instance*>(&instance); newInstance->setDataset(this); mInstances[index] = &instance; } int Instances::numInstances() const { return (int)mInstances.size(); } void Instances::copyInstances(const int from, const Instances &dest, const int num) { for (int i = 0; i < num; i++) { Instance *newInstance = new Instance(dest.instance(i).weight(), dest.instance(i).toDoubleArray()); newInstance->setDataset(const_cast<Instances*>(this)); mInstances.push_back(newInstance); } } Instance &Instances::instance(const int index) const { return *mInstances[index]; } void Instances::initialize(const Instances &dataset, int capacity) { if (capacity < 0) { capacity = 0; } // Strings only have to be "shallow" copied because // they can't be modified. mClassIndex = dataset.mClassIndex; mRelationName = dataset.mRelationName; mAttributes = dataset.mAttributes; mNamesToAttributeIndices = dataset.mNamesToAttributeIndices; mInstances = std::vector<Instance*>(capacity); } Attribute &Instances::classAttribute() const { if (mClassIndex < 0) { throw "Class index is negative (not set)!"; } return attribute(mClassIndex); } int Instances::numClasses() const { if (mClassIndex < 0) { throw "Class index is negative (not set)!"; } if (!classAttribute().isNominal()) { return 1; } else { return classAttribute().numValues(); } } Instance &Instances::lastInstance() const { return *mInstances[mInstances.size() - 1]; } void Instances::deleteWithMissing(const int attIndex) { std::vector<Instance*> newInstances; int totalInst = numInstances(); for (int i = 0; i < totalInst; i++) { if (!instance(i).isMissing(attIndex)) { newInstances.push_back(&instance(i)); } } mInstances = newInstances; } void Instances::deleteWithMissing(const Attribute &att) { deleteWithMissing(att.index()); } void Instances::deleteWithMissingClass() { if (mClassIndex < 0) { throw "Class index is negative (not set)!"; } deleteWithMissing(mClassIndex); } double Instances::sumOfWeights() const { double sum = 0; for (int i = 0; i < numInstances(); i++) { sum += instance(i).weight(); } return sum; } Instances *Instances::trainCV(const int numFolds, const int numFold) { int numInstForFold, first, offset; Instances *train; if (numFolds < 2) { throw std::invalid_argument("Number of folds must be at least 2!"); } if (numFolds > numInstances()) { throw "Can't have more folds than instances!"; } numInstForFold = numInstances() / numFolds; if (numFold < numInstances() % numFolds) { numInstForFold++; offset = numFold; } else { offset = numInstances() % numFolds; } train = new Instances(this, numInstances() - numInstForFold); first = numFold * (numInstances() / numFolds) + offset; copyInstances(0, train, first); copyInstances(first + numInstForFold, train, numInstances() - first - numInstForFold); return train; } Instances *Instances::testCV(const int numFolds, const int numFold) { int numInstForFold, first, offset; Instances *test; if (numFolds < 2) { throw std::invalid_argument("Number of folds must be at least 2!"); } if (numFolds > numInstances()) { throw "Can't have more folds than instances!"; } numInstForFold = numInstances() / numFolds; if (numFold < numInstances() % numFolds) { numInstForFold++; offset = numFold; } else { offset = numInstances() % numFolds; } test = new Instances(this, numInstForFold); first = numFold * (numInstances() / numFolds) + offset; copyInstances(first, test, numInstForFold); return test; } void Instances::Sort(const int attIndex) { if (!attribute(attIndex).isNominal()) { // Use quicksort from Utils class for sorting double_array vals(numInstances()); std::vector<Instance*> backup(vals.size()); for (int i = 0; i < vals.size(); i++) { Instance &inst = instance(i); backup[i] = &inst; double val = inst.value(attIndex); if (Utils::isMissingValue(val)) { vals[i] = std::numeric_limits<double>::max(); } else { vals[i] = val; } } int_array sortOrder = Utils::sortWithNoMissingValues(vals); for (int i = 0; i < vals.size(); i++) { mInstances[i] = backup[sortOrder[i]]; } } else { sortBasedOnNominalAttribute(attIndex); } } void Instances::Sort(const Attribute &att) { Sort(att.index()); } void Instances::sortBasedOnNominalAttribute(const int attIndex) { // Figure out number of instances for each attribute value // and store original list of instances away int_array counts((attribute(attIndex)).numValues()); std::vector<Instance*> backup(numInstances()); int j = 0; for (auto inst : mInstances) { backup[j++] = inst; if (!inst->isMissing(attIndex)) { counts[static_cast<int>(inst->value(attIndex))]++; } } // Indices to figure out where to add instances int_array indices(counts.size()); int start = 0; for (int i = 0; i < counts.size(); i++) { indices[i] = start; start += counts[i]; } for (auto inst : backup) { // Use backup here if (!inst->isMissing(attIndex)) { mInstances[indices[static_cast<int>(inst->value(attIndex))]++] = inst; } else { mInstances[start++] = inst; } } } string Instances::getRelationName() const { return mRelationName; } void Instances::setRelationName(const string &name) { mRelationName = name; } double_array Instances::attributeToDoubleArray(const int index) const { int totalInst = numInstances(); double_array result; for (int i = 0; i < totalInst; i++) { result.push_back(instance(i).value(index)); } return result; }
25.264463
119
0.591975
sudarsun
1e96c8415812536d618641cf19b018660ba0b7a6
2,494
cpp
C++
atcoder/arc011/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
atcoder/arc011/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
atcoder/arc011/B/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
// atcoder/arc011/B/main.cpp // author: @___Johniel // github: https://github.com/johniel/ #include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; for (auto& i: v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { for (auto& i: v) is >> i; return is; } template<typename T> ostream& operator << (ostream& os, set<T> s) { os << "#{"; for (auto& i: s) os << i << ","; os << "}"; return os; } template<typename K, typename V> ostream& operator << (ostream& os, map<K, V> m) { os << "{"; for (auto& i: m) os << i << ","; os << "}"; return os; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } using lli = long long int; using ull = unsigned long long; using point = complex<double>; using str = string; template<typename T> using vec = vector<T>; constexpr array<int, 8> di({0, 1, -1, 0, 1, -1, 1, -1}); constexpr array<int, 8> dj({1, 0, 0, -1, 1, -1, -1, 1}); constexpr lli mod = 1e9 + 7; int main(int argc, char *argv[]) { std::ios_base::sync_with_stdio(0); std::cin.tie(0); std::cout.setf(std::ios_base::fixed); std::cout.precision(15); int n; while (cin >> n) { vec<str> v(n); cin >> v; vec<str> u; each (s, v) { str t; each (c, s) { c = tolower(c); if (c == 'a' || c == 'i' || c == 'u' || c == 'e' || c == 'o') continue; if (c == 'b' || c == 'c') t += '1'; if (c == 'd' || c == 'w') t += '2'; if (c == 't' || c == 'j') t += '3'; if (c == 'f' || c == 'q') t += '4'; if (c == 'l' || c == 'v') t += '5'; if (c == 's' || c == 'x') t += '6'; if (c == 'p' || c == 'm') t += '7'; if (c == 'h' || c == 'k') t += '8'; if (c == 'n' || c == 'g') t += '9'; if (c == 'z' || c == 'r') t += '0'; } if (t.size()) u.push_back(t); } for (int i = 0; i < u.size(); ++i) { if (i) cout << ' '; cout << u[i]; } cout << endl; } return 0; }
34.164384
150
0.480754
Johniel
1e9904710a041b6f25f4adc797faec875a3e87ad
14,976
cpp
C++
reconstruction/gadgetron/CS_LAB_Gadget/src/ELASTIX_GADGET/ElastixRegistrationGadget.cpp
alwaysbefun123/CS_MoCo_LAB
a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b
[ "BSD-2-Clause" ]
83
2017-08-11T09:18:17.000Z
2022-01-23T03:08:00.000Z
reconstruction/gadgetron/CS_LAB_Gadget/src/ELASTIX_GADGET/ElastixRegistrationGadget.cpp
MrYuwan/CS_MoCo_LAB
a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b
[ "BSD-2-Clause" ]
4
2017-09-19T23:02:12.000Z
2020-11-23T11:25:18.000Z
reconstruction/gadgetron/CS_LAB_Gadget/src/ELASTIX_GADGET/ElastixRegistrationGadget.cpp
MrYuwan/CS_MoCo_LAB
a26e8e483624b2e4ee669e7a069ba9c74d2d2e4b
[ "BSD-2-Clause" ]
49
2017-03-19T18:41:55.000Z
2021-11-25T08:25:44.000Z
/* file name : ElastixRegistrationGadget.cpp author : Martin Schwartz ([email protected]) Thomas Kuestner ([email protected]) version : 1.2 date : 13.10.2015 23.03.2017 - update for Gadgetron v3.8 23.01.2018 - renaming description : implementation of the class ElastixRegistrationGadget - only 3D (x,y,t) and 4D data (x,y,z,t) provided */ #include "ElastixRegistrationGadget.h" #include <boost/algorithm/string/predicate.hpp> #include "SomeFunctions.h" using namespace Gadgetron; ElastixRegistrationGadget::ElastixRegistrationGadget() { } ElastixRegistrationGadget::~ElastixRegistrationGadget() { } int ElastixRegistrationGadget::process_config(ACE_Message_Block *mb) { #ifdef __GADGETRON_VERSION_HIGHER_3_6__ log_output_ = LogOutput.value(); sPathParam_ = PathParam.value(); sPathLog_ = PathLog.value(); #else log_output_ = *(get_bool_value("LogOutput").get()); sPathParam_ = *(get_string_value("PathParam").get()); sPathLog_ = *(get_string_value("PathLog").get()); #endif // ensure that path variable ends with dir separator #ifdef __WIN32__ #define DIR_SEPARATOR "\\" #else #define DIR_SEPARATOR "/" #endif if (boost::algorithm::ends_with(sPathLog_, DIR_SEPARATOR)) { sPathLog_ += DIR_SEPARATOR; } return GADGET_OK; } int ElastixRegistrationGadget::process(GadgetContainerMessage<ISMRMRD::ImageHeader> *m1, GadgetContainerMessage<hoNDArray<float> > *m2) { // create references for easier usage const hoNDArray<float> &data = *m2->getObjectPtr(); std::vector<size_t> dimensions = *data.get_dimensions(); // determine number of gate dimensions const size_t number_of_gate_dimensions = data.get_number_of_dimensions() > 3 ? data.get_number_of_dimensions()-3 : data.get_number_of_dimensions()-1; // get gate dimensions const std::vector<size_t> gate_dimensions(dimensions.end()-number_of_gate_dimensions, dimensions.end()); // determine number of images const size_t number_of_images = std::accumulate(dimensions.end()-number_of_gate_dimensions, dimensions.end(), 1, std::multiplies<size_t>()); // other dimensions are dimension of one image const std::vector<size_t> dimensions_of_image(dimensions.begin(), dimensions.end()-number_of_gate_dimensions); // check for image dimensions bool skip_registration = false; if (dimensions_of_image.size() < 2 || dimensions_of_image.size() > 3) { GWARN("Dataset does not contain 2D or 3D images - Skip registration...\n"); skip_registration = true; } else if (number_of_images <= 1) { GWARN("There must be at least two images to register them - Skip registration...\n"); skip_registration = true; } // skip registration if it cannot be performed if (skip_registration) { if (this->next()->putq(m1) < 0) { return GADGET_FAIL; } return GADGET_OK; } /* ------------------------------------------------------------------- */ /* --------------- create registration parameter data ---------------- */ /* ------------------------------------------------------------------- */ GINFO("Load elastix parameter file..\n"); // Create parser for transform parameters text file. ParserType::Pointer file_parser = ParserType::New(); GINFO("search for parameter file - %s..\n", sPathParam_.c_str()); // Try parsing transform parameters text file. file_parser->SetParameterFileName(sPathParam_); try { file_parser->ReadParameterFile(); } catch (itk::ExceptionObject &e) { std::cout << e.what() << std::endl; } RegistrationParametersType parameters = file_parser->GetParameterMap(); GINFO("parameter file - %s - loaded..\n", sPathParam_.c_str()); /* ------------------------------------------------------------------- */ /* -------------------- init elastix registration -------------------- */ /* ------------------------------------------------------------------- */ // print dimensions std::stringstream ss; ss << "size - "; for (size_t i = 0; i < dimensions_of_image.size(); i++) { ss << dimensions_of_image.at(i) << " "; } ss << number_of_images; GDEBUG("%s\n", ss.str().c_str()); // get fixed image from dataset std::vector<size_t> fixed_image_dimensions = dimensions_of_image; hoNDArray<float> fixed_image(fixed_image_dimensions, const_cast<float*>(data.get_data_ptr()), false); // create registered (output) image hoNDArray<float> output_image(*data.get_dimensions()); memcpy(output_image.get_data_ptr(), fixed_image.get_data_ptr(), fixed_image.get_number_of_bytes()); // create array for deformation field with dimensions [X Y Z CombinedPhases VectorComponents(2 or 3)] std::vector<size_t> output_df_dimensions = dimensions_of_image; output_df_dimensions.push_back(number_of_images - 1); output_df_dimensions.push_back(dimensions_of_image.size()); hoNDArray<float> output_deformation_field(&output_df_dimensions); // set itk image parameter ImportFilterType::Pointer itkImportFilter = ImportFilterType::New(); ImportFilterType::SizeType itkSize; itkSize[0] = dimensions_of_image.at(0); itkSize[1] = dimensions_of_image.at(1); itkSize[2] = dimensions_of_image.size() >= 3 ? dimensions_of_image.at(2) : 1; // ITK handels 3D image, so if we have a 2D moving image, 3rd dimension=1 ImportFilterType::IndexType itkStart; itkStart.Fill(0); ImportFilterType::RegionType itkRegion; itkRegion.SetIndex(itkStart); itkRegion.SetSize(itkSize); itkImportFilter->SetRegion(itkRegion); double itkOrigin[3]; itkOrigin[0] = 0.0; itkOrigin[1] = 0.0; itkOrigin[2] = 0.0; itkImportFilter->SetOrigin(itkOrigin); double itkSpacing[3]; itkSpacing[0] = m1->getObjectPtr()->field_of_view[0]/m1->getObjectPtr()->matrix_size[0]; itkSpacing[1] = m1->getObjectPtr()->field_of_view[1]/m1->getObjectPtr()->matrix_size[1]; itkSpacing[2] = m1->getObjectPtr()->field_of_view[2]/m1->getObjectPtr()->matrix_size[2]; itkImportFilter->SetSpacing(itkSpacing); float *fLocalBuffer = new float[fixed_image.get_number_of_elements()]; memcpy(fLocalBuffer, fixed_image.get_data_ptr(), fixed_image.get_number_of_bytes()); itkImportFilter->SetImportPointer(fLocalBuffer, fixed_image.get_number_of_elements(), true); ImageType::Pointer itkFixedImage = ImageType::New(); itkFixedImage = itkImportFilter->GetOutput(); itkImportFilter->Update(); /* ------------------------------------------------------------------- */ /* --------- loop over moving images and perform registration -------- */ /* ------------------------------------------------------------------- */ GINFO("Loop over moving images..\n"); // loop over respiration // #pragma omp parallel for // Note: Elastix itselfs parallels quite good. Some serious error can occur if you parallelise here! for (size_t calculated_images = 1; calculated_images < number_of_images; calculated_images++) { GINFO("%i of %i ...\n", calculated_images, number_of_images-1); // calculate offset for one single image const size_t moving_image_offset = std::accumulate(std::begin(dimensions_of_image), std::end(dimensions_of_image), 1, std::multiplies<size_t>())*calculated_images; // accumulate() := dimensions_of_image[0]*dimensions_of_image[1]*... // crop moving image from 4D dataset std::vector<size_t> moving_image_dimensions = dimensions_of_image; hoNDArray<float> moving_image(moving_image_dimensions, const_cast<float*>(data.get_data_ptr()) + moving_image_offset, false); float *fLocalBuffer = new float[moving_image.get_number_of_elements()]; memcpy(fLocalBuffer, moving_image.get_data_ptr(), moving_image.get_number_of_bytes()); itkImportFilter->SetImportPointer(fLocalBuffer, moving_image.get_number_of_elements(), true); ImageType::Pointer itkMovingImage = ImageType::New(); itkMovingImage = itkImportFilter->GetOutput(); itkImportFilter->Update(); // image registration elastix::ELASTIX *elastix_obj = new elastix::ELASTIX(); int error = 0; try { // perform registration with (FixedImage, MovingImage, ParameterFile, OutputPath, ElastixLog, ConsoleOutput, FixedImageMask, MovingImageMask) error = elastix_obj->RegisterImages(static_cast<itk::DataObject::Pointer>(itkFixedImage.GetPointer()), static_cast<itk::DataObject::Pointer>(itkMovingImage.GetPointer()), parameters, sPathLog_, log_output_, false, 0, 0); } catch (itk::ExitEvent &err) { // error handling - write message and fill array with zeros GERROR("Error event catched directly from elastix\n"); } // get output image ImageType *itkOutputImage = NULL; if (error == 0) { if (elastix_obj->GetResultImage().IsNotNull()) { itkOutputImage = static_cast<ImageType*>(elastix_obj->GetResultImage().GetPointer()); } else { GERROR("GetResultImage() is NULL \n", error); } } else { // error handling - write message and fill array with zeros GERROR("array is zero\n", error); } // set output image to zeros if non-existent void *memcpy_pointer = NULL; ImageType::Pointer zero_image; if (itkOutputImage != NULL) { memcpy_pointer = itkOutputImage->GetBufferPointer(); } else { ImageType::IndexType start; for (size_t i = 0; i < 3; i++) { start[i] = 0; } ImageType::SizeType size; for (size_t i = 0; i < dimensions_of_image.size(); i++) { size[i] = dimensions_of_image[i]; } size[dimensions_of_image.size()] = number_of_images; ImageType::RegionType region; region.SetSize(size); region.SetIndex(start); zero_image = ImageType::New(); zero_image->SetRegions(region); zero_image->Allocate(); zero_image->FillBuffer(0.0); memcpy_pointer = zero_image->GetBufferPointer(); } // copy image to new registered 4D image memcpy(output_image.get_data_ptr()+moving_image_offset, memcpy_pointer, moving_image.get_number_of_bytes()); // clean up delete elastix_obj; elastix_obj = NULL; // calculate deformation field std::string transformix_command = std::string("transformix -def all -out ")+sPathLog_+std::string(" -tp ")+sPathLog_+std::string("TransformParameters.0.txt"); int term_status = system(transformix_command.c_str()); if (WIFEXITED(term_status)) { // transformix completed successfully. Handle case here. // create new dimension vector for array (dimensions e.g. 3 256 256 72) - should also apply on 2D image std::vector<size_t> deformation_field_dims; deformation_field_dims.push_back(dimensions_of_image.size()); for (size_t i = 0; i < dimensions_of_image.size(); i++) { deformation_field_dims.push_back(dimensions_of_image.at(i)); } // create new array for deformation field image hoNDArray<float> deformation_field(&deformation_field_dims); std::string deformation_field_file_name = sPathLog_ + std::string("deformationField.mhd"); // read out image switch (dimensions_of_image.size()) { case 2: read_itk_to_hondarray<2>(deformation_field, deformation_field_file_name.c_str(), fixed_image.get_number_of_elements()); break; case 3: read_itk_to_hondarray<3>(deformation_field, deformation_field_file_name.c_str(), fixed_image.get_number_of_elements()); break; default: GERROR("Image dimension (%d) is neither 2D nor 3D! Abort.\n", dimensions_of_image.size()); return GADGET_FAIL; } // permute data (in ITK dim is: [value_vector size_x size_y size_z]) // we want to output: (layer with value_vector X component, layer with Y,...) // so: [value X Y Z] -> [X Y Z value] std::vector<size_t> new_dim_order; new_dim_order.push_back(1); new_dim_order.push_back(2); new_dim_order.push_back(3); new_dim_order.push_back(0); deformation_field = permute(deformation_field, new_dim_order); // save deformation fields for (size_t i = 0; i < dimensions_of_image.size(); i++) { const size_t df_offset = i * moving_image.get_number_of_elements(); const size_t output_df_offset = moving_image.get_number_of_elements() * ( // all slots (4th dimension 3D images) have same size, so multiply it with position) i * output_deformation_field.get_size(3) // select correct vector component (X|Y[|Z]) + (calculated_images - 1) // select correct image ); // and copy permuted data into great return image memcpy(output_deformation_field.get_data_ptr()+output_df_offset, deformation_field.get_data_ptr()+df_offset, moving_image.get_number_of_bytes()); } } else { GWARN("No deformation field for state %d available (Errors in transformix).\n", calculated_images); } } // clean up the elastix/transformix generated files std::vector<std::string> files_to_remove; files_to_remove.push_back(std::string("deformationField.mhd")); files_to_remove.push_back(std::string("deformationField.raw")); if (!log_output_) { files_to_remove.push_back(std::string("transformix.log")); } files_to_remove.push_back(std::string("TransformParameters.0.txt")); files_to_remove.push_back(std::string("IterationInfo.0.R0.txt")); files_to_remove.push_back(std::string("IterationInfo.0.R1.txt")); files_to_remove.push_back(std::string("IterationInfo.0.R2.txt")); files_to_remove.push_back(std::string("IterationInfo.0.R3.txt")); while (files_to_remove.size() > 0) { std::string file_to_remove = sPathLog_ + files_to_remove.back(); if (remove(file_to_remove.c_str()) != 0) { GWARN("Could not remove %s. Please delete it manually!\n", file_to_remove.c_str()); } // delete last element in list files_to_remove.pop_back(); } // free memory m2->release(); // new GadgetContainer GadgetContainerMessage<hoNDArray<float> > *cm2 = new GadgetContainerMessage<hoNDArray<float> >(); // concatenate data with header m1->cont(cm2); // create output try { cm2->getObjectPtr()->create(*output_image.get_dimensions()); } catch (std::runtime_error &err) { GEXCEPTION(err,"Unable to allocate new image array\n"); m1->release(); return GADGET_FAIL; } // copy data memcpy(cm2->getObjectPtr()->get_data_ptr(), output_image.get_data_ptr(), output_image.get_number_of_bytes()); // Now pass on image if (this->next()->putq(m1) < 0) { return GADGET_FAIL; } // ########## create deformation field message ########### // copy header GadgetContainerMessage<ISMRMRD::ImageHeader> *m1_df = new GadgetContainerMessage<ISMRMRD::ImageHeader>(); fCopyImageHeader(m1_df, m1->getObjectPtr()); // new GadgetContainer GadgetContainerMessage<hoNDArray<float> > *m2_df = new GadgetContainerMessage<hoNDArray<float> >(); // concatenate data with header m1_df->cont(m2_df); // create output try { m2_df->getObjectPtr()->create(*output_deformation_field.get_dimensions()); } catch (std::runtime_error &err) { GEXCEPTION(err,"Unable to allocate new deformation field array\n"); m1_df->release(); return GADGET_FAIL; } // copy data memcpy(m2_df->getObjectPtr()->get_data_ptr(), output_deformation_field.begin(), output_deformation_field.get_number_of_bytes()); // Now pass on deformation field if (this->next()->putq(m1_df) < 0) { return GADGET_FAIL; } return GADGET_OK; } GADGET_FACTORY_DECLARE(ElastixRegistrationGadget)
36.705882
235
0.71047
alwaysbefun123
1e9e457e811076929716813d2d8c2004010b2fe0
7,081
cxx
C++
test/rtkadjointoperatorstest.cxx
cyrilmory/CyrilsRTK
bb829a9d6aff45181d1642b4b050dde999169ff8
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
test/rtkadjointoperatorstest.cxx
cyrilmory/CyrilsRTK
bb829a9d6aff45181d1642b4b050dde999169ff8
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
test/rtkadjointoperatorstest.cxx
cyrilmory/CyrilsRTK
bb829a9d6aff45181d1642b4b050dde999169ff8
[ "Apache-2.0", "BSD-3-Clause" ]
null
null
null
#include "rtkMacro.h" #include "rtkTest.h" #include "itkRandomImageSource.h" #include "rtkConstantImageSource.h" #include "rtkJosephBackProjectionImageFilter.h" #include "rtkJosephForwardProjectionImageFilter.h" #ifdef RTK_USE_CUDA #include "rtkCudaForwardProjectionImageFilter.h" #include "rtkCudaRayCastBackProjectionImageFilter.h" #endif /** * \file rtkadjointoperatorstest.cxx * * \brief Tests whether forward and back projectors are matched * * This test generates a random volume "v" and a random set of projections "p", * and compares the scalar products <Rv , p> and <v, R* p>, where R is either the * Joseph forward projector or the Cuda ray cast forward projector, * and R* is either the Joseph back projector or the Cuda ray cast back projector. * If R* is indeed the adjoint of R, these scalar products are equal. * * \author Cyril Mory */ int main(int, char** ) { const unsigned int Dimension = 3; typedef float OutputPixelType; #ifdef USE_CUDA typedef itk::CudaImage< OutputPixelType, Dimension > OutputImageType; #else typedef itk::Image< OutputPixelType, Dimension > OutputImageType; #endif #if FAST_TESTS_NO_CHECKS const unsigned int NumberOfProjectionImages = 3; #else const unsigned int NumberOfProjectionImages = 180; #endif // Random image sources typedef itk::RandomImageSource< OutputImageType > RandomImageSourceType; RandomImageSourceType::Pointer randomVolumeSource = RandomImageSourceType::New(); RandomImageSourceType::Pointer randomProjectionsSource = RandomImageSourceType::New(); // Constant sources typedef rtk::ConstantImageSource< OutputImageType > ConstantImageSourceType; ConstantImageSourceType::Pointer constantVolumeSource = ConstantImageSourceType::New(); ConstantImageSourceType::Pointer constantProjectionsSource = ConstantImageSourceType::New(); // Image meta data RandomImageSourceType::PointType origin; RandomImageSourceType::SizeType size; RandomImageSourceType::SpacingType spacing; // Volume metadata origin[0] = -127.; origin[1] = -127.; origin[2] = -127.; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = 2; spacing[0] = 252.; spacing[1] = 252.; spacing[2] = 252.; #else size[0] = 64; size[1] = 64; size[2] = 64; spacing[0] = 4.; spacing[1] = 4.; spacing[2] = 4.; #endif randomVolumeSource->SetOrigin( origin ); randomVolumeSource->SetSpacing( spacing ); randomVolumeSource->SetSize( size ); randomVolumeSource->SetMin( 0. ); randomVolumeSource->SetMax( 1. ); randomVolumeSource->SetNumberOfThreads(2); //With 1, it's deterministic constantVolumeSource->SetOrigin( origin ); constantVolumeSource->SetSpacing( spacing ); constantVolumeSource->SetSize( size ); constantVolumeSource->SetConstant( 0. ); // Projections metadata origin[0] = -255.; origin[1] = -255.; origin[2] = -255.; #if FAST_TESTS_NO_CHECKS size[0] = 2; size[1] = 2; size[2] = NumberOfProjectionImages; spacing[0] = 504.; spacing[1] = 504.; spacing[2] = 504.; #else size[0] = 64; size[1] = 64; size[2] = NumberOfProjectionImages; spacing[0] = 8.; spacing[1] = 8.; spacing[2] = 8.; #endif randomProjectionsSource->SetOrigin( origin ); randomProjectionsSource->SetSpacing( spacing ); randomProjectionsSource->SetSize( size ); randomProjectionsSource->SetMin( 0. ); randomProjectionsSource->SetMax( 100. ); randomProjectionsSource->SetNumberOfThreads(2); //With 1, it's deterministic constantProjectionsSource->SetOrigin( origin ); constantProjectionsSource->SetSpacing( spacing ); constantProjectionsSource->SetSize( size ); constantProjectionsSource->SetConstant( 0. ); // Update all sources TRY_AND_EXIT_ON_ITK_EXCEPTION( randomVolumeSource->Update() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( constantVolumeSource->Update() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( randomProjectionsSource->Update() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( constantProjectionsSource->Update() ); // Geometry object typedef rtk::ThreeDCircularProjectionGeometry GeometryType; GeometryType::Pointer geometry = GeometryType::New(); for(unsigned int noProj=0; noProj<NumberOfProjectionImages; noProj++) geometry->AddProjection(600., 1200., noProj*360./NumberOfProjectionImages); for (unsigned int panel = 0; panel<2; panel++) { if (panel==0) std::cout << "\n\n****** Testing with flat panel ******" << std::endl; else { std::cout << "\n\n****** Testing with cylindrical panel ******" << std::endl; geometry->SetRadiusCylindricalDetector(200); } std::cout << "\n\n****** Joseph Forward projector ******" << std::endl; typedef rtk::JosephForwardProjectionImageFilter<OutputImageType, OutputImageType> JosephForwardProjectorType; JosephForwardProjectorType::Pointer fw = JosephForwardProjectorType::New(); fw->SetInput(0, constantProjectionsSource->GetOutput()); fw->SetInput(1, randomVolumeSource->GetOutput()); fw->SetGeometry( geometry ); TRY_AND_EXIT_ON_ITK_EXCEPTION( fw->Update() ); std::cout << "\n\n****** Joseph Back projector ******" << std::endl; typedef rtk::JosephBackProjectionImageFilter<OutputImageType, OutputImageType> JosephBackProjectorType; JosephBackProjectorType::Pointer bp = JosephBackProjectorType::New(); bp->SetInput(0, constantVolumeSource->GetOutput()); bp->SetInput(1, randomProjectionsSource->GetOutput()); bp->SetGeometry( geometry.GetPointer() ); TRY_AND_EXIT_ON_ITK_EXCEPTION( bp->Update() ); CheckScalarProducts<OutputImageType, OutputImageType>(randomVolumeSource->GetOutput(), bp->GetOutput(), randomProjectionsSource->GetOutput(), fw->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; #ifdef USE_CUDA std::cout << "\n\n****** Cuda Ray Cast Forward projector ******" << std::endl; typedef rtk::CudaForwardProjectionImageFilter<OutputImageType, OutputImageType> CudaForwardProjectorType; CudaForwardProjectorType::Pointer cfw = CudaForwardProjectorType::New(); cfw->SetInput(0, constantProjectionsSource->GetOutput()); cfw->SetInput(1, randomVolumeSource->GetOutput()); cfw->SetGeometry( geometry ); TRY_AND_EXIT_ON_ITK_EXCEPTION( cfw->Update() ); std::cout << "\n\n****** Cuda Ray Cast Back projector ******" << std::endl; typedef rtk::CudaRayCastBackProjectionImageFilter CudaRayCastBackProjectorType; CudaRayCastBackProjectorType::Pointer cbp = CudaRayCastBackProjectorType::New(); cbp->SetInput(0, constantVolumeSource->GetOutput()); cbp->SetInput(1, randomProjectionsSource->GetOutput()); cbp->SetGeometry( geometry.GetPointer() ); cbp->SetNormalize(false); TRY_AND_EXIT_ON_ITK_EXCEPTION( cbp->Update() ); CheckScalarProducts<OutputImageType, OutputImageType>(randomVolumeSource->GetOutput(), cbp->GetOutput(), randomProjectionsSource->GetOutput(), cfw->GetOutput()); std::cout << "\n\nTest PASSED! " << std::endl; #endif } return EXIT_SUCCESS; }
36.880208
167
0.71473
cyrilmory
1ea6dfec202cda0320e555a1851f1e84df6b819f
1,041
cpp
C++
userland/libraries/libc/stdio/sprintf.cpp
pro-hacker64/pranaOS
01e5f0ba7fc7b561a08ba60ea6b3890202ac97c7
[ "BSD-2-Clause" ]
null
null
null
userland/libraries/libc/stdio/sprintf.cpp
pro-hacker64/pranaOS
01e5f0ba7fc7b561a08ba60ea6b3890202ac97c7
[ "BSD-2-Clause" ]
null
null
null
userland/libraries/libc/stdio/sprintf.cpp
pro-hacker64/pranaOS
01e5f0ba7fc7b561a08ba60ea6b3890202ac97c7
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2021, krishpranav * * SPDX-License-Identifier: BSD-2-Clause */ // includes #include <pranaos/Printf.h> #include <stdio.h> #include <string.h> void string_printf_append(printf_info_t *info, char c) { if (info->allocated == -1) { strapd((char *)info->output, c); } else { strnapd((char *)info->output, c, info->allocated); } } int snprintf(char *s, size_t n, const char *fmt, ...) { va_list va; va_start(va, fmt); int result = vsnprintf(s, n, fmt, va); va_end(va); return result; } int vsnprintf(char *s, size_t n, const char *fmt, va_list va) { if (n == 0) { return 0; } printf_info_t info = {}; info.format = fmt; info.append = string_printf_append; info.output = s; info.allocated = n; s[0] = '\0'; return __printf(&info, va); } int sprintf(char *s, const char *fmt, ...) { va_list va; va_start(va, fmt); int result = vsnprintf(s, 65535, fmt, va); va_end(va); return result; }
16.265625
61
0.574448
pro-hacker64
1eb33682f3eb3cfd3ff55740a2c528520dbc0b1f
331
cpp
C++
C语言程序设计基础/meiju.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
63
2021-01-10T02:32:17.000Z
2022-03-30T04:08:38.000Z
C语言程序设计基础/meiju.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
2
2021-06-09T05:38:58.000Z
2021-12-14T13:53:54.000Z
C语言程序设计基础/meiju.cpp
xiabee/BIT-CS
5d8d8331e6b9588773991a872c259e430ef1eae1
[ "Apache-2.0" ]
20
2021-01-12T11:49:36.000Z
2022-03-26T11:04:58.000Z
#include<stdio.h> #include<math.h> double a,b,c,d; double f(double x) { return a*sin(x)*sin(x) + b*cos(x)*cos(x) + c*sin(x) + d*cos(x); } int main() { double L,R,i; scanf("%d%d%d%d%lf%lf",&a,&b,&c,&d,&L,&R); double ans=f(1); for(i=L; i<=R; i+=0.1) ans= f(i)>ans ? f(i) : ans; printf("%.1lf\n",ans); return 0; }
15.761905
44
0.519637
xiabee
1eb52945757c16dcf9574a6a9ddc466f0a3c729b
4,135
cpp
C++
opencl/test/unit_test/aub_tests/command_stream/copy_engine_aub_tests_xehp_and_later.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
opencl/test/unit_test/aub_tests/command_stream/copy_engine_aub_tests_xehp_and_later.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
opencl/test/unit_test/aub_tests/command_stream/copy_engine_aub_tests_xehp_and_later.cpp
mattcarter2017/compute-runtime
1f52802aac02c78c19d5493dd3a2402830bbe438
[ "Intel", "MIT" ]
null
null
null
/* * Copyright (C) 2022 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "opencl/test/unit_test/aub_tests/command_stream/copy_engine_aub_tests_xehp_and_later.h" #include "shared/test/common/test_macros/test.h" using namespace NEO; using SingleTileCopyEngineTests = CopyEngineXeHPAndLater<1>; HWTEST_F(SingleTileCopyEngineTests, givenNotCompressedBufferWhenBltExecutedThenCompressDataAndResolve) { givenNotCompressedBufferWhenBltExecutedThenCompressDataAndResolveImpl<FamilyType>(); } HWTEST_F(SingleTileCopyEngineTests, givenHostPtrWhenBlitCommandToCompressedBufferIsDispatchedThenCopiedDataIsValid) { givenHostPtrWhenBlitCommandToCompressedBufferIsDispatchedThenCopiedDataIsValidImpl<FamilyType>(); } HWTEST_F(SingleTileCopyEngineTests, givenDstHostPtrWhenBlitCommandFromCompressedBufferIsDispatchedThenCopiedDataIsValid) { givenDstHostPtrWhenBlitCommandFromCompressedBufferIsDispatchedThenCopiedDataIsValidImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenDstHostPtrWhenBlitCommandFromNotCompressedBufferIsDispatchedThenCopiedDataIsValid) { givenDstHostPtrWhenBlitCommandFromNotCompressedBufferIsDispatchedThenCopiedDataIsValidImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenSrcHostPtrWhenBlitCommandToNotCompressedBufferIsDispatchedThenCopiedDataIsValid) { givenSrcHostPtrWhenBlitCommandToNotCompressedBufferIsDispatchedThenCopiedDataIsValidImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenBufferWithOffsetWhenHostPtrBlitCommandIsDispatchedFromHostPtrThenDataIsCorrectlyCopied) { givenBufferWithOffsetWhenHostPtrBlitCommandIsDispatchedFromHostPtrThenDataIsCorrectlyCopiedImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenBufferWithOffsetWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopied) { givenBufferWithOffsetWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopiedImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenOffsetsWhenBltExecutedThenCopiedDataIsValid) { givenOffsetsWhenBltExecutedThenCopiedDataIsValidImpl<FamilyType>(); } HWTEST_F(SingleTileCopyEngineTests, givenSrcCompressedBufferWhenBlitCommandToDstCompressedBufferIsDispatchedThenCopiedDataIsValid) { givenSrcCompressedBufferWhenBlitCommandToDstCompressedBufferIsDispatchedThenCopiedDataIsValidImpl<FamilyType>(); } HWTEST_F(SingleTileCopyEngineTests, givenCompressedBufferWhenAuxTranslationCalledThenResolveAndCompress) { givenCompressedBufferWhenAuxTranslationCalledThenResolveAndCompressImpl<FamilyType>(); } using SingleTileCopyEngineSystemMemoryTests = CopyEngineXeHPAndLater<1, false>; HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineSystemMemoryTests, givenSrcSystemBufferWhenBlitCommandToDstSystemBufferIsDispatchedThenCopiedDataIsValid) { givenSrcSystemBufferWhenBlitCommandToDstSystemBufferIsDispatchedThenCopiedDataIsValidImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenReadBufferRectWithOffsetWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopied) { givenReadBufferRectWithOffsetWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopiedImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenWriteBufferRectWithOffsetWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopied) { givenWriteBufferRectWithOffsetWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopiedImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenCopyBufferRectWithOffsetWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopied) { givenCopyBufferRectWithOffsetWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopiedImpl<FamilyType>(); } HWCMDTEST_F(IGFX_XE_HP_CORE, SingleTileCopyEngineTests, givenCopyBufferRectWithBigSizesWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopied) { givenCopyBufferRectWithBigSizesWhenHostPtrBlitCommandIsDispatchedToHostPtrThenDataIsCorrectlyCopiedImpl<FamilyType>(); }
53.701299
158
0.903507
mattcarter2017
1eb76061f8a582692e239a691630e62fec3b3923
2,433
hxx
C++
opencascade/BRepBuilderAPI_VertexInspector.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/BRepBuilderAPI_VertexInspector.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
opencascade/BRepBuilderAPI_VertexInspector.hxx
mgreminger/OCP
92eacb99497cd52b419c8a4a8ab0abab2330ed42
[ "Apache-2.0" ]
null
null
null
// Created on: 2011-11-24 // Created by: ANNA MASALSKAYA // Copyright (c) 2011-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef BRepBuilderAPI_VertexInspector_HeaderFile #define BRepBuilderAPI_VertexInspector_HeaderFile #include <TColStd_ListOfInteger.hxx> #include <NCollection_Vector.hxx> #include <gp_XY.hxx> #include <gp_XYZ.hxx> #include <NCollection_CellFilter.hxx> typedef NCollection_Vector<gp_XYZ> VectorOfPoint; //======================================================================= //! Class BRepBuilderAPI_VertexInspector //! derived from NCollection_CellFilter_InspectorXYZ //! This class define the Inspector interface for CellFilter algorithm, //! working with gp_XYZ points in 3d space. //! Used in search of coincidence points with a certain tolerance. //======================================================================= class BRepBuilderAPI_VertexInspector : public NCollection_CellFilter_InspectorXYZ { public: typedef Standard_Integer Target; //! Constructor; remembers the tolerance BRepBuilderAPI_VertexInspector (const Standard_Real theTol):myTol(theTol*theTol) {} //! Keep the points used for comparison void Add (const gp_XYZ& thePnt) { myPoints.Append (thePnt); } //! Clear the list of adjacent points void ClearResList() { myResInd.Clear(); } //! Set current point to search for coincidence void SetCurrent (const gp_XYZ& theCurPnt) { myCurrent = theCurPnt; } //! Get list of indexes of points adjacent with the current const TColStd_ListOfInteger& ResInd() { return myResInd; } //! Implementation of inspection method Standard_EXPORT NCollection_CellFilter_Action Inspect (const Standard_Integer theTarget); private: Standard_Real myTol; TColStd_ListOfInteger myResInd; VectorOfPoint myPoints; gp_XYZ myCurrent; }; #endif
31.192308
92
0.722154
mgreminger
1eb8edac94392d03ea02d20df8a1f446909bb3ed
8,297
cpp
C++
src/uniform_spacetime_be_identity.cpp
zap150/besthea
b7a9bb80a936f380af2d2c2e7ee3cc713d3792ca
[ "BSD-3-Clause" ]
null
null
null
src/uniform_spacetime_be_identity.cpp
zap150/besthea
b7a9bb80a936f380af2d2c2e7ee3cc713d3792ca
[ "BSD-3-Clause" ]
null
null
null
src/uniform_spacetime_be_identity.cpp
zap150/besthea
b7a9bb80a936f380af2d2c2e7ee3cc713d3792ca
[ "BSD-3-Clause" ]
1
2021-09-15T01:59:34.000Z
2021-09-15T01:59:34.000Z
/* Copyright (c) 2020, VSB - Technical University of Ostrava and Graz University of Technology All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the names of VSB - Technical University of Ostrava and Graz University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL VSB - TECHNICAL UNIVERSITY OF OSTRAVA AND GRAZ UNIVERSITY OF TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "besthea/uniform_spacetime_be_identity.h" #include "besthea/basis_tri_p0.h" #include "besthea/basis_tri_p1.h" #include "besthea/quadrature.h" template< class test_space_type, class trial_space_type > besthea::bem::uniform_spacetime_be_identity< test_space_type, trial_space_type >::uniform_spacetime_be_identity( test_space_type & test_space, trial_space_type & trial_space, int order_regular ) : _data( ), _test_space( &test_space ), _trial_space( &trial_space ), _order_regular( order_regular ) { auto & test_basis = _test_space->get_basis( ); auto & trial_basis = _trial_space->get_basis( ); const auto & st_mesh = _test_space->get_mesh( ); set_block_dim( st_mesh.get_n_temporal_elements( ) ); set_dim_domain( trial_basis.dimension_global( ) ); set_dim_range( test_basis.dimension_global( ) ); } template< class test_space_type, class trial_space_type > besthea::bem::uniform_spacetime_be_identity< test_space_type, trial_space_type >::~uniform_spacetime_be_identity( ) { } template< class test_space_type, class trial_space_type > void besthea::bem::uniform_spacetime_be_identity< test_space_type, trial_space_type >::assemble( ) { std::vector< los > ii; std::vector< los > jj; std::vector< sc > vv; assemble_triplets( ii, jj, vv ); lo n_rows = _test_space->get_basis( ).dimension_global( ); lo n_columns = _trial_space->get_basis( ).dimension_global( ); _data.set_from_triplets( n_rows, n_columns, ii, jj, vv ); } template< class test_space_type, class trial_space_type > void besthea::bem::uniform_spacetime_be_identity< test_space_type, trial_space_type >::assemble( matrix_type & global_matrix ) const { std::vector< los > ii; std::vector< los > jj; std::vector< sc > vv; assemble_triplets( ii, jj, vv ); lo n_rows = _test_space->get_basis( ).dimension_global( ); lo n_columns = _trial_space->get_basis( ).dimension_global( ); global_matrix.set_from_triplets( n_rows, n_columns, ii, jj, vv ); } template< class test_space_type, class trial_space_type > void besthea::bem::uniform_spacetime_be_identity< test_space_type, trial_space_type >::assemble_triplets( std::vector< los > & ii, std::vector< los > & jj, std::vector< sc > & vv ) const { auto & test_basis = _test_space->get_basis( ); auto & trial_basis = _trial_space->get_basis( ); const auto & st_mesh = _test_space->get_mesh( ); sc timestep = st_mesh.get_timestep( ); lo n_loc_rows = test_basis.dimension_local( ); lo n_loc_columns = trial_basis.dimension_local( ); lo n_elements = st_mesh.get_n_spatial_elements( ); std::vector< lo > test_l2g( n_loc_rows ); std::vector< lo > trial_l2g( n_loc_columns ); ii.reserve( n_elements * n_loc_rows * n_loc_columns ); jj.reserve( n_elements * n_loc_rows * n_loc_columns ); vv.reserve( n_elements * n_loc_rows * n_loc_columns ); const std::vector< sc, besthea::allocator_type< sc > > & x1_ref = quadrature::triangle_x1( _order_regular ); const std::vector< sc, besthea::allocator_type< sc > > & x2_ref = quadrature::triangle_x2( _order_regular ); const std::vector< sc, besthea::allocator_type< sc > > & w = quadrature::triangle_w( _order_regular ); lo size = w.size( ); sc value, test, trial, area; linear_algebra::coordinates< 3 > n; for ( lo i_elem = 0; i_elem < n_elements; ++i_elem ) { st_mesh.get_spatial_normal( i_elem, n ); area = st_mesh.spatial_area( i_elem ); test_basis.local_to_global( i_elem, test_l2g ); trial_basis.local_to_global( i_elem, trial_l2g ); for ( lo i_loc_test = 0; i_loc_test < n_loc_rows; ++i_loc_test ) { for ( lo i_loc_trial = 0; i_loc_trial < n_loc_columns; ++i_loc_trial ) { value = 0.0; for ( lo i_quad = 0; i_quad < size; ++i_quad ) { test = test_basis.evaluate( i_elem, i_loc_test, x1_ref[ i_quad ], x2_ref[ i_quad ], n.data( ) ); trial = trial_basis.evaluate( i_elem, i_loc_trial, x1_ref[ i_quad ], x2_ref[ i_quad ], n.data( ) ); value += w[ i_quad ] * test * trial; } ii.push_back( test_l2g[ i_loc_test ] ); jj.push_back( trial_l2g[ i_loc_trial ] ); vv.push_back( value * timestep * area ); } } } } template< class test_space_type, class trial_space_type > void besthea::bem::uniform_spacetime_be_identity< test_space_type, trial_space_type >::apply( const block_vector_type & x, block_vector_type & y, bool trans, sc alpha, sc beta ) const { lo block_dim = ( _test_space->get_mesh( ) ).get_n_temporal_elements( ); for ( lo diag = 0; diag < block_dim; ++diag ) { _data.apply( x.get_block( diag ), y.get_block( diag ), trans, alpha, beta ); } } template< class test_space_type, class trial_space_type > void besthea::bem::uniform_spacetime_be_identity< test_space_type, trial_space_type >::apply( const distributed_block_vector_type & x, distributed_block_vector_type & y, bool trans, sc alpha, sc beta ) const { lo block_dim = ( _test_space->get_mesh( ) ).get_n_temporal_elements( ); for ( lo diag = 0; diag < block_dim; ++diag ) { if ( y.am_i_owner( diag ) && x.am_i_owner( diag ) ) { _data.apply( x.get_block( diag ), y.get_block( diag ), trans, alpha, beta ); } } } template class besthea::bem::uniform_spacetime_be_identity< besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p0 >, besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p0 > >; template class besthea::bem::uniform_spacetime_be_identity< besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p0 >, besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p1 > >; template class besthea::bem::uniform_spacetime_be_identity< besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p1 >, besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p1 > >; // Needed for L2 projection which is const template class besthea::bem::uniform_spacetime_be_identity< const besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p0 >, const besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p0 > >; template class besthea::bem::uniform_spacetime_be_identity< const besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p0 >, const besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p1 > >; template class besthea::bem::uniform_spacetime_be_identity< const besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p1 >, const besthea::bem::uniform_spacetime_be_space< besthea::bem::basis_tri_p1 > >;
44.368984
80
0.731951
zap150
1eb9d76983e39fb2b97243f0bf26b4d703fe6360
1,689
cpp
C++
src/RNG.cpp
komatura/Voltage-noise-generator
31332f9ae4a0ce5a2a259ad136b75d67831da637
[ "MIT" ]
null
null
null
src/RNG.cpp
komatura/Voltage-noise-generator
31332f9ae4a0ce5a2a259ad136b75d67831da637
[ "MIT" ]
null
null
null
src/RNG.cpp
komatura/Voltage-noise-generator
31332f9ae4a0ce5a2a259ad136b75d67831da637
[ "MIT" ]
1
2018-07-27T22:38:43.000Z
2018-07-27T22:38:43.000Z
#include "RNG.h" #include <chrono> unsigned int RNG::_seed = chrono::system_clock::now().time_since_epoch().count(); mt19937 RNG::_RNGBase; Real_RNG RNG::_floatGen = nullptr; Int_RNG RNG::_intGen = nullptr; Real_Normal_RNG RNG::_normalFloatGen = nullptr; void RNG::Initialize() { _RNGBase.seed(_seed); _floatGen.reset(new uniform_real_distribution<double>(0.0, 1.0)); _intGen.reset(new uniform_int_distribution<int>(0, 10000000)); _normalFloatGen.reset(new normal_distribution<double>(0, 0.2)); } void RNG::Clear() { _floatGen.release(); _intGen.release(); _normalFloatGen.release(); } void RNG::setMaxValue(const int& max) { uniform_int_distribution<int>::param_type params(0, max); _intGen->param(params); } int RNG::getInt() { return _intGen->operator()(_RNGBase); } int RNG::getInt(const int& max) { return (max / 100) * _intGen->operator()(_RNGBase); } int RNG::getInt(const int& min, const int& max) { return (max / 100) * _intGen->operator()(_RNGBase) + min; } double RNG::getDouble() { return _floatGen->operator()(_RNGBase); } double RNG::getDouble(const double& max) { return (max / 100.0) * _floatGen->operator()(_RNGBase); } double RNG::getDouble(const double& min, const double& max) { return (max / 100.0) * _floatGen->operator()(_RNGBase) + min; } unsigned int RNG::getSeed() { return _seed; } double RNG::getDoubleFloat() { return _normalFloatGen->operator()(_RNGBase); } void RNG::setSigma(const double& sigma) { // _normalFloatGen.reset(new normal_distribution<double>(0, sigma)); normal_distribution<double>::param_type params(0.0, sigma); _normalFloatGen->param(params); // _normalFloatGen->reset(); }
20.349398
81
0.703375
komatura
1ebd5ccb4500d7b1441fc1c721a0782502940cfe
876
cpp
C++
plugins/qnx/_hook_ui_color.cpp
mmuman/skinobe
c3aa05a650161d59749f9e468a5ee895fd8d6498
[ "MIT" ]
1
2019-03-01T05:32:17.000Z
2019-03-01T05:32:17.000Z
plugins/sequel/_hook_ui_color.cpp
mmuman/skinobe
c3aa05a650161d59749f9e468a5ee895fd8d6498
[ "MIT" ]
null
null
null
plugins/sequel/_hook_ui_color.cpp
mmuman/skinobe
c3aa05a650161d59749f9e468a5ee895fd8d6498
[ "MIT" ]
null
null
null
#include <stdio.h> #include <OS.h> #include <InterfaceDefs.h> #ifdef __cplusplus extern "C" { #endif static const rgb_color gonxColors[10] = { {0, 0, 0, 255}, // null color {239, 235, 231, 255}, // B_PANEL_BACKGROUND_COLOR {239, 235, 231, 255}, // B_MENU_BACKGROUND_COLOR {255, 203, 0, 255}, // B_WINDOW_TAB_COLOR //{115, 120, 184, 255}, // B_KEYBOARD_NAVIGATION_COLOR {80, 114, 154, 255}, // B_KEYBOARD_NAVIGATION_COLOR {51, 102, 152, 255}, // B_DESKTOP_COLOR {247, 247, 247, 255}, // B_MENU_SELECTION_BACKGROUND_COLOR {0, 0, 30, 255}, // B_MENU_ITEM_TEXT_COLOR {0, 0, 50, 255}, // B_MENU_SELECTED_ITEM_TEXT_COLOR {0, 255, 255, 255} // }; rgb_color hooked_ui_color__F11color_which(color_which which) { int iwhich = *(int *)&which; puts("ui_color() hook called"); if (iwhich < 0 || iwhich > 9) iwhich = 0; return gonxColors[iwhich]; } #ifdef __cplusplus } #endif
23.675676
60
0.689498
mmuman
3630afa4a87715974b8ec5b25ca81e148e323c96
994
cpp
C++
gym/102784/F.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
1
2021-07-16T19:59:39.000Z
2021-07-16T19:59:39.000Z
gym/102784/F.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
gym/102784/F.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <random> #include <chrono> using namespace std; using namespace __gnu_pbds; #define endl '\n' typedef long long ll; typedef pair<int, int> pii; // typedef tree<int, null_type,less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set; // mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); // template<typename T> // static T randint(T lo, T hi){ // return uniform_int_distribution<T>(lo, hi)(rng); // } int main(){ ios_base::sync_with_stdio(0); cin.tie(0); // freopen("settling.in", "r", stdin); // freopen("settling.out", "w", stdout); ll a, b; cin >> a >> b; ll ans = 0, num = 0; for(ll i = 62; i >= 0; i--){ ll b1 = (a & (1ll << i)) != 0; if(b1) ans += (1ll << i); else{ ll n_num = num | (1ll << i); if(n_num <= b){ num += (1ll << i); ans += (1ll << i); } } } cout << ans << endl; return 0; }
19.490196
102
0.603622
albexl
363177a43a385f5312278583ef45f023df1bc59c
22,100
cpp
C++
imdexp/src/ImdExp.cpp
olivierchatry/iri3d
cae98c61d9257546d0fc81e69709297d04a17a14
[ "MIT" ]
2
2022-01-02T08:12:29.000Z
2022-02-12T22:15:11.000Z
imdexp/src/ImdExp.cpp
olivierchatry/iri3d
cae98c61d9257546d0fc81e69709297d04a17a14
[ "MIT" ]
null
null
null
imdexp/src/ImdExp.cpp
olivierchatry/iri3d
cae98c61d9257546d0fc81e69709297d04a17a14
[ "MIT" ]
1
2022-01-02T08:09:51.000Z
2022-01-02T08:09:51.000Z
/******************************************************************** created: 2003/02/03 created: 4:2:2003 20:17 filename: e:\_dev\tmp\imdexp\src\imdexp.cpp file path: e:\_dev\tmp\imdexp\src file base: imdexp file ext: cpp author: Chatry Olivier alias gruiiik purpose: Main exporter function. *********************************************************************/ #include <stdafx.h> #include <imd2/imd2.hpp> #include <utility> /* * consttructor destructor */ ImdExp::ImdExp() : _material_list(0), _log(0) { } ImdExp::~ImdExp() { } ////////////////////////////////////////////////////////////////////////// /* * return pointer to max interface */ Interface *ImdExp::GetInterface() { return ip; } /* * give number of file extension handled by the plugin * for instance, we only handle imd file. */ int ImdExp::ExtCount() { return 1; } /* * give the string of given extension. * Because we handle only one extension, we * just return a string without any test. */ const TCHAR *ImdExp::Ext(int n) { return GetString(IDS_IMDEXTENSION); } /* * Long description of our plugin */ const TCHAR *ImdExp::LongDesc() { return GetString(IDS_LONGDESCRIPTION); } /* * Short description of our plugin */ const TCHAR *ImdExp::ShortDesc() { return GetString(IDS_SHORTDESCRIPTION); } /* * My name :) */ const TCHAR *ImdExp::AuthorName() { return GetString(IDS_ME); } /* * Stupid copyright (i hate copyright :)) message */ const TCHAR *ImdExp::CopyrightMessage() { return GetString(IDS_COPYRIGHT); } /* * Version of our plugin */ unsigned int ImdExp::Version() { return IMDEXP_VERSION; } ////////////////////////////////////////////////////////////////////////// // callback def. #include "callback.h" ////////////////////////////////////////////////////////////////////////// /* * About our plugin, just create a sample dialog box * from IDD_ABOUTBOX resource. */ void ImdExp::ShowAbout(HWND hwnd) { DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DIALOGABOUT), hwnd, AboutBoxDlgProc, 0); } /* * Other message function, return empty string */ const TCHAR *ImdExp::OtherMessage1() { return _T(""); } const TCHAR *ImdExp::OtherMessage2() { return _T(""); } void ImdExp::PopulateTreeView(HWND hwnd, INode *node, HTREEITEM parent) { _node_count++; if (node == 0) node = ip->GetRootNode(); char buffer[512]; ObjectState os = node->EvalWorldState(0); sprintf(buffer, "%s", node->GetName()); HTREEITEM me = AddNode(hwnd, IDC_TREESCENE, buffer, parent); for (int c = 0; c < node->NumberOfChildren(); c++) PopulateTreeView(hwnd, node->GetChildNode(c), me); } /* * Suported option, only export for instance. */ BOOL ImdExp::SupportsOptions(int ext, DWORD options) { assert(ext == 0); return (options == SCENE_EXPORT_SELECTED) ? TRUE : FALSE; } ////////////////////////////////////////////////////////////////////////// // utility function ////////////////////////////////////////////////////////////////////////// Modifier *ImdExp::FindModifier(INode *node, Class_ID &class_id) { Object *object = node->GetObjectRef(); if (object == 0) return 0; while (object->SuperClassID() == GEN_DERIVOB_CLASS_ID) { IDerivedObject *derived_object = static_cast<IDerivedObject *>(object); for (int mi = 0; mi < derived_object->NumModifiers(); ++mi) { Modifier *m = derived_object->GetModifier(mi); Loger::Get().Printf("[ImdExp::FindModifier] Find Modifier %s", m->GetName()); if (m->ClassID() == class_id) return m; } object = derived_object->GetObjRef(); } return 0; } ////////////////////////////////////////////////////////////////////////// // mesh importer ////////////////////////////////////////////////////////////////////////// void ImdExp::ImportMeshData(INode *node, ObjectState &os) { // import only triangular data. // bones are processed in another loop. if (!IsNodeBone(node)) ImportTriangularData(node, os); } Matrix3 ImdExp::GetNodeOffsetTM(INode *node) { Matrix3 offset_tm(1); Point3 pos = node->GetObjOffsetPos(); offset_tm.PreTranslate(pos); Quat quat = node->GetObjOffsetRot(); PreRotateMatrix(offset_tm, quat); ScaleValue scale_value = node->GetObjOffsetScale(); ApplyScaling(offset_tm, scale_value); return offset_tm; } /* * Export data */ void ImdExp::ImportDataFromMax(INode *node) { // node->Selected() ObjectState os = node->EvalWorldState(_plugin_config._begin_frame); if (os.obj) { switch (os.obj->SuperClassID()) { case GEOMOBJECT_CLASS_ID: ImportMeshData(node, os); break; case CAMERA_CLASS_ID: break; case LIGHT_CLASS_ID: ImportLightData(node, os); break; case SHAPE_CLASS_ID: break; case HELPER_CLASS_ID: case BONE_CLASS_ID: break; } } for (int c = 0; c < node->NumberOfChildren(); c++) ImportDataFromMax(node->GetChildNode(c)); } /* * Free all allocated data */ void ImdExp::FreeAll() { element_list_it_t it; Loger::Get().Print("++ [ImdExp::FreeAll]"); for (it = _elements.begin(); it != _elements.end(); ++it) delete (*it); _elements.resize(0); Loger::Get().Print("-- [ImdExp::FreeAll]"); } unsigned short ImdExp::CountElementOf(element_type type) { element_list_it_t it; unsigned short count = 0; for (it = _elements.begin(); it != _elements.end(); ++it) { if ((*it)->_type == type) count++; } return count; } std::string ImdExp::GetFilePath(std::string str) { size_t pos_sep = str.find_last_of("\\/"); return str.substr(0, pos_sep + 1); } std::string ImdExp::GetFileName(std::string str) { size_t pos_sep = str.find_last_of("\\/") + 1; return str.substr(pos_sep); } std::string ImdExp::GetFileNameWithoutExtension(std::string str) { size_t pos_sep = str.find_last_of("\\/") + 1; size_t pos_point = str.find_last_of("."); return str.substr(pos_sep, pos_point - pos_sep); } int ImdExp::TruncateValueToPower2(int value) { int bit = 32; while (bit--) if (value >> bit) return (1 << bit); return 0; } ////////////////////////////////////////////////////////////////////////// // write our imd2 file. void ImdExp::ExportImd2Material(imd2_object_t &object, std::string &path) { ImportedMaterial::material_data_list_it_t it; int count = 0; ilInit(); iluInit(); ilutInit(); iluImageParameter(ILU_FILTER, ILU_BILINEAR); for (it = _material_list->_material_data.begin(); it != _material_list->_material_data.end(); ++it) { MaterialData *material_data = *it; char *file_name_path; memset(object.imd2_material[count].file_name, 0, IMD2_MAX_NAME); file_name_path = material_data->_diffuse_map; if (file_name_path == 0) file_name_path = material_data->_env_map; if (file_name_path == 0) { _log->Printf("!!! Invalid texture file name for material %s\n", material_data->_name); continue; } // copy bitmap file to imd2 folder. std::string file_name = GetFileNameWithoutExtension(file_name_path); std::string new_file_name_path(path); file_name += ".png"; new_file_name_path += file_name; ILuint image_id; ilGenImages(1, &image_id); ilBindImage(image_id); iluLoadImage(file_name_path); int convert_width = TruncateValueToPower2(ilGetInteger(IL_IMAGE_WIDTH)); int convert_height = TruncateValueToPower2(ilGetInteger(IL_IMAGE_WIDTH)); int middle = 0; if (convert_height != convert_width) middle = TruncateValueToPower2((convert_width + convert_height) / 2); else middle = convert_width; if (middle > 512) middle = 512; if (middle < 8) middle = 8; ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); iluScale(middle, middle, 1); DeleteFile(new_file_name_path.c_str()); ilSaveImage((ILstring)new_file_name_path.c_str()); ilDeleteImages(1, &image_id); strncpy(object.imd2_material[count].file_name, file_name.c_str(), IMD2_MAX_NAME - 1); // defin material id !!! object.imd2_material[count].material_id = (int)(material_data); _log->Printf("inserting material file [%s]", object.imd2_material[count].file_name); material_data->_diffuse_map = strdup(new_file_name_path.c_str()); material_data->_env_map = 0; count++; } } void MatrixToFloatP(float *m, Matrix3 &max_mat) { Point3 p = max_mat.GetRow(0); m[0] = p.x; m[1] = p.y; m[2] = p.z; m[3] = 0.0f; p = max_mat.GetRow(1); m[4] = p.x; m[5] = p.y; m[6] = p.z; m[7] = 0.0f; p = max_mat.GetRow(2); m[8] = p.x; m[9] = p.y; m[10] = p.z; m[11] = 0.0f; p = max_mat.GetRow(3); m[12] = p.x; m[13] = p.y; m[14] = p.z; m[15] = 1.0f; } void ImdExp::ExportImd2Mesh(imd2_object_t &object) { element_list_it_t it; // allocate data object.imd2_object_header.have_skin = false; object.imd2_mesh = new imd2_mesh_t[object.imd2_object_header.num_mesh]; imd2_mesh_t *mesh = object.imd2_mesh; memset(mesh, 0, object.imd2_object_header.num_mesh * sizeof(imd2_mesh_t)); for (it = _elements.begin(); it != _elements.end(); ++it) { ImportedElements *el = *it; if (el->_type == mesh_element) { ImportedMesh *imesh = (ImportedMesh *)el; strncpy(mesh->imd2_mesh_header.name, imesh->_name.c_str(), IMD2_MAX_NAME - 1); size_t vertex_count = imesh->_mesh_data[0]._vertex.size(); mesh->imd2_mesh_header.num_vertex = (short)vertex_count; object.imd2_object_header.have_skin |= imesh->_skin != 0; mesh->imd2_mesh_header.have_skin = imesh->_skin != 0; mesh->user_data = new char[imesh->_user_properties.size() + 1]; strcpy(mesh->user_data, imesh->_user_properties.c_str()); mesh->imd2_mesh_header.material_id = (int)imesh->_material; mesh->imd2_face.num_section = (unsigned short)imesh->_strip.size(); mesh->imd2_face.imd2_section = new imd2_face_section_t[mesh->imd2_face.num_section]; for (int index_strip = 0; index_strip < mesh->imd2_face.num_section; ++index_strip) { mesh->imd2_face.imd2_section[index_strip].num_indice = (unsigned short)imesh->_strip[index_strip]._face_index.size(); mesh->imd2_face.imd2_section[index_strip].indice = new unsigned short[mesh->imd2_face.imd2_section[index_strip].num_indice]; for (size_t index_face = 0; index_face < imesh->_strip[index_strip]._face_index.size(); ++index_face) mesh->imd2_face.imd2_section[index_strip].indice[index_face] = imesh->_strip[index_strip]._face_index[index_face]; } ////////////////////////////////////////////////////////////////////////// // copy vertex data if (!_plugin_config._sample_matrix) { mesh->imd2_vertex = new imd2_vertex_t[vertex_count * object.imd2_object_header.num_anim]; mesh->imd2_matrix = 0; // save object matrix. for (int index_anim = 0; index_anim < object.imd2_object_header.num_anim; ++index_anim) for (size_t index_vertex = 0; index_vertex < vertex_count; ++index_vertex) { size_t offset = vertex_count * index_anim + index_vertex; MeshData &mesh_data = imesh->_mesh_data[index_anim]; std::swap(mesh_data._vertex[index_vertex].y, mesh_data._vertex[index_vertex].z); std::swap(mesh_data._normal[index_vertex].y, mesh_data._normal[index_vertex].z); mesh_data._vertex[index_vertex] = mesh_data._matrix * mesh_data._vertex[index_vertex]; Matrix3 tmp = mesh_data._matrix; tmp.NoTrans(); mesh_data._normal[index_vertex] = tmp * mesh_data._normal[index_vertex]; memcpy(mesh->imd2_vertex[offset].normal, mesh_data._normal[index_vertex], sizeof(float) * 3); memcpy(mesh->imd2_vertex[offset].pos, mesh_data._vertex[index_vertex], sizeof(float) * 3); uint r = (uint)(imesh->_mesh_color_mapping._color[index_vertex].x * 255) & 0xff; uint g = (uint)(imesh->_mesh_color_mapping._color[index_vertex].y * 255) & 0xff; uint b = (uint)(imesh->_mesh_color_mapping._color[index_vertex].z * 255) & 0xff; mesh->imd2_vertex[offset].color = (r << 16 | g << 8 | b); mesh->imd2_vertex[offset].uv[0] = imesh->_mesh_color_mapping._mapping[index_vertex]._uv.x; mesh->imd2_vertex[offset].uv[1] = 1.0f - imesh->_mesh_color_mapping._mapping[index_vertex]._uv.y; } } else { mesh->imd2_vertex = new imd2_vertex_t[vertex_count]; mesh->imd2_matrix = new imd2_matrix_t[object.imd2_object_header.num_anim]; for (size_t index_vertex = 0; index_vertex < vertex_count; ++index_vertex) { MeshData &mesh_data = imesh->_mesh_data[0]; std::swap(mesh_data._vertex[index_vertex].y, mesh_data._vertex[index_vertex].z); std::swap(mesh_data._normal[index_vertex].y, mesh_data._normal[index_vertex].z); memcpy(mesh->imd2_vertex[index_vertex].normal, mesh_data._normal[index_vertex], sizeof(float) * 3); memcpy(mesh->imd2_vertex[index_vertex].pos, mesh_data._vertex[index_vertex], sizeof(float) * 3); uint r = (uint)(imesh->_mesh_color_mapping._color[index_vertex].x * 255) & 0xff; uint g = (uint)(imesh->_mesh_color_mapping._color[index_vertex].y * 255) & 0xff; uint b = (uint)(imesh->_mesh_color_mapping._color[index_vertex].z * 255) & 0xff; mesh->imd2_vertex[index_vertex].color = (r << 16 | g << 8 | b); mesh->imd2_vertex[index_vertex].uv[0] = imesh->_mesh_color_mapping._mapping[index_vertex]._uv.x; mesh->imd2_vertex[index_vertex].uv[1] = 1.0f - imesh->_mesh_color_mapping._mapping[index_vertex]._uv.y; } for (int index_anim = 0; index_anim < object.imd2_object_header.num_anim; ++index_anim) { Matrix3 &max_mat = imesh->_mesh_data[index_anim]._matrix; float *m = mesh->imd2_matrix[index_anim].m; MatrixToFloatP(m, max_mat); } } ////////////////////////////////////////////////////////////////////////// // exporting skining information if needed; if (object.imd2_object_header.have_skin && imesh->_skin) { int skinned_vertex = 0; int count_bones = 0; // first count all bone linked to this vertex. int vertex_count = mesh->imd2_mesh_header.num_vertex; mesh->imd2_skin = new imd2_skin_t[vertex_count]; for (int index_vertex = 0; index_vertex != vertex_count; ++index_vertex) { count_bones = 0; ImportedSkin *skin = imesh->_skin; ImportedSkin::skin_data_list_t &s_list = skin->_skin_data; ImportedSkin::skin_data_list_it_t it(s_list.begin()); for (; it != s_list.end(); ++it) { std::vector<PointWeight>::iterator it_w(it->second._point_weight.begin()); for (; it_w != it->second._point_weight.end(); ++it_w) if (it_w->_point_index == index_vertex) count_bones++; } mesh->imd2_skin[index_vertex].num_bones_assigned = count_bones; mesh->imd2_skin[index_vertex].weight = new imd2_weight_t[count_bones]; count_bones = 0; it = s_list.begin(); for (; it != s_list.end(); ++it) { std::vector<PointWeight>::iterator it_w(it->second._point_weight.begin()); for (; it_w != it->second._point_weight.end(); ++it_w) if (it_w->_point_index == index_vertex) { int bone_index = it->second._bone_index; mesh->imd2_skin[index_vertex].weight[count_bones].weight = it_w->_weight; mesh->imd2_skin[index_vertex].weight[count_bones].bone_index = bone_index; count_bones++; skinned_vertex++; } } } mesh->imd2_mesh_header.num_skinned = skinned_vertex; } mesh++; } } object.imd2_object_header.num_bones = GetNumBones(ip->GetRootNode()); Loger::Get().Printf("End converting to imd2, Num bones = %d", object.imd2_object_header.num_bones); } void ImdExp::ExportImd2Tag(imd2_object_t &object) { element_list_it_t it; // allocate data object.imd2_tag = new imd2_tag_t[object.imd2_object_header.num_tag]; imd2_tag_t *tag = object.imd2_tag; memset(tag, 0, object.imd2_object_header.num_tag * sizeof(imd2_tag_t)); for (it = _elements.begin(); it != _elements.end(); ++it) { ImportedElements *el = *it; if (el->_type == tag_element) { ImportedTag *itag = (ImportedTag *)el; strncpy(tag->name, itag->_name.c_str(), IMD2_MAX_NAME - 1); tag->user_data = new char[itag->_user_properties.size() + 1]; tag->tag_data = new imd2_tag_data_t[object.imd2_object_header.num_anim]; strcpy(tag->user_data, itag->_user_properties.c_str()); for (int index_anim = 0; index_anim < object.imd2_object_header.num_anim; ++index_anim) { tag->tag_data[index_anim].pos[0] = itag->_tag_data[index_anim]->_pos.x; tag->tag_data[index_anim].pos[1] = itag->_tag_data[index_anim]->_pos.y; tag->tag_data[index_anim].pos[2] = itag->_tag_data[index_anim]->_pos.z; } tag++; } } } void ImdExp::SaveObjectFile(const TCHAR *c_file_name) { std::string file_name(c_file_name); std::string name; std::string path; imd2_object_t *object = new imd2_object_t; memset(object, 0, sizeof(imd2_object_t)); // got path. _file_name = file_name; object->imd2_object_header.matrix_sampling = _plugin_config._sample_matrix; _log->Printf("---------------------------"); name = GetFileNameWithoutExtension(file_name); _log->Printf("Object name = %s", name.c_str()); path = GetFilePath(file_name); _log->Printf("Path = %s", path.c_str()); strncpy(object->imd2_object_header.name, name.c_str(), IMD2_MAX_NAME - 1); object->imd2_object_header.num_anim = _plugin_config._end_frame - _plugin_config._begin_frame + 1; object->imd2_object_header.num_mesh = CountElementOf(mesh_element); if (_material_list == 0) object->imd2_object_header.num_material = 0; else { object->imd2_object_header.num_material = (unsigned short)_material_list->_material_data.size(); object->imd2_material = new imd2_material_t[object->imd2_object_header.num_material]; ExportImd2Material(*object, path); } object->imd2_object_header.num_tag = CountElementOf(tag_element); object->imd2_object_header.num_light = 0; // ountElementOf(light_element); // TODO. ExportImd2Mesh(*object); ExportImd2Tag(*object); save_imd2(object, c_file_name); free_imd2(object); } int ImdExp::GetNumBones(INode *node) { int count = 0; if (IsNodeBone(node)) count += 1; for (int i = 0; i < node->NumberOfChildren(); i++) count += GetNumBones(node->GetChildNode(i)); return count; } Matrix3 &ImdExp::FixCoordSys(Matrix3 &tm) { // swap 2nd and 3rd rows Point3 row = tm.GetRow(1); tm.SetRow(1, tm.GetRow(2)); tm.SetRow(2, row); // swap 2nd and 3rd columns Point4 column = tm.GetColumn(1); tm.SetColumn(1, tm.GetColumn(2)); tm.SetColumn(2, column); tm.SetRow(0, tm.GetRow(0)); tm.SetColumn(0, tm.GetColumn(0)); return tm; } Point3 &ImdExp::FixCoordSys(Point3 &pnt) { float tmp; tmp = pnt.y; pnt.y = pnt.z; pnt.z = tmp; return pnt; } void ImdExp::RecursiveSaveBone(imd2_bone_file_t *imd2_bone, BoneData *data, int &index, int parent) { imd2_bone->bones[index].imd2_bone_header.bone_index = data->_bone_index; imd2_bone->bones[index].imd2_bone_header.bone_parent = parent; memset(imd2_bone->bones[index].imd2_bone_header.name, 0, IMD2_MAX_NAME); strncpy(imd2_bone->bones[index].imd2_bone_header.name, data->_name.c_str(), IMD2_MAX_NAME - 1); imd2_bone->bones[index].imd2_bone_header.name[IMD2_MAX_NAME - 1] = 0; int anim_count = imd2_bone->imd2_bone_file_header.anim_count; imd2_bone->bones[index].imd2_bone_anim = new imd2_bone_anim_t[anim_count]; int parent_index = imd2_bone->bones[index].imd2_bone_header.bone_index; for (int i = 0; i < anim_count; ++i) { imd2_bone_anim_t *anim = &(imd2_bone->bones[index].imd2_bone_anim[i]); MatrixToFloatP(anim->matrix, data->_animation[i].matrix); } index++; size_t child_count = data->_bone_child.size(); for (size_t b = 0; b < child_count; ++b) RecursiveSaveBone(imd2_bone, &(data->_bone_child[b]), index, parent_index); } void ImdExp::SaveBoneFile(const TCHAR *c_file_name, ImportedBone *bones) { int bone_count = GetNumBones(ip->GetRootNode()); imd2_bone_file_t *imd2_bone = new imd2_bone_file_t; int index = 0; imd2_bone->imd2_bone_file_header.anim_count = _plugin_config._end_bone_frame - _plugin_config._begin_bone_frame + 1; imd2_bone->imd2_bone_file_header.bone_count = bone_count; imd2_bone->bones = new imd2_bone_t[bone_count]; for (size_t i = 0; i < bones->_bone_data.size(); ++i) { RecursiveSaveBone(imd2_bone, &(bones->_bone_data[i]), index); continue; } save_imd2_bone(imd2_bone, c_file_name); free_imd2_bone(imd2_bone); // count bones. } /* * Main export function */ int ImdExp::DoExport(const TCHAR *name, ExpInterface *ei, Interface *i, BOOL suppressPrompts /* =FALSE */, DWORD options /* =0 */) { BOOL showPrompts = suppressPrompts ? FALSE : TRUE; ip = i; _file_name = name; _bone_file_name = _file_name.substr(0, _file_name.find_last_of(".")); _bone_file_name += ".imdbone"; LoadConfig(); if (DialogBoxParam(hInstance, MAKEINTRESOURCE(IDD_DIALOGCONFIG), ip->GetMAXHWnd(), ExportDlgProc, (LPARAM)this) != IDOK) return 0; SaveConfig(); if (_plugin_config._log_window) { Loger::Get().Create(hInstance, _plugin_config._dos_log_window); Loger::Get().Show(); Loger::Get().EnableOk(false); } _log = &(Loger::Get()); if (_plugin_config._export_object) ImportDataFromMax(ip->GetRootNode()); // bones import if (_plugin_config._export_bones) { ImportedBone *bones = ImportBoneData(); if (bones != 0) { _elements.push_back(bones); SaveBoneFile(_bone_file_name.c_str(), bones); } } if (_plugin_config._export_object) SaveObjectFile(name); Loger::Get().EnableOk(); FreeAll(); return 1; }
33.283133
132
0.643891
olivierchatry
3635153692425bbee319815b8082362e37273878
380
cpp
C++
docs/mfc/codesnippet/CPP/cobarray-class_12.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
14
2018-01-28T18:10:55.000Z
2021-11-16T13:21:18.000Z
docs/mfc/codesnippet/CPP/cobarray-class_12.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
null
null
null
docs/mfc/codesnippet/CPP/cobarray-class_12.cpp
jmittert/cpp-docs
cea5a8ee2b4764b2bac4afe5d386362ffd64e55a
[ "CC-BY-4.0", "MIT" ]
2
2018-11-01T12:33:08.000Z
2021-11-16T13:21:19.000Z
CObArray arr; CAge* pa1; CAge* pa2; arr.Add(pa1 = new CAge(21)); // Element 0 arr.Add(pa2 = new CAge(40)); // Element 1 ASSERT(arr.GetSize() == 2); arr.RemoveAll(); // Pointers removed but objects not deleted. ASSERT(arr.GetSize() == 0); delete pa1; delete pa2; // Cleans up memory.
34.545455
70
0.5
jmittert
3639fe15dc674230ac5cc6730cbb3b449380b4ff
20,853
cpp
C++
DK/DKFoundation/DKStringW.cpp
Hongtae/DKGL
0dee0f0e211ad151db3943792ea29979cc8420f6
[ "BSD-3-Clause" ]
14
2015-09-12T01:32:05.000Z
2021-10-13T02:52:53.000Z
DK/DKFoundation/DKStringW.cpp
Hongtae/DKGL
0dee0f0e211ad151db3943792ea29979cc8420f6
[ "BSD-3-Clause" ]
null
null
null
DK/DKFoundation/DKStringW.cpp
Hongtae/DKGL
0dee0f0e211ad151db3943792ea29979cc8420f6
[ "BSD-3-Clause" ]
3
2015-11-10T03:12:49.000Z
2018-10-15T15:38:31.000Z
// // File: DKStringW.cpp // Author: Hongtae Kim ([email protected]) // // Copyright (c) 2004-2014 Hongtae Kim. All rights reserved. // #include <stdio.h> #include <stdarg.h> #include <string.h> #include <wctype.h> #include <wchar.h> #include "DKArray.h" #include "DKSet.h" #include "DKStringW.h" #include "DKStringU8.h" #include "DKBuffer.h" #ifdef _WIN32 #define wcstoll _wcstoi64 #define wcstoull _wcstoui64 #endif #ifdef __ANDROID__ #warning "CHECK 'wcstoll', 'wcstoull' FOR ANDROID!" long long int wcstoll(const wchar_t* str, wchar_t** endptr, int base) { return DKFoundation::DKStringU8(str).ToInteger(); } unsigned long long int wcstoull(const wchar_t* str, wchar_t** endptr, int base) { return DKFoundation::DKStringU8(str).ToUnsignedInteger(); } #endif namespace DKFoundation { namespace Private { namespace { const DKStringW::CharacterSet& WhitespaceCharacterSet(void) { static const struct WCSet { WCSet(void) { const DKUniCharW whitespaces[] = { 0x0009, 0x000a, 0x000b, 0x000c, 0x000d, 0x0020, 0x0085, 0x00a0, 0x1680, 0x180e, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 }; const size_t numChars = sizeof(whitespaces) / sizeof(DKUniCharW); set.Insert(whitespaces, numChars); } DKStringW::CharacterSet set; } whitespaceCharacterSet; return whitespaceCharacterSet.set; } inline DKUniCharW LowercaseChar(DKUniCharW c) { if (c >= L'A' && c <= L'Z') c = (c - L'A') + L'a'; return c; } inline int CompareCaseInsensitive(const DKUniCharW* a, const DKUniCharW* b) { if (a == b) return 0; if (a == NULL) a = L""; if (b == NULL) b = L""; const DKUniCharW *p = a; const DKUniCharW *q = b; int cmp = 0; for ( ; *p || *q; ++p, ++q) { cmp = LowercaseChar(*p) - LowercaseChar(*q); if (cmp != 0) return cmp; } return LowercaseChar(*p) - LowercaseChar(*q); } inline int CompareCaseSensitive(const DKUniCharW* a, const DKUniCharW* b) { if (a == b) return 0; if (a == NULL) a = L""; if (b == NULL) b = L""; const DKUniCharW *p = a; const DKUniCharW *q = b; int cmp = 0; for ( ; *p || *q; ++p, ++q) { cmp = (*p) - (*q); if (cmp != 0) return cmp; } return (*p) - (*q); } } } } using namespace DKFoundation; const DKStringW& DKStringW::EmptyString() { static DKStringW s = L""; return s; } DKStringEncoding DKStringW::SystemEncoding(void) { return DKStringWEncoding(); } // DKStringW class DKStringW::DKStringW(void) : stringData(NULL) { } DKStringW::DKStringW(DKStringW&& str) : stringData(NULL) { stringData = str.stringData; str.stringData = NULL; } DKStringW::DKStringW(const DKStringW& str) : stringData(NULL) { this->SetValue(str); } DKStringW::DKStringW(const DKUniCharW* str, size_t len) : stringData(NULL) { this->SetValue(str, len); } DKStringW::DKStringW(const DKUniChar8* str, size_t len) : stringData(NULL) { this->SetValue(str, len); } DKStringW::DKStringW(const void* str, size_t len, DKStringEncoding e) : stringData(NULL) { this->SetValue(str, len, e); } DKStringW::DKStringW(DKUniCharW c) : stringData(NULL) { this->SetValue(&c, 1); } DKStringW::DKStringW(DKUniChar8 c) : stringData(NULL) { this->SetValue(&c, 1); } DKStringW::~DKStringW(void) { if (stringData) DKMemoryHeapFree(stringData); } DKStringW DKStringW::Format(const DKUniChar8* fmt, ...) { DKStringW ret = L""; if (fmt && fmt[0]) { va_list ap; va_start(ap, fmt); ret = FormatV(fmt, ap); va_end(ap); } return ret; } DKStringW DKStringW::Format(const DKUniCharW* fmt, ...) { DKStringW ret = L""; if (fmt && fmt[0]) { va_list ap; va_start(ap, fmt); ret = FormatV(fmt, ap); va_end(ap); } return ret; } DKStringW DKStringW::FormatV(const DKUniChar8* fmt, va_list v) { DKStringW ret = L""; if (fmt && fmt[0]) { #ifdef __GNUC__ va_list v2; va_copy(v2, v); DKStringFormatV(ret, fmt, v); va_end(v2); #else DKStringFormatV(ret, fmt, v); #endif } return ret; } DKStringW DKStringW::FormatV(const DKUniCharW* fmt, va_list v) { DKStringW ret = L""; if (fmt && fmt[0]) { #ifdef __GNUC__ va_list v2; va_copy(v2, v); DKStringFormatV(ret, fmt, v); va_end(v2); #else DKStringFormatV(ret, fmt, v); #endif } return ret; } size_t DKStringW::Length(void) const { size_t len = 0; if (stringData) { while (stringData[len]) len++; } return len; } size_t DKStringW::Bytes(void) const { return Length() * sizeof(DKUniCharW); } long DKStringW::Find(DKUniCharW c, long begin) const { if (begin < 0) begin = 0; const DKUniCharW *data = stringData; size_t len = Length(); for (long i = begin; i < (long)len; ++i) { if (data[i] == c) return (long)i; } return -1; } long DKStringW::Find(const DKUniCharW* str, long begin) const { if (str == NULL) return -1; if (begin < 0) begin = 0; long strLength = (long)wcslen(str); long maxLength = (long)Length() - strLength; for (long i = begin; i <= maxLength; ++i) { if (wcsncmp(&stringData[i], str, strLength) == 0) return (long)i; } return -1; } long DKStringW::Find(const DKStringW& str, long begin) const { return Find((const DKUniCharW*)str, begin); } long DKStringW::FindWhitespaceCharacter(long begin) const { return FindAnyCharactersInSet(Private::WhitespaceCharacterSet(), begin); } long DKStringW::FindAnyCharactersInSet(const CharacterSet& cs, long begin) const { if (cs.Count() > 0) { size_t len = Length(); for (size_t i = begin; i < len; ++i) { if (cs.Contains(this->stringData[i])) return (long)i; } } return -1; } DKStringW DKStringW::Right(long index) const { DKStringW string; size_t len = Length(); if (index < (long)len) { if (index < 0) index = 0; int count = len - index; if (count < 0) count = 0; DKUniCharW* tmp = (DKUniCharW*)DKMemoryHeapAlloc((len+1) * sizeof(DKUniCharW)); memset(tmp, 0, sizeof(DKUniCharW) * (len+1)); wcsncpy(tmp, &stringData[index], count); string = tmp; DKMemoryHeapFree(tmp); } return string; } DKStringW DKStringW::Left(size_t count) const { DKStringW string; if (count > 0) { size_t len = Length(); if (count > len) count = len; DKUniCharW* tmp = (DKUniCharW*)DKMemoryHeapAlloc((len+1) * sizeof(DKUniCharW)); memset(tmp, 0 , sizeof(DKUniCharW) * (len+1)); wcsncpy(tmp, stringData, count); string = tmp; DKMemoryHeapFree(tmp); } return string; } DKStringW DKStringW::Mid(long index, size_t count) const { DKStringW string = L""; if (count == 0) return string; size_t len = Length(); if (count > 0 && index + count < len) { DKUniCharW* buff = (DKUniCharW*)DKMemoryHeapAlloc((count+1) * sizeof(DKUniCharW)); wcsncpy(buff, &stringData[index], count); buff[count] = 0; string = buff; DKMemoryHeapFree(buff); } else { string = Right(index); } return string; } DKStringW DKStringW::LowercaseString(void) const { if (stringData) { DKUniCharW *buff = (DKUniCharW*)DKMemoryHeapAlloc((Length()+1) * sizeof(DKUniCharW)); int i; for (i = 0 ; stringData[i] != 0; ++i) { buff[i] = towlower(stringData[i]); } buff[i] = 0; DKStringW ret = buff; DKMemoryHeapFree(buff); return ret; } return DKStringW(L""); } DKStringW DKStringW::UppercaseString(void) const { if (stringData) { DKUniCharW *buff = (DKUniCharW*)DKMemoryHeapAlloc((Length()+1) * sizeof(DKUniCharW)); int i; for (i = 0 ; stringData[i] != 0; ++i) { buff[i] = towupper(stringData[i]); } buff[i] = 0; DKStringW ret = buff; DKMemoryHeapFree(buff); return ret; } return DKStringW(L""); } int DKStringW::Compare(const DKUniCharW* str) const { return Private::CompareCaseSensitive(stringData, str); } int DKStringW::Compare(const DKStringW& str) const { return Private::CompareCaseSensitive(stringData, str.stringData); } int DKStringW::CompareNoCase(const DKUniCharW* str) const { return Private::CompareCaseInsensitive(stringData, str); } int DKStringW::CompareNoCase(const DKStringW& str) const { return Private::CompareCaseInsensitive(stringData, str.stringData); } int DKStringW::Replace(const DKUniCharW c1, const DKUniCharW c2) { if (!stringData) return 0; if (c1 == c2) return 0; int result = 0; if (c1) { if (c2) { for (size_t i = 0; stringData[i]; ++i) { if (stringData[i] == c1) { stringData[i] = c2; ++result; } } } else { size_t len = Length(); DKUniCharW* tmp = (DKUniCharW*)DKMemoryHeapAlloc((len+1) * sizeof(DKUniCharW)); size_t tmpLen = 0; for (size_t i = 0; stringData[i]; ++i) { if (stringData[i] == c1) ++result; else tmp[tmpLen++] = stringData[i]; } tmp[tmpLen] = 0; this->SetValue(tmp, tmpLen); DKMemoryHeapFree(tmp); } } return result; } int DKStringW::Replace(const DKUniCharW* strOld, const DKUniCharW* strNew) { if (strOld == NULL || strOld[0] == 0) return 0; size_t len = Length(); if (len == 0) return 0; if (strNew == NULL) strNew = L""; size_t len1 = (size_t)wcslen(strOld); if (len < len1) return 0; long index = Find(strOld); if (index < 0) return 0; DKStringW prev = Left(index) + strNew; DKStringW next = Right(index + len1); int ret = next.Replace(strOld, strNew) + 1; this->SetValue(prev + next); return ret; } int DKStringW::Replace(const DKStringW& src, const DKStringW& dst) { return Replace((const DKUniCharW*)src, (const DKUniCharW*)dst); } DKStringW& DKStringW::Insert(long index, const DKUniCharW* str) { if (str == NULL) return *this; size_t len = Length(); if (index > (long)len) { return Append(str); } int newStrLen = (int)wcslen(str); if (newStrLen) { DKUniCharW* tmp = (DKUniCharW*)DKMemoryHeapAlloc((len + newStrLen + 4) * sizeof(DKUniCharW)); memset(tmp, 0, sizeof(DKUniCharW) * (len + newStrLen + 4)); if (index > 0) { wcsncpy(tmp, stringData, index); } wcscat(tmp, str); wcscat(tmp, &stringData[index]); this->SetValue(tmp); DKMemoryHeapFree(tmp);; } return *this; } DKStringW& DKStringW::Insert(long index, DKUniCharW ch) { return Insert(index, (const DKUniCharW*)DKStringW(ch)); } DKStringW DKStringW::FilePathString(void) const { DKStringW str(*this); #ifdef _WIN32 str.Replace(L'/', L'\\'); #else str.Replace(L'\\', L'/'); #endif return str; } DKStringW DKStringW::FilePathStringByAppendingPath(const DKStringW& path) const { DKStringW str(*this); str.TrimWhitespaces(); size_t len = str.Length(); if (len > 0) { size_t pathLen = path.Length(); if (pathLen > 0) { const wchar_t* pathStr = path; while (pathStr[0] == L'/' || pathStr[0] == L'\\') pathStr++; if (pathStr[0]) { if (str[len - 1] != L'/' && str[len - 1] != L'\\') { str.Append(L"/"); } str.Append(pathStr); } } } else { str = path; str.TrimWhitespaces(); } return str.FilePathString(); } DKStringW DKStringW::LastPathComponent(void) const { DKStringW result = L"/"; StringArray strs = PathComponents(); size_t c = strs.Count(); if (c > 0) result = strs.Value(c - 1); return result; } DKStringW::StringArray DKStringW::PathComponents(void) const { CharacterSet cs = {L'/', L'\\'}; return SplitByCharactersInSet(cs, true); } bool DKStringW::IsWhitespaceCharacterAtIndex(long index) const { DKASSERT_DEBUG(Length() > index); return Private::WhitespaceCharacterSet().Contains(stringData[index]); } DKStringW& DKStringW::TrimWhitespaces(void) { size_t len = Length(); if (len == 0) return *this; size_t begin = 0; // finding whitespaces at beginning. while (begin < len) { if (!this->IsWhitespaceCharacterAtIndex(begin)) break; begin++; } if (begin < len) { size_t end = len-1; // finding whitespaces at ending. while (end > begin) { if (!this->IsWhitespaceCharacterAtIndex(end)) break; end--; } if (end >= begin) { DKStringW tmp = this->Mid(begin, end - begin + 1); return SetValue(tmp); } } else { // string is whitespaces entirely. return this->SetValue(L""); } return *this; } DKStringW& DKStringW::RemoveWhitespaces(long begin, long count) { begin = Max(begin, 0); size_t length = Length(); if (begin >= length) return *this; if (count < 0) count = length - begin; else count = Min<long>(length - begin, count); if (count <= 0) return *this; DKUniCharW* buffer = (DKUniCharW*)DKMemoryHeapAlloc((count+2) * sizeof(DKUniCharW)); size_t bufferIndex = 0; for (long i = 0; i < count; i++) { if (!IsWhitespaceCharacterAtIndex(i + begin)) { buffer[bufferIndex++] = stringData[i+begin]; } } buffer[bufferIndex] = NULL; DKStringW tmp = DKStringW(buffer) + Right(begin + count); DKMemoryHeapFree(buffer); return *this = tmp; } bool DKStringW::HasPrefix(const DKStringW& str) const { return str.Compare(this->Left( str.Length() )) == 0; } bool DKStringW::HasSuffix(const DKStringW& str) const { return str.Compare(this->Right( this->Length() - str.Length() )) == 0; } DKStringW& DKStringW::RemovePrefix(const DKStringW& str) { if (HasPrefix(str)) { this->SetValue( this->Right( str.Length() ) ); } return *this; } DKStringW& DKStringW::RemoveSuffix(const DKStringW& str) { if (HasSuffix(str)) { this->SetValue( this->Left( this->Length() - str.Length()) ); } return *this; } DKStringW& DKStringW::Append(const DKStringW& str) { return Append((const DKUniCharW*)str); } DKStringW& DKStringW::Append(const DKUniCharW* str, size_t len) { if (str && str[0]) { size_t len1 = Length(); size_t len2 = 0; for (len2 = 0; str[len2] && len2 < len; len2++) {} size_t totalLen = len1 + len2; if (totalLen > 0) { DKUniCharW* buff = (DKUniCharW*)DKMemoryHeapAlloc((len1 + len2 + 1) * sizeof(DKUniCharW)); memset(buff, 0, sizeof(DKUniCharW) * (len1 + len2 + 1)); if (stringData && stringData[0]) { wcscat(buff, stringData); //wcscat_s(pNewBuff, nLen+nLen2+4, stringData); } wcscat(buff, str); //wcscat_s(pNewBuff, nLen+nLen2+4, str); if (stringData) DKMemoryHeapFree(stringData); stringData = buff; } } return *this; } DKStringW& DKStringW::Append(const DKUniChar8* str, size_t len) { DKStringW s = L""; DKStringSetValue(s, str, len); return this->Append(s); } DKStringW& DKStringW::Append(const void* str, size_t bytes, DKStringEncoding e) { DKStringW s = L""; DKStringSetValue(s, str, bytes, e); return this->Append(s); } DKStringW& DKStringW::SetValue(const DKStringW& str) { if (str.stringData == this->stringData) return *this; if (this->stringData) DKMemoryHeapFree(this->stringData); this->stringData = NULL; size_t len = str.Length(); if (len > 0) { DKASSERT_DEBUG(str.stringData != NULL); this->stringData = (DKUniCharW*)DKMemoryHeapAlloc((len+1) * sizeof(DKUniCharW)); wcscpy(this->stringData, str.stringData); } return *this; } DKStringW& DKStringW::SetValue(const DKUniCharW* str, size_t len) { if (str == stringData && len >= this->Length()) return *this; DKUniCharW* buff = NULL; if (str && str[0]) { for (size_t i = 0; i < len; ++i) { if (str[i] == 0) { len = i; break; } } if (len > 0) { buff = (DKUniCharW*)DKMemoryHeapAlloc((len+1) * sizeof(DKUniCharW)); memcpy(buff, str, len * sizeof(DKUniCharW)); buff[len] = NULL; } } if (stringData) DKMemoryHeapFree(stringData); stringData = buff; return *this; } DKStringW& DKStringW::SetValue(const DKUniChar8* str, size_t len) { if (str && str[0]) DKStringSetValue(*this, str, len); else SetValue((const DKUniCharW*)NULL, 0); return *this; } DKStringW& DKStringW::SetValue(const void* str, size_t bytes, DKStringEncoding e) { DKStringSetValue(*this, str, bytes, e); return *this; } // assignment operators DKStringW& DKStringW::operator = (DKStringW&& str) { if (this != &str) { if (stringData) DKMemoryHeapFree(stringData); stringData = str.stringData; str.stringData = NULL; } return *this; } DKStringW& DKStringW::operator = (const DKStringW& str) { if (this != &str) return this->SetValue(str); return *this; } DKStringW& DKStringW::operator = (const DKUniCharW* str) { return this->SetValue(str); } DKStringW& DKStringW::operator = (const DKUniChar8* str) { return this->SetValue(str); } DKStringW& DKStringW::operator = (DKUniCharW ch) { return this->SetValue(&ch, 1); } DKStringW& DKStringW::operator = (DKUniChar8 ch) { return this->SetValue(&ch, 1); } // conversion operators DKStringW::operator const DKUniCharW*(void) const { if (this && this->stringData) return (const DKUniCharW*)this->stringData; return L""; } // concatention operators DKStringW& DKStringW::operator += (const DKStringW& str) { return Append(str); } DKStringW& DKStringW::operator += (const DKUniCharW* str) { return Append(str); } DKStringW& DKStringW::operator += (const DKUniChar8* str) { return Append(str); } DKStringW& DKStringW::operator += (DKUniCharW ch) { return Append(&ch, 1); } DKStringW& DKStringW::operator += (DKUniChar8 ch) { return Append(&ch, 1); } DKStringW DKStringW::operator + (const DKStringW& str) const { return DKStringW(*this).Append(str); } DKStringW DKStringW::operator + (const DKUniCharW* str) const { return DKStringW(*this).Append(str); } DKStringW DKStringW::operator + (const DKUniChar8* str) const { return DKStringW(*this).Append(str); } DKStringW DKStringW::operator + (DKUniCharW c) const { return DKStringW(*this).Append(&c, 1); } DKStringW DKStringW::operator + (DKUniChar8 c) const { return DKStringW(*this).Append(&c, 1); } DKObject<DKData> DKStringW::Encode(DKStringEncoding e) const { DKObject<DKBuffer> data = DKObject<DKBuffer>::New(); DKStringEncode(data, *this, e); return data.SafeCast<DKData>(); } long long DKStringW::ToInteger(void) const { if (stringData && stringData[0]) return wcstoll(stringData, 0, 0); return 0LL; } unsigned long long DKStringW::ToUnsignedInteger(void) const { if (stringData && stringData[0]) return wcstoull(stringData, 0, 0); return 0ULL; } double DKStringW::ToRealNumber(void) const { if (stringData && stringData[0]) return wcstod(stringData, 0); return 0.0; } DKStringW::IntegerArray DKStringW::ToIntegerArray(const DKStringW& delimiter, bool ignoreEmptyString) const { StringArray strings = Split(delimiter, ignoreEmptyString); IntegerArray result; result.Reserve(strings.Count()); for (size_t i = 0; i < strings.Count(); ++i) result.Add(strings.Value(i).ToInteger()); return result; } DKStringW::UnsignedIntegerArray DKStringW::ToUnsignedIntegerArray(const DKStringW& delimiter, bool ignoreEmptyString) const { StringArray strings = Split(delimiter, ignoreEmptyString); UnsignedIntegerArray result; result.Reserve(strings.Count()); for (size_t i = 0; i < strings.Count(); ++i) result.Add(strings.Value(i).ToUnsignedInteger()); return result; } DKStringW::RealNumberArray DKStringW::ToRealNumberArray(const DKStringW& delimiter, bool ignoreEmptyString) const { StringArray strings = Split(delimiter, ignoreEmptyString); RealNumberArray result; result.Reserve(strings.Count()); for (size_t i = 0; i < strings.Count(); ++i) result.Add(strings.Value(i).ToRealNumber()); return result; } DKStringW::StringArray DKStringW::Split(const DKStringW& delimiter, bool ignoreEmptyString) const { StringArray strings; size_t len = Length(); size_t dlen = delimiter.Length(); if (dlen == 0) { strings.Add(*this); return strings; } long begin = 0; while (begin < len) { long next = this->Find(delimiter, begin); if (next >= begin) { DKStringW subString = this->Mid(begin, next - begin); if (ignoreEmptyString == false || subString.Length() > 0) strings.Add(this->Mid(begin, next - begin)); begin = next + dlen; } else { DKStringW subString = this->Right(begin); if (subString.Length() > 0) strings.Add(subString); break; } } return strings; } DKStringW::StringArray DKStringW::SplitByCharactersInSet(const CharacterSet& cs, bool ignoreEmptyString) const { StringArray strings; size_t len = Length(); size_t numCs = cs.Count(); if (numCs == 0) { strings.Add(*this); return strings; } long begin = 0; while (begin < len) { long next = this->FindAnyCharactersInSet(cs, begin); if (next >= begin) { DKStringW subString = this->Mid(begin, next - begin); if (ignoreEmptyString == false || subString.Length() > 0) strings.Add(subString); begin = next + 1; } else { DKStringW subString = this->Right(begin); if (subString.Length() > 0) strings.Add(subString); break; } } return strings; } DKStringW::StringArray DKStringW::SplitByWhitespace(void) const { return SplitByCharactersInSet(Private::WhitespaceCharacterSet(), true); }
19.525281
123
0.659617
Hongtae
363b6761c2d571e3c8242874aae14ffecb346baa
6,677
cpp
C++
Lambgine/lua/LambLua.cpp
lambage/Lambgine
e59836015469db797ef4706e42f65bebecfd86df
[ "MIT" ]
null
null
null
Lambgine/lua/LambLua.cpp
lambage/Lambgine
e59836015469db797ef4706e42f65bebecfd86df
[ "MIT" ]
null
null
null
Lambgine/lua/LambLua.cpp
lambage/Lambgine
e59836015469db797ef4706e42f65bebecfd86df
[ "MIT" ]
null
null
null
#include <stdafx.h> #include "LambLua.h" #include <Lambgine.h> extern "C" { #include <lua.h> #include <lualib.h> #include <lauxlib.h> } #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "LuaTest.h" #include <luacppinterface.h> #define EXIT_CONDITION -2 #if !defined(LUA_PROMPT) #define LUA_PROMPT "> " #define LUA_PROMPT2 ">> " #endif #define LUA_PROGNAME "lua" #define LUA_MAXINPUT 512 #include <io.h> #include <stdio.h> #define lua_stdin_is_tty() _isatty(_fileno(stdin)) #define lua_readline(L,b,p) \ ((void)L, fputs(p, stdout), fflush(stdout), /* show prompt */ \ fgets(b, LUA_MAXINPUT, stdin) != NULL) /* get line */ #define lua_saveline(L,idx) { (void)L; (void)idx; } #define lua_freeline(L,b) { (void)L; (void)b; } #include <stdio.h> #define luai_writestring(s,l) fwrite((s), sizeof(char), (l), stdout) #define luai_writeline() (luai_writestring("\n", 1), fflush(stdout)) static lua_State *globalL = NULL; static const char *progname = LUA_PROGNAME; /* mark in error messages for incomplete statements */ #define EOFMARK "<eof>" #define marklen (sizeof(EOFMARK)/sizeof(char) - 1) struct LambLua::LambLuaImpl { std::shared_ptr<lua_State> L = nullptr; Lua lua; LambLuaImpl() : L(luaL_newstate(), lua_close), lua(L) { lua.LoadStandardLibraries(); OpenTest(&lua); } ~LambLuaImpl() { if (L.get() != nullptr) { lua_close(L.get()); } } static void lstop(lua_State *L, lua_Debug *ar) { (void)ar; /* unused arg. */ lua_sethook(L, NULL, 0, 0); luaL_error(L, "interrupted!"); } static void laction(int i) { signal(i, SIG_DFL); /* if another SIGINT happens before lstop, terminate process (default action) */ lua_sethook(globalL, lstop, LUA_MASKCALL | LUA_MASKRET | LUA_MASKCOUNT, 1); } static void l_message(const char *pname, const char *msg) { if (pname) luai_writestringerror("%s: ", pname); luai_writestringerror("%s\n", msg); } static int report(lua_State *L, int status) { if (status != LUA_OK && !lua_isnil(L, -1)) { const char *msg = lua_tostring(L, -1); if (msg == NULL) msg = "(error object is not a string)"; l_message(progname, msg); lua_pop(L, 1); /* force a complete garbage collection in case of errors */ lua_gc(L, LUA_GCCOLLECT, 0); } return status; } /* the next function is called unprotected, so it must avoid errors */ static void finalreport(lua_State *L, int status) { if (status != LUA_OK) { const char *msg = (lua_type(L, -1) == LUA_TSTRING) ? lua_tostring(L, -1) : NULL; if (msg == NULL) msg = "(error object is not a string)"; l_message(progname, msg); lua_pop(L, 1); } } static int traceback(lua_State *L) { const char *msg = lua_tostring(L, 1); if (msg) luaL_traceback(L, L, msg, 1); else if (!lua_isnoneornil(L, 1)) { /* is there an error object? */ if (!luaL_callmeta(L, 1, "__tostring")) /* try its 'tostring' metamethod */ lua_pushliteral(L, "(no error message)"); } return 1; } static int docall(lua_State *L, int narg, int nres) { int status; int base = lua_gettop(L) - narg; /* function index */ lua_pushcfunction(L, traceback); /* push traceback function */ lua_insert(L, base); /* put it under chunk and args */ globalL = L; /* to be available to 'laction' */ signal(SIGINT, laction); status = lua_pcall(L, narg, nres, base); signal(SIGINT, SIG_DFL); lua_remove(L, base); /* remove traceback function */ return status; } static const char *get_prompt(lua_State *L, int firstline) { const char *p; lua_getglobal(L, firstline ? "_PROMPT" : "_PROMPT2"); p = lua_tostring(L, -1); if (p == NULL) p = (firstline ? LUA_PROMPT : LUA_PROMPT2); return p; } static int incomplete(lua_State *L, int status) { if (status == LUA_ERRSYNTAX) { size_t lmsg; const char *msg = lua_tolstring(L, -1, &lmsg); if (lmsg >= marklen && strcmp(msg + lmsg - marklen, EOFMARK) == 0) { lua_pop(L, 1); return 1; } } return 0; /* else... */ } static int pushline(lua_State *L, int firstline) { char buffer[LUA_MAXINPUT]; char *b = buffer; size_t l; const char *prmt = get_prompt(L, firstline); int readstatus = lua_readline(L, b, prmt); lua_pop(L, 1); /* remove result from 'get_prompt' */ if (readstatus == 0) return 0; /* no input */ l = strlen(b); if (l > 0 && b[l - 1] == '\n') /* line ends with newline? */ b[l - 1] = '\0'; /* remove it */ if (firstline && b[0] == '=') /* first line starts with `=' ? */ lua_pushfstring(L, "return %s", b + 1); /* change it to `return' */ else lua_pushstring(L, b); lua_freeline(L, b); return 1; } static int loadline(lua_State *L) { int status; lua_settop(L, 0); if (!pushline(L, 1)) return -1; /* no input */ for (;;) { /* repeat until gets a complete line */ size_t l; const char *line = lua_tolstring(L, 1, &l); if (strcmp(line, "q") == 0 || strcmp(line, "exit") == 0 || strcmp(line, "quit") == 0 || strcmp(line, "qut") == 0) { return EXIT_CONDITION; } status = luaL_loadbuffer(L, line, l, "=stdin"); if (!incomplete(L, status)) break; /* cannot try to add lines? */ if (!pushline(L, 0)) /* no more input? */ return -1; lua_pushliteral(L, "\n"); /* add a new line... */ lua_insert(L, -2); /* ...between the two lines */ lua_concat(L, 3); /* join them */ } lua_saveline(L, 1); lua_remove(L, 1); /* remove line */ return status; } int DoTerminal() { int status; const char *oldprogname = progname; progname = NULL; while ((status = loadline(L.get())) != -1) { if (status == EXIT_CONDITION) { lua_settop(L.get(), 0); /* clear stack */ luai_writeline(); progname = oldprogname; return LUA_OK; } if (status == LUA_OK) status = docall(L.get(), 0, LUA_MULTRET); report(L.get(), status); if (status == LUA_OK && lua_gettop(L.get()) > 0) { /* any result to print? */ luaL_checkstack(L.get(), LUA_MINSTACK, "too many results to print"); lua_getglobal(L.get(), "print"); lua_insert(L.get(), 1); if (lua_pcall(L.get(), lua_gettop(L.get()) - 1, 0, 0) != LUA_OK) l_message(progname, lua_pushfstring(L.get(), "error calling " LUA_QL("print") " (%s)", lua_tostring(L.get(), -1))); } } lua_settop(L.get(), 0); /* clear stack */ luai_writeline(); progname = oldprogname; return status; } }; LAMBGINE_API LambLua::LambLua() : mImpl(std::make_unique<LambLua::LambLuaImpl>()) { } LAMBGINE_API LambLua::~LambLua() { } LAMBGINE_API lua_State* LambLua::GetLuaState() { return mImpl->L.get(); } LAMBGINE_API int LambLua::DoTerminal() { return mImpl->DoTerminal(); }
25.779923
116
0.62603
lambage
364297fd6ce094d48185ede26f277e964433fe8c
163
hpp
C++
src/components/tower_preview.hpp
Green-Sky/miniTD
b710c0e312dcd44ed3ac797c9b7931ab54972c3a
[ "MIT" ]
7
2022-01-27T17:11:23.000Z
2022-03-29T12:09:26.000Z
src/components/tower_preview.hpp
Green-Sky/miniTD
b710c0e312dcd44ed3ac797c9b7931ab54972c3a
[ "MIT" ]
null
null
null
src/components/tower_preview.hpp
Green-Sky/miniTD
b710c0e312dcd44ed3ac797c9b7931ab54972c3a
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> namespace mini_td::Components { struct TowerPreview { float time_accu {0.f}; uint16_t art {0}; }; } // mini_td::Components
10.866667
31
0.693252
Green-Sky
364a380c82e0b3bcd721ef5f9dbe562cc00723b6
2,761
hpp
C++
include/eve/function/fdim.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
340
2020-09-16T21:12:48.000Z
2022-03-28T15:40:33.000Z
include/eve/function/fdim.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
383
2020-09-17T06:56:35.000Z
2022-03-13T15:58:53.000Z
include/eve/function/fdim.hpp
leha-bot/eve
30e7a7f6bcc5cf524a6c2cc624234148eee847be
[ "MIT" ]
28
2021-02-27T23:11:23.000Z
2022-03-25T12:31:29.000Z
//================================================================================================== /* EVE - Expressive Vector Engine Copyright : EVE Contributors & Maintainers SPDX-License-Identifier: MIT */ //================================================================================================== #pragma once #include <eve/detail/overload.hpp> namespace eve { //================================================================================================ //! @addtogroup arithmetic //! @{ //! @var fdim //! //! @brief Callable object computing the positive difference. //! //! **Required header:** `#include <eve/function/fdim.hpp>` //! //! #### Members Functions //! //! | Member | Effect | //! |:-------------|:-----------------------------------------------------------| //! | `operator()` | the fdim operation | //! | `operator[]` | Construct a conditional version of current function object | //! //! --- //! //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} //! template< real_value T, real_value U> auto operator()( T x, U y ) const noexcept //! requires compatible< T, U >; //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! //! **Parameters** //! //!`x`, `y`: [values](@ref eve::value) //! //! **Return value** //! //!Returns the [elementwise](@ref glossary_elementwise) positive difference between `x` and `y`: //! * if `x>y`, x-y is returned //! * if `x<=y`, +0 is returned //! * otherwise a `Nan` is returned //! //! --- //! //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} //! auto operator[]( conditional_expression auto cond ) const noexcept; //! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //! //! Higher-order function generating a masked version of eve::fdim //! //! **Parameters** //! //! `cond` : conditional expression //! //! **Return value** //! //! A Callable object so that the expression `fdim[cond](x, ...)` is equivalent to `if_else(cond,fdim(x, ...),x)` //! //! --- //! //! #### Supported decorators //! //! * eve::diff<br> //! **Required header:** `#include <eve/function/diff/fdim.hpp>` //! //! The expression `diff_1st(fim)(x,y)` and `diff_2nd(fim)(x,y)` computes the partial //! derivatives of \f$f\f$, where \f$f\f$ is the function \f$(x,y) \rightarrow \ \max(0,x-y)\f$. //! //! #### Example //! //! @godbolt{doc/core/fdim.cpp} //! //! @} //================================================================================================ EVE_MAKE_CALLABLE(fdim_, fdim); } #include <eve/module/real/core/function/regular/generic/fdim.hpp>
32.869048
116
0.410721
leha-bot
36506db240e2bb5b7778bf27e3b97cb1da5ac004
1,632
cpp
C++
cf/contest/1504/e/e.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
cf/contest/1504/e/e.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
cf/contest/1504/e/e.cpp
woshiluo/oi
5637fb81b0e25013314783dc387f7fc93bf9d4b9
[ "Apache-2.0" ]
null
null
null
// Woshiluo<[email protected]> // 2021/04/03 22:59:31 // Blog: https://blog.woshiluo.com #include <cstdio> #include <cstdlib> #include <cstring> #include <queue> #include <iostream> #include <algorithm> typedef long long ll; typedef unsigned long long ull; template <class T> T Max( T a, T b ) { return a > b? a: b; } template <class T> T Min( T a, T b ) { return a < b? a: b; } template <class T> void chk_Max( T &a, T b ) { if( b > a ) a = b; } template <class T> void chk_Min( T &a, T b ) { if( b < a ) a = b; } template <typename T> T read() { T sum = 0, fl = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') fl = -1; for (; isdigit(ch); ch = getchar()) sum = sum * 10 + ch - '0'; return sum * fl; } const int N = 1e5 + 1e4; const int INF = 0x3f3f3f3f; struct City { int id, a, c; }cities[N]; bool cmp( City _a, City _b ) { return _a.a < _b.a; } struct QNode { int id, dis; bool operator< ( const QNode &b ) const { return this -> dis > b.dis; } }; int n; int f[N]; bool vis[N]; std::vector<int> wait[N]; int fd_nxt( int cur ) { int cur_a = cities[cur].c + cities[cur].a; int left = cur + 1, rig = n, res = n + 1; while( left <= rig ) { int mid = ( left + rig ) >> 1; if( cities[mid].a >= cur_a ) { res = mid; rig = mid - 1; } else left = mid + 1; } return res; } int main() { #ifdef woshiluo freopen( "e.in", "r", stdin ); freopen( "e.out", "w", stdout ); #endif scanf( "%d", &n ); for( int i = 1; i <= n; i ++ ) { scanf( "%d%d", &cities[i].a, &cities[i].c ); cities[i].id = i; } std::sort( cities + 1, cities + n + 1, cmp ); }
19.2
63
0.554534
woshiluo
3650c0c2a411ab3b0d42845129a929bbbb19f189
2,752
cpp
C++
oneflow/api/python/functional/common.cpp
MaoXianXin/oneflow
6caa52f3c5ba11a1d67f183bac4c1559b2a58ef5
[ "Apache-2.0" ]
null
null
null
oneflow/api/python/functional/common.cpp
MaoXianXin/oneflow
6caa52f3c5ba11a1d67f183bac4c1559b2a58ef5
[ "Apache-2.0" ]
null
null
null
oneflow/api/python/functional/common.cpp
MaoXianXin/oneflow
6caa52f3c5ba11a1d67f183bac4c1559b2a58ef5
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/api/python/functional/common.h" namespace oneflow { namespace one { namespace functional { namespace detail { Maybe<void> PySliceUnpack(PyObject* object, Py_ssize_t* start, Py_ssize_t* stop, Py_ssize_t* step) { PySliceObject* obj = (PySliceObject*)object; if (obj->step == Py_None) { *step = 1; } else { CHECK_OR_RETURN(_PyEval_SliceIndex(obj->step, step)) << "Invalid slice " << PyStringAsString(PyObject_Repr(object)); CHECK_NE_OR_RETURN(*step, 0) << "slice step cannot be zero."; if (*step < -PY_SSIZE_T_MAX) *step = -PY_SSIZE_T_MAX; } if (obj->start == Py_None) { *start = *step < 0 ? PY_SSIZE_T_MAX : 0; } else { CHECK_OR_RETURN(_PyEval_SliceIndex(obj->start, start)) << "Invalid slice " << PyStringAsString(PyObject_Repr(object)); } if (obj->stop == Py_None) { *stop = *step < 0 ? PY_SSIZE_T_MIN : PY_SSIZE_T_MAX; } else { CHECK_OR_RETURN(_PyEval_SliceIndex(obj->stop, stop)) << "Invalid slice " << PyStringAsString(PyObject_Repr(object)); } return Maybe<void>::Ok(); } const char* PyStringAsString(PyObject* object) { return PyBytes_AsString(PyUnicode_AsEncodedString(object, "utf-8", "~E~")); } Maybe<detail::IndexItem> UnpackIndexItem(PyObject* object) { if (object == Py_Ellipsis) { return std::make_shared<detail::IndexItem>(detail::EllipsisIndex{}); } else if (PySlice_Check(object)) { Py_ssize_t start, end, step; JUST(PySliceUnpack(object, &start, &end, &step)); return std::make_shared<detail::IndexItem>(start, end, step); } else if (PyLong_Check(object) && object != Py_False && object != Py_True) { return std::make_shared<detail::IndexItem>(static_cast<int64_t>(PyLong_AsLongLong(object))); } else if (object == Py_False || object == Py_True) { return std::make_shared<detail::IndexItem>(object == Py_True); } else if (object == Py_None) { return std::make_shared<detail::IndexItem>(detail::NoneIndex{}); } UNIMPLEMENTED_THEN_RETURN() << "Invalid index " << PyStringAsString(PyObject_Repr(object)); } } // namespace detail } // namespace functional } // namespace one } // namespace oneflow
35.282051
100
0.704942
MaoXianXin
365131668b894866ab5264ef428ecff74a49cf92
2,260
cpp
C++
Polynomial/polylist.cpp
eouedraogo4/Polynomial
2a7adba3119acb162525bf71a813e96e105627b0
[ "MIT" ]
null
null
null
Polynomial/polylist.cpp
eouedraogo4/Polynomial
2a7adba3119acb162525bf71a813e96e105627b0
[ "MIT" ]
null
null
null
Polynomial/polylist.cpp
eouedraogo4/Polynomial
2a7adba3119acb162525bf71a813e96e105627b0
[ "MIT" ]
null
null
null
#include "polylist.h" // Constructors PolyList::PolyList(PolyList const& other) { head = new PNode(*other.head); tail = head->next; len = other.len; } // Destructor PolyList::~PolyList() { while (head) { tail = head; head = head->next; delete tail; } } Status PolyList::Push(PolyList& PL, int n) { Function f = new PNode(n); f->next = PL.tail; PL.head->next = f; PL.tail = f; PL.len++; return OK; } Function& PolyList::GetFunction(PolyList const& PL, int pos) { int i = 0; Function f = PL.head; while (i++ < pos && f->next != NULL) f = f->next; return f; } Status PolyList::Display(PolyList const& PL, int i) { if (i <= 0 || i > PL.len) return ERROR; Polynomial::Display(GetFunction(PL, i)->data); return OK; } Status PolyList::DisplayAll(PolyList const& PL) { Function f = PL.tail; int i = 1; while (f != NULL) { std::cout << "f" << i++ << "(x) = "; Polynomial::Display(f->data); std::cout << '\n'; f = f->next; } return OK; } Function PolyList::Add(Function const& f, Function const& g) { Function res = new PNode(); res->data = Polynomial::Add(f->data, g->data); return res; } Function PolyList::Sub(Function const& f, Function const& g) { Function res = new PNode(); res->data = Polynomial::Sub(f->data, g->data); return res; } Function PolyList::Mul(Function const& f, Function const& g) { Function res = new PNode(); res->data = Polynomial::Mul(f->data, g->data); return res; } Status PolyList::Delete(PolyList& PL, int pos, Polynomial& p) { if (pos <= 0 || pos > PL.len) return ERROR; Function f = GetFunction(PL, pos - 1); Function tmp = f->next; f = f->next->next; p = tmp->data; delete tmp; PL.tail = PL.head->next; PL.len--; return OK; } double PolyList::Calculate(PolyList const& PL, int i, int x, Function& f) { if (i <= 0 || i > PL.len) return 0; f = GetFunction(PL, i); return Polynomial::Image(f->data,x); } Function PolyList::Derivative(PolyList const& PL, int i, Function& f) { if (i <= 0 || i > PL.len) return ERROR; f = GetFunction(PL, i); return new PNode(Polynomial::Derivative(f->data)); }
24.565217
93
0.582743
eouedraogo4
3653cc0b5e6fea3c18e6fd4a1e824a64bd097e8f
8,703
cpp
C++
stratum/job.cpp
now2more/yiimp
3506d3b0b8304e020d4ae01d11149ff6e49836c3
[ "MIT" ]
15
2018-01-12T16:21:45.000Z
2021-04-28T19:20:51.000Z
stratum/job.cpp
now2more/yiimp
3506d3b0b8304e020d4ae01d11149ff6e49836c3
[ "MIT" ]
7
2021-04-29T23:11:30.000Z
2022-01-17T09:33:13.000Z
stratum/job.cpp
now2more/yiimp
3506d3b0b8304e020d4ae01d11149ff6e49836c3
[ "MIT" ]
28
2020-11-07T02:28:52.000Z
2022-03-13T01:56:13.000Z
#include "stratum.h" //client->difficulty_remote = 0; //debuglog(" returning %x, %s, %s\n", job->id, client->sock->ip, #condition); \ #define RETURN_ON_CONDITION(condition, ret) \ if(condition) \ { \ return ret; \ } static bool job_assign_client(YAAMP_JOB *job, YAAMP_CLIENT *client, double maxhash) { RETURN_ON_CONDITION(client->deleted, true); RETURN_ON_CONDITION(client->jobid_next, true); RETURN_ON_CONDITION(client->jobid_locked && client->jobid_locked != job->id, true); RETURN_ON_CONDITION(client_find_job_history(client, job->id), true); RETURN_ON_CONDITION(maxhash > 0 && job->speed + client->speed > maxhash, true); if(!g_autoexchange && maxhash >= 0. && client->coinid != job->coind->id) { //debuglog("prevent client %c on %s, not the right coin\n", // client->username[0], job->coind->symbol); return true; } if(job->remote) { YAAMP_REMOTE *remote = job->remote; if(g_stratum_reconnect) {RETURN_ON_CONDITION(!client->extranonce_subscribe && !client->reconnectable, true);} else {RETURN_ON_CONDITION(!client->extranonce_subscribe, true);} RETURN_ON_CONDITION(client->reconnecting, true); RETURN_ON_CONDITION(job->count >= YAAMP_JOB_MAXSUBIDS, false); // RETURN_ON_CONDITION(client->difficulty_actual > remote->difficulty_actual, false); double difficulty_remote = client->difficulty_remote; if(remote->difficulty_actual < client->difficulty_actual) { RETURN_ON_CONDITION(client->difficulty_fixed, true); RETURN_ON_CONDITION(remote->difficulty_actual*4 < client->difficulty_actual, true); difficulty_remote = remote->difficulty_actual; } else if(remote->difficulty_actual > client->difficulty_actual) difficulty_remote = 0; if(remote->nonce2size == 2) { RETURN_ON_CONDITION(job->count > 0, false); strcpy(client->extranonce1, remote->nonce1); client->extranonce2size = 2; } else if(job->id != client->jobid_sent) { if(!job->remote_subids[client->extranonce1_id]) job->remote_subids[client->extranonce1_id] = true; else { int i=0; for(; i<YAAMP_JOB_MAXSUBIDS; i++) if(!job->remote_subids[i]) { job->remote_subids[i] = true; client->extranonce1_id = i; break; } RETURN_ON_CONDITION(i == YAAMP_JOB_MAXSUBIDS, false); } sprintf(client->extranonce1, "%s%02x", remote->nonce1, client->extranonce1_id); client->extranonce2size = remote->nonce2size-1; client->difficulty_remote = difficulty_remote; } client->jobid_locked = job->id; } else { strcpy(client->extranonce1, client->extranonce1_default); client->extranonce2size = client->extranonce2size_default; // decred uses an extradata field in block header, 2 first uint32 are set by the miner if (g_current_algo->name && !strcmp(g_current_algo->name,"decred")) { memset(client->extranonce1, '0', sizeof(client->extranonce1)); memcpy(&client->extranonce1[16], client->extranonce1_default, 8); client->extranonce1[24] = '\0'; } client->difficulty_remote = 0; client->jobid_locked = 0; } client->jobid_next = job->id; job->speed += client->speed; job->count++; // debuglog(" assign %x, %f, %d, %s\n", job->id, client->speed, client->reconnecting, client->sock->ip); if(strcmp(client->extranonce1, client->extranonce1_last) || client->extranonce2size != client->extranonce2size_last) { // debuglog("new nonce %x %s %s\n", job->id, client->extranonce1_last, client->extranonce1); if(!client->extranonce_subscribe) { strcpy(client->extranonce1_reconnect, client->extranonce1); client->extranonce2size_reconnect = client->extranonce2size; strcpy(client->extranonce1, client->extranonce1_default); client->extranonce2size = client->extranonce2size_default; client->reconnecting = true; client->lock_count++; client->unlock = true; client->jobid_sent = client->jobid_next; socket_send(client->sock, "{\"id\":null,\"method\":\"client.reconnect\",\"params\":[\"%s\",%d,0]}\n", g_tcp_server, g_tcp_port); } else { strcpy(client->extranonce1_last, client->extranonce1); client->extranonce2size_last = client->extranonce2size; socket_send(client->sock, "{\"id\":null,\"method\":\"mining.set_extranonce\",\"params\":[\"%s\",%d]}\n", client->extranonce1, client->extranonce2size); } } return true; } void job_assign_clients(YAAMP_JOB *job, double maxhash) { if (!job) return; job->speed = 0; job->count = 0; g_list_client.Enter(); // pass0 locked for(CLI li = g_list_client.first; li; li = li->next) { YAAMP_CLIENT *client = (YAAMP_CLIENT *)li->data; if(client->jobid_locked && client->jobid_locked != job->id) continue; bool b = job_assign_client(job, client, maxhash); if(!b) break; } // pass1 sent for(CLI li = g_list_client.first; li; li = li->next) { YAAMP_CLIENT *client = (YAAMP_CLIENT *)li->data; if(client->jobid_sent != job->id) continue; bool b = job_assign_client(job, client, maxhash); if(!b) break; } // pass2 extranonce_subscribe if(job->remote) for(CLI li = g_list_client.first; li; li = li->next) { YAAMP_CLIENT *client = (YAAMP_CLIENT *)li->data; if(!client->extranonce_subscribe) continue; bool b = job_assign_client(job, client, maxhash); if(!b) break; } // pass3 the rest for(CLI li = g_list_client.first; li; li = li->next) { YAAMP_CLIENT *client = (YAAMP_CLIENT *)li->data; bool b = job_assign_client(job, client, maxhash); if(!b) break; } g_list_client.Leave(); } void job_assign_clients_left(double factor) { bool b; for(CLI li = g_list_coind.first; li; li = li->next) { if(!job_has_free_client()) return; YAAMP_COIND *coind = (YAAMP_COIND *)li->data; if(!coind_can_mine(coind)) continue; if(!coind->job) continue; double nethash = coind_nethash(coind); g_list_client.Enter(); for(CLI li = g_list_client.first; li; li = li->next) { YAAMP_CLIENT *client = (YAAMP_CLIENT *)li->data; if (!g_autoexchange) { if (client->coinid == coind->id) factor = 100.; else factor = 0.; } //debuglog("%s %s factor %f nethash %.3f\n", coind->symbol, client->username, factor, nethash); if (factor > 0.) { b = job_assign_client(coind->job, client, nethash*factor); if(!b) break; } } g_list_client.Leave(); } } //////////////////////////////////////////////////////////////////////// pthread_mutex_t g_job_mutex; pthread_cond_t g_job_cond; void *job_thread(void *p) { CommonLock(&g_job_mutex); while(!g_exiting) { job_update(); pthread_cond_wait(&g_job_cond, &g_job_mutex); } } void job_init() { pthread_mutex_init(&g_job_mutex, 0); pthread_cond_init(&g_job_cond, 0); pthread_t thread3; pthread_create(&thread3, NULL, job_thread, NULL); } void job_signal() { CommonLock(&g_job_mutex); pthread_cond_signal(&g_job_cond); CommonUnlock(&g_job_mutex); } void job_update() { // debuglog("job_update()\n"); job_reset_clients(); ////////////////////////////////////////////////////////////////////////////////////////////////////// g_list_job.Enter(); job_sort(); for(CLI li = g_list_job.first; li; li = li->next) { YAAMP_JOB *job = (YAAMP_JOB *)li->data; if(!job_can_mine(job)) continue; job_assign_clients(job, job->maxspeed); job_unlock_clients(job); if(!job_has_free_client()) break; } job_unlock_clients(); g_list_job.Leave(); //////////////////////////////////////////////////////////////////////////////////////////////// g_list_coind.Enter(); coind_sort(); job_assign_clients_left(1); job_assign_clients_left(1); job_assign_clients_left(-1); g_list_coind.Leave(); //////////////////////////////////////////////////////////////////////////////////////////////// g_list_client.Enter(); for(CLI li = g_list_client.first; li; li = li->next) { YAAMP_CLIENT *client = (YAAMP_CLIENT *)li->data; if(client->deleted) continue; if(client->jobid_next) continue; debuglog("clients with no job\n"); g_current_algo->overflow = true; if(!g_list_coind.first) break; // here: todo: choose first can mine YAAMP_COIND *coind = (YAAMP_COIND *)g_list_coind.first->data; if(!coind) break; job_reset_clients(coind->job); coind_create_job(coind, true); job_assign_clients(coind->job, -1); break; } g_list_client.Leave(); //////////////////////////////////////////////////////////////////////////////////////////////// // usleep(100*YAAMP_MS); // int ready = 0; // debuglog("job_update\n"); g_list_job.Enter(); for(CLI li = g_list_job.first; li; li = li->next) { YAAMP_JOB *job = (YAAMP_JOB *)li->data; if(!job_can_mine(job)) continue; job_broadcast(job); // ready++; } // debuglog("job_update %d / %d jobs\n", ready, g_list_job.count); g_list_job.Leave(); }
24.794872
131
0.652304
now2more
3653f7cf95aab81a640bd4b30645356edf8b8b74
1,270
cpp
C++
ForYou.CodingInterviews/CPlus/ReadBook/ForYou.CodingInterviews.CPlusPlus.PrimerPlus007/002.cpp
Gun-Killer/CodingInterviews
0f06d9f7a79898fbce8a12726bd42077cf7ee071
[ "MIT" ]
null
null
null
ForYou.CodingInterviews/CPlus/ReadBook/ForYou.CodingInterviews.CPlusPlus.PrimerPlus007/002.cpp
Gun-Killer/CodingInterviews
0f06d9f7a79898fbce8a12726bd42077cf7ee071
[ "MIT" ]
null
null
null
ForYou.CodingInterviews/CPlus/ReadBook/ForYou.CodingInterviews.CPlusPlus.PrimerPlus007/002.cpp
Gun-Killer/CodingInterviews
0f06d9f7a79898fbce8a12726bd42077cf7ee071
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void towDArray(int num[][4], int rows); void towDArray2(int num[][4], int rows); void towDArray3(int (*num)[4], int rows); int main002() { int num = 10; const int* num_p = &num; //*num_p = 11; error const int num2 = 20; const int* num2_p = &num2; const int num3 = 30; //int* num3_p = &num3; error int numArr[][4] { {1,2,3}, {4,5,6}, {9,8,9}, }; towDArray(numArr, 3); towDArray2(numArr, 3); towDArray3(numArr, 3); return 0; } void towDArray(int num[][4], int rows) { int sum = 0; for (int i = 0; i < rows; i++) { for (int k = 0; k < 4; k++) { sum += num[i][k]; } } cout << "sum is " << sum << endl; } void towDArray2(int num[][4], int rows) { int sum = 0; for (int i = 0; i < rows; i++) { for (int k = 0; k < 4; k++) { sum += *(*(num + i) + k); } } cout << "sum is " << sum << endl; } void towDArray3(int(*num)[4], int rows) { int sum = 0; for (int i = 0; i < rows; i++) { for (int k = 0; k < 4; k++) { sum += *(*(num + i) + k); } } cout << "sum is " << sum << endl; }
17.162162
41
0.434646
Gun-Killer
365ee9a4ddfd2bda3664291ef34011aa024670cc
4,155
cpp
C++
CardReaderLibrary/RectangleHelper.cpp
klanderfri/CardReaderLibrary
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
4
2019-03-18T14:06:59.000Z
2021-07-17T18:36:12.000Z
CardReaderLibrary/RectangleHelper.cpp
klanderfri/ReadMagicCard
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
17
2018-04-12T18:03:16.000Z
2018-05-09T18:33:07.000Z
CardReaderLibrary/RectangleHelper.cpp
klanderfri/ReadMagicCard
71fc4b7fc6052a9ec3fb477fccd9b3fcfa0b9c60
[ "MIT" ]
1
2019-03-25T18:31:17.000Z
2019-03-25T18:31:17.000Z
#include "stdafx.h" #include "RectangleHelper.h" #include <opencv2\imgproc.hpp> using namespace cv; using namespace std; RectangleHelper::RectangleHelper() { } RectangleHelper::~RectangleHelper() { } RotatedRect RectangleHelper::GetRotatedRectangle(vector<TrendLine> verticalBorders, vector<TrendLine> horizontalBorders, double angleAdjustment) { //Make sure the borders are correct. bool isRightSize = verticalBorders.size() == 2 && horizontalBorders.size() == 2; if (!isRightSize) { throw ParameterException("Wrong number of borders! There should be exactly 2 vertical borders and 2 horizontal borders!"); } bool isParallel = TrendLine::IsParallel(verticalBorders[0], verticalBorders[1]); isParallel = TrendLine::IsParallel(horizontalBorders[0], horizontalBorders[1]) && isParallel; if (!isParallel) { throw ParameterException("The side borders are not paralell!"); } long double angle1 = TrendLine::GetDegreesBetweenLines(verticalBorders[0], horizontalBorders[0]); long double angle2 = TrendLine::GetDegreesBetweenLines(verticalBorders[1], horizontalBorders[1]); bool isPerpendicular = abs(angle1) == 90.0 && abs(angle2) == 90; if (!isPerpendicular) { throw ParameterException("The horizontal and vertical borders are not perpendicular!"); } //Get the corners. Point2d corner = TrendLine::GetIntersectionPoint(horizontalBorders[0], verticalBorders[0]); Point2d oppositeCorner = TrendLine::GetIntersectionPoint(horizontalBorders[1], verticalBorders[1]); //Calculate center. Point2d center = 0.5f * (corner + oppositeCorner); //Calculate angle. long double angle = (-1) * horizontalBorders[0].GetDegreesToAxisX(); angle += angleAdjustment; //Calculate size. long double height = TrendLine::GetPerpendicularDistance(horizontalBorders[0], horizontalBorders[1]); long double width = TrendLine::GetPerpendicularDistance(verticalBorders[0], verticalBorders[1]); Size2d size(width, height); //Create rectangle. RotatedRect rectangle(center, size, (float)angle); return rectangle; } double RectangleHelper::GetAnglesToStrightenUp(const RotatedRect rotatedRectangle, bool enforcePortraitMode) { if (enforcePortraitMode) { return (rotatedRectangle.size.height < rotatedRectangle.size.width) ? rotatedRectangle.angle + 90 : rotatedRectangle.angle; } else { double rotateAlternative1 = rotatedRectangle.angle; //Should always be negative. double rotateAlternative2 = rotatedRectangle.angle + 90; //Should always be positive. double smallestRotation = abs(rotateAlternative1) < rotateAlternative2 ? rotateAlternative1 : rotateAlternative2; return smallestRotation; } } float RectangleHelper::SmallestDistanceCenterToLimit(RotatedRect rectangle) { return min(rectangle.size.height, rectangle.size.width) / 2; } bool RectangleHelper::IsInitialized(RotatedRect rectangleToCheck) { float sum = abs(rectangleToCheck.angle) + abs(rectangleToCheck.center.x) + abs(rectangleToCheck.center.y) + abs(rectangleToCheck.size.area()); return sum != 0; } bool RectangleHelper::DoesRectangleContainPoint(RotatedRect rectangle, Point2f point) { //Implemented as suggested at: //http://answers.opencv.org/question/30330/check-if-a-point-is-inside-a-rotatedrect/?answer=190773#post-id-190773 //Get the corner points. Point2f corners[4]; rectangle.points(corners); //Convert the point array to a vector. //https://stackoverflow.com/a/8777619/1997617 Point2f* lastItemPointer = (corners + sizeof corners / sizeof corners[0]); vector<Point2f> contour(corners, lastItemPointer); //Check if the point is within the rectangle. double indicator = pointPolygonTest(contour, point, false); bool rectangleContainsPoint = (indicator >= 0); return rectangleContainsPoint; } void RectangleHelper::StretchRectangle(const RotatedRect rectangleToStretch, RotatedRect& outRectangle, float xFactor, float yFactor) { Point2f center(rectangleToStretch.center.x * xFactor, rectangleToStretch.center.y * yFactor); Size2f size(rectangleToStretch.size.width * xFactor, rectangleToStretch.size.height * yFactor); float angle = rectangleToStretch.angle; outRectangle = RotatedRect(center, size, angle); }
34.915966
146
0.776895
klanderfri
365f3b95d8f835a411e48511222a3793c6fa1c13
384
cpp
C++
src/depricated_code/barcodecounter.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
22
2016-08-11T06:16:25.000Z
2022-02-22T00:06:59.000Z
src/depricated_code/barcodecounter.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
9
2016-12-08T12:42:38.000Z
2021-12-28T20:12:15.000Z
src/depricated_code/barcodecounter.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
8
2017-06-26T13:15:06.000Z
2021-11-12T18:39:54.000Z
// // barcodecounter.cpp // barcode_project // // Created by luzhao on 12/25/15. // Copyright © 2015 luzhao. All rights reserved. // #include "barcodecounter.h" #include <string> #include "kmers_bitwisetransform.h" using std::string; namespace barcodeSpace{ BarcodeCounter::BarcodeCounter(size_t klen):_klen(klen) { this->_trans = kmersBitwiseTransform::getInstance(); } }
18.285714
56
0.729167
LaoZZZZZ
3666c7c081142a8678529552425d85854df760f2
9,331
cpp
C++
NOLF/ClientShellDLL/ParticleSystemFX.cpp
rastrup/no-one-lives-forever
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
[ "Unlicense" ]
65
2015-02-28T03:35:14.000Z
2021-09-23T05:43:33.000Z
NOLF/ClientShellDLL/ParticleSystemFX.cpp
rastrup/no-one-lives-forever
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
[ "Unlicense" ]
null
null
null
NOLF/ClientShellDLL/ParticleSystemFX.cpp
rastrup/no-one-lives-forever
dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54
[ "Unlicense" ]
27
2015-02-28T07:42:01.000Z
2022-02-11T01:35:20.000Z
// ----------------------------------------------------------------------- // // // MODULE : ParticleSystemFX.cpp // // PURPOSE : ParticleSystem special FX - Implementation // // CREATED : 10/24/97 // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "ParticleSystemFX.h" #include "iltclient.h" #include "ClientUtilities.h" #include "ClientServerShared.h" #include "GameClientShell.h" #include "VarTrack.h" #define MAX_PARTICLES_PER_SECOND 5000 #define MAX_PS_VIEW_DIST_SQR (10000*10000) // Max global distance to add particles extern CGameClientShell* g_pGameClientShell; extern LTVector g_vWorldWindVel; static VarTrack s_cvarTweak; // ----------------------------------------------------------------------- // // // ROUTINE: CParticleSystemFX::CParticleSystemFX // // PURPOSE: Construct // // ----------------------------------------------------------------------- // CParticleSystemFX::CParticleSystemFX() : CBaseParticleSystemFX() { m_bFirstUpdate = LTTRUE; m_fLastTime = 0.0f; m_fNextUpdate = 0.01f; } // ----------------------------------------------------------------------- // // // ROUTINE: CParticleSystemFX::Init // // PURPOSE: Init the particle system fx // // ----------------------------------------------------------------------- // LTBOOL CParticleSystemFX::Init(HLOCALOBJ hServObj, HMESSAGEREAD hMessage) { if (!CBaseParticleSystemFX::Init(hServObj, hMessage)) return LTFALSE; if (!hMessage) return LTFALSE; PSCREATESTRUCT ps; ps.hServerObj = hServObj; g_pLTClient->ReadFromMessageVector(hMessage, &(ps.vColor1)); g_pLTClient->ReadFromMessageVector(hMessage, &(ps.vColor2)); g_pLTClient->ReadFromMessageVector(hMessage, &(ps.vDims)); g_pLTClient->ReadFromMessageVector(hMessage, &(ps.vMinVel)); g_pLTClient->ReadFromMessageVector(hMessage, &(ps.vMaxVel)); ps.dwFlags = (uint32) g_pLTClient->ReadFromMessageFloat(hMessage); ps.fBurstWait = g_pLTClient->ReadFromMessageFloat(hMessage); ps.fBurstWaitMin = g_pLTClient->ReadFromMessageFloat(hMessage); ps.fBurstWaitMax = g_pLTClient->ReadFromMessageFloat(hMessage); ps.fParticlesPerSecond = g_pLTClient->ReadFromMessageFloat(hMessage); ps.fParticleLifetime = g_pLTClient->ReadFromMessageFloat(hMessage); ps.fParticleRadius = g_pLTClient->ReadFromMessageFloat(hMessage); ps.fGravity = g_pLTClient->ReadFromMessageFloat(hMessage); ps.fRotationVelocity = g_pLTClient->ReadFromMessageFloat(hMessage); ps.fViewDist = g_pLTClient->ReadFromMessageFloat(hMessage); ps.hstrTextureName = g_pLTClient->ReadFromMessageHString(hMessage); return Init(&ps); } // ----------------------------------------------------------------------- // // // ROUTINE: CParticleSystemFX::Init // // PURPOSE: Init the particle system // // ----------------------------------------------------------------------- // LTBOOL CParticleSystemFX::Init(SFXCREATESTRUCT* psfxCreateStruct) { if (!CBaseParticleSystemFX::Init(psfxCreateStruct)) return LTFALSE; // Set up our creation struct... PSCREATESTRUCT* pPS = (PSCREATESTRUCT*)psfxCreateStruct; m_cs = *pPS; // Set our (parent's) flags... m_dwFlags = m_cs.dwFlags; m_fRadius = m_cs.fParticleRadius; m_fGravity = m_cs.fGravity; m_vPos = m_cs.vPos; // Set our max viewable distance... m_fMaxViewDistSqr = m_cs.fViewDist*m_cs.fViewDist; m_fMaxViewDistSqr = m_fMaxViewDistSqr > MAX_PS_VIEW_DIST_SQR ? MAX_PS_VIEW_DIST_SQR : m_fMaxViewDistSqr; m_vMinOffset = -m_cs.vDims; m_vMaxOffset = m_cs.vDims; // Adjust velocities based on global wind values... m_cs.vMinVel += g_vWorldWindVel; m_cs.vMaxVel += g_vWorldWindVel; return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CParticleSystemFX::CreateObject // // PURPOSE: Create object associated the particle system. // // ----------------------------------------------------------------------- // LTBOOL CParticleSystemFX::CreateObject(ILTClient *pClientDE) { if (!pClientDE ) return LTFALSE; if (m_cs.hstrTextureName) { m_pTextureName = pClientDE->GetStringData(m_cs.hstrTextureName); } LTBOOL bRet = CBaseParticleSystemFX::CreateObject(pClientDE); if (bRet && m_hObject && m_hServerObject) { LTRotation rRot; pClientDE->GetObjectRotation(m_hServerObject, &rRot); pClientDE->SetObjectRotation(m_hObject, &rRot); uint32 dwUserFlags; pClientDE->GetObjectUserFlags(m_hServerObject, &dwUserFlags); if (!(dwUserFlags & USRFLG_VISIBLE)) { uint32 dwFlags = pClientDE->GetObjectFlags(m_hObject); pClientDE->SetObjectFlags(m_hObject, dwFlags & ~FLAG_VISIBLE); } } s_cvarTweak.Init(g_pLTClient, "TweakParticles", NULL, 0.0f); return bRet; } // ----------------------------------------------------------------------- // // // ROUTINE: CParticleSystemFX::Update // // PURPOSE: Update the particle system // // ----------------------------------------------------------------------- // LTBOOL CParticleSystemFX::Update() { if (!m_hObject || !m_pClientDE || m_bWantRemove) return LTFALSE; LTFLOAT fTime = m_pClientDE->GetTime(); // Hide/show the particle system if necessary... if (m_hServerObject) { uint32 dwUserFlags; m_pClientDE->GetObjectUserFlags(m_hServerObject, &dwUserFlags); uint32 dwFlags = m_pClientDE->GetObjectFlags(m_hObject); if (!(dwUserFlags & USRFLG_VISIBLE)) { // Once last puff as disappeared, hide the system (no new puffs // will be added...) if (dwFlags & FLAG_VISIBLE) { if (fTime > m_fLastTime + m_cs.fParticleLifetime) { m_pClientDE->SetObjectFlags(m_hObject, dwFlags & ~FLAG_VISIBLE); } } else { m_fLastTime = fTime; } return LTTRUE; } else { m_pClientDE->SetObjectFlags(m_hObject, dwFlags | FLAG_VISIBLE); } } // Debugging aid... if (s_cvarTweak.GetFloat() > 0) { TweakSystem(); } if (m_bFirstUpdate) { m_fLastTime = fTime; m_bFirstUpdate = LTFALSE; } // Make sure it is time to update... if (fTime < m_fLastTime + m_fNextUpdate) { return LTTRUE; } // Ok, how many to add this frame....(make sure time delta is no more than // 15 frames/sec... float fTimeDelta = fTime - m_fLastTime; fTimeDelta = fTimeDelta > 0.0666f ? 0.0666f : fTimeDelta; int nToAdd = (int) floor(m_cs.fParticlesPerSecond * fTimeDelta); nToAdd = LTMIN(nToAdd, (int)(MAX_PARTICLES_PER_SECOND * fTimeDelta)); nToAdd = GetNumParticles(nToAdd); m_pClientDE->AddParticles(m_hObject, nToAdd, &m_vMinOffset, &m_vMaxOffset, // Position offset &(m_cs.vMinVel), &(m_cs.vMaxVel), // Velocity &(m_cs.vColor1), &(m_cs.vColor2), // Color m_cs.fParticleLifetime, m_cs.fParticleLifetime); // Determine when next update should occur... if (m_cs.fBurstWait > 0.001f) { m_fNextUpdate = m_cs.fBurstWait * GetRandom(m_cs.fBurstWaitMin, m_cs.fBurstWaitMax); } else { m_fNextUpdate = 0.001f; } // Rotate the particle system... if (m_cs.fRotationVelocity != 0.0f) { LTRotation rRot; m_pClientDE->GetObjectRotation(m_hObject, &rRot); m_pClientDE->EulerRotateY(&rRot, g_pGameClientShell->GetFrameTime() * m_cs.fRotationVelocity); m_pClientDE->SetObjectRotation(m_hObject, &rRot); } m_fLastTime = fTime; return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CParticleSystemFX::TweakSystem // // PURPOSE: Tweak the particle system // // ----------------------------------------------------------------------- // void CParticleSystemFX::TweakSystem() { LTFLOAT fIncValue = 0.01f; LTBOOL bChanged = LTFALSE; LTVector vScale; vScale.Init(); uint32 dwPlayerFlags = g_pGameClientShell->GetPlayerFlags(); // Move faster if running... if (dwPlayerFlags & BC_CFLG_RUN) { fIncValue = .5f; } // Move Red up/down... if ((dwPlayerFlags & BC_CFLG_FORWARD) || (dwPlayerFlags & BC_CFLG_REVERSE)) { //m_cs.vMinVel //m_cs.vMaxVel //m_cs.vColor1 //m_cs.vColor2 bChanged = LTTRUE; } // Add/Subtract number of particles per second if ((dwPlayerFlags & BC_CFLG_STRAFE_RIGHT) || (dwPlayerFlags & BC_CFLG_STRAFE_LEFT)) { fIncValue = dwPlayerFlags & BC_CFLG_STRAFE_RIGHT ? fIncValue : -fIncValue; m_cs.fParticlesPerSecond += (LTFLOAT)(fIncValue * 101.0); m_cs.fParticlesPerSecond = m_cs.fParticlesPerSecond < 0.0f ? 0.0f : (m_cs.fParticlesPerSecond > MAX_PARTICLES_PER_SECOND ? MAX_PARTICLES_PER_SECOND : m_cs.fParticlesPerSecond); bChanged = LTTRUE; } // Lower/Raise burst wait... if ((dwPlayerFlags & BC_CFLG_JUMP) || (dwPlayerFlags & BC_CFLG_DUCK)) { fIncValue = dwPlayerFlags & BC_CFLG_DUCK ? -fIncValue : fIncValue; bChanged = LTTRUE; } if (bChanged) { g_pGameClientShell->CSPrint("Particles per second: %.2f", m_cs.fParticlesPerSecond); } }
27.125
112
0.600686
rastrup