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
sequencelengths
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
sequencelengths
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
sequencelengths
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
5fea1034974be509fb893f4ef79ba7f60bff7ad6
1,739
cpp
C++
vstgui/tests/unittest/lib/cpoint_test.cpp
GizzZmo/vstgui
477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e
[ "BSD-3-Clause" ]
205
2019-06-09T18:40:27.000Z
2022-03-24T01:53:49.000Z
vstgui/tests/unittest/lib/cpoint_test.cpp
GizzZmo/vstgui
477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e
[ "BSD-3-Clause" ]
11
2019-02-09T16:15:34.000Z
2021-03-24T06:28:56.000Z
vstgui/tests/unittest/lib/cpoint_test.cpp
GizzZmo/vstgui
477a3de78ecbcf25f52cce9ad49c5feb0b15ea9e
[ "BSD-3-Clause" ]
30
2019-06-11T04:05:46.000Z
2022-03-29T15:52:14.000Z
// This file is part of VSTGUI. It is subject to the license terms // in the LICENSE file found in the top-level directory of this // distribution and at http://github.com/steinbergmedia/vstgui/LICENSE #include "../../../lib/cpoint.h" #include "../unittests.h" namespace VSTGUI { TESTCASE(CPointTest, TEST(unequal, EXPECT(CPoint (0, 0) != CPoint (1, 1)); EXPECT(CPoint (0, 0) != CPoint (0, 1)); EXPECT(CPoint (0, 0) != CPoint (1, 0)); ); TEST(equal, EXPECT(CPoint (0, 0) == CPoint (0, 0)); ); TEST(operatorAddAssign, CPoint p (1, 1); p += CPoint (1, 1); EXPECT(p == CPoint (2, 2)); ); TEST(operatorSubtractAssign, CPoint p (2, 2); p -= CPoint (1, 1); EXPECT(p == CPoint (1, 1)); ); TEST(operatorAdd, CPoint p (2, 2); auto p2 = p + CPoint (1, 1); EXPECT(p2 == CPoint (3, 3)); EXPECT(p == CPoint (2, 2)); ); TEST(operatorSubtract, CPoint p (2, 2); auto p2 = p - CPoint (1, 1); EXPECT(p2 == CPoint (1, 1)); EXPECT(p == CPoint (2, 2)); ); TEST(operatorInverse, CPoint p (2, 2); auto p2 = -p; EXPECT(p2 == CPoint (-2, -2)); EXPECT(p == CPoint (2, 2)); ); TEST(offsetCoords, CPoint p (1, 2); p.offset (1, 2); EXPECT(p == CPoint (2, 4)); ); TEST(offsetPoint, CPoint p (1, 2); p.offset (CPoint (2, 3)); EXPECT(p == CPoint (3, 5)); ); TEST(offsetInverse, CPoint p (5, 3); p.offsetInverse (CPoint(2, 1)); EXPECT(p == CPoint (3, 2)); ); TEST(makeIntegral, CPoint p (5.3, 4.2); p.makeIntegral (); EXPECT(p == CPoint (5, 4)); p (5.5, 4.5); p.makeIntegral (); EXPECT(p == CPoint (6, 5)); p (5.9, 4.1); p.makeIntegral (); EXPECT(p == CPoint (6, 4)); p (5.1, 4.501); p.makeIntegral (); EXPECT(p == CPoint (5, 5)); ); ); } // VSTGUI
19.539326
70
0.565267
GizzZmo
5feb4e69c10ca0a874238cb07dbe30865b23f5dc
658
cpp
C++
modules/augment/src/uniformnoise.cpp
FadyEssam/opencv_contrib
8ebe2629ec7ae17338f6dc7acceada82151185ed
[ "BSD-3-Clause" ]
null
null
null
modules/augment/src/uniformnoise.cpp
FadyEssam/opencv_contrib
8ebe2629ec7ae17338f6dc7acceada82151185ed
[ "BSD-3-Clause" ]
1
2019-07-11T20:21:36.000Z
2019-07-11T20:21:36.000Z
modules/augment/src/uniformnoise.cpp
FadyEssam/opencv_contrib
8ebe2629ec7ae17338f6dc7acceada82151185ed
[ "BSD-3-Clause" ]
null
null
null
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html. #include "precomp.hpp" namespace cv { namespace augment { UniformNoise::UniformNoise(float _low, float _high) { low = _low; high = _high; } void UniformNoise::image(InputArray src, OutputArray dst) { addWeighted(src, 1.0, noise, 1.0, 0.0, dst); } Rect2f UniformNoise::rectangle(const Rect2f& src) { return src; } void UniformNoise::init(const Mat& srcImage) { noise = Mat(srcImage.size(), srcImage.type(),Scalar(0)); randu(noise, low, high); } }}
21.933333
90
0.711246
FadyEssam
5fedfe656a8f4eb606b3b48b506acf7b76af47db
32,654
cpp
C++
src/main/cpp/driver/ps_ds4_controller.cpp
morrky89/PSMoveSteamVRBridge
03d29b14d1738597523bd059d30736cb0d075d37
[ "Apache-2.0" ]
147
2017-03-28T21:32:25.000Z
2022-01-03T14:43:58.000Z
src/main/cpp/driver/ps_ds4_controller.cpp
morrky89/PSMoveSteamVRBridge
03d29b14d1738597523bd059d30736cb0d075d37
[ "Apache-2.0" ]
129
2017-04-01T20:34:52.000Z
2021-04-06T07:34:49.000Z
src/main/cpp/driver/ps_ds4_controller.cpp
morrky89/PSMoveSteamVRBridge
03d29b14d1738597523bd059d30736cb0d075d37
[ "Apache-2.0" ]
53
2017-03-29T19:31:40.000Z
2022-03-13T11:38:23.000Z
#define _USE_MATH_DEFINES #include "constants.h" #include "server_driver.h" #include "utils.h" #include "settings_util.h" #include "driver.h" #include "facing_handsolver.h" #include "ps_ds4_controller.h" #include "trackable_device.h" #include <assert.h> namespace steamvrbridge { // -- PSDualshock4ControllerConfig ----- configuru::Config PSDualshock4ControllerConfig::WriteToJSON() { configuru::Config &pt= ControllerConfig::WriteToJSON(); // Throwing power settings pt["linear_velocity_multiplier"] = linear_velocity_multiplier; pt["linear_velocity_exponent"] = linear_velocity_exponent; // General Settings pt["rumble_suppressed"] = rumble_suppressed; pt["extend_y_cm"] = extend_Y_meters * 100.f; pt["extend_x_cm"] = extend_Z_meters * 100.f; pt["rotate_z_90"] = z_rotate_90_degrees; pt["calibration_offset_cm"] = calibration_offset_meters * 100.f; pt["thumbstick_deadzone"] = thumbstick_deadzone; pt["disable_alignment_gesture"] = disable_alignment_gesture; pt["use_orientation_in_hmd_alignment"] = use_orientation_in_hmd_alignment; //PSMove controller button -> fake touchpad mappings WriteEmulatedTouchpadAction(pt, k_PSMButtonID_PS); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Triangle); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Circle); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Cross); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Square); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Left); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Up); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Right); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Down); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Options); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Share); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_Touchpad); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_LeftJoystick); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_RightJoystick); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_LeftShoulder); WriteEmulatedTouchpadAction(pt, k_PSMButtonID_RightShoulder); return pt; } bool PSDualshock4ControllerConfig::ReadFromJSON(const configuru::Config &pt) { if (!ControllerConfig::ReadFromJSON(pt)) return false; // Throwing power settings linear_velocity_multiplier = pt.get_or<float>("linear_velocity_multiplier", linear_velocity_multiplier); linear_velocity_exponent = pt.get_or<float>("linear_velocity_exponent", linear_velocity_exponent); // General Settings rumble_suppressed = pt.get_or<bool>("rumble_suppressed", rumble_suppressed); extend_Y_meters = pt.get_or<float>("extend_y_cm", 0.f) / 100.f; extend_Z_meters = pt.get_or<float>("extend_x_cm", 0.f) / 100.f; z_rotate_90_degrees = pt.get_or<bool>("rotate_z_90", z_rotate_90_degrees); calibration_offset_meters = pt.get_or<float>("calibration_offset_cm", 6.f) / 100.f; thumbstick_deadzone = pt.get_or<float>("thumbstick_deadzone", thumbstick_deadzone); disable_alignment_gesture = pt.get_or<bool>("disable_alignment_gesture", disable_alignment_gesture); use_orientation_in_hmd_alignment = pt.get_or<bool>("use_orientation_in_hmd_alignment", use_orientation_in_hmd_alignment); // DS4 controller button -> fake touchpad mappings ReadEmulatedTouchpadAction(pt, k_PSMButtonID_PS); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Triangle); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Circle); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Cross); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Square); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Left); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Up); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Right); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_DPad_Down); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Options); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Share); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_Touchpad); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_LeftJoystick); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_RightJoystick); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_LeftShoulder); ReadEmulatedTouchpadAction(pt, k_PSMButtonID_RightShoulder); return true; } // -- PSDualshock4Controller ----- PSDualshock4Controller::PSDualshock4Controller( PSMControllerID psmControllerId, vr::ETrackedControllerRole trackedControllerRole, const char *psmSerialNo) : Controller() , m_parentController(nullptr) , m_nPSMControllerId(psmControllerId) , m_PSMServiceController(nullptr) , m_nPoseSequenceNumber(0) , m_resetPoseButtonPressTime() , m_bResetPoseRequestSent(false) , m_resetAlignButtonPressTime() , m_bResetAlignRequestSent(false) , m_touchpadDirectionsUsed(false) , m_bUseControllerOrientationInHMDAlignment(false) , m_lastSanitizedLeftThumbstick_X(0.f) , m_lastSanitizedLeftThumbstick_Y(0.f) , m_lastSanitizedRightThumbstick_X(0.f) , m_lastSanitizedRightThumbstick_Y(0.f) { char svrIdentifier[256]; Utils::GenerateControllerSteamVRIdentifier(svrIdentifier, sizeof(svrIdentifier), psmControllerId); m_strSteamVRSerialNo = svrIdentifier; m_lastTouchpadPressTime = std::chrono::high_resolution_clock::now(); if (psmSerialNo != NULL) { m_strPSMControllerSerialNo = psmSerialNo; } // Tell PSM Client API that we are listening to this controller id PSM_AllocateControllerListener(psmControllerId); m_PSMServiceController = PSM_GetController(psmControllerId); m_TrackedControllerRole = trackedControllerRole; m_trackingStatus = vr::TrackingResult_Uninitialized; } PSDualshock4Controller::~PSDualshock4Controller() { PSM_FreeControllerListener(m_PSMServiceController->ControllerID); m_PSMServiceController = nullptr; } vr::EVRInitError PSDualshock4Controller::Activate(vr::TrackedDeviceIndex_t unObjectId) { vr::EVRInitError result = Controller::Activate(unObjectId); if (result == vr::VRInitError_None) { Logger::Info("PSDualshock4Controller::Activate - Controller %d Activated\n", unObjectId); // If we aren't doing the alignment gesture then just pretend we have tracking // This will suppress the alignment gesture dialog in the monitor if (getConfig()->disable_alignment_gesture || CServerDriver_PSMoveService::getInstance()->IsHMDTrackingSpaceCalibrated()) { m_trackingStatus = vr::TrackingResult_Running_OK; } else { CServerDriver_PSMoveService::getInstance()->LaunchPSMoveMonitor(); } PSMRequestID requestId; if (PSM_StartControllerDataStreamAsync( m_PSMServiceController->ControllerID, PSMStreamFlags_includePositionData | PSMStreamFlags_includePhysicsData, &requestId) != PSMResult_Error) { PSM_RegisterCallback(requestId, PSDualshock4Controller::start_controller_response_callback, this); } // Setup controller properties { vr::CVRPropertyHelpers *properties = vr::VRProperties(); properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceOff_String, "{psmove}gamepad_status_off.png"); properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceSearching_String, "{psmove}gamepad_status_ready.png"); properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceSearchingAlert_String, "{psmove}gamepad_status_ready_alert.png"); properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceReady_String, "{psmove}gamepad_status_ready.png"); properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceReadyAlert_String, "{psmove}gamepad_status_ready_alert.png"); properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceNotReady_String, "{psmove}gamepad_status_error.png"); properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceStandby_String, "{psmove}gamepad_status_ready.png"); properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_NamedIconPathDeviceAlertLow_String, "{psmove}gamepad_status_ready_low.png"); properties->SetBoolProperty(m_ulPropertyContainer, vr::Prop_WillDriftInYaw_Bool, true); properties->SetBoolProperty(m_ulPropertyContainer, vr::Prop_DeviceIsWireless_Bool, true); properties->SetBoolProperty(m_ulPropertyContainer, vr::Prop_DeviceProvidesBatteryStatus_Bool, false); properties->SetInt32Property(m_ulPropertyContainer, vr::Prop_DeviceClass_Int32, vr::TrackedDeviceClass_Controller); // The {psmove} syntax lets us refer to rendermodels that are installed // in the driver's own resources/rendermodels directory. The driver can // still refer to SteamVR models like "generic_hmd". if (getConfig()->override_model.length() > 0) { properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_RenderModelName_String, getConfig()->override_model.c_str()); } else { properties->SetStringProperty(m_ulPropertyContainer, vr::Prop_RenderModelName_String, "{psmove}dualshock4_controller"); } // Set device properties vr::VRProperties()->SetInt32Property(m_ulPropertyContainer, vr::Prop_ControllerRoleHint_Int32, m_TrackedControllerRole); vr::VRProperties()->SetStringProperty(m_ulPropertyContainer, vr::Prop_ManufacturerName_String, "Sony"); vr::VRProperties()->SetUint64Property(m_ulPropertyContainer, vr::Prop_HardwareRevision_Uint64, 1313); vr::VRProperties()->SetUint64Property(m_ulPropertyContainer, vr::Prop_FirmwareVersion_Uint64, 1315); vr::VRProperties()->SetStringProperty(m_ulPropertyContainer, vr::Prop_ModelNumber_String, "Dualshock4"); vr::VRProperties()->SetStringProperty(m_ulPropertyContainer, vr::Prop_SerialNumber_String, m_strPSMControllerSerialNo.c_str()); } } return result; } void PSDualshock4Controller::start_controller_response_callback( const PSMResponseMessage *response, void *userdata) { PSDualshock4Controller *controller = reinterpret_cast<PSDualshock4Controller *>(userdata); if (response->result_code == PSMResult::PSMResult_Success) { Logger::Info("PSDualshock4Controller::start_controller_response_callback - Controller stream started\n"); // Create the special case system button (bound to PS button) controller->CreateButtonComponent(k_PSMButtonID_System); // Create buttons components controller->CreateButtonComponent(k_PSMButtonID_PS); controller->CreateButtonComponent(k_PSMButtonID_Triangle); controller->CreateButtonComponent(k_PSMButtonID_Circle); controller->CreateButtonComponent(k_PSMButtonID_Cross); controller->CreateButtonComponent(k_PSMButtonID_Square); controller->CreateButtonComponent(k_PSMButtonID_DPad_Up); controller->CreateButtonComponent(k_PSMButtonID_DPad_Down); controller->CreateButtonComponent(k_PSMButtonID_DPad_Left); controller->CreateButtonComponent(k_PSMButtonID_DPad_Right); controller->CreateButtonComponent(k_PSMButtonID_Options); controller->CreateButtonComponent(k_PSMButtonID_Share); controller->CreateButtonComponent(k_PSMButtonID_Touchpad); controller->CreateButtonComponent(k_PSMButtonID_LeftJoystick); controller->CreateButtonComponent(k_PSMButtonID_RightJoystick); controller->CreateButtonComponent(k_PSMButtonID_LeftShoulder); controller->CreateButtonComponent(k_PSMButtonID_RightShoulder); // Create axis components controller->CreateAxisComponent(k_PSMAxisID_LeftTrigger); controller->CreateAxisComponent(k_PSMAxisID_RightTrigger); controller->CreateAxisComponent(k_PSMAxisID_LeftJoystick_X); controller->CreateAxisComponent(k_PSMAxisID_LeftJoystick_Y); controller->CreateAxisComponent(k_PSMAxisID_RightJoystick_X); controller->CreateAxisComponent(k_PSMAxisID_RightJoystick_Y); // Create components for emulated trackpad controller->CreateButtonComponent(k_PSMButtonID_EmulatedTrackpadTouched); controller->CreateButtonComponent(k_PSMButtonID_EmulatedTrackpadPressed); controller->CreateAxisComponent(k_PSMAxisID_EmulatedTrackpad_X); controller->CreateAxisComponent(k_PSMAxisID_EmulatedTrackpad_Y); // Create haptic components controller->CreateHapticComponent(k_PSMHapticID_LeftRumble); controller->CreateHapticComponent(k_PSMHapticID_RightRumble); } } void PSDualshock4Controller::Deactivate() { Logger::Info("PSDualshock4Controller::Deactivate - Controller stream stopped\n"); PSM_StopControllerDataStreamAsync(m_PSMServiceController->ControllerID, nullptr); Controller::Deactivate(); } void PSDualshock4Controller::UpdateControllerState() { static const uint64_t s_kTouchpadButtonMask = vr::ButtonMaskFromId(vr::k_EButton_SteamVR_Touchpad); assert(m_PSMServiceController != nullptr); assert(m_PSMServiceController->IsConnected); const PSMDualShock4 &clientView = m_PSMServiceController->ControllerState.PSDS4State; const bool bStartRealignHMDTriggered = (clientView.ShareButton == PSMButtonState_PRESSED && clientView.OptionsButton == PSMButtonState_PRESSED) || (clientView.ShareButton == PSMButtonState_PRESSED && clientView.OptionsButton == PSMButtonState_DOWN) || (clientView.ShareButton == PSMButtonState_DOWN && clientView.OptionsButton == PSMButtonState_PRESSED); // See if the recenter button has been held for the requisite amount of time bool bRecenterRequestTriggered = false; { PSMButtonState resetPoseButtonState = clientView.OptionsButton; switch (resetPoseButtonState) { case PSMButtonState_PRESSED: { m_resetPoseButtonPressTime = std::chrono::high_resolution_clock::now(); } break; case PSMButtonState_DOWN: { if (!m_bResetPoseRequestSent) { const float k_hold_duration_milli = 250.f; std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now(); std::chrono::duration<float, std::milli> pressDurationMilli = now - m_resetPoseButtonPressTime; if (pressDurationMilli.count() >= k_hold_duration_milli) { bRecenterRequestTriggered = true; } } } break; case PSMButtonState_RELEASED: { m_bResetPoseRequestSent = false; } break; } } // If SHARE was just pressed while and OPTIONS was held or vice versa, // recenter the controller orientation pose and start the realignment of the controller to HMD tracking space. if (bStartRealignHMDTriggered && !getConfig()->disable_alignment_gesture) { Logger::Info("PSDualshock4Controller::UpdateControllerState(): Calling StartRealignHMDTrackingSpace() in response to controller chord.\n"); PSM_ResetControllerOrientationAsync(m_PSMServiceController->ControllerID, k_psm_quaternion_identity, nullptr); m_bResetPoseRequestSent = true; // We have the transform of the HMD in world space. // The controller's position is a few inches ahead of the HMD's on the HMD's local -Z axis. PSMVector3f controllerLocalOffsetFromHmdPosition = *k_psm_float_vector3_zero; controllerLocalOffsetFromHmdPosition = { 0.0f, 0.0f, -1.0f * getConfig()->calibration_offset_meters }; try { PSMPosef hmdPose = Utils::GetHMDPoseInMeters(); PSMPosef realignedPose = Utils::RealignHMDTrackingSpace(*k_psm_quaternion_identity, controllerLocalOffsetFromHmdPosition, m_PSMServiceController->ControllerID, hmdPose, getConfig()->use_orientation_in_hmd_alignment); CServerDriver_PSMoveService::getInstance()->SetHMDTrackingSpace(realignedPose); } catch (std::exception & e) { // Log an error message and safely carry on Logger::Error(e.what()); } m_bResetAlignRequestSent = true; } else if (bRecenterRequestTriggered) { Logger::Info("PSDualshock4Controller::UpdateControllerState(): Calling ClientPSMoveAPI::reset_orientation() in response to controller button press.\n"); PSM_ResetControllerOrientationAsync(m_PSMServiceController->ControllerID, k_psm_quaternion_identity, nullptr); m_bResetPoseRequestSent = true; } else { // System Button hard-coded to PS button Controller::UpdateButton(k_PSMButtonID_System, clientView.PSButton); // Process all the native buttons Controller::UpdateButton(k_PSMButtonID_PS, clientView.PSButton); Controller::UpdateButton(k_PSMButtonID_Triangle, clientView.TriangleButton); Controller::UpdateButton(k_PSMButtonID_Circle, clientView.CircleButton); Controller::UpdateButton(k_PSMButtonID_Cross, clientView.CrossButton); Controller::UpdateButton(k_PSMButtonID_Square, clientView.SquareButton); Controller::UpdateButton(k_PSMButtonID_DPad_Up, clientView.DPadUpButton); Controller::UpdateButton(k_PSMButtonID_DPad_Down, clientView.DPadDownButton); Controller::UpdateButton(k_PSMButtonID_DPad_Left, clientView.DPadLeftButton); Controller::UpdateButton(k_PSMButtonID_DPad_Right, clientView.DPadRightButton); Controller::UpdateButton(k_PSMButtonID_Options, clientView.OptionsButton); Controller::UpdateButton(k_PSMButtonID_Share, clientView.ShareButton); Controller::UpdateButton(k_PSMButtonID_Touchpad, clientView.TrackPadButton); Controller::UpdateButton(k_PSMButtonID_LeftJoystick, clientView.L3Button); Controller::UpdateButton(k_PSMButtonID_RightJoystick, clientView.R3Button); Controller::UpdateButton(k_PSMButtonID_LeftShoulder, clientView.L1Button); Controller::UpdateButton(k_PSMButtonID_RightShoulder, clientView.R1Button); // Thumbstick handling UpdateThumbsticks(); // Touchpad handling UpdateEmulatedTrackpad(); // Trigger handling Controller::UpdateAxis(k_PSMAxisID_LeftTrigger, clientView.LeftTriggerValue / 255.f); Controller::UpdateAxis(k_PSMAxisID_RightTrigger, clientView.RightTriggerValue / 255.f); } } void PSDualshock4Controller::RemapThumbstick( const float thumb_stick_x, const float thumb_stick_y, float &out_sanitized_x, float &out_sanitized_y) { const float thumb_stick_radius = sqrtf(thumb_stick_x*thumb_stick_x + thumb_stick_y * thumb_stick_y); // Moving a thumb-stick outside of the deadzone is consider a touchpad touch if (thumb_stick_radius >= getConfig()->thumbstick_deadzone) { // Rescale the thumb-stick position to hide the dead zone const float rescaledRadius = (thumb_stick_radius - getConfig()->thumbstick_deadzone) / (1.f - getConfig()->thumbstick_deadzone); // Set the thumb-stick axis out_sanitized_x = (rescaledRadius / thumb_stick_radius) * thumb_stick_x; out_sanitized_y = (rescaledRadius / thumb_stick_radius) * thumb_stick_y; } else { out_sanitized_x= 0.f; out_sanitized_y= 0.f; } } void PSDualshock4Controller::UpdateThumbsticks() { const PSMDualShock4 &clientView = m_PSMServiceController->ControllerState.PSDS4State; RemapThumbstick( clientView.LeftAnalogX, clientView.LeftAnalogY, m_lastSanitizedLeftThumbstick_X, m_lastSanitizedLeftThumbstick_Y); RemapThumbstick( clientView.RightAnalogX, clientView.RightAnalogY, m_lastSanitizedRightThumbstick_X, m_lastSanitizedRightThumbstick_Y); Controller::UpdateAxis(k_PSMAxisID_LeftJoystick_X, m_lastSanitizedLeftThumbstick_X); Controller::UpdateAxis(k_PSMAxisID_LeftJoystick_Y, m_lastSanitizedLeftThumbstick_Y); Controller::UpdateAxis(k_PSMAxisID_RightJoystick_X, m_lastSanitizedRightThumbstick_X); Controller::UpdateAxis(k_PSMAxisID_RightJoystick_Y, m_lastSanitizedRightThumbstick_Y); } // Updates the state of the controllers touchpad axis relative to its position over time and active state. void PSDualshock4Controller::UpdateEmulatedTrackpad() { // Bail if the config hasn't enabled the emulated trackpad if (!HasButton(k_PSMButtonID_EmulatedTrackpadPressed) && !HasButton(k_PSMButtonID_EmulatedTrackpadPressed)) return; // Find the highest priority emulated touch pad action (if any) eEmulatedTrackpadAction highestPriorityAction= k_EmulatedTrackpadAction_None; for (int buttonIndex = 0; buttonIndex < static_cast<int>(k_PSMButtonID_Count); ++buttonIndex) { eEmulatedTrackpadAction action= getConfig()->ps_button_id_to_emulated_touchpad_action[buttonIndex]; if (action != k_EmulatedTrackpadAction_None) { PSMButtonState button_state= PSMButtonState_UP; if (Controller::GetButtonState((ePSMButtonID)buttonIndex, button_state)) { if (button_state == PSMButtonState_DOWN || button_state == PSMButtonState_PRESSED) { if (action >= highestPriorityAction) { highestPriorityAction= action; } if (action >= k_EmulatedTrackpadAction_Press) { break; } } } } } float touchpad_x = 0.f; float touchpad_y = 0.f; PSMButtonState emulatedTouchPadTouchedState= PSMButtonState_UP; PSMButtonState emulatedTouchPadPressedState= PSMButtonState_UP; if (highestPriorityAction == k_EmulatedTrackpadAction_Touch) { emulatedTouchPadTouchedState= PSMButtonState_DOWN; } else if (highestPriorityAction == k_EmulatedTrackpadAction_Press) { emulatedTouchPadTouchedState= PSMButtonState_DOWN; emulatedTouchPadPressedState= PSMButtonState_DOWN; } if (highestPriorityAction > k_EmulatedTrackpadAction_Press) { emulatedTouchPadTouchedState= PSMButtonState_DOWN; emulatedTouchPadPressedState= PSMButtonState_DOWN; // If the action specifies a specific trackpad direction, // then use the given trackpad axis switch (highestPriorityAction) { case k_EmulatedTrackpadAction_Left: touchpad_x= -1.f; touchpad_y= 0.f; break; case k_EmulatedTrackpadAction_Up: touchpad_x= 0.f; touchpad_y= 1.f; break; case k_EmulatedTrackpadAction_Right: touchpad_x= 1.f; touchpad_y= 0.f; break; case k_EmulatedTrackpadAction_Down: touchpad_x= 0.f; touchpad_y= -1.f; break; case k_EmulatedTrackpadAction_UpLeft: touchpad_x = -0.707f; touchpad_y = 0.707f; break; case k_EmulatedTrackpadAction_UpRight: touchpad_x = 0.707f; touchpad_y = 0.707f; break; case k_EmulatedTrackpadAction_DownLeft: touchpad_x = -0.707f; touchpad_y = -0.707f; break; case k_EmulatedTrackpadAction_DownRight: touchpad_x = 0.707f; touchpad_y = -0.707f; break; } } else if (getConfig()->ps_button_id_to_emulated_touchpad_action[k_PSMButtonID_LeftJoystick] != k_EmulatedTrackpadAction_None) { // Consider the touchpad pressed if the left thumbstick is deflected at all. const bool bIsTouched= fabsf(m_lastSanitizedLeftThumbstick_X) + fabsf(m_lastSanitizedLeftThumbstick_Y) > 0.f; if (bIsTouched) { emulatedTouchPadTouchedState= PSMButtonState_DOWN; emulatedTouchPadPressedState= PSMButtonState_DOWN; touchpad_x= m_lastSanitizedLeftThumbstick_X; touchpad_y= m_lastSanitizedLeftThumbstick_Y; } } else if (getConfig()->ps_button_id_to_emulated_touchpad_action[k_PSMButtonID_RightJoystick] != k_EmulatedTrackpadAction_None) { // Consider the touchpad pressed if the right thumbstick is deflected at all. const bool bIsTouched= fabsf(m_lastSanitizedRightThumbstick_X) + fabsf(m_lastSanitizedRightThumbstick_Y) > 0.f; if (bIsTouched) { emulatedTouchPadTouchedState= PSMButtonState_DOWN; emulatedTouchPadPressedState= PSMButtonState_DOWN; touchpad_x= m_lastSanitizedRightThumbstick_X; touchpad_y= m_lastSanitizedRightThumbstick_Y; } } Controller::UpdateButton(k_PSMButtonID_EmulatedTrackpadTouched, emulatedTouchPadTouchedState); Controller::UpdateButton(k_PSMButtonID_EmulatedTrackpadPressed, emulatedTouchPadPressedState); Controller::UpdateAxis(k_PSMAxisID_EmulatedTrackpad_X, touchpad_x); Controller::UpdateAxis(k_PSMAxisID_EmulatedTrackpad_Y, touchpad_y); } void PSDualshock4Controller::UpdateTrackingState() { assert(m_PSMServiceController != nullptr); assert(m_PSMServiceController->IsConnected); const PSMDualShock4 &view = m_PSMServiceController->ControllerState.PSDS4State; // The tracking status will be one of the following states: m_Pose.result = m_trackingStatus; m_Pose.deviceIsConnected = m_PSMServiceController->IsConnected; // These should always be false from any modern driver. These are for Oculus DK1-like // rotation-only tracking. Support for that has likely rotted in vrserver. m_Pose.willDriftInYaw = false; m_Pose.shouldApplyHeadModel = false; // No prediction since that's already handled in the psmove service m_Pose.poseTimeOffset = -0.016f; // No transform due to the current HMD orientation m_Pose.qDriverFromHeadRotation.w = 1.f; m_Pose.qDriverFromHeadRotation.x = 0.0f; m_Pose.qDriverFromHeadRotation.y = 0.0f; m_Pose.qDriverFromHeadRotation.z = 0.0f; m_Pose.vecDriverFromHeadTranslation[0] = 0.f; m_Pose.vecDriverFromHeadTranslation[1] = 0.f; m_Pose.vecDriverFromHeadTranslation[2] = 0.f; // Set position { const PSMVector3f &position = view.Pose.Position; m_Pose.vecPosition[0] = position.x * k_fScalePSMoveAPIToMeters; m_Pose.vecPosition[1] = position.y * k_fScalePSMoveAPIToMeters; m_Pose.vecPosition[2] = position.z * k_fScalePSMoveAPIToMeters; } // virtual extend controllers if (getConfig()->extend_Y_meters != 0.0f || getConfig()->extend_Z_meters != 0.0f) { const PSMQuatf &orientation = view.Pose.Orientation; PSMVector3f shift = { (float)m_Pose.vecPosition[0], (float)m_Pose.vecPosition[1], (float)m_Pose.vecPosition[2] }; if (getConfig()->extend_Z_meters != 0.0f) { PSMVector3f local_forward = { 0, 0, -1 }; PSMVector3f global_forward = PSM_QuatfRotateVector(&orientation, &local_forward); shift = PSM_Vector3fScaleAndAdd(&global_forward, getConfig()->extend_Z_meters, &shift); } if (getConfig()->extend_Y_meters != 0.0f) { PSMVector3f local_forward = { 0, -1, 0 }; PSMVector3f global_forward = PSM_QuatfRotateVector(&orientation, &local_forward); shift = PSM_Vector3fScaleAndAdd(&global_forward, getConfig()->extend_Y_meters, &shift); } m_Pose.vecPosition[0] = shift.x; m_Pose.vecPosition[1] = shift.y; m_Pose.vecPosition[2] = shift.z; } // Set rotational coordinates { const PSMQuatf &orientation = view.Pose.Orientation; m_Pose.qRotation.w = getConfig()->z_rotate_90_degrees ? -orientation.w : orientation.w; m_Pose.qRotation.x = orientation.x; m_Pose.qRotation.y = orientation.y; m_Pose.qRotation.z = getConfig()->z_rotate_90_degrees ? -orientation.z : orientation.z; } // Set the physics state of the controller /*{ const PSMPhysicsData &physicsData = view.PhysicsData; m_Pose.vecVelocity[0] = physicsData.LinearVelocityCmPerSec.x * abs(pow(abs(physicsData.LinearVelocityCmPerSec.x), m_fLinearVelocityExponent)) * k_fScalePSMoveAPIToMeters * m_fLinearVelocityMultiplier; m_Pose.vecVelocity[1] = physicsData.LinearVelocityCmPerSec.y * abs(pow(abs(physicsData.LinearVelocityCmPerSec.y), m_fLinearVelocityExponent)) * k_fScalePSMoveAPIToMeters * m_fLinearVelocityMultiplier; m_Pose.vecVelocity[2] = physicsData.LinearVelocityCmPerSec.z * abs(pow(abs(physicsData.LinearVelocityCmPerSec.z), m_fLinearVelocityExponent)) * k_fScalePSMoveAPIToMeters * m_fLinearVelocityMultiplier; m_Pose.vecAcceleration[0] = physicsData.LinearAccelerationCmPerSecSqr.x * k_fScalePSMoveAPIToMeters; m_Pose.vecAcceleration[1] = physicsData.LinearAccelerationCmPerSecSqr.y * k_fScalePSMoveAPIToMeters; m_Pose.vecAcceleration[2] = physicsData.LinearAccelerationCmPerSecSqr.z * k_fScalePSMoveAPIToMeters; m_Pose.vecAngularVelocity[0] = physicsData.AngularVelocityRadPerSec.x; m_Pose.vecAngularVelocity[1] = physicsData.AngularVelocityRadPerSec.y; m_Pose.vecAngularVelocity[2] = physicsData.AngularVelocityRadPerSec.z; m_Pose.vecAngularAcceleration[0] = physicsData.AngularAccelerationRadPerSecSqr.x; m_Pose.vecAngularAcceleration[1] = physicsData.AngularAccelerationRadPerSecSqr.y; m_Pose.vecAngularAcceleration[2] = physicsData.AngularAccelerationRadPerSecSqr.z; }*/ m_Pose.poseIsValid = view.bIsPositionValid && view.bIsOrientationValid; // This call posts this pose to shared memory, where all clients will have access to it the next // moment they want to predict a pose. vr::VRServerDriverHost()->TrackedDevicePoseUpdated(m_unSteamVRTrackedDeviceId, m_Pose, sizeof(vr::DriverPose_t)); } // TODO - Make use of amplitude and frequency for Buffered Haptics, will give us patterning and panning vibration // See: https://developer.oculus.com/documentation/pcsdk/latest/concepts/dg-input-touch-haptic/ void PSDualshock4Controller::UpdateRumbleState(PSMControllerRumbleChannel channel) { Controller::HapticState *haptic_state= GetHapticState( channel == PSMControllerRumbleChannel_Left ? k_PSMHapticID_LeftRumble : k_PSMHapticID_RightRumble); if (haptic_state == nullptr) return; if (!getConfig()->rumble_suppressed) { // pulse duration - the length of each pulse // amplitude - strength of vibration // frequency - speed of each pulse // convert to microseconds, the max duration received from OpenVR appears to be 5 micro seconds uint16_t pendingHapticPulseDurationMicroSecs = static_cast<uint16_t>(haptic_state->pendingHapticDurationSecs * 1000000); const float k_max_rumble_update_rate = 33.f; // Don't bother trying to update the rumble faster than 30fps (33ms) const float k_max_pulse_microseconds = 5000.f; // Docs suggest max pulse duration of 5ms, but we'll call 1ms max std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now(); bool bTimoutElapsed = true; if (haptic_state->lastTimeRumbleSentValid) { std::chrono::duration<double, std::milli> timeSinceLastSend = now - haptic_state->lastTimeRumbleSent; bTimoutElapsed = timeSinceLastSend.count() >= k_max_rumble_update_rate; } // See if a rumble request hasn't come too recently if (bTimoutElapsed) { float rumble_fraction = (static_cast<float>(pendingHapticPulseDurationMicroSecs) / k_max_pulse_microseconds) * haptic_state->pendingHapticAmplitude; if (rumble_fraction > 0) { steamvrbridge::Logger::Debug( "PSDualshock4Controller::UpdateRumble: m_pendingHapticPulseDurationSecs=%f, pendingHapticPulseDurationMicroSecs=%d, rumble_fraction=%f\n", haptic_state->pendingHapticDurationSecs, pendingHapticPulseDurationMicroSecs, rumble_fraction); } // Unless a zero rumble intensity was explicitly set, // don't rumble less than 35% (no enough to feel) if (haptic_state->pendingHapticDurationSecs != 0) { if (rumble_fraction < 0.35f) { // rumble values less 35% isn't noticeable rumble_fraction = 0.35f; } } // Keep the pulse intensity within reasonable bounds if (rumble_fraction > 1.f) { rumble_fraction = 1.f; } // Actually send the rumble to the server PSM_SetControllerRumble(m_PSMServiceController->ControllerID, channel, rumble_fraction); // Remember the last rumble we went and when we sent it haptic_state->lastTimeRumbleSent = now; haptic_state->lastTimeRumbleSentValid = true; // Reset the pending haptic pulse duration. // If another call to TriggerHapticPulse() is made later, it will stomp this value. // If no future haptic event is received by ServerDriver then the next call to UpdateRumbleState() // in k_max_rumble_update_rate milliseconds will set the rumble_fraction to 0.f // This effectively makes the shortest rumble pulse k_max_rumble_update_rate milliseconds. haptic_state->pendingHapticDurationSecs = DEFAULT_HAPTIC_DURATION; haptic_state->pendingHapticAmplitude = DEFAULT_HAPTIC_AMPLITUDE; haptic_state->pendingHapticFrequency = DEFAULT_HAPTIC_FREQUENCY; } } else { // Reset the pending haptic pulse duration since rumble is suppressed. haptic_state->pendingHapticDurationSecs = DEFAULT_HAPTIC_DURATION; haptic_state->pendingHapticAmplitude = DEFAULT_HAPTIC_AMPLITUDE; haptic_state->pendingHapticFrequency = DEFAULT_HAPTIC_FREQUENCY; } } void PSDualshock4Controller::Update() { Controller::Update(); if (IsActivated() && m_PSMServiceController->IsConnected) { int seq_num = m_PSMServiceController->OutputSequenceNum; // Only other updating incoming state if it actually changed and is due for one if (m_nPoseSequenceNumber < seq_num) { m_nPoseSequenceNumber = seq_num; UpdateTrackingState(); UpdateControllerState(); } // Update the outgoing state UpdateRumbleState(PSMControllerRumbleChannel_Left); UpdateRumbleState(PSMControllerRumbleChannel_Right); } } void PSDualshock4Controller::RefreshWorldFromDriverPose() { TrackableDevice::RefreshWorldFromDriverPose(); // Mark the calibration process as done once we have setup the world from driver pose m_trackingStatus = vr::TrackingResult_Running_OK; } }
43.772118
155
0.784866
morrky89
5feeb313522dbb912920abf6105287aa0f6676cb
9,638
cpp
C++
FDTD/EncodeOutput.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
FDTD/EncodeOutput.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
FDTD/EncodeOutput.cpp
plisdku/trogdor6
d77eb137dd0c03635c0016801ada54117697e521
[ "MIT" ]
null
null
null
/* * EncodeOutput.cpp * Trogdor6 * * Created by Paul Hansen on 3/23/11. * Copyright 2011 Stanford University. All rights reserved. * * This file is covered by the MIT license. See LICENSE.txt. */ #include "EncodeOutput.h" #include "SimulationDescription.h" #include "VoxelizedPartition.h" #include "operations/OutputEHDB.h" #include "rle/SupportRegion3.h" #include "rle/MergeRunlines.h" #include "Support.h" #include <vector> using namespace std; using namespace RLE; using namespace YeeUtilities; struct CallbackOutput { CallbackOutput(vector<RunlineOutput> & runlines) : mRunlines(runlines) {} void operator()(const std::int64_t indices[], const std::uint64_t strides[], std::uint64_t length, std::uint64_t numStreams) { RunlineOutput runline(indices[0], length); mRunlines.push_back(runline); } vector<RunlineOutput> & mRunlines; }; typedef CallbackOutput CallbackSource; struct CallbackSparseOutput { CallbackSparseOutput(vector<RunlineOutput> & runlines) : mRunlines(runlines) {} void operator()(const std::int64_t indices[], const std::uint64_t strides[], std::uint64_t length, std::uint64_t numStreams) { RunlineOutput runline(indices[0], length); mRunlines.push_back(runline); } vector<RunlineOutput> & mRunlines; }; struct CallbackOutputAverageTwo { CallbackOutputAverageTwo(vector<RunlineAverageTwo> & runlines) : mRunlines(runlines) {} void operator()(const std::int64_t indices[], const std::uint64_t strides[], std::uint64_t length, std::uint64_t numStreams) { RunlineAverageTwo runline(indices[0], indices[1], length); mRunlines.push_back(runline); } vector<RunlineAverageTwo> & mRunlines; }; struct CallbackTensorialOutput { CallbackTensorialOutput( vector<RunlineTensorialOutput> & runlines) : mRunlines(runlines) {} void operator()(const std::int64_t indices[], const std::uint64_t strides[], std::uint64_t length, std::uint64_t numStreams) { RunlineTensorialOutput runline(indices[0], indices[1], length); mRunlines.push_back(runline); } vector<RunlineTensorialOutput> & mRunlines; }; EncodeOutput:: EncodeOutput(const GridDescription & gridDesc, const VoxelizedPartition & vp) : mGridDesc(gridDesc), mVoxelGrid(vp) { } Pointer<OutputEHDB> EncodeOutput:: encode(const OutputDescription & outputDesc) const { Pointer<OutputEHDB> output(new OutputEHDB(outputDesc, gridDescription().dxyz(), gridDescription().dt(), gridDescription().origin())); SupportRegion3 supp, suppShifted; for (int ff = 0; ff < outputDesc.fields().size(); ff++) { const OutputField & field(outputDesc.fields().at(ff)); if (field.field() == kEE || field.field() == kHH) { if (field.ii() == field.jj()) encodeTensorialDiagonalOutput(*output, outputDesc, field); else encodeTensorialOffDiagonalOutput(*output, outputDesc, field); } else if (field.octant() == 0 || field.octant() == 7) encodeInterpolatedOutput(*output, outputDesc, field); else if (field.field() == kJ || field.field() == kM) encodeSparseOutput(*output, outputDesc, field); else encodeStandardOutput(*output, outputDesc, field); } return output; } void EncodeOutput:: encodeStandardOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() == field.jj()); int xyz = field.ii(); const IndexArray3 & fieldIndices = voxelGrid().fieldIndices().field(field.field(), xyz); vector<RunlineOutput> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); IndexArray3 outputIndices; restriction(fieldIndices, supp, outputIndices); IndexArray3 const* inds[] = { &outputIndices }; CallbackOutput callback(runlines); RLE::mergeOverlapping(inds, 1, callback); } output.appendField(field, runlines); } void EncodeOutput:: encodeSparseOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() == field.jj()); int xyz = field.ii(); const IndexArray3 & fieldIndices = voxelGrid().fieldIndices().field(field.field(), xyz); vector<RunlineOutput> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); SupportRegion3 emptyCells = supp - fieldIndices; IndexArray3 outputIndices, emptyIndices(emptyCells); restriction(fieldIndices, supp, outputIndices); IndexArray3 const* inds[] = { &outputIndices, &emptyIndices }; // this DOES work, using the standard output callback. CallbackOutput callback(runlines); RLE::mergeOverlapping(inds, 2, callback); } output.appendField(field, runlines); } void EncodeOutput:: encodeInterpolatedOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() == field.jj()); int xyz = field.ii(); const IndexArray3 & fieldIndices = voxelGrid().fieldIndices().field(field.field(), xyz); vector<RunlineAverageTwo> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); SupportRegion3 suppShifted; if (field.field() == kE || field.field() == kD || field.field() == kJ) { assert(field.octant() == 0); translate(supp, suppShifted, (-Vector3<std::int64_t>::unit(xyz)).asArray()); } else if (field.field() == kH || field.field() == kB || field.field() == kM) { assert(field.octant() == 7); translate(supp, suppShifted, Vector3<std::int64_t>::unit(xyz).asArray()); } else throw(std::logic_error("Bad field")); IndexArray3 outputIndices, outputIndicesShifted; restriction(fieldIndices, supp, outputIndices); restriction(fieldIndices, suppShifted, outputIndicesShifted); IndexArray3 const* inds[] = { &outputIndices, &outputIndicesShifted }; CallbackOutputAverageTwo callback(runlines); RLE::mergeOverlapping(inds, 2, callback); } output.appendField(field, runlines); } void EncodeOutput:: encodeTensorialDiagonalOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() == field.jj()); assert(field.field() == kEE || field.field() == kHH); int xyz = field.ii(); // These are the fields we want to output, e.g. Exx. const IndexArray3 & tensorialIndices = voxelGrid().fieldIndices().field(field.field(), xyz, xyz); vector<RunlineTensorialOutput> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); // These are the "backup fields." For diagonal permittivities, the Exx // field is just ordinary Ex, since there are no Exy and Exz components. const IndexArray3 & vectorialIndices = (field.field() == kEE) ? voxelGrid().fieldIndices().e(xyz) : voxelGrid().fieldIndices().h(xyz); IndexArray3 mainIndices, backupIndices; restriction(tensorialIndices, supp, mainIndices); restriction(vectorialIndices, supp, backupIndices); IndexArray3 const* inds[] = { &mainIndices, &backupIndices }; CallbackTensorialOutput callback(runlines); RLE::mergeOverlapping(inds, 2, callback); } output.appendTensorialDiagonalField(field, runlines); } void EncodeOutput:: encodeTensorialOffDiagonalOutput(OutputEHDB & output, const OutputDescription & outputDesc, const OutputField & field) const { assert(field.ii() != field.jj()); assert(field.field() == kEE || field.field() == kHH); const IndexArray3 & tensorialIndices = voxelGrid().fieldIndices().field(field.field(), field.ii(), field.jj()); vector<RunlineTensorialOutput> runlines; for (int rr = 0; rr < outputDesc.regions().size(); rr++) { SupportRegion3 supp = support(outputDesc.regions().at(rr).yeeCells(), Vector3b(voxelGrid().extents().nodeYeeCells().num())); IndexArray3 outputIndices, emptyIndices(supp); restriction(tensorialIndices, supp, outputIndices); IndexArray3 const* inds[] = { &outputIndices, &emptyIndices }; CallbackTensorialOutput callback(runlines); RLE::mergeOverlapping(inds, 2, callback); } output.appendTensorialOffDiagonalField(field, runlines); }
30.596825
88
0.630629
plisdku
5fef168528168f3c92178c86d0dad2e17cfd3203
746
cpp
C++
codechef/lapindrome.cpp
NIKU-SINGH/problemsolving
f7dd9d065a945a2f59e84580f926d35949ce3be2
[ "MIT" ]
null
null
null
codechef/lapindrome.cpp
NIKU-SINGH/problemsolving
f7dd9d065a945a2f59e84580f926d35949ce3be2
[ "MIT" ]
1
2021-07-07T14:37:03.000Z
2021-07-07T14:39:58.000Z
codechef/lapindrome.cpp
NIKU-SINGH/problemsolving
f7dd9d065a945a2f59e84580f926d35949ce3be2
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { // your code goes here int t; cin>>t; while(t--) { string str; cin>>str; int n = str.length(); int part1freq[26] ={0}; int part2freq[26]={0}; for(int i=0;i<n/2;i++) { part1freq[str[i]-'a']++; } for(int j=(n+1)/2;j<n;j++) { part2freq[str[j]-'a']++; } int res=0; for(int i=0;i<26;i++) { if(part1freq[i] != part2freq[i]) { res++; break; } } if(res==0) cout<<"YES"<<"\n"; else cout<<"NO"<<"\n"; } return 0; }
16.217391
44
0.349866
NIKU-SINGH
5ffb6add8895c91cfa81e7e0f06f13ade6048f8a
2,942
cpp
C++
source/internal/logger.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
1
2016-04-26T04:16:55.000Z
2016-04-26T04:16:55.000Z
source/internal/logger.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
null
null
null
source/internal/logger.cpp
HeliosInteractive/libkeen
f31246c2f0a705b9f1c25e4400d96a62408c37e6
[ "MIT" ]
2
2016-04-14T16:57:03.000Z
2020-02-21T00:17:48.000Z
#include "internal/logger.hpp" #include <iostream> #include <fstream> #include <iomanip> #include <chrono> #include <ctime> // by default turn on both file and console // logging behaviors. #ifndef LIBKEEN_LOG_TO_CONSOLE # define LIBKEEN_LOG_TO_CONSOLE 1 #endif #ifndef LIBKEEN_LOG_TO_LOGFILE # define LIBKEEN_LOG_TO_LOGFILE 1 #endif namespace { std::string now() { auto now = std::chrono::system_clock::now(); auto now_time_t = std::chrono::system_clock::to_time_t(now); std::stringstream ss; ss << std::put_time(std::localtime(&now_time_t), "%Y-%m-%d %X"); return ss.str(); }} namespace libkeen { namespace internal { Logger::~Logger() { log("Logger " + mType + " is shutdown."); } Logger::Logger(const std::string& type) : mType(type) , mLogToFile(true) , mLogToConsole(true) { log("Logger " + mType + " is started."); } void Logger::log(const std::string& message) { #if LIBKEEN_LOG_TO_CONSOLE || LIBKEEN_LOG_TO_LOGFILE try { std::lock_guard<decltype(mMutex)> lock(mMutex); std::stringstream msg; msg << "[" << mType << "][" << std::this_thread::get_id() << "][" << now() << "]: " << message << std::endl; #if LIBKEEN_LOG_TO_CONSOLE if (mLogToConsole) { std::cout << msg.str(); } #endif // LIBKEEN_LOG_TO_CONSOLE #if LIBKEEN_LOG_TO_LOGFILE if (mLogToFile) { std::ofstream("libkeen.log", std::ios_base::app | std::ios_base::out) << msg.str(); } #endif // LIBKEEN_LOG_TO_LOGFILE } catch (const std::exception& ex) { std::cerr << "Logger failed: " << ex.what() << std::endl; } catch (...) { std::cerr << "Logger failed." << std::endl; } #endif } void Logger::enableLogToFile(bool on /*= true*/) { std::lock_guard<decltype(mMutex)> lock(mMutex); mLogToFile = on; } void Logger::enableLogToConsole(bool on /*= true*/) { std::lock_guard<decltype(mMutex)> lock(mMutex); mLogToConsole = on; } void Logger::pull(std::vector<LoggerRef>& container) { if (!container.empty()) container.clear(); container.push_back(loggers::debug()); container.push_back(loggers::error()); container.push_back(loggers::warn()); container.push_back(loggers::info()); } std::shared_ptr<Logger> loggers::debug() { static std::shared_ptr<Logger> debug_logger = std::make_shared<Logger>("debug"); return debug_logger; } std::shared_ptr<Logger> loggers::error() { static std::shared_ptr<Logger> error_logger = std::make_shared<Logger>("error"); return error_logger; } std::shared_ptr<Logger> loggers::warn() { static std::shared_ptr<Logger> warn_logger = std::make_shared<Logger>("warn"); return warn_logger; } std::shared_ptr<Logger> loggers::info() { static std::shared_ptr<Logger> info_logger = std::make_shared<Logger>("info"); return info_logger; } }}
22.120301
95
0.633583
HeliosInteractive
5ffc113e32897d21acdfb1256f6c36cb28d1b377
4,297
cpp
C++
Project/AudioManager.cpp
OiCGame/GameJam01
7860098d235678cbe32215c733366d4fb973ea5e
[ "MIT" ]
null
null
null
Project/AudioManager.cpp
OiCGame/GameJam01
7860098d235678cbe32215c733366d4fb973ea5e
[ "MIT" ]
null
null
null
Project/AudioManager.cpp
OiCGame/GameJam01
7860098d235678cbe32215c733366d4fb973ea5e
[ "MIT" ]
null
null
null
#include "AudioManager.h" CAudioManager::CAudioManager() { } CAudioManager::~CAudioManager() { } CAudioManager& CAudioManager::Singleton(void) { static CAudioManager obj; return obj; } void CAudioManager::Play(SoundBufferKey key) { auto temp = SoundBufferAsset(key); auto it = std::find(m_pSounds.begin(), m_pSounds.end(), temp); if (it == m_pSounds.end()) { m_pSounds.push_back(temp); } // if if (temp) { temp->Play(); } // if } void CAudioManager::Play(SoundStreamBufferKey key) { auto temp = SoundStreamBufferAsset(key); auto it = std::find(m_pSounds.begin(), m_pSounds.end(), temp); if (it == m_pSounds.end()) { m_pSounds.push_back(temp); } // if if(temp){ temp->Play(); } // if } bool CAudioManager::Load(void) { if (!CSoundBufferAsset::Load(SoundBufferKey::Sound0, "shot1.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if auto sound = SoundBufferAsset(SoundBufferKey::Sound0); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::boomerang, "boomerang1.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::boomerang); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::shot_struck, "shot-struck1.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::shot_struck); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::enemy_explosion, "enemy_explosion.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::enemy_explosion); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::player_explosion, "player_explosion.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::player_explosion); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::ok_se, "ok_se.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::ok_se); if (!CSoundBufferAsset::Load(SoundBufferKey::flash_01, "shakin1.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::flash_01); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::flash_02, "shakin2.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::flash_02); m_pSounds.push_back(sound); if (!CSoundBufferAsset::Load(SoundBufferKey::item_get, "itemGet.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if sound = SoundBufferAsset(SoundBufferKey::item_get); m_pSounds.push_back(sound); if (!CSoundStreamBufferAsset::Load(SoundStreamBufferKey::Bgm0, "game_bgm.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if auto bgm0 = SoundStreamBufferAsset(SoundStreamBufferKey::Bgm0); bgm0->SetLoop(true); m_pSounds.push_back(bgm0); if (!CSoundStreamBufferAsset::Load(SoundStreamBufferKey::title, "title_bgm.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if bgm0 = SoundStreamBufferAsset(SoundStreamBufferKey::title); bgm0->SetLoop(true); m_pSounds.push_back(bgm0); if (!CSoundStreamBufferAsset::Load(SoundStreamBufferKey::gameclear, "gameclear_bgm.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if bgm0 = SoundStreamBufferAsset(SoundStreamBufferKey::gameclear); bgm0->SetLoop(true); m_pSounds.push_back(bgm0); if (!CSoundStreamBufferAsset::Load(SoundStreamBufferKey::gameover, "gameover_bgm.mp3")) { MOF_PRINTLOG("failed to load sound"); return false; } // if bgm0 = SoundStreamBufferAsset(SoundStreamBufferKey::gameover); bgm0->SetLoop(true); m_pSounds.push_back(bgm0); return true; } void CAudioManager::Update(void) { for (auto sound : m_pSounds) { if (sound) { sound->Update(); } // if } // for } void CAudioManager::Release(void) { for (auto sound : m_pSounds) { if (sound) { sound->Release(); sound.reset(); } // if } // for m_pSounds.clear(); }
30.475177
92
0.695136
OiCGame
5ffca5a8fee1bfe85e677a558fb668dc73292ed0
472
cpp
C++
array/sumofallsubarray.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
5
2021-12-03T14:29:16.000Z
2022-02-04T09:06:37.000Z
array/sumofallsubarray.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
null
null
null
array/sumofallsubarray.cpp
riti2409/forplacements
9e8fb99c9d65b04eea71abb3fbdcffc2a1433a04
[ "MIT" ]
2
2022-01-16T14:20:42.000Z
2022-01-17T06:49:01.000Z
//5 // 1 2 0 7 2 //o/p-> 1,3,3,10,12,2,2,9,11,0,7,9,7,9,2, #include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int arr[n]; for (int i = 0; i < n; i++) { cin >> arr[i]; } int currsum=0; for (int i = 0; i < n; i++) { currsum=0; for (int j = i; j < n; j++) { currsum+=arr[j]; cout<<currsum<<","; } } return 0; }
14.30303
42
0.358051
riti2409
5fff380e5006a8672a31e48f8f2f7a1f46761144
1,689
cpp
C++
ipc2/ipc2.cpp
Elexir-Stefan/ray-usermode
9a1c7d773496493482cf2e711fe1808b537db63a
[ "MIT" ]
null
null
null
ipc2/ipc2.cpp
Elexir-Stefan/ray-usermode
9a1c7d773496493482cf2e711fe1808b537db63a
[ "MIT" ]
null
null
null
ipc2/ipc2.cpp
Elexir-Stefan/ray-usermode
9a1c7d773496493482cf2e711fe1808b537db63a
[ "MIT" ]
null
null
null
#include <raykernel.h> #include <exception> #include <video/VideoStream.h> #include <processes/processes.h> #include <ipc/ipc.h> #include <sstream> using namespace Kernel; using namespace Kernel::IPC; using namespace Kernel::Processes; /** * TestFunction used as callback */ int TestFunction(int arg2, float arg3) { kout << "This function worked properly! " << arg2 << VideoStream::endl; return 666; } char* ToString(int number, char* result) { char* nPtr = result + strlen(result); std::ostringstream sin; sin << number; strcpy(nPtr, sin.str().c_str()); return result; } float AnotherTestFunction(char arg1, int arg2, int arg3) { kout << "This is another test function -- " << arg2 << " (" << arg3 << ")" << VideoStream::endl; return 1.4142f; } int UserProgramEntry(const char *arguments) { try { Sync waitForOther = Sync("dingsbums", TRUE); // Register our connection Communication::Register("andererProzess", "Wartet auf eine Verbindung"); Socket& socket = Communication::CreateSocket("dessenSocket"); socket.AddLocalCallback(int, TestFunction, int, float); socket.AddLocalCallback(char*, ToString, int, char*); socket.AddRemoteMethod(char, int, float); socket.AddRemoteMethod(float, char, int, int); try { UNUSED Plug* plug = new Plug(socket); waitForOther.Go(TRUE); } catch(IPCSetupException &e) { kout << "An error occured while registering the socket!" << VideoStream::endl; } Thread::Sleep(); // never reaches this point... return 0; } catch (IPCSetupException &e) { kout << "An error occured while setting up the communication wall." << VideoStream::endl; return -1; } }
19.870588
97
0.6791
Elexir-Stefan
2700c4b0db0f1c1293d72965144c99c28dd89578
1,540
cpp
C++
Accepted_The 2000's ACM-ICPC/P2783 (Robots).cpp
peneksglazami/acm-icpc-training
a3c41b65b8f8523713f9859b076f300a12c4e7f3
[ "CC0-1.0" ]
null
null
null
Accepted_The 2000's ACM-ICPC/P2783 (Robots).cpp
peneksglazami/acm-icpc-training
a3c41b65b8f8523713f9859b076f300a12c4e7f3
[ "CC0-1.0" ]
null
null
null
Accepted_The 2000's ACM-ICPC/P2783 (Robots).cpp
peneksglazami/acm-icpc-training
a3c41b65b8f8523713f9859b076f300a12c4e7f3
[ "CC0-1.0" ]
null
null
null
/*************************************************** Problem: 2783 - Robots ACM ICPC - North America - Mid Central - 2003/2004 Solved by Andrey Grigorov ***************************************************/ #include <stdio.h> #include <vector> #include <queue> using namespace std; typedef struct{ int row,col; } garbage; class Compare{ public: bool operator()(garbage a, garbage b){ return ((a.row > b.row) || ((a.row == b.row) && (a.col > b.col))); } }; int main(){ priority_queue <garbage, vector<garbage>, Compare > pq1,pq2; int r,c,rob_cnt; garbage g,cur_g; scanf("%d %d",&r,&c); while ((r != -1) || (c != -1)){ while (!pq1.empty()) pq1.pop(); while (!pq2.empty()) pq2.pop(); do{ g.row = r; g.col = c; pq1.push(g); scanf("%d %d",&r,&c); }while (r || c); rob_cnt = 0; while (!pq1.empty()){ rob_cnt++; g.row = 0; g.col = 0; while (!pq1.empty()){ cur_g = pq1.top(); pq1.pop(); if ((g.row <= cur_g.row) && (g.col <= cur_g.col)){ g = cur_g; } else pq2.push(cur_g); } while (!pq2.empty()){ pq1.push(pq2.top()); pq2.pop(); } } printf("%d\n",rob_cnt); scanf("%d %d",&r,&c); } return 0; }
24.83871
78
0.380519
peneksglazami
dfd6b713f18b58b836b96f6fc5f669da6bc435ff
517
cpp
C++
cpp/data/grid.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
null
null
null
cpp/data/grid.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
null
null
null
cpp/data/grid.cpp
equivalence1/ml_lib
92d75ab73bc2d77ba8fa66022c803c06cad66f21
[ "Apache-2.0" ]
null
null
null
#include "grid.h" void Grid::binarize(ConstVecRef<float> row, VecRef<uint8_t> dst) const { for (int64_t f = 0; f < features_.size(); ++f) { dst[f] = computeBin(row[origFeatureIndex(f)], borders_[f]); } } void Grid::binarize(const Vec& x, Buffer<uint8_t>& to) const { assert(x.device().deviceType() == ComputeDeviceType::Cpu); assert(to.device().deviceType() == ComputeDeviceType::Cpu); const auto values = x.arrayRef(); const auto dst = to.arrayRef(); binarize(values, dst); }
28.722222
72
0.644101
equivalence1
dfd8d1e701891eb5373cf737aa8c8970666e3637
699
cpp
C++
Luogu/luogu4317.cpp
wzl19371/OI-LIfe
f7f54542d1369b5e4047fcbb2e26c1c64d22ee26
[ "MIT" ]
1
2020-10-05T02:07:52.000Z
2020-10-05T02:07:52.000Z
Luogu/luogu4317.cpp
wzl19371/OI-LIfe
f7f54542d1369b5e4047fcbb2e26c1c64d22ee26
[ "MIT" ]
null
null
null
Luogu/luogu4317.cpp
wzl19371/OI-LIfe
f7f54542d1369b5e4047fcbb2e26c1c64d22ee26
[ "MIT" ]
null
null
null
#include <cstdio> using namespace std; typedef long long ll; const ll p=10000007; ll n,f[107][107],t[107]; ll qpow(ll x,ll y){ ll ans=1; while(y){ if(y&1) ans=ans*x%p; x=x*x%p; y>>=1; } return ans; } ll dp(int n,int m){ if(m>n||!n||m<0) return 0; if(f[n][m]) return f[n][m]; if(n==m||!m) return f[n][m]=1; return f[n][m]=dp(n-1,m)+dp(n-1,m-1); } int main(){ scanf("%lld",&n); for(int i=1;i<=60;i++) for(int j=1;j<=60;j++) dp(i,j); int ct=0; for(ll i=60;i>=0;i--){ if(n&(1ll<<i)){ for(int j=1;j<=i;j++) t[ct+j]+=f[i][j]; t[++ct]++; } } ll ans=1; for(int i=1;i<=60;i++) ans=ans*qpow(i,t[i])%p; printf("%lld\n",ans); return 0; }
19.416667
57
0.492132
wzl19371
dfdbd34f1489377b3c0d503948724cef06abae30
389
cpp
C++
Competitive Programming/part_02/deque.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
1
2022-03-24T06:38:53.000Z
2022-03-24T06:38:53.000Z
Competitive Programming/part_02/deque.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
null
null
null
Competitive Programming/part_02/deque.cpp
l0rdluc1f3r/CppCompetitiveProgramming
71376b5a6182dc446811072c73a2b13f33110d4c
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> int main(){ std::deque<int> d1; std::deque<int> d2(5, 10); std::deque<int> d3(d2); std::deque<int> d4(d2.begin(), d2.end()); int arr[] = {1,2,3,4,5}; std::deque<int> d5(arr, arr+5); for(auto &el : d5){ std::cout<<el<<" "; } if(d5.empty()){ std::cout<<"Oh No"; } d1.push_back(10); d1.push_front(20); d1.emplace_back(10); d1.emplace_front(20); }
18.52381
42
0.573265
l0rdluc1f3r
dfe7a9aee06726f7894b1bed816b96427f5c00d0
686
cxx
C++
templates/initmodule.cxx
lukeolson/crappy
fdd9449f7976e2a4e678db06e1b8d1a8bfef4e84
[ "BSD-3-Clause" ]
null
null
null
templates/initmodule.cxx
lukeolson/crappy
fdd9449f7976e2a4e678db06e1b8d1a8bfef4e84
[ "BSD-3-Clause" ]
null
null
null
templates/initmodule.cxx
lukeolson/crappy
fdd9449f7976e2a4e678db06e1b8d1a8bfef4e84
[ "BSD-3-Clause" ]
null
null
null
#include <Python.h> #include "crappy.h" extern "C" { #include "crappy_impl.h" static char crappy_doc[] = "Docstring for crappy."; #if PY_VERSION_HEX >= 0x03000000 static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "crappy", NULL, -1, crappy_methods, NULL, NULL, NULL, NULL }; PyObject *PyInit_crappy(void) { PyObject *m; m = PyModule_Create(&moduledef); import_array(); return m; } #else PyMODINIT_FUNC initcrappy(void) { PyObject *m; m = Py_InitModule3("crappy", crappy_methods, crappy_doc); import_array(); if (m == NULL) { Py_FatalError("can't initialize module crappy"); } } #endif }
16.333333
61
0.639942
lukeolson
dfea84a2adab64773bce92477019e19b41ecd308
509
cpp
C++
source/jz28.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
source/jz28.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
source/jz28.cpp
loganautomata/leetcode
5a626c91f271bae231328c92a3be23eba227f66e
[ "MIT" ]
null
null
null
#include "jz28.h" using namespace std; bool Jz28::IsMirror(TreeNode* left, TreeNode* right) { if(left == nullptr && right == nullptr) return true; else if (left == nullptr || right == nullptr || left->val != right->val) return false; // 迭代终止条件, 遍历完至少一颗树, 或者发现两颗树不是镜像. return IsMirror(left->right, right->left) && IsMirror(left->left, right->right); } bool Jz28::isSymmetric(TreeNode* root) { if (root == nullptr) return true; // 排除树为空的特殊情形 return IsMirror(root->left, root->right); }
26.789474
124
0.664047
loganautomata
dfeec959a6ac004088e326a95d987644c70b9f92
514
cpp
C++
2014/node.cpp
Yww729604/XidianCodeTest
bf99657fc58718f1edd2e91291420ee5e2c58d21
[ "MIT" ]
1
2022-02-05T16:37:13.000Z
2022-02-05T16:37:13.000Z
2014/node.cpp
Yww729604/XidianCodeTest
bf99657fc58718f1edd2e91291420ee5e2c58d21
[ "MIT" ]
null
null
null
2014/node.cpp
Yww729604/XidianCodeTest
bf99657fc58718f1edd2e91291420ee5e2c58d21
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef struct node { int data; string s; string t; struct node *next; }*linkList; void init(linkList &l) { int d; while(cin>>d) { linkList tempNode = (linkList)malloc(sizeof(struct node)); tempNode->data = d; tempNode->next = l; l = tempNode; } } void print(linkList l) { linkList p = l; while(p != NULL) { cout<<p->data<<" "; p = p->next; } } int main(int argc, char const *argv[]) { linkList l = NULL; init(l); print(l); return 0; }
12.536585
60
0.61284
Yww729604
dffd810adde01422c379df331b7e6794ae00f53a
292
hpp
C++
fw/include/fw/BasicEffect.hpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
null
null
null
fw/include/fw/BasicEffect.hpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
9
2016-12-09T13:02:18.000Z
2019-09-13T09:29:18.000Z
fw/include/fw/BasicEffect.hpp
sienkiewiczkm/framework
9940403404aa5c67186fe09b0910de3a6c8e9762
[ "MIT" ]
null
null
null
#pragma once #include "Effect.hpp" namespace fw { class BasicEffect: public EffectBase { public: BasicEffect(); virtual ~BasicEffect(); void create(); virtual void destroy(); virtual void begin(); virtual void end(); protected: void createShaders(); }; }
12.166667
27
0.643836
sienkiewiczkm
dffef375e236877eca4d7bcfdbbc268ffc6ea653
4,319
cpp
C++
nTA/Source/igui_BuildButton.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
2
2020-05-09T20:50:12.000Z
2021-06-20T08:34:58.000Z
nTA/Source/igui_BuildButton.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
null
null
null
nTA/Source/igui_BuildButton.cpp
loganjones/nTA-Total-Annihilation-Clone
d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14
[ "MIT" ]
2
2018-01-08T00:12:04.000Z
2020-06-14T10:56:50.000Z
// igui_BuildButton.cpp // \author Logan Jones ///////////////////////// \date 4/25/2002 /// \file /// \brief ... ///////////////////////////////////////////////////////////////////// #include "igui.h" #include "igui_BuildButton.h" #include "game.h" #include "snd.h" ///////////////////////////////////////////////////////////////////// // Default Construction/Destruction // igui_BuildButton::igui_BuildButton():gadget_Button() {} igui_BuildButton::~igui_BuildButton() {} // ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // igui_BuildButton::OnInitButtonImages() // \author Logan Jones /////////////////////////////////////////// \date 11/5/2002 // //=================================================================== // void igui_BuildButton::OnInitButtonImages() { theInterface->ControlBar().LoadBuildButton( this, m_CommonData, m_ButtonInfo ); } // End igui_BuildButton::OnInitButtonImages() ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // igui_BuildButton::OnRender() // \author Logan Jones ///////////////////////////////// \date 02-02-2003 // //=================================================================== // void igui_BuildButton::OnRender() { const igui_BuildOrders* pOrders = theInterface->ControlBar().m_CurrentSelection->BuildOrders(); int Amount; // Render the button first gadget_Button::OnRender(); // If the selected unit has build orders and those oreders include this item then render the amount info if( pOrders && (Amount=pOrders->Amount(m_CommonData.Name))!=0 ) { // Setup the info string depending on the amount (less than 0 indicates infinite) if( Amount>0 ) m_BuildText[0] = '+', itoa( Amount, m_BuildText+1, 10 ); else m_BuildText[0] = '~', m_BuildText[1] = '\0'; // Render the info gfx->SetCurrentFont( guiResources.Fonts.Standard ); gfx->RenderStringCenteredAt( m_ScreenPosition + std_Point(m_Size.width/2, m_Size.height-6) + (m_Pressed ? std_Point(1,1) : std_Point(0,0)), m_BuildText, TRUE, FALSE ); } } // End igui_BuildButton::OnRender() ///////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // igui_BuildButton::OnCursorMove() // \author Logan Jones ///////////////////////////////////// \date 5/1/2002 // //==================================================================== // Parameters: // std_Point& ptCursor - // DWORD dwFlags - // void igui_BuildButton::OnCursorMove( std_Point& ptCursor, DWORD dwFlags ) { // Call the default gadget_Button::OnCursorMove( ptCursor, dwFlags ); // Display the type information for the unit represented by this button theInterface->InfoBar().DisplayBuildInfo( theGame.Units.GetUnitType(m_CommonData.Name) ); } // End igui_BuildButton::OnCursorMove() ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// // igui_BuildButton::OnPressed() // \author Logan Jones ////////////////////////////////// \date 4/27/2002 // //==================================================================== // Parameters: // DWORD dwButton - Button that completed the press // void igui_BuildButton::OnPressed( DWORD dwButton ) { // Send the pressed message //SendMessage( m_pParent, igui_msg_BuildButtonPressed, (DWORD)(LPTSTR(m_CommonData.Name)), dwButton ); sound.PlaySound( (dwButton==1) ? guiResources.Sounds.AddBuild : guiResources.Sounds.SubBuild ); theInterface->BuildButtonPressed( m_CommonData.Name, (m_CommonData.CommonAttribs&8)!=0, dwButton==1 ); } // End igui_BuildButton::OnPressed() ////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// // End - igui_BuildButton.cpp // ///////////////////////////////
37.556522
114
0.447094
loganjones
5f0b0bee274cc3e652992befca93a04e990ea2c6
18,825
cpp
C++
samples/Hello/third-party/fuzzylite/fuzzylite/src/rule/Antecedent.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
samples/Hello/third-party/fuzzylite/fuzzylite/src/rule/Antecedent.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
samples/Hello/third-party/fuzzylite/fuzzylite/src/rule/Antecedent.cpp
okocsis/ios-cmake
ca61d83725bc5b1a755928f4592badbd9a8b37f4
[ "BSD-3-Clause" ]
null
null
null
/* fuzzylite (R), a fuzzy logic control library in C++. Copyright (C) 2010-2017 FuzzyLite Limited. All rights reserved. Author: Juan Rada-Vilela, Ph.D. <[email protected]> This file is part of fuzzylite. fuzzylite is free software: you can redistribute it and/or modify it under the terms of the FuzzyLite License included with the software. You should have received a copy of the FuzzyLite License along with fuzzylite. If not, see <http://www.fuzzylite.com/license/>. fuzzylite is a registered trademark of FuzzyLite Limited. */ #include "fl/rule/Antecedent.h" #include "fl/Engine.h" #include "fl/factory/HedgeFactory.h" #include "fl/factory/FactoryManager.h" #include "fl/hedge/Any.h" #include "fl/rule/Expression.h" #include "fl/rule/Rule.h" #include "fl/term/Aggregated.h" #include "fl/variable/InputVariable.h" #include "fl/variable/OutputVariable.h" #include <stack> namespace fl { Antecedent::Antecedent() : _text(""), _expression(fl::null) { } Antecedent::~Antecedent() { _expression.reset(fl::null); } void Antecedent::setText(const std::string& text) { this->_text = text; } std::string Antecedent::getText() const { return this->_text; } Expression* Antecedent::getExpression() const { return this->_expression.get(); } void Antecedent::setExpression(Expression* expression) { this->_expression.reset(expression); } bool Antecedent::isLoaded() const { return _expression.get() != fl::null; } scalar Antecedent::activationDegree(const TNorm* conjunction, const SNorm* disjunction) const { return this->activationDegree(conjunction, disjunction, _expression.get()); } scalar Antecedent::activationDegree(const TNorm* conjunction, const SNorm* disjunction, const Expression* node) const { if (not isLoaded()) { throw Exception("[antecedent error] antecedent <" + getText() + "> is not loaded", FL_AT); } const Expression::Type expression = node->type(); if (expression == Expression::Proposition) { const Proposition* proposition = static_cast<const Proposition*> (node); if (not proposition->variable->isEnabled()) { return 0.0; } if (not proposition->hedges.empty()) { //if last hedge is "Any", apply hedges in reverse order and return degree std::vector<Hedge*>::const_reverse_iterator rit = proposition->hedges.rbegin(); if (dynamic_cast<Any*> (*rit)) { scalar result = (*rit)->hedge(fl::nan); while (++rit != proposition->hedges.rend()) { result = (*rit)->hedge(result); } return result; } } scalar result = fl::nan; Variable::Type variableType = proposition->variable->type(); if (variableType == Variable::Input) { result = proposition->term->membership(proposition->variable->getValue()); } else if (variableType == Variable::Output) { result = static_cast<OutputVariable*> (proposition->variable) ->fuzzyOutput()->activationDegree(proposition->term); } if (not proposition->hedges.empty()) { for (std::vector<Hedge*>::const_reverse_iterator rit = proposition->hedges.rbegin(); rit != proposition->hedges.rend(); ++rit) { result = (*rit)->hedge(result); } } return result; } //if node is an operator if (expression == Expression::Operator) { const Operator* fuzzyOperator = static_cast<const Operator*> (node); if (not (fuzzyOperator->left and fuzzyOperator->right)) { std::ostringstream ex; ex << "[syntax error] left and right operands must exist"; throw Exception(ex.str(), FL_AT); } if (fuzzyOperator->name == Rule::andKeyword()) { if (not conjunction) throw Exception("[conjunction error] " "the following rule requires a conjunction operator:\n" + _text, FL_AT); return conjunction->compute( this->activationDegree(conjunction, disjunction, fuzzyOperator->left), this->activationDegree(conjunction, disjunction, fuzzyOperator->right)); } if (fuzzyOperator->name == Rule::orKeyword()) { if (not disjunction) throw Exception("[disjunction error] " "the following rule requires a disjunction operator:\n" + _text, FL_AT); return disjunction->compute( this->activationDegree(conjunction, disjunction, fuzzyOperator->left), this->activationDegree(conjunction, disjunction, fuzzyOperator->right)); } std::ostringstream ex; ex << "[syntax error] operator <" << fuzzyOperator->name << "> not recognized"; throw Exception(ex.str(), FL_AT); } else { std::ostringstream ss; ss << "[antecedent error] expected a Proposition or Operator, but found <"; if (node) ss << node->toString(); ss << ">"; throw Exception(ss.str(), FL_AT); } } Complexity Antecedent::complexity(const TNorm* conjunction, const SNorm* disjunction) const { return complexity(conjunction, disjunction, _expression.get()); } Complexity Antecedent::complexity(const TNorm* conjunction, const SNorm* disjunction, const Expression* node) const { if (not isLoaded()) { return Complexity(); } Complexity result; const Expression::Type expression = node->type(); if (expression == Expression::Proposition) { const Proposition* proposition = static_cast<const Proposition*> (node); if (not proposition->variable->isEnabled()) { return result; } if (not proposition->hedges.empty()) { //if last hedge is "Any", apply hedges in reverse order and return degree std::vector<Hedge*>::const_reverse_iterator rit = proposition->hedges.rbegin(); if (dynamic_cast<Any*> (*rit)) { result += (*rit)->complexity(); while (++rit != proposition->hedges.rend()) { result = (*rit)->complexity(); } return result; } } Variable::Type variableType = proposition->variable->type(); if (variableType == Variable::Input) { result += proposition->term->complexity(); } else if (variableType == Variable::Output) { OutputVariable* outputVariable = static_cast<OutputVariable*> (proposition->variable); result += outputVariable->fuzzyOutput()->complexityOfActivationDegree(); } if (not proposition->hedges.empty()) { for (std::vector<Hedge*>::const_reverse_iterator rit = proposition->hedges.rbegin(); rit != proposition->hedges.rend(); ++rit) { result += (*rit)->complexity(); } } return result; } //if node is an operator if (expression == Expression::Operator) { const Operator* fuzzyOperator = static_cast<const Operator*> (node); if (not (fuzzyOperator->left and fuzzyOperator->right)) { std::ostringstream ex; ex << "[syntax error] left and right operands must exist"; throw Exception(ex.str(), FL_AT); } if (fuzzyOperator->name == Rule::andKeyword()) { if (conjunction) { result += conjunction->complexity(); } result += complexity(conjunction, disjunction, fuzzyOperator->left) + complexity(conjunction, disjunction, fuzzyOperator->right); return result; } if (fuzzyOperator->name == Rule::orKeyword()) { if (disjunction) { result += disjunction->complexity(); } result += complexity(conjunction, disjunction, fuzzyOperator->left) + complexity(conjunction, disjunction, fuzzyOperator->right); return result; } } return Complexity(); } void Antecedent::unload() { _expression.reset(fl::null); } void Antecedent::load(const Engine* engine) { load(getText(), engine); } void Antecedent::load(const std::string& antecedent, const Engine* engine) { FL_DBG("Antecedent: " << antecedent); unload(); setText(antecedent); if (Op::trim(antecedent).empty()) { throw Exception("[syntax error] antecedent is empty", FL_AT); } /* Builds an proposition tree from the antecedent of a fuzzy rule. The rules are: 1) After a variable comes 'is', 2) After 'is' comes a hedge or a term 3) After a hedge comes a hedge or a term 4) After a term comes a variable or an operator */ Function function; std::string postfix = function.toPostfix(antecedent); FL_DBG("Postfix: " << postfix); std::stringstream tokenizer(postfix); std::string token; enum FSM { S_VARIABLE = 1, S_IS = 2, S_HEDGE = 4, S_TERM = 8, S_AND_OR = 16 }; int state = S_VARIABLE; std::stack<Expression*> expressionStack; Proposition* proposition = fl::null; try { while (tokenizer >> token) { if (state bitand S_VARIABLE) { Variable* variable = fl::null; if (engine->hasInputVariable(token)) variable = engine->getInputVariable(token); else if (engine->hasOutputVariable(token)) variable = engine->getOutputVariable(token); if (variable) { proposition = new Proposition; proposition->variable = variable; expressionStack.push(proposition); state = S_IS; FL_DBG("Token <" << token << "> is variable"); continue; } } if (state bitand S_IS) { if (token == Rule::isKeyword()) { state = S_HEDGE bitor S_TERM; FL_DBG("Token <" << token << "> is keyword"); continue; } } if (state bitand S_HEDGE) { HedgeFactory* factory = FactoryManager::instance()->hedge(); if (factory->hasConstructor(token)) { Hedge* hedge = factory->constructObject(token); proposition->hedges.push_back(hedge); if (dynamic_cast<Any*> (hedge)) { state = S_VARIABLE bitor S_AND_OR; } else { state = S_HEDGE bitor S_TERM; } FL_DBG("Token <" << token << "> is hedge"); continue; } } if (state bitand S_TERM) { if (proposition->variable->hasTerm(token)) { proposition->term = proposition->variable->getTerm(token); state = S_VARIABLE bitor S_AND_OR; FL_DBG("Token <" << token << "> is term"); continue; } } if (state bitand S_AND_OR) { if (token == Rule::andKeyword() or token == Rule::orKeyword()) { if (expressionStack.size() < 2) { std::ostringstream ex; ex << "[syntax error] logical operator <" << token << "> expects two operands," << "but found <" << expressionStack.size() << "> in antecedent"; throw Exception(ex.str(), FL_AT); } Operator* fuzzyOperator = new Operator; fuzzyOperator->name = token; fuzzyOperator->right = expressionStack.top(); expressionStack.pop(); fuzzyOperator->left = expressionStack.top(); expressionStack.pop(); expressionStack.push(fuzzyOperator); state = S_VARIABLE bitor S_AND_OR; FL_DBG("Subtree: " << fuzzyOperator->toString() << "(" << fuzzyOperator->left->toString() << ") " << "(" << fuzzyOperator->right->toString() << ")"); continue; } } //If reached this point, there was an error if ((state bitand S_VARIABLE) or (state bitand S_AND_OR)) { std::ostringstream ex; ex << "[syntax error] antecedent expected variable or logical operator, but found <" << token << ">"; throw Exception(ex.str(), FL_AT); } if (state bitand S_IS) { std::ostringstream ex; ex << "[syntax error] antecedent expected keyword <" << Rule::isKeyword() << ">, but found <" << token << ">"; throw Exception(ex.str(), FL_AT); } if ((state bitand S_HEDGE) or (state bitand S_TERM)) { std::ostringstream ex; ex << "[syntax error] antecedent expected hedge or term, but found <" << token << ">"; throw Exception(ex.str(), FL_AT); } std::ostringstream ex; ex << "[syntax error] unexpected token <" << token << "> in antecedent"; throw Exception(ex.str(), FL_AT); } if (not ((state bitand S_VARIABLE) or (state bitand S_AND_OR))) { //only acceptable final state if (state bitand S_IS) { std::ostringstream ex; ex << "[syntax error] antecedent expected keyword <" << Rule::isKeyword() << "> after <" << token << ">"; throw Exception(ex.str(), FL_AT); } if ((state bitand S_HEDGE) or (state bitand S_TERM)) { std::ostringstream ex; ex << "[syntax error] antecedent expected hedge or term after <" << token << ">"; throw Exception(ex.str(), FL_AT); } } if (expressionStack.size() != 1) { std::vector<std::string> errors; while (expressionStack.size() > 1) { Expression* expression = expressionStack.top(); expressionStack.pop(); errors.push_back(expression->toString()); delete expression; } std::ostringstream ex; ex << "[syntax error] unable to parse the following expressions in antecedent <" << Op::join(errors, " ") << ">"; throw Exception(ex.str(), FL_AT); } } catch (...) { for (std::size_t i = 0; i < expressionStack.size(); ++i) { delete expressionStack.top(); expressionStack.pop(); } throw; } setExpression(expressionStack.top()); } std::string Antecedent::toString() const { return toInfix(getExpression()); } std::string Antecedent::toPrefix(const Expression* node) const { if (not isLoaded()) { throw Exception("[antecedent error] antecedent <" + _text + "> is not loaded", FL_AT); } if (not node) node = getExpression(); if (dynamic_cast<const Proposition*> (node)) { return node->toString(); } std::stringstream ss; if (const Operator * fuzzyOperator = dynamic_cast<const Operator*> (node)) { ss << fuzzyOperator->toString() << " " << toPrefix(fuzzyOperator->left) << " " << toPrefix(fuzzyOperator->right) << " "; } else { ss << "[antecedent error] unknown class of Expression <" << (node ? node->toString() : "null") << ">"; } return ss.str(); } std::string Antecedent::toInfix(const Expression* node) const { if (not isLoaded()) { throw Exception("[antecedent error] antecedent <" + _text + "> is not loaded", FL_AT); } if (not node) node = getExpression(); if (dynamic_cast<const Proposition*> (node)) { return node->toString(); } std::stringstream ss; if (const Operator * fuzzyOperator = dynamic_cast<const Operator*> (node)) { ss << toInfix(fuzzyOperator->left) << " " << fuzzyOperator->toString() << " " << toInfix(fuzzyOperator->right) << " "; } else { ss << "[antecedent error] unknown class of Expression <" << (node ? node->toString() : "null") << ">"; } return ss.str(); } std::string Antecedent::toPostfix(const Expression* node) const { if (not isLoaded()) { throw Exception("[antecedent error] antecedent <" + _text + "> is not loaded", FL_AT); } if (not node) node = getExpression(); if (dynamic_cast<const Proposition*> (node)) { return node->toString(); } std::stringstream ss; if (const Operator * fuzzyOperator = dynamic_cast<const Operator*> (node)) { ss << toPostfix(fuzzyOperator->left) << " " << toPostfix(fuzzyOperator->right) << " " << fuzzyOperator->toString() << " "; } else { ss << "[antecedent error] unknown class of Expression <" << (node ? node->toString() : "null") << ">"; } return ss.str(); } }
42.020089
130
0.511766
okocsis
5f0b11c4cd68c112a699f2ce03244a5e7c0a8e3a
2,075
cpp
C++
cmd/qc.cpp
cbutakoff/DSI-Studio
d77dffa4526d66da421fa84f7187e85bca6bce7c
[ "BSD-3-Clause" ]
null
null
null
cmd/qc.cpp
cbutakoff/DSI-Studio
d77dffa4526d66da421fa84f7187e85bca6bce7c
[ "BSD-3-Clause" ]
null
null
null
cmd/qc.cpp
cbutakoff/DSI-Studio
d77dffa4526d66da421fa84f7187e85bca6bce7c
[ "BSD-3-Clause" ]
null
null
null
#include <QString> #include <QStringList> #include <QFileInfo> #include "program_option.hpp" #include "libs/dsi/image_model.hpp" QStringList search_files(QString dir,QString filter); std::string quality_check_src_files(QString dir) { std::ostringstream out; QStringList filenames = search_files(dir,"*.src.gz"); out << "FileName\tImage dimension\tResolution\tDWI count\tMax b-value\tB-table matched\tNeighboring DWI correlation" << std::endl; int dwi_count = 0; float max_b = 0; for(int i = 0;check_prog(i,filenames.size());++i) { out << QFileInfo(filenames[i]).baseName().toStdString() << "\t"; ImageModel handle; unique_prog(true); if (!handle.load_from_file(filenames[i].toStdString().c_str())) { out << "Cannot load SRC file" << std::endl; continue; } unique_prog(false); // output image dimension out << image::vector<3,int>(handle.voxel.dim.begin()) << "\t"; // output image resolution out << handle.voxel.vs << "\t"; // output DWI count int cur_dwi_count = 0; out << (cur_dwi_count = handle.src_bvalues.size()) << "\t"; if(i == 0) dwi_count = cur_dwi_count; // output max_b float cur_max_b = 0; out << (cur_max_b = *std::max_element(handle.src_bvalues.begin(),handle.src_bvalues.end())) << "\t"; if(i == 0) max_b = cur_max_b; // check shell structure out << (max_b == cur_max_b && cur_dwi_count == dwi_count ? "Yes\t" : "No\t"); // calculate neighboring DWI correlation out << handle.quality_control_neighboring_dwi_corr() << "\t"; out << std::endl; } return out.str(); } /** perform reconstruction */ int qc(void) { std::string file_name = po.get("source"); if(QFileInfo(file_name.c_str()).isDir()) { file_name += "\\src_report.txt"; std::ofstream out(file_name.c_str()); out << quality_check_src_files(file_name.c_str()); } return 0; }
30.514706
134
0.595663
cbutakoff
5f0e3f2dd7ee0392eb3e547e9dc2ff6d8748df75
1,193
hpp
C++
tooling/data/prefix_splitter.hpp
victorlaurentiu/tsmp
5391ffb488d7db9555405965ede5c63800fbb71f
[ "MIT" ]
23
2021-10-30T09:32:58.000Z
2022-01-23T19:39:26.000Z
tooling/data/prefix_splitter.hpp
victorlaurentiu/tsmp
5391ffb488d7db9555405965ede5c63800fbb71f
[ "MIT" ]
null
null
null
tooling/data/prefix_splitter.hpp
victorlaurentiu/tsmp
5391ffb488d7db9555405965ede5c63800fbb71f
[ "MIT" ]
4
2021-10-31T13:05:29.000Z
2021-11-27T03:18:48.000Z
#pragma once #include "types.hpp" #include <fmt/core.h> #include <fmt/ranges.h> #include <algorithm> #include <iterator> namespace data { class prefix_splitter_t { public: prefix_splitter_t(const std::vector<record_decl_t>& records = {}, std::vector<std::string> trivial_types = {}); void add_record(record_decl_t record); const std::vector<field_decl_t>& fields() const; const std::vector<function_decl_t>& functions() const; const std::vector<record_decl_t>& records() const; static std::string strip_special_chars(std::string input); std::string render() const; private: bool has_field(const field_decl_t& field, const std::vector<field_decl_t>& field_list) const; bool has_function(const function_decl_t& function, const std::vector<function_decl_t>& function_list) const; void add_field(const field_decl_t& field); void add_function(const function_decl_t& function); bool field_list_match(const record_decl_t& lhs, const record_decl_t& rhs) const; std::vector<field_decl_t> m_fields; std::vector<function_decl_t> m_functions; std::vector<record_decl_t> m_records; std::vector<std::string> m_trivial_types; }; }
31.394737
115
0.736798
victorlaurentiu
5f10a140d8b55a3b61668b65754fdce6601f3d16
2,058
hpp
C++
include/shadertoy/pre.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
2
2020-02-23T09:33:07.000Z
2021-11-15T18:23:13.000Z
include/shadertoy/pre.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
2
2019-08-09T15:48:07.000Z
2020-11-16T13:51:56.000Z
include/shadertoy/pre.hpp
vtavernier/libshadertoy
a0b2a133199383cc7e9bcb3c0300f39eb95177c0
[ "MIT" ]
3
2019-12-12T09:42:34.000Z
2020-12-14T03:56:30.000Z
#ifndef _SHADERTOY_PRE_HPP_ #define _SHADERTOY_PRE_HPP_ #include "shadertoy/shadertoy_export.h" /// Base namespace for libshadertoy namespace shadertoy { /// Definition of rendering buffers namespace buffers { struct buffer_output; class basic_buffer; class program_buffer; class toy_buffer; } /// Shader source compiler types namespace compiler { class basic_part; class template_part; class file_part; class program_template; } /// Geometry primitives namespace geometry { class basic_geometry; class screen_quad; } /// OpenGL wrapper helpers namespace gl { class null_buffer_error; class buffer; class opengl_error; class null_framebuffer_error; class framebuffer; class null_program_error; class attrib_location; class uniform_location; class program_link_error; class program_validate_error; class program; class null_query_error; class query; class null_sampler_error; class sampler; class null_renderbuffer_error; class renderbuffer; class null_shader_error; class shader_compilation_error; class shader_allocator; class shader; class null_texture_error; class texture_allocator; class texture; class null_vertex_array_error; class vertex_array; } /// Buffer input class definitions namespace inputs { class basic_input; class buffer_input; class checker_input; class error_input; class exr_input; class file_input; class image_input; class jpeg_input; class noise_input; class soil_input; } /// Swap chain member class definitions namespace members { class basic_member; class buffer_member; class screen_member; } /// Miscellaneous utilities namespace utils { } class basic_shader_inputs; class bound_inputs_base; class swap_chain; class render_context; class shader_compiler; class texture_engine; } // Include template and utilities everywhere #include "shadertoy/shadertoy_error.hpp" #include "shadertoy/size.hpp" #include "shadertoy/member_swap_policy.hpp" #endif /* _SHADERTOY_PRE_HPP_ */
17.294118
44
0.76725
vtavernier
5f126bb8b7c978139132b0742118e7df3dc353d8
71
cc
C++
logs/doc/02_window.cc
chanchann/Burger_client
548753124b563123a479f3e3a5a42f792001d673
[ "MIT" ]
null
null
null
logs/doc/02_window.cc
chanchann/Burger_client
548753124b563123a479f3e3a5a42f792001d673
[ "MIT" ]
null
null
null
logs/doc/02_window.cc
chanchann/Burger_client
548753124b563123a479f3e3a5a42f792001d673
[ "MIT" ]
null
null
null
/** * https://blog.csdn.net/Zhanganliu/article/details/79927310 * */
17.75
60
0.676056
chanchann
5f1a72bb9a4c910ddbe4a97a8b109b5681b1f070
4,044
cpp
C++
projector_fun/data/metaballs.cpp
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
projector_fun/data/metaballs.cpp
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
projector_fun/data/metaballs.cpp
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "metaballs.h" using namespace std; using namespace glm; namespace asdf { namespace projector_fun { metaballs_t::metaballs_t() { balls.reserve(5); balls.push_back(metaball_t{vec3{0.0f, 0.0f, 0.0f}, 50.0f}); balls.push_back(metaball_t{vec3{-100.0f, 100.0f, 0.0f}, 50.0f, vec3{20.0f, -150.0f, 0.0f}}); balls.push_back(metaball_t{vec3{280.0f, -280.0f, 0.0f}, 20.0f, vec3{100.0f, -100.0f, 0.0f}}); balls.push_back(metaball_t{vec3{0.0f, 0.0f, 0.0f}, 10.0f, vec3{100.0f, 20.0f, 0.0f}}); //pre-fill for(size_t i = 0; i < (texture_width * texture_height); ++i) { color_data[i] = clear_color; } texture = std::make_shared<texture_t>("metaball_texture", color_data, texture_width, texture_height); } vec3 metaballs_t::get_pos(const size_t x, const size_t y) const { auto halfwidth = texture_width / 2; auto halfheight = texture_height / 2; auto screenpos = texture_to_screen_space(ivec2{x, y}, ivec2{halfwidth, halfheight}); return vec3(screenpos.x, screenpos.y, 0.0f); } void metaballs_t::draw_metaballs() { //clear for(size_t i = 0; i < (texture_width * texture_height); ++i) { color_data[i] = clear_color; } for(size_t y = 0; y < texture_height; ++y) { for(size_t x = 0; x < texture_width; ++x) { float sum = 0; // Value to act as a summation of all Metaballs' fields applied to this particular pixel for(auto const& ball : balls) { sum += ball.calc(get_pos(x,y)); } draw_pixel(x, y, sum); } } // LOG("max sum: %f", max_sum); texture->write(color_data, texture_width, texture_height); } void metaballs_t::draw_pixel(const size_t x, const size_t y, const float sum) { float min_threshold = 0.99f * draw_mode != shaded; float max_threshold = 1.01f; bool should_draw = false; should_draw |= (draw_mode == hollow) && sum >= min_threshold && sum <= max_threshold; should_draw |= (draw_mode == fill) && sum >= min_threshold; should_draw |= (draw_mode == shaded) && sum >= min_threshold; should_draw |= (draw_mode == inverse) && sum <= max_threshold; if(should_draw) { auto color = COLOR_WHITE; if(draw_mode == shaded) { color = color_data[y * texture_width + x]; color += glm::min(1.0f, sum/5.0f) * COLOR_WHITE; } color_data[y * texture_width + x] = color; } } std::shared_ptr<texture_t> metaballs_t::array_to_texture() { draw_metaballs(); return std::make_shared<texture_t>("metaball test" , color_data , texture_width, texture_height); } void metaballs_t::update(float dt) { float extra_wrap_space = 0.0f; for(auto const& ball : balls) { extra_wrap_space = glm::max(ball.radius, extra_wrap_space); } extra_wrap_space *= 4; // extra_wrap_space = glm::max(texture->halfwidth, texture->halfheight); auto ball_lower_bounds = glm::vec3{-texture->halfwidth - extra_wrap_space, -texture->halfheight - extra_wrap_space, 0.0f}; auto ball_upper_bounds = glm::vec3{ texture->halfwidth + extra_wrap_space, texture->halfheight + extra_wrap_space, 0.0f}; for(auto& ball : balls) { // wrap around sides ball.position.x *= 1 - (2 * (ball.position.x > ball_upper_bounds.x || ball.position.x < ball_lower_bounds.x)); ball.position.y *= 1 - (2 * (ball.position.y > ball_upper_bounds.y || ball.position.y < ball_lower_bounds.y)); ball.position += ball.velocity * dt; } } } }
32.095238
130
0.560584
mflagel
5f21d84c5ad5cc082a87ea46dcf513cbcc1485f8
165
hh
C++
src/debug.hh
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
src/debug.hh
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
src/debug.hh
nojhan/kakoune
c8156429c4685189e0a6b7bd0f273dc64432db2c
[ "Unlicense" ]
null
null
null
#ifndef debug_hh_INCLUDED #define debug_hh_INCLUDED #include "string.hh" namespace Kakoune { void write_debug(const String& str); } #endif // debug_hh_INCLUDED
11.785714
36
0.775758
nojhan
5f23c46d08dbd90a6786bc62dbb46ddd5bf8d734
367
cpp
C++
Exercicios/42.cpp
thiago1590/Exercicios_LinguagemC_1periodo
a7affcbb121493ef8abb556a6bdb7c28926144df
[ "MIT" ]
null
null
null
Exercicios/42.cpp
thiago1590/Exercicios_LinguagemC_1periodo
a7affcbb121493ef8abb556a6bdb7c28926144df
[ "MIT" ]
null
null
null
Exercicios/42.cpp
thiago1590/Exercicios_LinguagemC_1periodo
a7affcbb121493ef8abb556a6bdb7c28926144df
[ "MIT" ]
null
null
null
#include <stdio.h> int calculo(int anos, int meses, int dias, int result) { result = (365 * anos) + (30 * meses) + dias;} int main() { int anos, meses, dias, result,a; printf("digite sua idade em anos meses e dias"); scanf("%d %d %d", &anos, &meses, &dias); a = calculo(anos, meses, dias, result); printf(" sua idade em dias eh %d", a); return 0; }
19.315789
55
0.607629
thiago1590
5f245914a64789f52ed6e45ea844f1f14ffb2212
787
cpp
C++
OnitamaEngine/Source/MoveInformation/MoveInformation.cpp
CodeGorger/OnitamaEngine
641930951ce272ee4922c5dfe57cc3b25b1ed37a
[ "MIT" ]
1
2021-09-14T16:25:02.000Z
2021-09-14T16:25:02.000Z
OnitamaEngine/Source/MoveInformation/MoveInformation.cpp
CodeGorger/OnitamaEngine
641930951ce272ee4922c5dfe57cc3b25b1ed37a
[ "MIT" ]
null
null
null
OnitamaEngine/Source/MoveInformation/MoveInformation.cpp
CodeGorger/OnitamaEngine
641930951ce272ee4922c5dfe57cc3b25b1ed37a
[ "MIT" ]
null
null
null
#include "MoveInformation.h" bool MoveInformation::ParseMove(std::string inTcpMove) { if (inTcpMove.size() > 20) { //"Invalid inTcpMove string is exceeded the maximal allowed length" return false; } size_t indexOfFirstSemicolon = inTcpMove.find_first_of(";"); _cardName=inTcpMove.substr(0, indexOfFirstSemicolon); _figureStartPosition.ParseFromChessString( inTcpMove.substr(indexOfFirstSemicolon,2)); size_t indexOfFirstCharAfterSemicolon = indexOfFirstSemicolon + 2; _figureEndPosition.ParseFromChessString( inTcpMove.substr(indexOfFirstCharAfterSemicolon, 2)); _isInitialized = true; return true; } std::string MoveInformation::ToString() { return _cardName + ";" + _figureStartPosition.ToChessString() + _figureEndPosition.ToChessString(); }
22.485714
69
0.768742
CodeGorger
5f26fe6923b37dc6264b51411b8612ec8e293614
930
cpp
C++
src/utils/dll.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2020-04-10T14:39:00.000Z
2021-02-11T15:52:16.000Z
src/utils/dll.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
2
2019-12-17T08:50:20.000Z
2020-02-03T09:37:56.000Z
src/utils/dll.cpp
TiWinDeTea/NinjaClown
fdd48e62466f11036fa0360fad2bcb182d6d3352
[ "MIT" ]
1
2020-08-19T03:06:52.000Z
2020-08-19T03:06:52.000Z
#include "utils/dll.hpp" #ifdef OS_WINDOWS # include "utils/system.hpp" #endif namespace utils { dll::~dll() { if (m_handle == nullptr) { return; } #if defined OS_WINDOWS FreeLibrary(m_handle); #elif defined OS_LINUX dlclose(m_handle); #endif } dll::operator bool() const { return m_handle != nullptr; } std::string dll::error() const { #if defined OS_WINDOWS return sys_last_error(); #elif defined OS_LINUX const char *error = dlerror(); if (error == nullptr) { return ""; } return error; #endif } bool dll::load(const char *dll_path) { #if defined OS_WINDOWS if (m_handle != nullptr) { FreeLibrary(m_handle); } m_handle = LoadLibrary(dll_path); #elif defined OS_LINUX if (m_handle != nullptr) { dlclose(m_handle); } m_handle = dlopen(dll_path, RTLD_NOW); #endif return m_handle != nullptr; } bool dll::load(const std::string &dll_path) { return load(dll_path.c_str()); } } // namespace utils
16.034483
45
0.692473
TiWinDeTea
5f2c025588e266c2452f1bc787d861692e79a247
2,668
hpp
C++
lib/malloy/core/detail/controller_run_result.hpp
Tectu/malloy
066adfe3ac312ac4c0b4a745603faed650400f5a
[ "MIT" ]
22
2021-04-17T17:32:14.000Z
2022-03-29T09:42:03.000Z
lib/malloy/core/detail/controller_run_result.hpp
Tectu/malloy
066adfe3ac312ac4c0b4a745603faed650400f5a
[ "MIT" ]
98
2021-04-03T18:53:19.000Z
2022-02-06T10:49:30.000Z
lib/malloy/core/detail/controller_run_result.hpp
Tectu/malloy
066adfe3ac312ac4c0b4a745603faed650400f5a
[ "MIT" ]
3
2021-05-12T15:17:11.000Z
2021-12-28T03:15:46.000Z
#pragma once #include <boost/asio/executor_work_guard.hpp> #include <boost/asio/io_context.hpp> #include <boost/asio/use_future.hpp> #include <spdlog/logger.h> #include <memory> #include <thread> #include <stdexcept> namespace malloy::detail { /** * Controller configuration. */ struct controller_config { /** * The number of worked threads for the I/O context to use. */ std::size_t num_threads = 1; /** * The logger instance to use. */ std::shared_ptr<spdlog::logger> logger; void validate() { if (!logger) throw std::logic_error{"invalid config: logger is null"}; else if (num_threads == 0) throw std::logic_error{"invalid config: cannot have 0 threads"}; }; }; template<typename T> class controller_run_result { public: controller_run_result(const controller_config& cfg, T ctrl, std::unique_ptr<boost::asio::io_context> ioc) : m_io_ctx{std::move(ioc)}, m_workguard{m_io_ctx->get_executor()}, m_ctrl{std::move(ctrl)} { // Create the I/O context threads m_io_threads.reserve(cfg.num_threads - 1); for (std::size_t i = 0; i < cfg.num_threads; i++) { m_io_threads.emplace_back( [this] { m_io_ctx->run(); }); } // Log cfg.logger->debug("starting i/o context."); } ~controller_run_result() { // Stop the `io_context`. This will cause `run()` // to return immediately, eventually destroying the // `io_context` and all of the sockets in it. m_io_ctx->stop(); // Tell the workguard that we no longer need it's service m_workguard.reset(); for (auto& thread : m_io_threads) { thread.join(); }; } /** * @brief Block until all queued async actions completed */ void run() { m_workguard.reset(); m_io_ctx->run(); } private: using workguard_t = boost::asio::executor_work_guard<boost::asio::io_context::executor_type>; std::unique_ptr<boost::asio::io_context> m_io_ctx; workguard_t m_workguard; std::vector<std::thread> m_io_threads; T m_ctrl; // This order matters, the T may destructor need access to something related to the io context }; } // namespace malloy::detail
28.084211
115
0.53973
Tectu
5f2dc3edcc7d8f849aefa87bc990ccc20f81fcb7
1,259
cpp
C++
Tree/Binary_Tree/main.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
Tree/Binary_Tree/main.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
Tree/Binary_Tree/main.cpp
AshishS-1123/Data-Structures
58c36b7f1e0bc72064aac5ff53f96c7df34e52b5
[ "MIT" ]
null
null
null
#include <iostream> #include "binary_tree.cpp" #include "traverse.cpp" using namespace std; int main() { // create a tree object binaryTree tree = binaryTree(); // insert 10, 20, 30, 40, 50, 60 cout << "\nAfter adding 10..."; tree.insert_element(10); tree.print_tree(); cout << "\nAfter adding 20..."; tree.insert_element(20); tree.print_tree(); cout << "\nAfter adding 30..."; tree.insert_element(30); tree.print_tree(); cout << "\nAfter adding 40..."; tree.insert_element(40); tree.print_tree(); cout << "\nAfter adding 50..."; tree.insert_element(50); tree.print_tree(); cout << "\nAfter adding 60..."; tree.insert_element(60); tree.print_tree(); // print inorder traversal of tree cout << "\nInorder traversal of tree::\n\t"; traverse_inorder(tree); // print preorder traversal of tree cout << "\nPreorder traversal of tree::\n\t"; traverse_preorder(tree); // print postrder traversal of tree cout << "\nPostorder traversal of tree::\n\t"; traverse_postorder(tree); // print level order traversal cout << "\nLevel Order traversal of tree::\n\t"; traverse_level(tree); cout << "\n"; return 0; }
20.639344
52
0.612391
AshishS-1123
5f2ff7f49f8e5b1f37b9117542c9bfe0af6fbc11
2,113
cpp
C++
src/apps/S3DAnalyzer/widgets/widthhintlabel.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
8
2017-04-16T16:38:15.000Z
2020-04-20T03:23:15.000Z
src/apps/S3DAnalyzer/widgets/widthhintlabel.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
40
2017-04-12T17:24:44.000Z
2017-12-21T18:41:23.000Z
src/apps/S3DAnalyzer/widgets/widthhintlabel.cpp
hugbed/OpenS3D
4ffad16f9b0973404b59eb1424cc45f68754fe12
[ "BSD-3-Clause" ]
6
2017-07-13T21:51:09.000Z
2021-05-18T16:22:03.000Z
#include "widthhintlabel.h" #include <gsl/gsl_util> WidthHintLabel::WidthHintLabel(QWidget* parent) : QLabel(parent) { initPixmaps(); setAlignment(Qt::AlignCenter); setSizePolicy(QSizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed)); auto&& pixmap = m_pixmaps[static_cast<int>(State::Neutral)]; setMinimumSize(pixmap->width() + 5, pixmap->height() + 4); } void WidthHintLabel::setState(State state) { setPixmap(*gsl::at(m_pixmaps, static_cast<int>(state))); update(); } void WidthHintLabel::updateHint(float ratio) { // ok this is the worst // todo: think a bit more about this // it's way worse to have more than not enough range if (inRange(0.8f, 1.0f, ratio)) { setState(State::Neutral); } else if (inRange(0.7f, 0.8f, ratio)) { setState(State::ShouldWiden); } else if (inRange(1.0f, 1.05f, ratio)) { setState(State::ShouldNarrow); } else if (inRange(0.6f, 0.7f, ratio)) { setState(State::ShouldWidenMuch); } else if (inRange(1.05f, 1.1f, ratio)) { setState(State::ShouldNarrowMuch); } else if (ratio < 0.6f) { setState(State::ShouldWidenVeryMuch); } else if (ratio >= 1.1f) { setState(State::ShouldNarrowVeryMuch); } update(); } // todo, this should be outside bool WidthHintLabel::inRange(float min, float max, float value) { return min <= value && value < max; } void WidthHintLabel::initPixmaps() { initPixmap(State::ShouldNarrowVeryMuch, ":icons/in_arrows_red.png"); initPixmap(State::ShouldNarrowMuch, ":icons/in_arrows_orange.png"); initPixmap(State::ShouldNarrow, ":icons/in_arrows_green.png"); initPixmap(State::ShouldWidenVeryMuch, ":icons/out_arrows_red.png"); initPixmap(State::ShouldWidenMuch, ":icons/out_arrows_orange.png"); initPixmap(State::ShouldWiden, ":icons/out_arrows_green.png"); initPixmap(State::Neutral, ":icons/neutral_arrows.png"); setPixmap(*m_pixmaps[static_cast<int>(State::Neutral)]); } void WidthHintLabel::initPixmap(State state, const QString& filepath) { auto pixmap = std::make_unique<QPixmap>(filepath); gsl::at(m_pixmaps, static_cast<int>(state)) = std::move(pixmap); }
33.539683
73
0.708471
hugbed
5f311ccb8f94cd59ff9a022f220547b79ca01ba1
1,134
cpp
C++
OpenGL_Planetarium/Cubemap.cpp
vmkarhula/Planetarium
f99acf1c98f2789a3eae70eba69d83ab4cba2a43
[ "MIT" ]
null
null
null
OpenGL_Planetarium/Cubemap.cpp
vmkarhula/Planetarium
f99acf1c98f2789a3eae70eba69d83ab4cba2a43
[ "MIT" ]
null
null
null
OpenGL_Planetarium/Cubemap.cpp
vmkarhula/Planetarium
f99acf1c98f2789a3eae70eba69d83ab4cba2a43
[ "MIT" ]
null
null
null
#include "Cubemap.h" #include <iostream> #include "stb/stb_image.h" Cubemap::Cubemap(std::vector<std::string> paths) { glGenTextures(1, &m_GLID); glBindTexture(GL_TEXTURE_CUBE_MAP, m_GLID); int width, height, nrChannels; for (unsigned int i = 0; i < paths.size(); i++) { unsigned char* data = stbi_load(paths[i].c_str(), &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); stbi_image_free(data); } else { std::cerr << "Cubemap failed to load texture at path:" << paths[i] << std::endl; stbi_image_free(data); } } glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } Cubemap::~Cubemap() { glDeleteTextures(1, &m_GLID); }
23.142857
113
0.741623
vmkarhula
5f3d6887aeba89c27f8cd0eaa2fe4b7d778f677d
1,206
cpp
C++
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
1
2021-05-19T23:02:04.000Z
2021-05-19T23:02:04.000Z
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
null
null
null
bistro/cron/CrontabItem.cpp
jiazerojia/bistro
95c8d9cf9786ff87d845d7732622a46d90de5f58
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "bistro/bistro/cron/CrontabItem.h" #include <memory> #include <stdexcept> #include <folly/dynamic.h> #include "bistro/bistro/cron/EpochCrontabItem.h" #include "bistro/bistro/cron/StandardCrontabItem.h" // Add stateful Cron support for more robustness, see README for a design. using namespace folly; using namespace std; namespace facebook { namespace bistro { unique_ptr<const CrontabItem> CrontabItem::fromDynamic( const dynamic& d, boost::local_time::time_zone_ptr tz) { if (!d.isObject()) { throw runtime_error("CrontabItem must be an object"); } if (d.find("epoch") != d.items().end()) { return unique_ptr<CrontabItem>(new detail_cron::EpochCrontabItem(d, tz)); } return unique_ptr<CrontabItem>(new detail_cron::StandardCrontabItem(d, tz)); } string CrontabItem::getPrintable() const { throw logic_error("getPrintable not implemented"); } }}
27.409091
79
0.733002
jiazerojia
5f3f6e57bd25a9f84975ffcae87ddcc1b522466e
757
hpp
C++
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
patrykkolodziej/Explit
155a35e4b8951764e6bedb8847d3196561a4255c
[ "MIT" ]
18
2019-05-09T10:24:53.000Z
2021-05-17T04:39:47.000Z
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
danielkrupinski/Expl
74124b67361cd29dd34389d692e43df86f83d072
[ "MIT" ]
6
2019-05-09T16:26:01.000Z
2019-05-14T11:30:18.000Z
Explit/Explit/sdk/interfaces/valve/i_base_client_dll.hpp
patrykkolodziej/Explit
155a35e4b8951764e6bedb8847d3196561a4255c
[ "MIT" ]
8
2019-05-08T17:28:24.000Z
2021-03-25T09:52:44.000Z
#pragma once #include "i_global_vars.hpp" #include "../../misc/valve/client_class.hpp" #include "../../misc/valve/i_app_system.hpp" class i_base_client_dll { public: virtual int connect(createinterfacefn app_system_factory, i_global_vars_base *p_globals) = 0; virtual int disconnect(void) = 0; virtual int init(createinterfacefn app_system_factory, i_global_vars_base *p_globals) = 0; virtual void post_init() = 0; virtual void shutdown(void) = 0; virtual void level_init_pre_entity(char const* p_map_name) = 0; virtual void level_init_post_entity() = 0; virtual void level_shutdown(void) = 0; virtual client_class* get_all_classes(void) = 0; };
42.055556
107
0.667107
patrykkolodziej
5f3f78d4cc8e7c4b773fff444541a7cc366b55de
441
cpp
C++
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
GraphMIC/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
43
2016-04-11T11:34:05.000Z
2022-03-31T03:37:57.000Z
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
1
2016-05-17T12:58:16.000Z
2016-05-17T12:58:16.000Z
modules/logic/src/Logic/Cv/gmLogicCvBase.cpp
kevinlq/GraphMIC
8fc2aeb0143ee1292c6757f010fc9e8c68823e2b
[ "BSD-3-Clause" ]
14
2016-05-13T20:23:16.000Z
2021-12-20T10:33:19.000Z
#include "gmLogicCvBase.hpp" namespace gm { namespace Logic { namespace Cv { Base::Base(const QString& name) : Logic::Base("cv", name) { log_trace(Log::New); this->setRunnable(true); this->setUseTimer(true); } Base::~Base() { log_trace(Log::Del); } } } }
19.173913
69
0.394558
GraphMIC
5f414de234732722d05c50fc338e610a8d84e190
2,363
hpp
C++
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
2
2016-08-06T06:21:02.000Z
2017-01-10T05:45:13.000Z
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
1
2017-04-15T20:54:59.000Z
2017-04-15T20:54:59.000Z
y2018/utils/udpClientServer.hpp
valkyrierobotics/vision2018
aa82e936c5481b7cc43a46ff5f6e68702c2166c2
[ "BSD-2-Clause" ]
3
2016-07-30T06:19:55.000Z
2017-02-07T01:55:05.000Z
// UDP Client Server -- send/receive UDP packets // Copyright (C) 2013 Made to Order Software Corp. // // 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 2 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, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef UDP_CLIENT_SERVER_H #define UDP_CLIENT_SERVER_H #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <stdexcept> #include <errno.h> #include <stdio.h> namespace udp_client_server { class udp_client_server_runtime_error : public std::runtime_error { public: udp_client_server_runtime_error(const char *w) : std::runtime_error(w) {} }; class udp_client { public: udp_client(const std::string& addr, int port); ~udp_client(); int get_socket() const; int get_port() const; std::string get_addr() const; int send(const char *msg, size_t size); private: int f_socket; int f_port; std::string f_addr; struct addrinfo * f_addrinfo; }; class udp_server { public: udp_server(const std::string& addr, int port); ~udp_server(); int get_socket() const; int get_port() const; std::string get_addr() const; int recv(char *msg, size_t max_size); int timed_recv(char *msg, size_t max_size, int max_wait_ms); private: int f_socket; int f_port; std::string f_addr; struct addrinfo * f_addrinfo; }; } // namespace udp_client_server #endif // UDP_CLIENT_SERVER_H
29.5375
81
0.60474
valkyrierobotics
5f4b0db7e754be422bc7951f5cf621ed8fab7015
3,458
cpp
C++
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
16
2017-01-11T17:28:03.000Z
2021-09-27T16:12:01.000Z
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
null
null
null
widgets/demos/ex-translucent-clock/clock.cpp
sfaure-witekio/qt-training-material
d166e4ed9cc5f5faab85b0337c5844c4cdcb206e
[ "BSD-3-Clause" ]
4
2017-03-17T02:44:32.000Z
2021-01-22T07:57:34.000Z
/************************************************************************* * * Copyright (c) 2016 The Qt Company * All rights reserved. * * See the LICENSE.txt file shipped along with this file for the license. * *************************************************************************/ #include <QtGui> #include <QtWidgets> #include "clock.h" Clock::Clock(QWidget *parent) : QWidget(parent, Qt::FramelessWindowHint | Qt::WindowSystemMenuHint) { QTimer *timer = new QTimer(this); connect(timer, &QTimer::timeout, this, static_cast<void (Clock::*)()>(&Clock::update)); timer->start(1000); QAction *quitAction = new QAction(tr("E&xit"), this); quitAction->setShortcut(tr("Ctrl+Q")); connect(quitAction, &QAction::triggered, qApp, &QApplication::quit); addAction(quitAction); setAttribute(Qt::WA_TranslucentBackground); setContextMenuPolicy(Qt::ActionsContextMenu); setToolTip(tr("Drag the clock with the left mouse button.\n" "Use the right mouse button to open a context menu.")); setWindowTitle(tr("Analog Clock")); } void Clock::mousePressEvent(QMouseEvent *event) { if (event->button() == Qt::LeftButton) { dragPosition = event->globalPos() - frameGeometry().topLeft(); event->accept(); } } void Clock::mouseMoveEvent(QMouseEvent *event) { if (event->buttons() & Qt::LeftButton) { move(event->globalPos() - dragPosition); event->accept(); } } void Clock::paintEvent(QPaintEvent *) { static const QPoint hourHand[3] = { QPoint(7, 8), QPoint(-7, 8), QPoint(0, -40) }; static const QPoint minuteHand[3] = { QPoint(7, 8), QPoint(-7, 8), QPoint(0, -70) }; QColor hourColor(191, 0, 0); QColor minuteColor(0, 0, 191, 191); int side = qMin(width(), height()); QTime time = QTime::currentTime(); QPainter painter(this); painter.setRenderHint(QPainter::Antialiasing); painter.translate(width() / 2, height() / 2); QRadialGradient gradient(0.0, 0.0, side*0.5, 0.0, 0.0); gradient.setColorAt(0.0, QColor(255, 255, 255, 255)); gradient.setColorAt(0.1, QColor(255, 255, 255, 31)); gradient.setColorAt(0.7, QColor(255, 255, 255, 31)); gradient.setColorAt(0.8, QColor(0, 31, 0, 31)); gradient.setColorAt(0.9, QColor(255, 255, 255, 255)); gradient.setColorAt(1.0, QColor(255, 255, 255, 255)); painter.setPen(QColor(0, 0, 0, 32)); painter.setBrush(gradient); painter.drawEllipse(-side/2.0 + 1, -side/2.0 + 1, side - 2, side - 2); painter.scale(side / 200.0, side / 200.0); painter.setPen(Qt::NoPen); painter.setBrush(hourColor); painter.save(); painter.rotate(30.0 * ((time.hour() + time.minute() / 60.0))); painter.drawConvexPolygon(hourHand, 3); painter.restore(); painter.setPen(hourColor); for (int i = 0; i < 12; ++i) { painter.drawLine(88, 0, 96, 0); painter.rotate(30.0); } painter.setPen(Qt::NoPen); painter.setBrush(minuteColor); painter.save(); painter.rotate(6.0 * (time.minute() + time.second() / 60.0)); painter.drawConvexPolygon(minuteHand, 3); painter.restore(); painter.setPen(minuteColor); for (int j = 0; j < 60; ++j) { if ((j % 5) != 0) painter.drawLine(92, 0, 96, 0); painter.rotate(6.0); } } QSize Clock::sizeHint() const { return QSize(200, 200); }
27.664
91
0.588201
sfaure-witekio
5f4d34bace6ee9cd7d0e379eafef77ab8e33cbb0
7,687
hh
C++
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
14
2020-07-31T09:35:23.000Z
2021-11-15T11:18:35.000Z
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
saphIR/include/ir/types.hh
balayette/saphIR-project
18da494ac21e5433fdf1c646be02c9bf25177d7d
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <vector> #include "utils/assert.hh" #include "utils/scoped.hh" #include "ir/ops.hh" #include "utils/symbol.hh" #include "utils/ref.hh" #define DEFAULT_SIZE (42) namespace mach { struct target; } namespace types { enum class type { INT, STRING, VOID, INVALID }; enum class signedness { INVALID, SIGNED, UNSIGNED }; struct ty { virtual ~ty() = default; ty(mach::target &target) : target_(target) {} virtual std::string to_string() const = 0; // t can be assigned to this virtual bool assign_compat(const ty *t) const = 0; // this can be cast to t virtual bool cast_compat(const ty *) const { return false; } // return the resulting type if this BINOP t is correctly typed, // nullptr otherwise. // TODO: This is where implicit type conversions would be handled virtual utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const = 0; // return the resulting type if UNARYOP this is correctly typed, // nullptr otherwise. virtual utils::ref<ty> unaryop_type(ops::unaryop unaryop) const = 0; virtual ty *clone() const = 0; virtual bool size_modifier(size_t sz) { return sz == DEFAULT_SIZE; } virtual size_t size() const { UNREACHABLE("size() on type " + to_string() + " with no size"); } virtual signedness get_signedness() const { return signedness::INVALID; } virtual void set_signedness(types::signedness) { UNREACHABLE("Trying to set signedness on type {}", to_string()); } /* * Structs and arrays have a size which is different from the size * that the codegen uses to manipulate them: they're actually * pointers */ virtual size_t assem_size() const { return size(); } mach::target &target() { return target_; } protected: mach::target &target_; }; bool operator==(const ty *ty, const type &t); bool operator!=(const ty *ty, const type &t); struct builtin_ty : public ty { builtin_ty(mach::target &target); builtin_ty(type t, signedness is_signed, mach::target &target); builtin_ty(type t, size_t size, signedness is_signed, mach::target &target); std::string to_string() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual builtin_ty *clone() const override { return new builtin_ty(ty_, size_, size_modif_, is_signed_, target_); } size_t size() const override; bool size_modifier(size_t sz) override; type ty_; virtual signedness get_signedness() const override { return is_signed_; } virtual void set_signedness(types::signedness sign) override { is_signed_ = sign; } private: builtin_ty(type t, size_t size, size_t size_modif, signedness is_signed, mach::target &target); size_t size_; size_t size_modif_; signedness is_signed_; }; struct pointer_ty : public ty { private: pointer_ty(utils::ref<ty> ty, unsigned ptr); public: pointer_ty(utils::ref<ty> ty); std::string to_string() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual pointer_ty *clone() const override { return new pointer_ty(ty_, ptr_); } virtual signedness get_signedness() const override { return ty_->get_signedness(); } size_t size() const override; size_t pointed_size() const; utils::ref<ty> ty_; unsigned ptr_; }; bool is_scalar(const ty *ty); utils::ref<ty> deref_pointer_type(utils::ref<ty> ty); bool is_integer(const ty *ty); struct composite_ty : public ty { composite_ty(mach::target &target) : ty(target) {} }; struct array_ty : public composite_ty { array_ty(utils::ref<types::ty> type, size_t n); std::string to_string() const override; size_t size() const override; bool assign_compat(const ty *t) const override; bool cast_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual array_ty *clone() const override { return new array_ty(ty_, n_); } virtual signedness get_signedness() const override { return signedness::UNSIGNED; } virtual size_t assem_size() const override { return 8; } utils::ref<types::ty> ty_; size_t n_; }; struct braceinit_ty : public composite_ty { braceinit_ty(const std::vector<utils::ref<types::ty>> &types); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual braceinit_ty *clone() const override { return new braceinit_ty(types_); } std::vector<utils::ref<types::ty>> types_; }; struct struct_ty : public composite_ty { struct_ty(const symbol &name, const std::vector<symbol> &names, const std::vector<utils::ref<types::ty>> &types); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual struct_ty *clone() const override { return new struct_ty(name_, names_, types_); } virtual size_t assem_size() const override { return 8; } std::optional<size_t> member_index(const symbol &name); size_t member_offset(const symbol &name); utils::ref<ty> member_ty(const symbol &name); size_t size() const override; virtual signedness get_signedness() const override { // structs behave as pointers return signedness::UNSIGNED; } std::vector<utils::ref<types::ty>> types_; symbol name_; std::vector<symbol> names_; private: size_t size_; }; struct fun_ty : public ty { fun_ty(utils::ref<types::ty> ret_ty, const std::vector<utils::ref<types::ty>> &arg_tys, bool variadic); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual fun_ty *clone() const override { return new fun_ty(ret_ty_, arg_tys_, variadic_); } virtual signedness get_signedness() const override { return signedness::INVALID; } virtual size_t assem_size() const override { return 8; } utils::ref<types::ty> ret_ty_; std::vector<utils::ref<types::ty>> arg_tys_; bool variadic_; }; /* * The parser outputs named_ty everywhere a type is used, and they are replaced * by pointers to actual types during semantic analysis. * This is necessary because of type declarations that the parser doesn't track. */ struct named_ty : public ty { named_ty(const symbol &name, mach::target &target, size_t sz = DEFAULT_SIZE); std::string to_string() const override; bool assign_compat(const ty *t) const override; utils::ref<ty> binop_compat(ops::binop binop, const ty *t) const override; utils::ref<ty> unaryop_type(ops::unaryop binop) const override; virtual named_ty *clone() const override { return new named_ty(name_, target_, sz_); } size_t size() const override; symbol name_; private: int sz_; }; utils::ref<ty> concretize_type(utils::ref<ty> &t, utils::scoped_map<symbol, utils::ref<ty>> tmap); utils::ref<fun_ty> normalize_function_pointer(utils::ref<ty> ty); } // namespace types
24.877023
80
0.712372
balayette
5f519bc1c25c34290477e9ce07ed8842754151f5
10,370
cpp
C++
src/audio/CBasicSound.cpp
JackCarlson/Avara
2d79f6a21855759e427e13ee2d791257bc8c8c71
[ "MIT" ]
77
2016-10-30T18:37:14.000Z
2022-02-13T05:02:55.000Z
src/audio/CBasicSound.cpp
tra/Avara
5a6b5a4f2cf29e8b2ddf7dd3f422579f37a14dab
[ "MIT" ]
135
2018-09-09T06:46:04.000Z
2022-01-29T19:33:12.000Z
src/audio/CBasicSound.cpp
tra/Avara
5a6b5a4f2cf29e8b2ddf7dd3f422579f37a14dab
[ "MIT" ]
19
2018-09-09T02:02:46.000Z
2022-03-16T08:21:08.000Z
/* Copyright ©1994-1996, Juri Munkki All rights reserved. File: CBasicSound.c Created: Friday, December 23, 1994, 10:57 Modified: Tuesday, September 3, 1996, 21:27 */ #include "CBasicSound.h" #include "CSoundHub.h" #include "CSoundMixer.h" #include <assert.h> void CBasicSound::Release() { if (itsHub) { if (motionLink) itsHub->ReleaseLink(motionLink); if (controlLink) itsHub->ReleaseLink(controlLink); itsHub->Restock(this); } } void CBasicSound::SetLoopCount(short count) { loopCount[0] = loopCount[1] = count; } void CBasicSound::SetRate(Fixed theRate) { // Not applicable } Fixed CBasicSound::GetSampleRate() { return itsMixer->samplingRate; } void CBasicSound::SetSoundLength(Fixed seconds) { int numSamples; numSamples = FMul(seconds >> 8, GetSampleRate() >> 8); numSamples -= sampleLen; if (numSamples > 0 && loopEnd > loopStart) { loopCount[0] = numSamples / (loopEnd - loopStart); loopCount[1] = loopCount[0]; } else { loopCount[0] = 0; loopCount[1] = 0; } } void CBasicSound::Start() { itsMixer->AddSound(this); } void CBasicSound::SetVolume(Fixed vol) { masterVolume = vol; volumes[0] = masterVolume >> (17 - VOLUMEBITS); volumes[1] = volumes[0]; } void CBasicSound::SetDirectVolumes(Fixed vol0, Fixed vol1) { volumes[0] = vol0 >> (17 - VOLUMEBITS); volumes[1] = vol1 >> (17 - VOLUMEBITS); } void CBasicSound::StopSound() { stopNow = true; } void CBasicSound::CheckSoundLink() { SoundLink *aLink; Fixed *s, *d; Fixed timeConversion; Fixed t; aLink = motionLink; timeConversion = itsMixer->timeConversion; s = aLink->nSpeed; d = aLink->speed; *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); *d++ = FMul(*s++, timeConversion); s = aLink->nLoc; d = aLink->loc; *d++ = *s++; *d++ = *s++; *d++ = *s++; s = aLink->speed; d = aLink->loc; t = aLink->t; *d++ -= *s++ * t; *d++ -= *s++ * t; *d++ -= *s++ * t; aLink->meta = metaNoData; } void CBasicSound::SetSoundLink(SoundLink *linkPtr) { if (linkPtr) linkPtr->refCount++; if (motionLink) itsHub->ReleaseLink(motionLink); motionLink = linkPtr; } void CBasicSound::SetControlLink(SoundLink *linkPtr) { if (linkPtr) linkPtr->refCount++; if (controlLink) itsHub->ReleaseLink(controlLink); controlLink = linkPtr; } void CBasicSound::Reset() { motionLink = NULL; controlLink = NULL; itsSamples = NULL; sampleLen = 0; sampleData = NULL; loopStart = 0; loopEnd = 0; loopCount[0] = loopCount[1] = 0; stopNow = false; volumeMax = VOLUMERANGE >> 1; distanceDelay = true; } void CBasicSound::UseSamplePtr(Sample *samples, int numSamples) { currentCount[0].i = 0; currentCount[0].f = 0; currentCount[1].i = 0; currentCount[1].f = 0; sampleLen = numSamples; sampleData = samples; loopStart = 0; loopEnd = 0; loopCount[0] = loopCount[1] = 0; // Don't loop. } void CBasicSound::UseSamples(SampleHeaderHandle theSample) { if (theSample) { itsSamples = theSample; UseSamplePtr(sizeof(SampleHeader) + (Sample *)*theSample, (*theSample)->len); loopStart = (*itsSamples)->loopStart; loopEnd = (*itsSamples)->loopEnd; loopCount[0] = loopCount[1] = (*itsSamples)->loopCount; } else { UseSamplePtr(NULL, 0); } } void CBasicSound::CalculatePosition(int t) { CSoundMixer *m; SoundLink *s; short i; m = itsMixer; s = motionLink; squareAcc[0] = squareAcc[1] = 0; for (i = 0; i < 3; i++) { relPos[i] = s->loc[i] - m->motion.loc[i] + (s->speed[i] - m->motion.speed[i]) * t; FSquareAccumulate(relPos[i], squareAcc); } if (0x007Fffff < (unsigned int)squareAcc[0]) dSquare = 0x7FFFffff; else dSquare = ((squareAcc[0] & 0x00FFFFFF) << 8) | ((squareAcc[1] & 0xFF000000) >> 24); } void CBasicSound::SanityCheck() { if (loopStart == loopEnd) { loopCount[0] = loopCount[1] = 0; } } void CBasicSound::FirstFrame() { SanityCheck(); if (motionLink && distanceDelay) { int delta; if (motionLink->meta == metaNewData) CheckSoundLink(); CalculatePosition(itsMixer->frameStartTime); delta = FMul(FSqroot(squareAcc), itsMixer->distanceToSamples); currentCount[0].i -= delta; currentCount[1].i -= delta; } } void CBasicSound::CalculateMotionVolume() { Fixed rightDot; CSoundMixer *m = itsMixer; Fixed adjustedVolume; if (motionLink->meta == metaNewData) CheckSoundLink(); CalculatePosition(m->frameStartTime); if (dSquare == 0) dSquare = m->distanceAdjust >> 2; adjustedVolume = FMulDivNZ(masterVolume, m->distanceAdjust, dSquare); if (adjustedVolume > m->maxAdjustedVolume) adjustedVolume = m->maxAdjustedVolume; if (m->stereo) { distance = FSqroot(squareAcc); if (distance > 0) { rightDot = FMul(relPos[0], m->rightVector[0]); rightDot += FMul(relPos[1], m->rightVector[1]); rightDot += FMul(relPos[2], m->rightVector[2]); rightDot = FDiv(rightDot, distance); } else { rightDot = 0; // Middle, if distance = 0 } if (m->strongStereo) { // "Hard" stereo effect for loudspeakers users. // Sound position LEFT MIDDLE RIGHT // Left channel 1.0 0.5 0.0 // Right channel 0.0 0.5 1.0 volumes[0] = FMul(FIX(1) - rightDot, adjustedVolume) >> (18 - VOLUMEBITS); volumes[1] = FMul(FIX(1) + rightDot, adjustedVolume) >> (18 - VOLUMEBITS); } else { // "Soft" stereo effect for headphones users. // Sound position LEFT MIDDLE RIGHT // Left channel 1.0 0.66 0.33 // Right channel 0.33 0.66 1.0 adjustedVolume /= 3; volumes[0] = FMul(FIX(2) - rightDot, adjustedVolume) >> (18 - VOLUMEBITS); volumes[1] = FMul(FIX(2) + rightDot, adjustedVolume) >> (18 - VOLUMEBITS); // With headphones, it is irritating, if one headphone is producing // sound (pressure) and the other one is not. For these cases, the // volume of the otherwise silent channel is set to 1 to avoid the problem. if (!volumes[0] ^ !volumes[1]) { if (!volumes[0]) volumes[0] = 1; if (!volumes[1]) volumes[1] = 1; } } balance = rightDot; } else { volumes[0] = adjustedVolume >> (17 - VOLUMEBITS); volumes[1] = volumes[0]; balance = 0; } if (volumes[0] > volumeMax) volumes[0] = volumeMax; if (volumes[1] > volumeMax) volumes[1] = volumeMax; } short CBasicSound::CalcVolume(short theChannel) { if (controlLink) { if (controlLink->meta == metaSuspend) return 0; else if (controlLink->meta == metaFade) { loopCount[0] = 0; loopCount[1] = 0; } } if (motionLink && motionLink->meta == metaFade) { loopCount[0] = 0; loopCount[1] = 0; } if (currentCount[0].i <= -itsMixer->soundBufferSize) { volumes[theChannel] = 0; } else if (motionLink && theChannel == 0) { CalculateMotionVolume(); } return volumes[theChannel]; } void CBasicSound::WriteFrame(short theChannel, short volumeAllowed) { Sample *s; WordSample *d; SampleConvert *converter; int thisCount; int remaining; int baseCount = currentCount[0].i; int loopCopy = loopCount[0]; converter = &itsMixer->volumeLookup[volumeAllowed - 1]; d = itsMixer->mixTo[theChannel]; if (baseCount >= 0) { thisCount = itsMixer->soundBufferSize; } else { d -= baseCount; thisCount = itsMixer->soundBufferSize + baseCount; baseCount = 0; } do { s = sampleData + baseCount; remaining = baseCount + thisCount - loopEnd; if (loopCopy && remaining > 0) { if (loopCopy > 0) // Negative loopCount will loop forever. loopCopy--; thisCount -= remaining; baseCount = loopStart; } else { remaining = 0; } if (thisCount + baseCount > sampleLen) { thisCount = sampleLen - baseCount; remaining = 0; } assert(0 && "port asm"); /* TODO: port asm { clr.w D0 move.l converter,A0 subq.w #1,thisCount bmi.s @nothing @loop move.b (s)+,D0 move.w 0(A0,D0.w*2),D1 add.w D1,(d)+ dbra thisCount,@loop @nothing } */ thisCount = remaining; } while (thisCount); } Boolean CBasicSound::EndFrame() { if (stopNow || (motionLink && motionLink->meta == metaKillNow) || (controlLink && controlLink->meta == metaKillNow)) { stopNow = true; } else { if (controlLink && controlLink->meta == metaSuspend) { return false; } if (loopCount[0]) { int thisCount = itsMixer->soundBufferSize; int remaining; do { if (loopCount[0]) { remaining = currentCount[0].i + thisCount - loopEnd; if (remaining > 0) { if (loopCount[0] > 0) // Negative loopCount will loop forever. loopCount[0]--; currentCount[0].i = loopStart; thisCount -= remaining; } else remaining = 0; } else remaining = 0; currentCount[0].i += thisCount; thisCount = remaining; } while (thisCount); } else { currentCount[0].i += itsMixer->soundBufferSize; } } if (loopCount[0] == 0 && currentCount[0].i >= sampleLen) stopNow = true; return stopNow; }
25.73201
91
0.548987
JackCarlson
34fc3eca1e3505b2d07896cb4ecee2a367e95d62
5,408
cpp
C++
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
null
null
null
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
1
2017-04-22T21:38:20.000Z
2017-04-22T21:38:20.000Z
src/core/renderer/shader.cpp
mdsitton/LudumDare38
afa00173cf245fef215aa10024bf397c01711f53
[ "BSD-2-Clause" ]
null
null
null
#include "config.hpp" #include <iostream> #include <stdexcept> #include <spdlog/spdlog.h> #include <glad/glad.h> #include "vfs.hpp" #include "shader.hpp" namespace ORCore { static std::shared_ptr<spdlog::logger> logger; static int _programCount = 0; Shader::Shader(ShaderInfo _info): info(_info) { logger = spdlog::get("default"); init_gl(); } void Shader::init_gl() { shader = glCreateShader(info.type); std::string data {read_file(info.path)}; const char *c_str = data.c_str(); glShaderSource(shader, 1, &c_str, nullptr); glCompileShader(shader); } Shader::~Shader() { glDeleteShader(shader); } void Shader::check_error() { GLint status; glGetShaderiv(shader, GL_COMPILE_STATUS, &status); // TODO - probably need to make a custom exception class for this.. if (status != GL_TRUE) { GLint length; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &length); auto logData = std::make_unique<GLchar[]>(length+1); logData[length] = '\0'; // Make sure it is null terminated. glGetShaderInfoLog(shader, length, nullptr, logData.get()); logger->error(logData.get()); throw std::runtime_error("Shader compilation failed."); } else { logger->info("Shader compiled sucessfully."); } } ShaderProgram::ShaderProgram(Shader& vertex, Shader& fragment) : m_vertex(vertex), m_fragment(fragment) { logger = spdlog::get("default"); _programCount++; m_programID = _programCount; m_program = glCreateProgram(); glAttachShader(m_program, m_vertex.shader); glAttachShader(m_program, m_fragment.shader); glLinkProgram(m_program); } ShaderProgram::~ShaderProgram() { glDeleteProgram(m_program); } int ShaderProgram::get_id() { return m_programID; } void ShaderProgram::check_error() { // We want to check the compile/link status of the shaders all at once. // At some place that isn't right after the shader compilation step. // That way the drivers can better parallelize shader compilation. m_vertex.check_error(); m_fragment.check_error(); GLint status; glGetProgramiv(m_program, GL_LINK_STATUS, &status); // TODO - probably need to make a custom exception class for this.. if (status != GL_TRUE) { GLint length; glGetProgramiv(m_program, GL_INFO_LOG_LENGTH, &length); auto logData = std::make_unique<GLchar[]>(length+1); logData[length] = '\0'; // Make sure it is null terminated. glGetProgramInfoLog(m_program, length, nullptr, logData.get()); logger->error(logData.get()); throw std::runtime_error("Shader linkage failed."); } else { logger->info("Shader linked sucessfully."); } } void ShaderProgram::use() { glUseProgram(m_program); } void ShaderProgram::disuse() { glUseProgram(0); } int ShaderProgram::vertex_attribute(std::string name) { return glGetAttribLocation(m_program, name.c_str()); } int ShaderProgram::uniform_attribute(std::string name) { return glGetUniformLocation(m_program, name.c_str()); } void ShaderProgram::set_uniform(int uniform, int value) { glUniform1i(uniform, value); } void ShaderProgram::set_uniform(int uniform, float value) { glUniform1f(uniform, value); } void ShaderProgram::set_uniform(int uniform, const glm::vec2& value) { glUniform2fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::vec3& value) { glUniform3fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::vec4& value) { glUniform4fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat2& value) { glUniformMatrix2fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat3& value) { glUniformMatrix3fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const glm::mat4& value) { glUniformMatrix4fv(uniform, 1, GL_FALSE, &value[0][0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 2>& value) { glUniform2fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 3>& value) { glUniform3fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<float, 4>& value) { glUniform4fv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 2>& value) { glUniform2iv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 3>& value) { glUniform3iv(uniform, 1, &value[0]); } void ShaderProgram::set_uniform(int uniform, const std::array<int, 4>& value) { glUniform4iv(uniform, 1, &value[0]); } } // namespace ORCore
25.271028
83
0.611686
mdsitton
34fd456783bdd58cf5a710c3a4f029c2aeba3313
321
hpp
C++
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
4
2015-06-14T13:38:40.000Z
2020-11-07T02:29:59.000Z
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
1
2015-06-19T07:54:53.000Z
2015-11-12T10:38:21.000Z
src/rpcz/request_handler_ptr.hpp
jinq0123/rpcz
d273dc1a8de770cb4c2ddee98c17ce60c657d6ca
[ "Apache-2.0" ]
3
2015-06-15T02:28:39.000Z
2018-10-18T11:02:59.000Z
// Author: Jin Qing (http://blog.csdn.net/jq0123) #ifndef RPCZ_REQUEST_HANDLER_PTR_H #define RPCZ_REQUEST_HANDLER_PTR_H #include <boost/shared_ptr.hpp> namespace rpcz { class request_handler; typedef boost::shared_ptr<request_handler> request_handler_ptr; } // namespace rpcz #endif // RPCZ_REQUEST_HANDLER_PTR_H
20.0625
63
0.797508
jinq0123
34ff834048322fd5351a65e34660fef871d798db
719
cc
C++
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
src/lsp-protocol/static-data.cc
roflcopter4/electromechanical-lsp-client
553e4eeeac749986725046083abe6e4ca5eddb19
[ "MIT" ]
null
null
null
#include "Common.hh" #include "static-data.hh" namespace emlsp::rpc::lsp::data { #if 0 std::string const initialization_message = R"({ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "trace": "on", "locale": "en_US.UTF8", "clientInfo": { "name": ")" MAIN_PROJECT_NAME R"(", "version": ")" MAIN_PROJECT_VERSION_STRING R"(" }, "capabilities": { "textDocument.documentHighlight.dynamicRegistration": true } } })"s; #endif } // namespace emlsp::rpc::lsp::data namespace emlsp::test { NOINLINE void test01() { } } // namespace emlsp::test
20.542857
76
0.513213
roflcopter4
5502c9b9825deb1d0594bfef07db2cc22ef09594
3,642
cpp
C++
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
7
2015-03-10T03:36:16.000Z
2021-11-05T01:16:58.000Z
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
1
2020-06-23T10:02:33.000Z
2020-06-24T02:05:47.000Z
MonoNative.Tests/mscorlib/System/mscorlib_System_OverflowException_Fixture.cpp
brunolauze/MonoNative
959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66
[ "BSD-2-Clause" ]
null
null
null
// Mono Native Fixture // Assembly: mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // Namespace: System // Name: OverflowException // C++ Typed Name: mscorlib::System::OverflowException #include <gtest/gtest.h> #include <mscorlib/System/mscorlib_System_OverflowException.h> #include <mscorlib/System/Reflection/mscorlib_System_Reflection_MethodBase.h> #include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationInfo.h> #include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_StreamingContext.h> #include <mscorlib/System/mscorlib_System_Type.h> namespace mscorlib { namespace System { //Constructors Tests //OverflowException() TEST(mscorlib_System_OverflowException_Fixture,DefaultConstructor) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //OverflowException(mscorlib::System::String message) TEST(mscorlib_System_OverflowException_Fixture,Constructor_2) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //OverflowException(mscorlib::System::String message, mscorlib::System::Exception innerException) TEST(mscorlib_System_OverflowException_Fixture,Constructor_3) { mscorlib::System::OverflowException *value = new mscorlib::System::OverflowException(); EXPECT_NE(NULL, value->GetNativeObject()); } //Public Methods Tests //Public Properties Tests // Property InnerException // Return Type: mscorlib::System::Exception // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_InnerException_Test) { } // Property HelpLink // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_HelpLink_Test) { } // Property HelpLink // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_HelpLink_Test) { } // Property HResult // Return Type: mscorlib::System::Int32 // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_HResult_Test) { } // Property HResult // Return Type: mscorlib::System::Int32 // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_HResult_Test) { } // Property Message // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Message_Test) { } // Property Source // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Source_Test) { } // Property Source // Return Type: mscorlib::System::String // Property Set Method TEST(mscorlib_System_OverflowException_Fixture,set_Source_Test) { } // Property StackTrace // Return Type: mscorlib::System::String // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_StackTrace_Test) { } // Property TargetSite // Return Type: mscorlib::System::Reflection::MethodBase // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_TargetSite_Test) { } // Property Data // Return Type: mscorlib::System::Collections::IDictionary // Property Get Method TEST(mscorlib_System_OverflowException_Fixture,get_Data_Test) { } } }
22.7625
106
0.731466
brunolauze
5504cb8775368b3998df85f1df1ca63775176fd7
223
hh
C++
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
1
2020-01-06T09:43:56.000Z
2020-01-06T09:43:56.000Z
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
src/ast/Decl.hh
walecome/seal
204b2dbad9f0bf3ac77f5e32173de39ef1fb81c1
[ "MIT" ]
null
null
null
#pragma once #include "Statement.hh" // @TODO: Derive from something else class Decl : public Statement { MAKE_NONMOVABLE(Decl) MAKE_NONCOPYABLE(Decl) AST_NODE_NAME(Decl) protected: Decl() = default; };
18.583333
36
0.695067
walecome
550727d7b0ea51da785f910de3f02bb59e994fbc
746
hpp
C++
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
1
2021-02-19T13:02:23.000Z
2021-02-19T13:02:23.000Z
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
16
2021-02-11T04:23:48.000Z
2021-02-19T05:37:30.000Z
engine/source/util/util.hpp
aegooby/videosaurus
20e2dc52e3b06b15d546c8f0d4bba1f2c8b215ad
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../__common.hpp" namespace vs { namespace util { template<typename type> void print_arg(const type& arg) { std::cout << arg; } template<> void print_arg(const bool& arg) { std::cout << termcolor::bold << termcolor::yellow << (arg ? "true" : "false") << termcolor::reset; } template<> void print_arg(const std::string& arg) { std::cout << termcolor::magenta << "\"" << arg << "\"" << termcolor::reset; } void print_args() { } template<typename type, typename... types> void print_args(type&& arg, types&&... args) { print_arg(std::forward<type>(arg)); if constexpr (sizeof...(types)) std::cout << ", "; print_args(std::forward<types>(args)...); } } // namespace util } // namespace vs
21.941176
79
0.621984
aegooby
550915e6b36470976148ac116d6c97b7a88ddbe9
1,464
hpp
C++
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
1
2021-06-03T15:56:32.000Z
2021-06-03T15:56:32.000Z
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
1
2015-08-05T05:51:49.000Z
2015-08-05T05:51:49.000Z
src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_From.hpp
zanfire/sip-0x
de38b3ff782d2a63b69d7f785e2bd9ce7674abd5
[ "Apache-2.0" ]
null
null
null
#if !defined(SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__) #define SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__ #include "parser/tokens/TokenAbstract.hpp" #include "parser/tokens/Operators.hpp" #include "parser/tokens/TokenRegex.hpp" #include "parser/tokens/TokenNameAddr.hpp" #include "parser/tokens/TokenGenericParam.hpp" #include "parser/tokens/messageheaders/TokenSIPMessageHeader_base.hpp" namespace sip0x { namespace parser { // From = ( "From" / "f" ) HCOLON from-spec // from-spec = ( name-addr / addr-spec ) *( SEMI from-param ) // from-param = tag-param / generic-param // tag-param = "tag" EQUAL token class TokenSIPMessageHeader_From : public TokenSIPMessageHeader_base < Sequence<Alternative<TokenNameAddr, TokenAddrSpec>, Occurrence<Sequence<TokenSEMI, TokenGenericParam>>> > { public: TokenSIPMessageHeader_From() : TokenSIPMessageHeader_base("From", "(From)|(f)", Sequence<Alternative<TokenNameAddr, TokenAddrSpec>, Occurrence<Sequence<TokenSEMI, TokenGenericParam>>> ( Alternative<TokenNameAddr, TokenAddrSpec>( TokenNameAddr(), TokenAddrSpec() ), Occurrence<Sequence<TokenSEMI, TokenGenericParam>> ( Sequence<TokenSEMI, TokenGenericParam>(TokenSEMI(), TokenGenericParam()), 0, -1) ) ) { } }; } } #endif // SIP0X_PARSER_TOKENSIPMESSAGEHEADER_FROM_HPP__
34.857143
182
0.686475
zanfire
55096fa25ddc42207a712250b4c5fd9d67d95038
773
cpp
C++
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
HcPlu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
9
2017-10-07T13:35:45.000Z
2021-06-07T17:36:55.000Z
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
null
null
null
trainings/2015-10-13-Sichuan-Province-2012/A.cpp
zhijian-liu/acm-icpc
ab1f1d58bf2b4bf6677a2e4282fd3dadb3effbf8
[ "MIT" ]
3
2018-04-24T05:27:21.000Z
2019-04-25T06:06:00.000Z
#include <iostream> using namespace std; int a[10], used[22][22][22]; void solve() { for (int i = 1; i <= 3; i++) { scanf("%d", &a[i]); } sort(a + 1, a + 4); memset(used, 0, sizeof(used)); for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { for (int k = 1; k <= 3; k++) { if (i != j && j != k && i != k) { if (!used[a[i]][a[j]][a[k]]) { printf("%d %d %d\n", a[i], a[j], a[k]); used[a[i]][a[j]][a[k]] = 1; } } } } } } int main() { int tests; scanf("%d", &tests); for (int i = 1; i <= tests; i++) { printf("Case #%d:\n", i); solve(); } }
22.735294
63
0.315653
HcPlu
550aa8d1a5439a4dfa72d97d3345ac219f405660
3,494
cpp
C++
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
main.cpp
picorro/VulkanEngine
eca00b4332783a44692207ac4f057f292ca07328
[ "MIT" ]
null
null
null
/******************************************************************* ** This code is part of Breakout. ** ** Breakout is free software: you can redistribute it and/or modify ** it under the terms of the CC BY 4.0 license as published by ** Creative Commons, either version 4 of the License, or (at your ** option) any later version. ******************************************************************/ #include <glad.h> #include <glfw3.h> #include "game.h" #include "resourceManager.h" #include <iostream> // GLFW function declerations void framebuffer_size_callback(GLFWwindow* window, int width, int height); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode); // The Width of the screen const unsigned int SCREEN_WIDTH = 1080; // The height of the screen const unsigned int SCREEN_HEIGHT = 720; Game game(SCREEN_WIDTH, SCREEN_HEIGHT); int main(int argc, char* argv[]) { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif glfwWindowHint(GLFW_RESIZABLE, false); GLFWwindow* window = glfwCreateWindow(SCREEN_WIDTH, SCREEN_HEIGHT, "Engine", nullptr, nullptr); glfwMakeContextCurrent(window); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } glfwSetKeyCallback(window, key_callback); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // OpenGL configuration // -------------------- glViewport(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // initialize game // --------------- game.Init(); // deltaTime variables // ------------------- float deltaTime = 0.0f; float lastFrame = 0.0f; // start game within menu state // ---------------------------- game.State = GAME_MENU; while (!glfwWindowShouldClose(window)) { // calculate delta time // -------------------- float currentFrame = glfwGetTime(); deltaTime = currentFrame - lastFrame; lastFrame = currentFrame; glfwPollEvents(); // manage user input // ----------------- game.ProcessInput(); // update game state // ----------------- game.Update(deltaTime); // render // ------ glClearColor(0.0f, 0.0f, 0.4f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); game.Render(); glfwSwapBuffers(window); } // delete all resources as loaded using the resource manager // --------------------------------------------------------- ResourceManager::Clear(); glfwTerminate(); return 0; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { // when a user presses the escape key, we set the WindowShouldClose property to true, closing the application if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, true); if (key >= 0 && key < 1024) { if (action == GLFW_PRESS) game.Keys[key] = true; else if (action == GLFW_RELEASE) game.Keys[key] = false; } } void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); }
27.952
110
0.653692
picorro
550d4bfc530fd0ba42f49bed4131585a505fe65e
18,389
cc
C++
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
83
2019-12-03T08:42:15.000Z
2022-03-30T13:22:37.000Z
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
1
2021-08-06T10:40:57.000Z
2021-08-09T06:33:43.000Z
include/windows/google/protobuf/any_test.pb.cc
Thanalan/GameBookServer-master
506b4fe1eece1a3c0bd1100fe14764b63885b2bf
[ "MIT" ]
45
2020-05-29T03:22:48.000Z
2022-03-21T16:19:01.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/any_test.proto #include "google/protobuf/any_test.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2fany_2eproto ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<0> scc_info_Any_google_2fprotobuf_2fany_2eproto; namespace protobuf_unittest { class TestAnyDefaultTypeInternal { public: ::PROTOBUF_NAMESPACE_ID::internal::ExplicitlyConstructed<TestAny> _instance; } _TestAny_default_instance_; } // namespace protobuf_unittest static void InitDefaultsscc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::protobuf_unittest::_TestAny_default_instance_; new (ptr) ::protobuf_unittest::TestAny(); ::PROTOBUF_NAMESPACE_ID::internal::OnShutdownDestroyMessage(ptr); } ::protobuf_unittest::TestAny::InitAsDefaultInstance(); } ::PROTOBUF_NAMESPACE_ID::internal::SCCInfo<1> scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto = {{ATOMIC_VAR_INIT(::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsscc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto}, { &scc_info_Any_google_2fprotobuf_2fany_2eproto.base,}}; static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_google_2fprotobuf_2fany_5ftest_2eproto[1]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_google_2fprotobuf_2fany_5ftest_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_google_2fprotobuf_2fany_5ftest_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_google_2fprotobuf_2fany_5ftest_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, int32_value_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, any_value_), PROTOBUF_FIELD_OFFSET(::protobuf_unittest::TestAny, repeated_any_value_), }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::protobuf_unittest::TestAny)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::protobuf_unittest::_TestAny_default_instance_), }; const char descriptor_table_protodef_google_2fprotobuf_2fany_5ftest_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\036google/protobuf/any_test.proto\022\021protob" "uf_unittest\032\031google/protobuf/any.proto\"y" "\n\007TestAny\022\023\n\013int32_value\030\001 \001(\005\022\'\n\tany_va" "lue\030\002 \001(\0132\024.google.protobuf.Any\0220\n\022repea" "ted_any_value\030\003 \003(\0132\024.google.protobuf.An" "yb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_deps[1] = { &::descriptor_table_google_2fprotobuf_2fany_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::SCCInfoBase*const descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_sccs[1] = { &scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_once; static bool descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_initialized = false; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto = { &descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_initialized, descriptor_table_protodef_google_2fprotobuf_2fany_5ftest_2eproto, "google/protobuf/any_test.proto", 209, &descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_once, descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_sccs, descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto_deps, 1, 1, schemas, file_default_instances, TableStruct_google_2fprotobuf_2fany_5ftest_2eproto::offsets, file_level_metadata_google_2fprotobuf_2fany_5ftest_2eproto, 1, file_level_enum_descriptors_google_2fprotobuf_2fany_5ftest_2eproto, file_level_service_descriptors_google_2fprotobuf_2fany_5ftest_2eproto, }; // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_google_2fprotobuf_2fany_5ftest_2eproto = ( ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptors(&descriptor_table_google_2fprotobuf_2fany_5ftest_2eproto), true); namespace protobuf_unittest { // =================================================================== void TestAny::InitAsDefaultInstance() { ::protobuf_unittest::_TestAny_default_instance_._instance.get_mutable()->any_value_ = const_cast< PROTOBUF_NAMESPACE_ID::Any*>( PROTOBUF_NAMESPACE_ID::Any::internal_default_instance()); } class TestAny::_Internal { public: static const PROTOBUF_NAMESPACE_ID::Any& any_value(const TestAny* msg); }; const PROTOBUF_NAMESPACE_ID::Any& TestAny::_Internal::any_value(const TestAny* msg) { return *msg->any_value_; } void TestAny::clear_any_value() { if (GetArenaNoVirtual() == nullptr && any_value_ != nullptr) { delete any_value_; } any_value_ = nullptr; } void TestAny::clear_repeated_any_value() { repeated_any_value_.Clear(); } TestAny::TestAny() : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:protobuf_unittest.TestAny) } TestAny::TestAny(const TestAny& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _internal_metadata_(nullptr), repeated_any_value_(from.repeated_any_value_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_any_value()) { any_value_ = new PROTOBUF_NAMESPACE_ID::Any(*from.any_value_); } else { any_value_ = nullptr; } int32_value_ = from.int32_value_; // @@protoc_insertion_point(copy_constructor:protobuf_unittest.TestAny) } void TestAny::SharedCtor() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base); ::memset(&any_value_, 0, static_cast<size_t>( reinterpret_cast<char*>(&int32_value_) - reinterpret_cast<char*>(&any_value_)) + sizeof(int32_value_)); } TestAny::~TestAny() { // @@protoc_insertion_point(destructor:protobuf_unittest.TestAny) SharedDtor(); } void TestAny::SharedDtor() { if (this != internal_default_instance()) delete any_value_; } void TestAny::SetCachedSize(int size) const { _cached_size_.Set(size); } const TestAny& TestAny::default_instance() { ::PROTOBUF_NAMESPACE_ID::internal::InitSCC(&::scc_info_TestAny_google_2fprotobuf_2fany_5ftest_2eproto.base); return *internal_default_instance(); } void TestAny::Clear() { // @@protoc_insertion_point(message_clear_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; repeated_any_value_.Clear(); if (GetArenaNoVirtual() == nullptr && any_value_ != nullptr) { delete any_value_; } any_value_ = nullptr; int32_value_ = 0; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* TestAny::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); CHK_(ptr); switch (tag >> 3) { // int32 int32_value = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 8)) { int32_value_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // .google.protobuf.Any any_value = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(mutable_any_value(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // repeated .google.protobuf.Any repeated_any_value = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr -= 1; do { ptr += 1; ptr = ctx->ParseMessage(add_repeated_any_value(), ptr); CHK_(ptr); if (!ctx->DataAvailable(ptr)) break; } while (::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<::PROTOBUF_NAMESPACE_ID::uint8>(ptr) == 26); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, &_internal_metadata_, ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool TestAny::MergePartialFromCodedStream( ::PROTOBUF_NAMESPACE_ID::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::PROTOBUF_NAMESPACE_ID::uint32 tag; // @@protoc_insertion_point(parse_start:protobuf_unittest.TestAny) for (;;) { ::std::pair<::PROTOBUF_NAMESPACE_ID::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; switch (::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::GetTagFieldNumber(tag)) { // int32 int32_value = 1; case 1: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (8 & 0xFF)) { DO_((::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadPrimitive< ::PROTOBUF_NAMESPACE_ID::int32, ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::TYPE_INT32>( input, &int32_value_))); } else { goto handle_unusual; } break; } // .google.protobuf.Any any_value = 2; case 2: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (18 & 0xFF)) { DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, mutable_any_value())); } else { goto handle_unusual; } break; } // repeated .google.protobuf.Any repeated_any_value = 3; case 3: { if (static_cast< ::PROTOBUF_NAMESPACE_ID::uint8>(tag) == (26 & 0xFF)) { DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::ReadMessage( input, add_repeated_any_value())); } else { goto handle_unusual; } break; } default: { handle_unusual: if (tag == 0) { goto success; } DO_(::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); break; } } } success: // @@protoc_insertion_point(parse_success:protobuf_unittest.TestAny) return true; failure: // @@protoc_insertion_point(parse_failure:protobuf_unittest.TestAny) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void TestAny::SerializeWithCachedSizes( ::PROTOBUF_NAMESPACE_ID::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 int32_value = 1; if (this->int32_value() != 0) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32(1, this->int32_value(), output); } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 2, _Internal::any_value(this), output); } // repeated .google.protobuf.Any repeated_any_value = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->repeated_any_value_size()); i < n; i++) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteMessageMaybeToArray( 3, this->repeated_any_value(static_cast<int>(i)), output); } if (_internal_metadata_.have_unknown_fields()) { ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:protobuf_unittest.TestAny) } ::PROTOBUF_NAMESPACE_ID::uint8* TestAny::InternalSerializeWithCachedSizesToArray( ::PROTOBUF_NAMESPACE_ID::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 int32_value = 1; if (this->int32_value() != 0) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteInt32ToArray(1, this->int32_value(), target); } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( 2, _Internal::any_value(this), target); } // repeated .google.protobuf.Any repeated_any_value = 3; for (unsigned int i = 0, n = static_cast<unsigned int>(this->repeated_any_value_size()); i < n; i++) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessageToArray( 3, this->repeated_any_value(static_cast<int>(i)), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:protobuf_unittest.TestAny) return target; } size_t TestAny::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:protobuf_unittest.TestAny) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .google.protobuf.Any repeated_any_value = 3; { unsigned int count = static_cast<unsigned int>(this->repeated_any_value_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( this->repeated_any_value(static_cast<int>(i))); } } // .google.protobuf.Any any_value = 2; if (this->has_any_value()) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *any_value_); } // int32 int32_value = 1; if (this->int32_value() != 0) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::Int32Size( this->int32_value()); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TestAny::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:protobuf_unittest.TestAny) GOOGLE_DCHECK_NE(&from, this); const TestAny* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TestAny>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:protobuf_unittest.TestAny) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:protobuf_unittest.TestAny) MergeFrom(*source); } } void TestAny::MergeFrom(const TestAny& from) { // @@protoc_insertion_point(class_specific_merge_from_start:protobuf_unittest.TestAny) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; repeated_any_value_.MergeFrom(from.repeated_any_value_); if (from.has_any_value()) { mutable_any_value()->PROTOBUF_NAMESPACE_ID::Any::MergeFrom(from.any_value()); } if (from.int32_value() != 0) { set_int32_value(from.int32_value()); } } void TestAny::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:protobuf_unittest.TestAny) if (&from == this) return; Clear(); MergeFrom(from); } void TestAny::CopyFrom(const TestAny& from) { // @@protoc_insertion_point(class_specific_copy_from_start:protobuf_unittest.TestAny) if (&from == this) return; Clear(); MergeFrom(from); } bool TestAny::IsInitialized() const { return true; } void TestAny::InternalSwap(TestAny* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&repeated_any_value_)->InternalSwap(CastToBase(&other->repeated_any_value_)); swap(any_value_, other->any_value_); swap(int32_value_, other->int32_value_); } ::PROTOBUF_NAMESPACE_ID::Metadata TestAny::GetMetadata() const { return GetMetadataStatic(); } // @@protoc_insertion_point(namespace_scope) } // namespace protobuf_unittest PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::protobuf_unittest::TestAny* Arena::CreateMaybeMessage< ::protobuf_unittest::TestAny >(Arena* arena) { return Arena::CreateInternal< ::protobuf_unittest::TestAny >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
38.795359
203
0.73805
Thanalan
550de8d47b5f9f69b204979617fe7276bf2d5fba
11,501
cpp
C++
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
1
2020-04-29T07:29:27.000Z
2020-04-29T07:29:27.000Z
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
null
null
null
node/node.cpp
catenocrypt/tcpserver-libuv-sample
ad847ce3bb89adb92b6adf24e14a8f806580b7f1
[ "MIT" ]
null
null
null
#include "node.hpp" #include "peer_conn.hpp" #include "endpoint.hpp" #include "../lib/net_handler.hpp" #include "../lib/net_client.hpp" #include <cassert> #include <iostream> using namespace sample; using namespace std; NodeApp::PeerCandidateInfo::PeerCandidateInfo(std::string host_in, int port_in, int toTry_in) : myHost(host_in), myPort(port_in), myToTry(toTry_in), myConnTryCount(0), myConnectedCount(0) { } void NodeApp::PeerInfo::setClient(std::shared_ptr<NetClientBase>& client_in) { myClient = client_in; } void NodeApp::PeerInfo::resetClient() { myClient = nullptr; } NodeApp::NodeApp() : ServerApp() { myNetHandler = new NetHandler(this); } void NodeApp::start(AppParams const & appParams_in) { // add constant peer candidates, for localhost int n = 2; for (int i = 0; i < n; ++i) { addOutPeerCandidate("localhost", 5000 + i, 1); } // add extra peer candidates if (appParams_in.extraPeers.size() > 0) { for(int i = 0; i < appParams_in.extraPeers.size(); ++i) { if (appParams_in.extraPeers[i].length() > 0) { Endpoint extraPeerEp(appParams_in.extraPeers[i]); addOutPeerCandidate(extraPeerEp.getHost(), extraPeerEp.getPort(), 1000000); } } } myNetHandler->startWithListen(appParams_in.listenPort, appParams_in.listenPortRange); } void NodeApp::listenStarted(int port) { cout << "App: Listening on port " << port << endl; myName = ":" + to_string(port); // try to connect to clients tryOutConnections(); } void NodeApp::addOutPeerCandidate(std::string host_in, int port_in, int toTry_in) { PeerCandidateInfo pc = PeerCandidateInfo(host_in, port_in, toTry_in); string key = host_in + ":" + to_string(port_in); if (myPeerCands.find(key) != myPeerCands.end()) { // already present myPeerCands[key].myToTry = toTry_in + myPeerCands[key].myConnTryCount; return; } myPeerCands[key] = pc; cout << "App: Added peer candidate " << key << " " << myPeerCands.size() << endl; //debugPrintPeerCands(); } void NodeApp::debugPrintPeerCands() { cout << "PeerCands: " << myPeerCands.size() << " "; for (auto i = myPeerCands.begin(); i != myPeerCands.end(); ++i) { cout << "[" << i->first << " " << i->second.myToTry << " " << i->second.myConnTryCount << ":" << i->second.myConnectedCount << "] "; } cout << endl; } void NodeApp::debugPrintPeers() { cout << "Peers: " << myPeers.size() << " "; for (auto i = myPeers.begin(); i != myPeers.end(); ++i) { cout << "["; if (i->myClient == nullptr) cout << "n"; else cout << i->myClient->getPeerAddr() << " " << i->myClient->getCanonPeerAddr() << " " << (i->myClient->isConnected() ? "Y" : "N") << "] "; } cout << endl; } void NodeApp::tryOutConnections() { //cout << "NodeApp::tryOutConnections" << endl; // try to connect to clients for (auto i = myPeerCands.begin(); i != myPeerCands.end(); ++i) { //cout << i->second.myOutFlag << " " << i->second.myStickyFlag << " " << i->second.myConnTryCount << " " << (i->second.myOutClient == nullptr) << " " << i->second.myEndpoint.getEndpoint() << endl; if (i->second.myConnTryCount == 0 || i->second.myConnTryCount < i->second.myToTry) { if (!isPeerConnected(i->first, true)) { // try outgoing connection ++i->second.myConnTryCount; int res = tryOutConnection(i->second.myHost, i->second.myPort); if (!res) { // success ++i->second.myConnectedCount; } } } } } bool NodeApp::isPeerConnected(string peerAddr_in, bool outDir_in) { for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myOutFlag == outDir_in) { if (i->myClient != nullptr) { if (i->myClient->getPeerAddr() == peerAddr_in || i->myClient->getCanonPeerAddr() == peerAddr_in) { return true; } } } } return false; } int NodeApp::tryOutConnection(std::string host_in, int port_in) { // exclude localhost connections to self if ((":" + to_string(port_in)) == myName) { if (host_in == "localhost" || host_in == "127.0.0.1" || host_in == "::1" || host_in == "[::1]") { //cerr << "Ignoring peer candidate to self (" << host_in << ":" << port_in << ")" << endl; return 0; } } // try outgoing connection Endpoint ep = Endpoint(host_in, port_in); string key = ep.getEndpoint(); //cout << "Trying outgoing conn to " << key << endl; auto peerout = make_shared<PeerClientOut>(this, host_in, port_in); auto peerBase = dynamic_pointer_cast<NetClientBase>(peerout); PeerInfo p; p.setClient(peerBase); p.myOutFlag = true; myPeers.push_back(p); int res = peerout->connect(); if (res) { cerr << "Error from peer connect, " << res << endl; return res; } //debugPrintPeers(); return 0; } void NodeApp::stop() { myNetHandler->stop(); } void NodeApp::inConnectionReceived(std::shared_ptr<NetClientBase>& client_in) { assert(client_in != nullptr); string cliaddr = client_in->getPeerAddr(); cout << "App: New incoming connection: " << cliaddr << endl; PeerInfo p; p.setClient(client_in); p.myOutFlag = false; myPeers.push_back(p); //debugPrintPeers(); } void NodeApp::connectionClosed(NetClientBase* client_in) { assert(client_in != nullptr); string cliaddr = client_in->getPeerAddr(); cout << "App: Connection done: " << cliaddr << " " << myPeers.size() << endl; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient != nullptr) { if (i->myClient.get() == client_in || i->myClient->getPeerAddr() == cliaddr) { cout << "Removing disconnected client " << myPeers.size() << " " << i->myClient->getPeerAddr() << endl; i->resetClient(); } } } // remove disconnected clients bool changed = true; while (changed) { changed = false; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient.get() == nullptr) { myPeers.erase(i); changed = true; break; // for } } } } void NodeApp::messageReceived(NetClientBase & client_in, BaseMessage const & msg_in) { if (msg_in.getType() != MessageType::OtherPeer) { cout << "App: Received: from " << client_in.getNicePeerAddr() << " '" << msg_in.toString() << "'" << endl; } switch (msg_in.getType()) { case MessageType::Handshake: { HandshakeMessage const & hsMsg = dynamic_cast<HandshakeMessage const &>(msg_in); //cout << "Handshake message received, '" << hsMsg.getMyAddr() << "'" << endl; if (hsMsg.getMyVersion() != "V01") { cerr << "Wrong version ''" << hsMsg.getMyVersion() << "'" << endl; client_in.close(); return; } string peerEp = client_in.getPeerAddr(); if (!isPeerConnected(peerEp, false)) { cerr << "Error: cannot find client in peers list " << peerEp << endl; return; } HandshakeResponseMessage resp("V01", myName, peerEp); client_in.sendMessage(resp); // find canonical name of this peer: host is actual connected ip, port is reported by peer int peerPort = Endpoint(peerEp).getPort(); string canonHost = Endpoint(peerEp).getHost(); int canonPort = peerPort; string reportedPeerName = hsMsg.getMyAddr(); if (reportedPeerName.substr(0, 1) != ":") { cerr << "Could not retrieve listening port of incoming peer " << client_in.getPeerAddr() << " " << reportedPeerName << endl; } else { canonPort = stoi(reportedPeerName.substr(1)); string canonEp = canonHost + ":" + to_string(canonPort); if (canonEp != peerEp) { // canonical is different cout << "Canonical peer of " << peerEp << " is " << canonEp << endl; client_in.setCanonPeerAddr(canonEp); // try to connect ougoing too (to canonical peer addr) addOutPeerCandidate(canonHost, canonPort, 1); tryOutConnections(); } } sendOtherPeers(client_in); } break; case MessageType::Ping: { PingMessage const & pingMsg = dynamic_cast<PingMessage const &>(msg_in); //cout << "Ping message received, '" << pingMsg.getText() << "'" << endl; PingResponseMessage resp("Resp_from_" + myName + "_to_" + pingMsg.getText()); client_in.sendMessage(resp); } break; case MessageType::OtherPeer: { OtherPeerMessage const & peerMsg = dynamic_cast<OtherPeerMessage const &>(msg_in); //cout << "OtherPeer message received, " << peerMsg.getHost() << ":" << peerMsg.getPort() << " " << peerMsg.toString() << endl; addOutPeerCandidate(peerMsg.getHost(), peerMsg.getPort(), 1); tryOutConnections(); } break; case MessageType::HandshakeResponse: case MessageType::PingResponse: // OK, noop break; default: assert(false); } } void NodeApp::sendOtherPeers(NetClientBase & client_in) { // send current outgoing connection addresses auto peers = getConnectedPeers(); //cout << "NodeApp::sendOtherPeers " << peers.size() << " " << client_in.getPeerAddr() << endl; for(auto i = peers.begin(); i != peers.end(); ++i) { if (!client_in.isConnected()) { return; } string ep = i->getEndpoint(); //cout << ep << " " << client_in.getPeerAddr() << endl; if (ep != client_in.getPeerAddr()) { //cout << "sendOtherPeers " << client_in.getPeerAddr() << " " << i->getEndpoint() << endl; client_in.sendMessage(OtherPeerMessage(i->getHost(), i->getPort())); } } } vector<Endpoint> NodeApp::getConnectedPeers() const { // collect in a map to discard duplicates map<string, int> peers; for(auto i = myPeers.begin(); i != myPeers.end(); ++i) { if (i->myClient != nullptr && i->myClient->isConnected() && i->myClient->getCanonPeerAddr().length() > 0) { peers[i->myClient->getCanonPeerAddr()] = 1; } } // convert to vector vector<Endpoint> vec; for(auto i = peers.begin(); i != peers.end(); ++i) { vec.push_back(Endpoint(i->first)); } return vec; }
31.683196
204
0.536388
catenocrypt
550ed484a943b7c9c3414be1c5063ee32f77b838
965
cpp
C++
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
source/BinaryTree/144. Binary Tree Preorder Traversal.cpp
Tridu33/myclionarch
d4e41b3465a62a83cbf6c7119401c05009f4b636
[ "MIT" ]
null
null
null
//递归解法: class Solution { public: void prebintree(TreeNode * root,vector<int> &res){//记得传地址而不是传值&res if(root == nullptr) { return; } res.push_back(root->val); prebintree(root->left,res); prebintree(root->right,res); return; } vector<int> preorderTraversal(TreeNode* root) { vector <int> res; prebintree(root,res); return res; } }; //iter solution class Solution { public: vector<int> preorderTraversal(TreeNode* root) { if(root == nullptr) return {}; vector <int> res; stack <TreeNode*> stk; stk.emplace(root); while(!stk.empty()){ TreeNode* node = stk.top(); res.emplace_back(node->val); stk.pop(); if(node->right != nullptr) stk.emplace(node->right); if(node->left != nullptr) stk.emplace(node->left); } return res; } }; //Morris 遍历
22.44186
70
0.533679
Tridu33
55131cf89a253821832354b7d53c2f3b0a84d1ea
436
cpp
C++
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
null
null
null
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
47
2019-12-30T22:14:04.000Z
2022-03-26T02:04:06.000Z
old/src/channel/BufferWrapper.cpp
edwino-stein/elrond-common
145909bb883e9877e9de3325d2a9002639271200
[ "Apache-2.0" ]
null
null
null
#include "channel/BufferWrapper.hpp" using elrond::channel::BufferWrapper; /* **************************************************************************** ************** elrond::channel::BufferWrapper Implementation *************** ****************************************************************************/ BufferWrapper::BufferWrapper(elrond::byte* const data, const elrond::sizeT length): data(data), length(length) {}
39.636364
83
0.431193
edwino-stein
55156c345ef50bf7727bbde804a325a7ba4bd841
1,553
hpp
C++
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
69
2016-12-07T05:56:53.000Z
2020-11-27T20:59:05.000Z
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
103
2015-07-10T14:42:21.000Z
2020-09-09T16:16:21.000Z
src/morda/widgets/proxy/click_proxy.hpp
igagis/morda
dd7b58f7cb2689d56b7796cc9b6b9302aad1a529
[ "MIT" ]
18
2016-11-22T14:41:37.000Z
2020-04-22T18:16:10.000Z
/* morda - GUI framework Copyright (C) 2012-2021 Ivan Gagis <[email protected]> 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/>. */ /* ================ LICENSE END ================ */ #pragma once #include "../widget.hpp" namespace morda{ class click_proxy : virtual public widget{ bool is_pressed_ = false; bool deferred_release_ret; public: click_proxy(std::shared_ptr<morda::context> c, const treeml::forest& desc); click_proxy(const click_proxy&) = delete; click_proxy& operator=(const click_proxy&) = delete; bool on_mouse_button(const mouse_button_event& event)override; void on_hover_change(unsigned pointer_id)override; bool is_pressed()const noexcept{ return this->is_pressed_; } /** * @brief Handler for mouse press state changes. */ std::function<bool(click_proxy& w)> press_change_handler; /** * @brief Handler for clicked event. */ std::function<void(click_proxy& w)> click_handler; }; }
27.732143
79
0.714746
igagis
55164e1e221b2c4199fa953565a2f8df20edc4c7
936
cpp
C++
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
2
2015-12-26T21:20:12.000Z
2017-12-19T00:11:45.000Z
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
null
null
null
training/1-1-7-beads/cpp11/main.cpp
hsun324/usaco-solutions
27f77911971513a4d2b1b820eaa09802acadfefa
[ "MIT" ]
null
null
null
/* ID: <ID HERE> LANG: C++11 TASK: beads */ #include <fstream> #include <string> using namespace std; template <typename iterator> int get_stretch(iterator begin, iterator end) { auto iter = begin; auto current_type = *iter; while (iter++ != end) { if (*iter == 'w') continue; if (current_type == 'w') current_type = *iter; if (current_type != *iter) break; } return iter - begin; } int main() { ifstream cin("beads.in"); ofstream cout("beads.out"); int necklace_length; cin >> necklace_length; cin.ignore(1); string necklace; necklace.reserve(necklace_length * 2); cin >> necklace; necklace += necklace; int max_length = 0; auto iter = necklace.begin(), end = necklace.end(); auto riter = necklace.rend(), rend = necklace.rend(); while (iter != end) max_length = max(max_length, get_stretch(riter--, rend) + get_stretch(iter++, end)); cout << min(max_length, necklace_length) << endl; return 0; }
19.5
86
0.666667
hsun324
5517c8062ce0660d358616c3c258be1ce9fb3327
54
hpp
C++
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
4
2021-02-03T08:53:53.000Z
2022-03-14T06:02:35.000Z
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
1
2021-09-14T17:45:34.000Z
2021-09-15T13:51:39.000Z
include/EnvironmentHider.hpp
Raemien/CustomBackgroundsQuest
40ad901b33075420f63d6088f0280013cc5321c1
[ "MIT" ]
2
2021-09-09T01:21:23.000Z
2022-02-13T09:14:11.000Z
extern void HideMenuEnv(); extern void HideGameEnv();
18
26
0.777778
Raemien
55184abb4520a516bff065baa04688408fb61ed1
3,525
hpp
C++
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
33
2018-07-04T09:38:12.000Z
2021-06-19T06:11:45.000Z
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
null
null
null
demos/TIMDemo/skin/MaskSkin.hpp
wzaen/soui2
30735bbb84184fc26f0e70edbfede889e24fba5b
[ "MIT" ]
13
2018-07-01T01:55:17.000Z
2021-08-03T10:55:45.000Z
#ifndef __MASK_SKIN_HPP_ #define __MASK_SKIN_HPP_ #include "core/SSkin.h" //************************************ // 这个是 mask 遮罩 皮肤 头像 在skin.xml 里配置 需要 3个值 // src 和 imglist 一样 // mask_a 设置透明值 的rgb a // .a=3 .r=0 .g=1 .b=2 // mask 设置遮罩 图片 // <masklist name="default" src="image:default" mask_a="1" mask="image:mask_42" /> // 还提供了 //************************************ class SSkinMask: public SSkinImgList { SOUI_CLASS_NAME(SSkinMask, L"masklist") public: SSkinMask() : m_bmpMask(NULL) , m_bmpCache(NULL) , m_iMaskChannel(0) { } virtual ~SSkinMask() { } public: // protected: virtual void _Draw(IRenderTarget *pRT, LPCRECT rcDraw, DWORD dwState, BYTE byAlpha) { if(!m_pImg) return; SIZE sz = GetSkinSize(); RECT rcSrc={0,0,sz.cx,sz.cy}; if(m_bVertical) OffsetRect(&rcSrc,0, dwState * sz.cy); else OffsetRect(&rcSrc, dwState * sz.cx, 0); if(m_bmpCache) { RECT rcSrcEx = { 0, 0, m_bmpCache->Size().cx, m_bmpCache->Size().cy }; pRT->DrawBitmapEx(rcDraw, m_bmpCache, &rcSrcEx, GetExpandMode(), byAlpha); } else { RECT rcSrcEx = { 0, 0, m_pImg->Size().cx, m_pImg->Size().cy }; pRT->DrawBitmapEx(rcDraw, m_pImg, &rcSrcEx, GetExpandMode(), byAlpha); } //MakeCacheApha(pRT, rcDraw, rcSrc, byAlpha); } private: CAutoRefPtr<IBitmap> m_bmpMask; CAutoRefPtr<IBitmap> m_bmpCache; int m_iMaskChannel; // 对应 mask 的rgb a // .a=3 .r=0 .g=1 .b=2 protected: SOUI_ATTRS_BEGIN() ATTR_CUSTOM(L"src", OnAttrSrc) ATTR_INT(L"mask_a", m_iMaskChannel, FALSE) // 要先设置这个 不然就用默认 ATTR_CUSTOM(L"mask", OnAttrMask) //image.a SOUI_ATTRS_END() protected: HRESULT OnAttrSrc(const SStringW& strValue, BOOL bLoading) { m_pImg = LOADIMAGE2(strValue); if(NULL == m_pImg) return E_FAIL; if(NULL != m_bmpMask) MakeCacheApha(); return bLoading ? S_OK : S_FALSE; } HRESULT OnAttrMask(const SStringW& strValue, BOOL bLoading) { IBitmap* pImg = NULL; pImg = LOADIMAGE2(strValue); if (!pImg) { return E_FAIL; } m_bmpMask = pImg; pImg->Release(); m_bmpCache = NULL; GETRENDERFACTORY->CreateBitmap(&m_bmpCache); m_bmpCache->Init(m_bmpMask->Width(),m_bmpMask->Height()); if(NULL != m_pImg) MakeCacheApha(); return S_OK; } void MakeCacheApha() { SASSERT(m_bmpMask && m_bmpCache); CAutoRefPtr<IRenderTarget> pRTDst; GETRENDERFACTORY->CreateRenderTarget(&pRTDst, 0, 0); CAutoRefPtr<IRenderObj> pOldBmp; pRTDst->SelectObject(m_bmpCache, &pOldBmp); CRect rc(CPoint(0, 0), m_bmpCache->Size()); CRect rcSrc(CPoint(0, 0), m_pImg->Size()); pRTDst->DrawBitmapEx(rc, m_pImg, &rcSrc, GetExpandMode()); pRTDst->SelectObject(pOldBmp); //从mask的指定channel中获得alpha通道 LPBYTE pBitCache = (LPBYTE)m_bmpCache->LockPixelBits(); LPBYTE pBitMask = (LPBYTE)m_bmpMask->LockPixelBits(); LPBYTE pDst = pBitCache; LPBYTE pSrc = pBitMask + m_iMaskChannel; int nPixels = m_bmpCache->Width()*m_bmpCache->Height(); for(int i=0; i<nPixels; i++) { BYTE byAlpha = *pSrc; pSrc += 4; //源半透明,mask不透明时使用源的半透明属性 if(pDst[3] == 0xff || (pDst[3]!=0xFF &&byAlpha == 0)) {//源不透明,或者mask全透明 *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = ((*pDst) * byAlpha)>>8;//做premultiply *pDst++ = byAlpha; } } m_bmpCache->UnlockPixelBits(pBitCache); m_bmpMask->UnlockPixelBits(pBitMask); } }; ////////////////////////////////////////////////////////////////////////// #endif // __WINFILE_ICON_SKIN_HPP_
24.143836
84
0.63461
wzaen
55210b4c09d6343a045c00f1aab3c56a53b7accc
842
cpp
C++
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
30days/day26.cpp
sagi-z/hackerrank
ba6c75947626adb8b0fc89868cb3cb86f60aaa14
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <iterator> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int d1, m1, y1; int d2, m2, y2; istream_iterator<int> iter(cin); d1 = *iter++; m1 = *iter++; y1 = *iter++; d2 = *iter++; m2 = *iter++; y2 = *iter; int factor = 0; int baseFine = 0; if (y1 > y2) { baseFine = 10000; factor = 1; } else if (y1 == y2) { if (m1 > m2) { baseFine = 500; factor = m1 - m2; } else if (m1 == m2) { if (d1 > d2) { baseFine = 15; factor = d1 - d2; } } } cout << baseFine * factor << endl; return 0; }
18.711111
80
0.465558
sagi-z
55258619dc7b0fa1b8366e9eafff443d00ac4825
552
cpp
C++
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
classeA.cpp
RafaelNatsu/Projeto_Rafael_Natsu
71360db1788a2d3aa7d57de41ff90bff9e48f8bb
[ "MIT" ]
null
null
null
#include "classeA.hpp" classeA::classeA() { A1 = 0; A2 = 0; } classeA::~classeA(){} void classeA::MA1() { std::cout << "Metodo MA1" << std::endl; } void classeA::MA2() { std::cout << "Metodo MA2" << std::endl; } void classeA::MA3() { std::cout << "Alteração a classe A partir do clone" << std::endl; } int classeA::getA1() { return A1; } void classeA::setA1(int _a1) { A1 = _a1; } float classeA::getA2() { return A2; } void classeA::setA2(float _a2) { A2= _a2; }
12.266667
70
0.519928
RafaelNatsu
552ea5a5d0dee8d6d27ee878bf7c75c1e22c1589
10,777
cpp
C++
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
evs/src/v2/model/SnapshotDetails.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/evs/v2/model/SnapshotDetails.h" namespace HuaweiCloud { namespace Sdk { namespace Evs { namespace V2 { namespace Model { SnapshotDetails::SnapshotDetails() { id_ = ""; idIsSet_ = false; status_ = ""; statusIsSet_ = false; name_ = ""; nameIsSet_ = false; description_ = ""; descriptionIsSet_ = false; createdAt_ = ""; createdAtIsSet_ = false; updatedAt_ = ""; updatedAtIsSet_ = false; metadataIsSet_ = false; volumeId_ = ""; volumeIdIsSet_ = false; size_ = 0; sizeIsSet_ = false; osExtendedSnapshotAttributesprojectId_ = ""; osExtendedSnapshotAttributesprojectIdIsSet_ = false; osExtendedSnapshotAttributesprogress_ = ""; osExtendedSnapshotAttributesprogressIsSet_ = false; } SnapshotDetails::~SnapshotDetails() = default; void SnapshotDetails::validate() { } web::json::value SnapshotDetails::toJson() const { web::json::value val = web::json::value::object(); if(idIsSet_) { val[utility::conversions::to_string_t("id")] = ModelBase::toJson(id_); } if(statusIsSet_) { val[utility::conversions::to_string_t("status")] = ModelBase::toJson(status_); } if(nameIsSet_) { val[utility::conversions::to_string_t("name")] = ModelBase::toJson(name_); } if(descriptionIsSet_) { val[utility::conversions::to_string_t("description")] = ModelBase::toJson(description_); } if(createdAtIsSet_) { val[utility::conversions::to_string_t("created_at")] = ModelBase::toJson(createdAt_); } if(updatedAtIsSet_) { val[utility::conversions::to_string_t("updated_at")] = ModelBase::toJson(updatedAt_); } if(metadataIsSet_) { val[utility::conversions::to_string_t("metadata")] = ModelBase::toJson(metadata_); } if(volumeIdIsSet_) { val[utility::conversions::to_string_t("volume_id")] = ModelBase::toJson(volumeId_); } if(sizeIsSet_) { val[utility::conversions::to_string_t("size")] = ModelBase::toJson(size_); } if(osExtendedSnapshotAttributesprojectIdIsSet_) { val[utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id")] = ModelBase::toJson(osExtendedSnapshotAttributesprojectId_); } if(osExtendedSnapshotAttributesprogressIsSet_) { val[utility::conversions::to_string_t("os-extended-snapshot-attributes:progress")] = ModelBase::toJson(osExtendedSnapshotAttributesprogress_); } return val; } bool SnapshotDetails::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setId(refVal); } } if(val.has_field(utility::conversions::to_string_t("status"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("status")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setStatus(refVal); } } if(val.has_field(utility::conversions::to_string_t("name"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("name")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setName(refVal); } } if(val.has_field(utility::conversions::to_string_t("description"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("description")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setDescription(refVal); } } if(val.has_field(utility::conversions::to_string_t("created_at"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("created_at")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setCreatedAt(refVal); } } if(val.has_field(utility::conversions::to_string_t("updated_at"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("updated_at")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setUpdatedAt(refVal); } } if(val.has_field(utility::conversions::to_string_t("metadata"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("metadata")); if(!fieldValue.is_null()) { Object refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setMetadata(refVal); } } if(val.has_field(utility::conversions::to_string_t("volume_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("volume_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setVolumeId(refVal); } } if(val.has_field(utility::conversions::to_string_t("size"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("size")); if(!fieldValue.is_null()) { int32_t refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setSize(refVal); } } if(val.has_field(utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("os-extended-snapshot-attributes:project_id")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOsExtendedSnapshotAttributesprojectId(refVal); } } if(val.has_field(utility::conversions::to_string_t("os-extended-snapshot-attributes:progress"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("os-extended-snapshot-attributes:progress")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setOsExtendedSnapshotAttributesprogress(refVal); } } return ok; } std::string SnapshotDetails::getId() const { return id_; } void SnapshotDetails::setId(const std::string& value) { id_ = value; idIsSet_ = true; } bool SnapshotDetails::idIsSet() const { return idIsSet_; } void SnapshotDetails::unsetid() { idIsSet_ = false; } std::string SnapshotDetails::getStatus() const { return status_; } void SnapshotDetails::setStatus(const std::string& value) { status_ = value; statusIsSet_ = true; } bool SnapshotDetails::statusIsSet() const { return statusIsSet_; } void SnapshotDetails::unsetstatus() { statusIsSet_ = false; } std::string SnapshotDetails::getName() const { return name_; } void SnapshotDetails::setName(const std::string& value) { name_ = value; nameIsSet_ = true; } bool SnapshotDetails::nameIsSet() const { return nameIsSet_; } void SnapshotDetails::unsetname() { nameIsSet_ = false; } std::string SnapshotDetails::getDescription() const { return description_; } void SnapshotDetails::setDescription(const std::string& value) { description_ = value; descriptionIsSet_ = true; } bool SnapshotDetails::descriptionIsSet() const { return descriptionIsSet_; } void SnapshotDetails::unsetdescription() { descriptionIsSet_ = false; } std::string SnapshotDetails::getCreatedAt() const { return createdAt_; } void SnapshotDetails::setCreatedAt(const std::string& value) { createdAt_ = value; createdAtIsSet_ = true; } bool SnapshotDetails::createdAtIsSet() const { return createdAtIsSet_; } void SnapshotDetails::unsetcreatedAt() { createdAtIsSet_ = false; } std::string SnapshotDetails::getUpdatedAt() const { return updatedAt_; } void SnapshotDetails::setUpdatedAt(const std::string& value) { updatedAt_ = value; updatedAtIsSet_ = true; } bool SnapshotDetails::updatedAtIsSet() const { return updatedAtIsSet_; } void SnapshotDetails::unsetupdatedAt() { updatedAtIsSet_ = false; } Object SnapshotDetails::getMetadata() const { return metadata_; } void SnapshotDetails::setMetadata(const Object& value) { metadata_ = value; metadataIsSet_ = true; } bool SnapshotDetails::metadataIsSet() const { return metadataIsSet_; } void SnapshotDetails::unsetmetadata() { metadataIsSet_ = false; } std::string SnapshotDetails::getVolumeId() const { return volumeId_; } void SnapshotDetails::setVolumeId(const std::string& value) { volumeId_ = value; volumeIdIsSet_ = true; } bool SnapshotDetails::volumeIdIsSet() const { return volumeIdIsSet_; } void SnapshotDetails::unsetvolumeId() { volumeIdIsSet_ = false; } int32_t SnapshotDetails::getSize() const { return size_; } void SnapshotDetails::setSize(int32_t value) { size_ = value; sizeIsSet_ = true; } bool SnapshotDetails::sizeIsSet() const { return sizeIsSet_; } void SnapshotDetails::unsetsize() { sizeIsSet_ = false; } std::string SnapshotDetails::getOsExtendedSnapshotAttributesprojectId() const { return osExtendedSnapshotAttributesprojectId_; } void SnapshotDetails::setOsExtendedSnapshotAttributesprojectId(const std::string& value) { osExtendedSnapshotAttributesprojectId_ = value; osExtendedSnapshotAttributesprojectIdIsSet_ = true; } bool SnapshotDetails::osExtendedSnapshotAttributesprojectIdIsSet() const { return osExtendedSnapshotAttributesprojectIdIsSet_; } void SnapshotDetails::unsetosExtendedSnapshotAttributesprojectId() { osExtendedSnapshotAttributesprojectIdIsSet_ = false; } std::string SnapshotDetails::getOsExtendedSnapshotAttributesprogress() const { return osExtendedSnapshotAttributesprogress_; } void SnapshotDetails::setOsExtendedSnapshotAttributesprogress(const std::string& value) { osExtendedSnapshotAttributesprogress_ = value; osExtendedSnapshotAttributesprogressIsSet_ = true; } bool SnapshotDetails::osExtendedSnapshotAttributesprogressIsSet() const { return osExtendedSnapshotAttributesprogressIsSet_; } void SnapshotDetails::unsetosExtendedSnapshotAttributesprogress() { osExtendedSnapshotAttributesprogressIsSet_ = false; } } } } } }
25.00464
153
0.673286
yangzhaofeng
55307bf0b102da1dcbeca82bac7ed73adf53a86a
8,215
cpp
C++
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
MyProcessInjectControl/MFCMyProcCtlUI/MFCMyProcCtlUIDlg.cpp
shc0743/CLearn
e6580588102bb66fb76903deb6699f19b38f4676
[ "MIT" ]
null
null
null
 // MFCMyProcCtlUIDlg.cpp: 实现文件 // #include "pch.h" #include "framework.h" #include "MFCMyProcCtlUI.h" #include "MFCMyProcCtlUIDlg.h" #include "afxdialogex.h" #ifdef _DEBUG #define new DEBUG_NEW #endif #include <TlHelp32.h> using namespace std; CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX) { } void CAboutDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx) END_MESSAGE_MAP() // CMFCMyProcCtlUIDlg 对话框 CMFCMyProcCtlUIDlg::CMFCMyProcCtlUIDlg(CWnd* pParent /*=nullptr*/) : CDialogEx(IDD_MFCMYPROCCTLUI_DIALOG, pParent) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); hThread_refresh = NULL; //pImageList = new CImageList; //pImageList->Create(32, 32, ILC_COLOR32, 0, 1); } CMFCMyProcCtlUIDlg::~CMFCMyProcCtlUIDlg() { //delete pImageList; } void CMFCMyProcCtlUIDlg::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_LIST_PROCS, m_list_procs); } BEGIN_MESSAGE_MAP(CMFCMyProcCtlUIDlg, CDialogEx) ON_WM_SYSCOMMAND() ON_WM_PAINT() ON_WM_QUERYDRAGICON() ON_BN_CLICKED(IDC_BUTTON_REFRESH_PROCS, &CMFCMyProcCtlUIDlg::OnBnClickedButtonRefreshProcs) ON_BN_CLICKED(IDC_BUTTON_ATTACH_CONTROLLER, &CMFCMyProcCtlUIDlg::OnBnClickedButtonAttachController) ON_BN_CLICKED(IDC_BUTTON_DETACH_CONTROLLER, &CMFCMyProcCtlUIDlg::OnBnClickedButtonDetachController) END_MESSAGE_MAP() // CMFCMyProcCtlUIDlg 消息处理程序 DWORD __stdcall CMFCMyProcCtlUIDlg::Thread_RefreshList(PVOID arg) { CMFCMyProcCtlUIDlg* pobj = (CMFCMyProcCtlUIDlg*)arg; if (!pobj) return ERROR_INVALID_PARAMETER; pobj->GetDlgItem(IDC_BUTTON_ATTACH_CONTROLLER)->EnableWindow(0); pobj->GetDlgItem(IDC_BUTTON_DETACH_CONTROLLER)->EnableWindow(0); pobj->GetDlgItem(IDC_BUTTON_REFRESH_PROCS)->EnableWindow(0); pobj->m_list_procs.DeleteAllItems(); HANDLE hsnap = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (INVALID_HANDLE_VALUE == hsnap) return false; PROCESSENTRY32 pe = {0}; pe.dwSize = sizeof(PROCESSENTRY32); Process32First(hsnap, &pe); int index = 0; do { //HANDLE hProcess = // OpenProcess(pe.th32ProcessID, FALSE, PROCESS_QUERY_INFORMATION); //BOOL ok = FALSE; //if (hProcess) { // TCHAR buffer[2048] = { 0 }; DWORD size = 2047; // QueryFullProcessImageName(hProcess, 0, buffer, &size); // CloseHandle(hProcess); // HMODULE hMod = LoadLibrary(buffer); // if (hMod) { // pobj->pImageList->Add(LoadIcon(hMod, IDI_APPLICATION)); // ok = true; // } //} //if (!ok) { // pobj->pImageList->Add(LoadIcon(NULL, IDI_APPLICATION)); //} pobj->m_list_procs.InsertItem(index, to_wstring(pe.th32ProcessID).c_str()); pobj->m_list_procs.SetItemText(index, 1, pe.szExeFile); index++; } while (::Process32Next(hsnap, &pe)); ::CloseHandle(hsnap); if (pobj->cl.getopt(L"service-name")) { pobj->GetDlgItem(IDC_BUTTON_ATTACH_CONTROLLER)->EnableWindow(); pobj->GetDlgItem(IDC_BUTTON_DETACH_CONTROLLER)->EnableWindow(); } pobj->GetDlgItem(IDC_BUTTON_REFRESH_PROCS)->EnableWindow(); return 0; } BOOL CMFCMyProcCtlUIDlg::OnInitDialog() { CDialogEx::OnInitDialog(); // 将“关于...”菜单项添加到系统菜单中。 // IDM_ABOUTBOX 必须在系统命令范围内。 ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX); ASSERT(IDM_ABOUTBOX < 0xF000); CMenu* pSysMenu = GetSystemMenu(FALSE); if (pSysMenu != nullptr) { BOOL bNameValid; CString strAboutMenu; bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX); ASSERT(bNameValid); if (!strAboutMenu.IsEmpty()) { pSysMenu->AppendMenu(MF_SEPARATOR); pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu); } } // 设置此对话框的图标。 当应用程序主窗口不是对话框时,框架将自动 // 执行此操作 SetIcon(m_hIcon, TRUE); // 设置大图标 SetIcon(m_hIcon, FALSE); // 设置小图标 // TODO: 在此添加额外的初始化代码 m_list_procs.InsertColumn(0, L"PID", 0, 80, 0); m_list_procs.InsertColumn(1, L"Image Name", 0, 200, 0); m_list_procs.InsertItem(0, L"Loading"); m_list_procs.SetItemText(0, 1, L"Loading datas..."); //m_list_procs.SetImageList(pImageList, LVSIL_NORMAL); cl.parse(GetCommandLineW()); if (cl.getopt(L"service-name", ServiceName)) { CString wt; GetWindowText(wt); SetWindowTextW((L"[" + ServiceName + L"] - " + wt.GetBuffer()).c_str()); } try_create_reflush_thread: hThread_refresh = CreateThread(0, 0, Thread_RefreshList, this, 0, 0); if (hThread_refresh) { CloseHandle(hThread_refresh); } else { if (IDRETRY == MessageBox(L"CANNOT CREATE THREAD", 0, MB_ICONHAND | MB_RETRYCANCEL | MB_DEFBUTTON2)) goto try_create_reflush_thread; else EndDialog(-1); } return TRUE; // 除非将焦点设置到控件,否则返回 TRUE } void CMFCMyProcCtlUIDlg::OnSysCommand(UINT nID, LPARAM lParam) { if ((nID & 0xFFF0) == IDM_ABOUTBOX) { CAboutDlg dlgAbout; dlgAbout.DoModal(); } else { CDialogEx::OnSysCommand(nID, lParam); } } // 如果向对话框添加最小化按钮,则需要下面的代码 // 来绘制该图标。 对于使用文档/视图模型的 MFC 应用程序, // 这将由框架自动完成。 void CMFCMyProcCtlUIDlg::OnPaint() { if (IsIconic()) { CPaintDC dc(this); // 用于绘制的设备上下文 SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0); // 使图标在工作区矩形中居中 int cxIcon = GetSystemMetrics(SM_CXICON); int cyIcon = GetSystemMetrics(SM_CYICON); CRect rect; GetClientRect(&rect); int x = (rect.Width() - cxIcon + 1) / 2; int y = (rect.Height() - cyIcon + 1) / 2; // 绘制图标 dc.DrawIcon(x, y, m_hIcon); } else { CDialogEx::OnPaint(); } } //当用户拖动最小化窗口时系统调用此函数取得光标 //显示。 HCURSOR CMFCMyProcCtlUIDlg::OnQueryDragIcon() { return static_cast<HCURSOR>(m_hIcon); } void CMFCMyProcCtlUIDlg::OnBnClickedButtonRefreshProcs() { try_create_reflush_thread: hThread_refresh = CreateThread(0, 0, Thread_RefreshList, this, 0, 0); if (hThread_refresh) { CloseHandle(hThread_refresh); } else { if (IDRETRY == MessageBox(L"Cannot create thread", 0, MB_ICONHAND | MB_RETRYCANCEL | MB_DEFBUTTON2)) goto try_create_reflush_thread; } } bool CMFCMyProcCtlUIDlg::CheckAdminPriv() { if (!IsRunAsAdmin()) { if (IDRETRY == MessageBoxW(L"Administrator privileges are required to " "complete this operation.\nClick [Retry] to retry as an administrator.", L"Access is Denied", MB_ICONHAND | MB_RETRYCANCEL)) { if ((INT_PTR)ShellExecuteW(m_hWnd, L"runas", s2wc(GetProgramDir()), (L"/runas "s + GetCommandLineW()).c_str(), 0, 1) > 32) EndDialog(0); } return false; } return true; } void CMFCMyProcCtlUIDlg::OnBnClickedButtonAttachController() { if (!CheckAdminPriv()) return; POSITION pos = m_list_procs.GetFirstSelectedItemPosition(); if (pos != NULL) { while (pos) { int nItem = m_list_procs.GetNextSelectedItem(pos); // nItem是所选中行的序号 CString text = m_list_procs.GetItemText(nItem, 0); DWORD pid = atol(ws2c(text.GetBuffer())); HANDLE hPipe = NULL; WCHAR pipe_name[256]{ 0 }; DWORD tmp = 0; LoadStringW(NULL, IDS_STRING_SVC_CTRLPIPE, pipe_name, 255); wcscat_s(pipe_name, L"\\"); wcscat_s(pipe_name, ServiceName.c_str()); if (::WaitNamedPipeW(pipe_name, 10000)) { #pragma warning(push) #pragma warning(disable: 6001) hPipe = ::CreateFileW(pipe_name, GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); if (!hPipe || hPipe == INVALID_HANDLE_VALUE) { MessageBoxW(LastErrorStrW().c_str(), NULL, MB_ICONHAND); break; } DWORD dwMode = PIPE_READMODE_MESSAGE; (VOID)SetNamedPipeHandleState( hPipe, // pipe handle &dwMode, // new pipe mode NULL, // don't set maximum bytes NULL); // don't set maximum time string str = "Attach-Process-Control /pid=" + to_string(pid); ::WriteFile(hPipe, str.c_str(), (DWORD)str.length(), &tmp, NULL); auto _sub1 = [&] { MessageBox((_T("Error: "s) + ErrorCodeToString(atol(ws2s(pipe_name).c_str())) + TEXT("\nRaw data:") + pipe_name) .c_str(), 0, MB_ICONHAND); }; if (ReadFile(hPipe, pipe_name, 255, &tmp, 0)) { if (0 == wcscmp(L"0", pipe_name)) { MessageBox(ErrorCodeToString(0).c_str(), 0, MB_ICONINFORMATION); } else _sub1(); } else _sub1(); ::CloseHandle(hPipe); #pragma warning(pop) } else { MessageBoxW(ErrorCodeToStringW(ERROR_TIMEOUT).c_str(), 0, MB_ICONHAND); } } } } void CMFCMyProcCtlUIDlg::OnBnClickedButtonDetachController() { if (!CheckAdminPriv()) return; }
26.246006
79
0.709677
shc0743
553345d2e3f5d662bb794c85bfdcafd0b77fc691
8,688
cpp
C++
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/Qurses/util.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
/* Public Domain Curses */ #include "Qurses/curspriv.h" RCSID("$Id: util.c,v 1.71 2008/07/13 16:08:18 wmcbrine Exp $") /*man-start************************************************************** Name: util Synopsis: char *unctrl(chtype c); void filter(void); void use_env(bool x); int delay_output(int ms); int getcchar(const cchar_t *wcval, wchar_t *wch, attr_t *attrs, short *color_pair, void *opts); int setcchar(cchar_t *wcval, const wchar_t *wch, const attr_t attrs, short color_pair, const void *opts); wchar_t *wunctrl(cchar_t *wc); int PDC_mbtowc(wchar_t *pwc, const char *s, size_t n); size_t PDC_mbstowcs(wchar_t *dest, const char *src, size_t n); size_t PDC_wcstombs(char *dest, const wchar_t *src, size_t n); Description: unctrl() expands the text portion of the chtype c into a printable string. Control characters are changed to the "^X" notation; others are passed through. wunctrl() is the wide- character version of the function. filter() and use_env() are no-ops in PDCurses. delay_output() inserts an ms millisecond pause in output. getcchar() works in two modes: When wch is not NULL, it reads the cchar_t pointed to by wcval and stores the attributes in attrs, the color pair in color_pair, and the text in the wide-character string wch. When wch is NULL, getcchar() merely returns the number of wide characters in wcval. In either mode, the opts argument is unused. setcchar constructs a cchar_t at wcval from the wide-character text at wch, the attributes in attr and the color pair in color_pair. The opts argument is unused. Currently, the length returned by getcchar() is always 1 or 0. Similarly, setcchar() will only take the first wide character from wch, and ignore any others that it "should" take (i.e., combining characters). Nor will it correctly handle any character outside the basic multilingual plane (UCS-2). Return Value: unctrl() and wunctrl() return NULL on failure. delay_output() always returns OK. getcchar() returns the number of wide characters wcval points to when wch is NULL; when it's not, getcchar() returns OK or ERR. setcchar() returns OK or ERR. Portability X/Open BSD SYS V unctrl Y Y Y filter Y - 3.0 use_env Y - 4.0 delay_output Y Y Y getcchar Y setcchar Y wunctrl Y PDC_mbtowc - - - PDC_mbstowcs - - - PDC_wcstombs - - - **man-end****************************************************************/ #if __QOR_UNICODE # ifdef PDC_FORCE_UTF8 # include <string.h> # else # include <stdlib.h> # endif #endif //------------------------------------------------------------------------------ char* unctrl( chtype c ) { __QCS_FCONTEXT( "unctrl" ); static char strbuf[3] = {0, 0, 0}; chtype ic; ic = c & A_CHARTEXT; if (ic >= 0x20 && ic != 0x7f) /* normal characters */ { strbuf[0] = (char)ic; strbuf[1] = '\0'; return strbuf; } strbuf[0] = '^'; /* '^' prefix */ if (ic == 0x7f) /* 0x7f == DEL */ strbuf[1] = '?'; else /* other control */ strbuf[1] = (char)(ic + '@'); return strbuf; } //------------------------------------------------------------------------------ void filter(void) { __QCS_FCONTEXT( "filter" ); } //------------------------------------------------------------------------------ void use_env(bool x) { __QCS_FCONTEXT( "use_env" ); } //------------------------------------------------------------------------------ int delay_output(int ms) { __QCS_FCONTEXT( "delay_output" ); return napms( ms ); } #if __QOR_UNICODE //------------------------------------------------------------------------------ int getcchar( const cchar_t* wcval, wchar_t* wch, attr_t* attrs, short* color_pair, void* opts ) { __QCS_FCONTEXT( "getchar" ); if (!wcval) return ERR; if (wch) { if (!attrs || !color_pair) return ERR; *wch = (*wcval & A_CHARTEXT); *attrs = (*wcval & (A_ATTRIBUTES & ~A_COLOR)); *color_pair = PAIR_NUMBER(*wcval & A_COLOR); if (*wch) *++wch = L'\0'; return 0; } else return ((*wcval & A_CHARTEXT) != L'\0'); } //------------------------------------------------------------------------------ int setcchar( cchar_t* wcval, const wchar_t* wch, const attr_t attrs, short color_pair, const void* opts ) { __QCS_FCONTEXT( "setcchar" ); if (!wcval || !wch) return ERR; *wcval = *wch | attrs | COLOR_PAIR(color_pair); return 0; } //------------------------------------------------------------------------------ wchar_t* wunctrl( cchar_t* wc ) { __QCS_FCONTEXT( "wunctrl" ); static wchar_t strbuf[3] = {0, 0, 0}; cchar_t ic; PDC_LOG(("wunctrl() - called\n")); ic = *wc & A_CHARTEXT; if (ic >= 0x20 && ic != 0x7f) /* normal characters */ { strbuf[0] = (wchar_t)ic; strbuf[1] = L'\0'; return strbuf; } strbuf[0] = '^'; /* '^' prefix */ if (ic == 0x7f) /* 0x7f == DEL */ strbuf[1] = '?'; else /* other control */ strbuf[1] = (wchar_t)(ic + '@'); return strbuf; } //------------------------------------------------------------------------------ int PDC_mbtowc(wchar_t *pwc, const char *s, size_t n) { __QCS_FCONTEXT( "PDC_mbtowc" ); # ifdef PDC_FORCE_UTF8 wchar_t key; int i = -1; const unsigned char *string; if (!s || (n < 1)) return -1; if (!*s) return 0; string = (const unsigned char *)s; key = string[0]; /* Simplistic UTF-8 decoder -- only does the BMP, minimal validation */ if (key & 0x80) { if ((key & 0xe0) == 0xc0) { if (1 < n) { key = ((key & 0x1f) << 6) | (string[1] & 0x3f); i = 2; } } else if ((key & 0xe0) == 0xe0) { if (2 < n) { key = ((key & 0x0f) << 12) | ((string[1] & 0x3f) << 6) | (string[2] & 0x3f); i = 3; } } } else i = 1; if (i) *pwc = key; return i; # else return mbtowc(pwc, s, n); # endif } //------------------------------------------------------------------------------ size_t PDC_mbstowcs(wchar_t *dest, const char *src, size_t n) { __QCS_FCONTEXT( "PDC_mbstowcs" ); # ifdef PDC_FORCE_UTF8 size_t i = 0, len; if (!src || !dest) return 0; len = strlen(src); while (*src && i < n) { int retval = PDC_mbtowc(dest + i, src, len); if (retval < 1) return -1; src += retval; len -= retval; i++; } # else size_t i = mbstowcs(dest, src, n); # endif dest[i] = 0; return i; } //------------------------------------------------------------------------------ size_t PDC_wcstombs(char *dest, const wchar_t *src, size_t n) { __QCS_FCONTEXT( "PDC_wcstombs" ); # ifdef PDC_FORCE_UTF8 size_t i = 0; if (!src || !dest) return 0; while (*src && i < n) { chtype code = *src++; if (code < 0x80) { dest[i] = code; i++; } else if (code < 0x800) { dest[i] = ((code & 0x07c0) >> 6) | 0xc0; dest[i + 1] = (code & 0x003f) | 0x80; i += 2; } else { dest[i] = ((code & 0xf000) >> 12) | 0xe0; dest[i + 1] = ((code & 0x0fc0) >> 6) | 0x80; dest[i + 2] = (code & 0x003f) | 0x80; i += 3; } } # else size_t i = wcstombs(dest, src, n); # endif dest[i] = '\0'; return i; } #endif
26.487805
106
0.436119
mfaithfull
553c6630e13e876b18e0421953c8a53c297bc302
3,945
hpp
C++
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
threadsafe/queue/spsc_queue.hpp
AVasK/core
e8f73f2b92be1ac0a98bda2824682181c5575748
[ "MIT" ]
null
null
null
#pragma once #include <atomic> #include "../../cpu.hpp" // cacheline_size #include "../../range.hpp" #include "../auxiliary/tagged.hpp" // TaggedData #include "io_descriptors.hpp" // core::{queue_reader, queue_writer} #include <vector> template <typename T, typename size_type=unsigned> class spsc_queue { friend core::queue_reader<spsc_queue>; friend core::queue_writer<spsc_queue>; struct too_many_readers : std::exception {}; struct too_many_writers : std::exception {}; public: using value_type = T; static constexpr core::u8 max_writers = 1; static constexpr core::u8 max_readers = 1; spsc_queue(size_t size=2048) : ring(size), _size(size) { for (auto& elem : ring) { elem.tag.store(false); } } core::queue_reader<spsc_queue> reader() { if (n_readers < 1) return {*this}; else throw too_many_readers{}; } core::queue_writer<spsc_queue> writer() { if (n_writers < 1) return {*this}; else throw too_many_writers{}; } bool try_pop(T & data) { auto index = read_from + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( filled ) { data = std::move(slot.data); slot.tag.store(false, std::memory_order_release); read_from = index; return true; } return false; } bool try_push(T const& data) { auto index = write_to + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( !filled ) { slot.data = data; slot.tag.store(true, std::memory_order_release); write_to = index; return true; } return false; } bool try_push(T && data) { auto index = write_to + 1; auto& slot = ring[index % _size]; auto filled = slot.tag.load(std::memory_order_acquire); if ( !filled ) { slot.data = std::move(data); slot.tag.store(true, std::memory_order_release); write_to = index; return true; } return false; } void push(T const& data) { constexpr size_t n_spinwaits = 1;//100000; // std::cerr << "push...\n"; for (;;) { // std::cerr << "."; for (size_t _ : core::range(n_spinwaits)) { if (try_push(data)) return; } std::this_thread::yield(); } } void close() { active.store(false, std::memory_order_release); } bool closed() const { return !active.load(std::memory_order_acquire); } bool empty() const { return write_to == read_from; } explicit operator bool () const { return !(closed() && empty()); } void print_state() const { std::cerr << "Q: [" << read_from/*.load()*/ << " -> " << write_to/*.load()*/ << "] | active: " << std::boolalpha << active.load() << "\n"; std::cerr << "[ " << bool(*this) << " ]\n"; } void debug_ring() const { for (auto i : core::range(ring.size()) ) { auto& elem = ring[i]; char sym; auto filled = elem.tag.load(); if ( filled ) sym = '#'; else sym = ' '; if ( filled ) { std::cout << "[" << sym << "| " << elem.data << "]" << " @ " << i << "/" << ring.size() << "\n"; } } } private: std::vector< core::TaggedData<T, std::atomic<bool>> > ring; const size_type _size; alignas(core::device::CPU::cacheline_size) std::atomic<bool> active {true}; alignas(core::device::CPU::cacheline_size) size_type read_from {0}; unsigned n_readers {0}; alignas(core::device::CPU::cacheline_size) size_type write_to {0}; unsigned n_writers {0}; };
26.836735
146
0.532573
AVasK
553fa9919d6f85475b1ce52b5cd98398731f4ede
29,505
cpp
C++
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
null
null
null
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
1
2017-01-07T09:44:20.000Z
2017-01-07T09:44:20.000Z
libs/odbc/binder.cpp
hajokirchhoff/litwindow
7f574d4e80ee8339ac11c35f075857c20391c223
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright 2005-2006, Hajo Kirchhoff - Lit Window Productions, http://www.litwindow.com * This file is part of the Lit Window ODBC Library. All use of this material - copying * in full or part, including in other works, using in non-profit or for-profit work * and other uses - is governed by the licence contained in the Lit Window ODBC Library * distribution, file LICENCE.TXT * $Id: binder.cpp,v 1.10 2007/10/18 11:13:17 Hajo Kirchhoff Exp $ */ #include "stdafx.h" #include <sqlext.h> #include <litwindow/dataadapter.h> #include <litwindow/logging.h> #include <boost/bind.hpp> #include <boost/spirit/include/classic.hpp> #include <boost/spirit/include/classic_actor.hpp> #include <set> #include <iomanip> #include "litwindow/odbc/statement.h" #include <boost/uuid/uuid.hpp> #define new DEBUG_NEW using boost::uuids::uuid; template <> litwindow::tstring litwindow::converter<TIME_STRUCT>::to_string(const TIME_STRUCT &v) { basic_stringstream<TCHAR> out; if (v.hour<=23 && v.minute<=59 && v.second<=59) { const TCHAR *fmt=_T("%X"); struct tm t; memset(&t, 0, sizeof(t)); t.tm_hour=v.hour; t.tm_min=v.minute; t.tm_sec=v.second; use_facet<time_put<TCHAR> >(locale()).put(out.rdbuf(), out, _T(' '), &t, fmt, fmt+sizeof(fmt)/sizeof(*fmt)); } else { out << _T("time_invalid"); } return out.str(); } namespace { using namespace boost::spirit::classic; template <typename NumberValue> bool parse_time(const litwindow::tstring &newValue, NumberValue &hours, NumberValue &minutes, NumberValue &seconds) { hours=0; minutes=0; seconds=0; return parse( newValue.begin(), newValue.end(), limit_d(0u, 23u)[uint_parser<NumberValue, 10, 1, 2>()[assign_a(hours)]] >> !( limit_d(0u, 59u)[uint_parser<NumberValue, 10, 2, 2>()[assign_a(minutes)]] >> !limit_d(0u,59u)[uint_parser<NumberValue, 10, 2, 2>()[assign_a(seconds)]] ) >> !(as_lower_d[str_p(_T("am")) | str_p(_T("pm"))]) , space_p | chset_p(_T(":.-")) ).full; } }; template <> size_t litwindow::converter<TIME_STRUCT>::from_string(const litwindow::tstring &newValue, TIME_STRUCT &v) { ios_base::iostate st = 0; struct tm t; memset(&t, 0, sizeof(t)); { basic_istringstream<TCHAR> in(newValue); use_facet<time_get<TCHAR > >(locale()).get_time(in.rdbuf(), basic_istream<TCHAR>::_Iter(0), in, st, &t); } if (st & ios_base::failbit) { size_t hours=0, minutes=0, seconds=0; if (parse_time(newValue, hours, minutes, seconds)==false) { v.hour=v.minute=v.second=0; throw lwbase_error("invalid time format"); } else { v.hour=SQLUSMALLINT(hours); v.minute=SQLUSMALLINT(minutes); v.second=SQLUSMALLINT(seconds); } } else { v.hour=t.tm_hour; v.minute=t.tm_min; v.second=t.tm_sec; } return sizeof(TIME_STRUCT); } LWL_IMPLEMENT_ACCESSOR(TIME_STRUCT) namespace litwindow { namespace odbc {; #ifndef SQL_TVARCHAR #ifdef UNICODE #define SQL_TVARCHAR SQL_WVARCHAR #else #define SQL_TVARCHAR SQL_VARCHAR #endif #endif //#region binder public interface sqlreturn binder::bind_parameter(SQLUSMALLINT position, SQLSMALLINT in_out, SQLSMALLINT c_type, SQLSMALLINT sql_type, SQLULEN column_size, SQLSMALLINT decimal_digits, SQLPOINTER buffer, SQLLEN length, SQLLEN *len_ind) { bind_task bi; data_type_info &info=bi.m_bind_info; info.m_c_type=c_type; info.m_column_size=column_size; info.m_decimal=decimal_digits; info.m_len_ind_p=len_ind; info.m_position=position; info.m_sql_type=sql_type; info.m_target_ptr=buffer; info.m_target_size=length; info.m_type=0; bi.m_by_position=position; bi.m_in_out=in_out; m_parameters.add(bi); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_parameter(const bind_task &task) { m_parameters.add(task); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_parameter(SQLUSMALLINT pposition, const accessor &a, SQLSMALLINT in_out, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_position=pposition; bi.m_in_out=in_out; m_parameters.add(bi); } return rc; } sqlreturn binder::bind_parameter(const tstring &name, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_name=name; bi.m_in_out=unknown_bind_type; m_parameters.add(bi); } return rc; } sqlreturn binder::bind_parameter(const aggregate &a, solve_nested_names_enum solver) { return bind_aggregate(a, tstring(), solver, false); } sqlreturn binder::bind_column(SQLSMALLINT col, SQLSMALLINT c_type, SQLPOINTER target_ptr, SQLINTEGER size, SQLLEN* len_ind) { bind_task bi; bi.m_bind_info.m_c_type=c_type; bi.m_bind_info.m_target_ptr=target_ptr; bi.m_bind_info.m_target_size=size; bi.m_bind_info.m_position=col; bi.m_bind_info.m_len_ind_p=len_ind; bi.m_by_position=col; m_columns.add(bi); return sqlreturn(SQL_SUCCESS); } sqlreturn binder::bind_column(SQLSMALLINT col, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_by_position=col; if (len_ind) bi.m_bind_info.m_len_ind_p=len_ind; m_columns.add(bi); } return rc; } sqlreturn binder::bind_column(const tstring &column_name, const accessor &a, SQLLEN *len_ind) { bind_task bi; sqlreturn rc=get_bind_info(a, bi.m_bind_info); if (rc.ok()) { bi.m_by_name=column_name; if (len_ind) bi.m_bind_info.m_len_ind_p=len_ind; m_columns.add(bi); } return rc; } sqlreturn binder::bind_column(const aggregate &a, const tstring &table, solve_nested_names_enum solver) { return bind_aggregate(a, table, solver, true); } //#endregion sqlreturn binder::build_insert_statement_and_bind(tstring &sql, const tstring &table_name, statement *bind_to) const { tstring bind_parameters; size_t i; sqlreturn rc; if (m_columns.size()>0) { size_t last_element=m_columns.size()-1; SQLUSMALLINT parameter_index=0; for (i=0; i<=last_element && rc; ++i) { const bind_task &b(m_columns.get_bind_task(i)); if (b.m_bind_info.m_len_ind_p==0 || (*b.m_bind_info.m_len_ind_p!=SQL_IGNORE && *b.m_bind_info.m_len_ind_p!=SQL_DEFAULT)) { // bind values only if they are neither SQL_IGNORE or SQL_DEFAULT if (sql.length()==0) sql=_T("INSERT INTO ")+table_name+_T(" ("); else sql+=_T(", "); sql+= b.m_by_name; bind_parameters+= bind_parameters.length()>0 ? _T(", ?") : _T(") VALUES (?"); if (bind_to) { if (b.m_bind_info.m_accessor.is_valid()) rc=bind_to->bind_parameter_accessor(++parameter_index, SQL_PARAM_INPUT, b.m_bind_info.m_accessor, b.m_bind_info.m_len_ind_p); else rc=bind_to->bind_parameter(++parameter_index, SQL_PARAM_INPUT, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } } } } if (sql.length()==0) { return sqlreturn (_T("Table has no columns or all columns are being SQL_IGNORE-d. Cannot build insert statement."), err_logic_error); } sql+=bind_parameters + _T(")"); if (rc && bind_to) bind_to->set_statement(sql); return rc; } tstring binder::make_column_name(const tstring &c_identifier) { if (c_identifier.substr(0, 2)==_T("m_")) return c_identifier.substr(2); return c_identifier; } sqlreturn binder::bind_aggregate(const aggregate &a, size_t level, const tstring &prefix, solve_nested_names_enum solver, bool bind_to_columns) { sqlreturn rc; aggregate::iterator i; for (i=a.begin(); i!=a.end() && rc.ok(); ++i) { tstring column_name(make_column_name(s2tstring(i->get_name()))); tstring full_column_name; if ((solver & use_nested_levels)!=0 && prefix.length()>0) full_column_name=prefix+m_aggregate_scope_separator_char+column_name; else full_column_name=column_name; // attempt to bind the member as it is (completely) to a column. if (bind_to_columns) rc=bind_column(full_column_name, *i); else rc=bind_parameter(full_column_name, *i); if (rc.ok()==false) { // member could not be bound directly. See if it is an aggregate itself and bind its individual members if it is. if (i->is_aggregate()) { tstring new_prefix; if (i->is_inherited() && (solver&inheritance_as_nested)==0) new_prefix=prefix; else new_prefix=full_column_name; rc=bind_aggregate(i->get_aggregate(), level+1, new_prefix, solver, bind_to_columns); } } } return rc; } /// bind an aggregate adapter to the result columns sqlreturn binder::bind_aggregate(const aggregate &a, const tstring &prefix, solve_nested_names_enum solver, bool bind_to_columns) { tstring use_name; if (is_null(prefix)) use_name=s2tstring(a.get_class_name()); else use_name=prefix; return bind_aggregate(a, 0, use_name, solver, bind_to_columns); } sqlreturn binder::get_bind_info(const accessor &a, data_type_info &p_desc) { sqlreturn rc=data_type_lookup().get(a.get_type(), p_desc); if (rc.ok()) { p_desc.m_accessor=a; p_desc.m_target_ptr=a.get_member_ptr(); if (p_desc.m_target_size==0) p_desc.m_target_size=(SQLINTEGER)a.get_sizeof(); } return rc; } sqlreturn binder::do_bind_parameter(bind_task &b, statement &s) const { const parameter *p=s.get_parameter(b.m_by_position); if (p) { if (b.m_in_out==unknown_bind_type) { b.m_in_out=p->m_bind_type; } else if (b.m_in_out!=p->m_bind_type) { return sqlreturn(_("bind type used in the statement is different from bind parameter used in the C++ source")+b.m_by_name, odbc::err_logic_error); } } // else no parameter marker in statement sqlreturn rc=s.do_bind_parameter(b.m_by_position, b.m_in_out, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); return rc; } sqlreturn binder::do_bind_column(bind_task &b, statement &s) const { sqlreturn rc=s.do_bind_column(b.m_by_position, b.m_bind_info.m_c_type, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); return rc; } /** bind all parameters in the 'to bind' list to the statement. */ sqlreturn binder::do_bind_parameters(statement &s) { return m_parameters.prepare_binding(s, false); } sqlreturn binder::do_bind_columns(statement &s) { return m_columns.prepare_binding(s, true, s.get_column_count()); } sqlreturn binder::binder_lists::reset_bind_task_state(size_t pos, SQLINTEGER len_ind) { bind_task &b(m_elements[pos]); if (len_ind==statement::use_defaults) { if (b.m_bind_info.m_helper) // use the bind helper { *b.m_bind_info.m_len_ind_p= b.m_bind_info.m_helper->get_length(b.m_bind_info); } else if (b.m_bind_info.m_accessor.is_c_vector() && // use SQL_NTS if it is a char or wchar_t vector (old style C string) ((is_type<wchar_t>(b.m_bind_info.m_type) && b.m_bind_info.m_accessor.get_sizeof()>sizeof(wchar_t)) || (is_type<char>(b.m_bind_info.m_type) && b.m_bind_info.m_accessor.get_sizeof()>sizeof(char))) ) { *b.m_bind_info.m_len_ind_p=SQL_NTS; } else // use target_size as default size { *b.m_bind_info.m_len_ind_p=b.m_bind_info.m_target_size; } } else *b.m_bind_info.m_len_ind_p=len_ind; return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::reset_states(SQLINTEGER len_ind) { size_t i; for (i=0; i<m_elements.size(); ++i) { reset_bind_task_state(i, len_ind); } return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::set_column_state(SQLUSMALLINT col, SQLLEN len_ind) { if (col>=m_index.size()) return sqlreturn(_("no such column."), odbc::err_no_such_column); *m_index[col]->m_bind_info.m_len_ind_p=len_ind; return sqlreturn(SQL_SUCCESS); } sqlreturn binder::binder_lists::put() { sqlreturn rc; size_t i; for (i=0; i<m_elements.size() && rc; ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper) { rc=b.m_bind_info.m_helper->put_data(b.m_bind_info); } } return rc; } struct reset_intermediate_buffer_pointers { reset_intermediate_buffer_pointers(const unsigned char *buffer, SQLULEN size) { begin_ptr=buffer; if (buffer) end_ptr=buffer+size; else end_ptr=0; } const unsigned char *begin_ptr, *end_ptr; void operator()(SQLPOINTER &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } void operator()(SQLINTEGER * &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } #ifdef _WIN64 void operator()(SQLLEN * &p) const { if ((const unsigned char*)p>=begin_ptr && (const unsigned char*)p<end_ptr) p=0; } #endif }; sqlreturn binder::binder_lists::prepare_binding(statement &s, bool bind_as_columns, size_t columns_to_expect) { if (columns_to_expect) m_index.resize(columns_to_expect+1, 0); sqlreturn rc; m_needs_bind=false; fill(m_index.begin(), m_index.end(), static_cast<bind_task*>(0)); // the 'intermediate' buffer will be reset in this method // some pointers (cache, len_ind_p) might point into the intermediate buffer // to find and reset them, store beginning and end of the intermediate buffer reset_intermediate_buffer_pointers reset_ptrs((const unsigned char*)m_intermediate_buffer.get(), m_intermediate_buffer_size); m_intermediate_buffer_size=0; size_t i; for (i=0; i<m_elements.size(); ++i) { bind_task &b(m_elements[i]); if (m_intermediate_buffer.get()) { // reset pointers if they point into an existing intermediate buffer reset_ptrs(b.m_bind_info.m_len_ind_p); reset_ptrs(b.m_bind_info.m_target_ptr); reset_ptrs(b.m_cache); reset_ptrs(b.m_cache_len_ind_p); } if (b.m_by_position==-1) { SQLSMALLINT p; if (bind_as_columns) { p=s.find_column(b.m_by_name); } else { p=s.find_parameter(b.m_by_name); if (p!=-1) { const parameter *para=s.get_parameter(p); if (b.m_in_out==unknown_bind_type) { b.m_in_out=para->m_bind_type; } else if (b.m_in_out!=para->m_bind_type) { return sqlreturn(_("bind type used in the statement is different from bind parameter used in the C++ source")+b.m_by_name, odbc::err_logic_error); } } } if (p==-1) { return sqlreturn(tstring(_("no such "))+(bind_as_columns ? _("column ") : _("parameter "))+b.m_by_name, bind_as_columns ? err_no_such_column : err_no_such_parameter); } b.m_by_position=p; } else { tstringstream str; str << _("#:") << b.m_by_position; b.m_by_name=str.str(); } if (b.m_by_position>=(SQLSMALLINT)m_index.size()) m_index.resize(b.m_by_position+1, 0); m_index[b.m_by_position]=&m_elements[i]; b.m_bind_info.m_position=b.m_by_position; if (b.m_bind_info.m_helper) { // this is an extended binder, prepare the intermediate buffer if neccessary m_intermediate_buffer_size+=b.m_bind_info.m_helper->prepare_bind_buffer(b.m_bind_info, s, bind_as_columns ? bindto : bind_type(b.m_in_out)); } if (bind_as_columns==false && (b.m_bind_info.m_column_size==0 || b.m_bind_info.m_column_size==SQL_NTS) && b.m_bind_info.m_accessor.is_valid()) { // no column size specified. Try to calculate it. if (is_type<char>(b.m_bind_info.m_accessor)) b.m_bind_info.m_column_size=SQLUINTEGER(b.m_bind_info.m_accessor.get_sizeof()/sizeof(char)-1); else if (is_type<wchar_t>(b.m_bind_info.m_accessor)) b.m_bind_info.m_column_size=SQLUINTEGER(b.m_bind_info.m_accessor.get_sizeof()/sizeof(wchar_t)-1); } if (b.m_bind_info.m_len_ind_p==0) { m_intermediate_buffer_size+=sizeof(SQLLEN); } if (has_cache() && b.m_bind_info.m_target_size) { m_intermediate_buffer_size+=b.m_bind_info.m_target_size+sizeof(SQLLEN); } } m_intermediate_buffer.reset(m_intermediate_buffer_size>0 ? new unsigned char[m_intermediate_buffer_size] : 0); unsigned char *buffer=m_intermediate_buffer.get(); m_needs_get=m_needs_put=false; SQLULEN size_left=m_intermediate_buffer_size; for (i=0; i<m_elements.size() && rc.ok(); ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper && b.m_bind_info.m_target_ptr==0 && b.m_bind_info.m_target_size>0) { if (b.m_bind_info.m_target_size>size_left) { return sqlreturn(_("extended bind helper requesting more buffer space than is available"), odbc::err_logic_error); } b.m_bind_info.m_target_ptr=buffer; buffer+=b.m_bind_info.m_target_size; size_left-=b.m_bind_info.m_target_size; if (bind_as_columns) m_needs_put=m_needs_get=true; else { m_needs_put= b.m_in_out==SQL_PARAM_INPUT || b.m_in_out==SQL_PARAM_INPUT_OUTPUT; m_needs_get= b.m_in_out==SQL_PARAM_INPUT_OUTPUT || b.m_in_out==SQL_PARAM_OUTPUT; } } if (b.m_bind_info.m_len_ind_p==0) { b.m_bind_info.m_len_ind_p=(SQLLEN*)buffer; reset_bind_task_state(i, statement::use_defaults); //*b.m_bind_info.m_len_ind_p=b.m_bind_info.m_target_size; buffer+=sizeof(SQLLEN); size_left-=sizeof(SQLLEN); } if (has_cache() && b.m_bind_info.m_target_size) { b.m_cache=(SQLPOINTER)buffer; buffer+=b.m_bind_info.m_target_size; b.m_cache_len_ind_p=(SQLLEN*)buffer; buffer+=sizeof(SQLLEN); m_needs_get=true; size_left-=sizeof(SQLLEN)+b.m_bind_info.m_target_size; } else { b.m_cache=0; b.m_cache_len_ind_p=0; } if (b.m_bind_info.m_target_size>0 && b.m_bind_info.m_target_ptr!=0) { if (bind_as_columns) { rc=s.do_bind_column(b.m_by_position, b.m_bind_info.m_c_type, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } else { if (b.m_bind_info.m_column_size==0) m_needs_bind=true; // dynamic column size needs rebinding every time rc=s.do_bind_parameter(b.m_by_position, b.m_in_out, b.m_bind_info.m_c_type, b.m_bind_info.m_sql_type, b.m_bind_info.m_column_size, b.m_bind_info.m_decimal, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size, b.m_bind_info.m_len_ind_p); } } } return rc; } void binder::binder_lists::fix_SQL_NTS_len_ind_parameter_workaround(fix_workaround_enum action) { size_t pos; for (pos=0; pos<m_elements.size(); ++pos) { bind_task &b(m_elements[pos]); if (action==set_length) { b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute=false; if (b.m_in_out!=out && b.m_bind_info.m_len_ind_p && *b.m_bind_info.m_len_ind_p==SQL_NTS) { if (b.m_bind_info.m_c_type==SQL_C_CHAR) *b.m_bind_info.m_len_ind_p=(SQLINTEGER)strlen((const char*)b.m_bind_info.m_target_ptr) * sizeof(char); else if (b.m_bind_info.m_c_type==SQL_C_WCHAR) *b.m_bind_info.m_len_ind_p=(SQLINTEGER)wcslen((const wchar_t*)b.m_bind_info.m_target_ptr) * sizeof(wchar_t); b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute=true; } } else if (action==reset_length && b.m_bind_info.m_reset_len_ind_to_SQL_NTS_after_execute && b.m_in_out==in) { *b.m_bind_info.m_len_ind_p=SQL_NTS; } } } void binder::fix_SQL_NTS_len_ind_parameter_workaround(fix_workaround_enum action) { m_parameters.fix_SQL_NTS_len_ind_parameter_workaround(action); } SQLSMALLINT binder::find_column_or_parameter_by_target(const binder_lists &list, const const_accessor &a) const { size_t i; for (i=0; i<list.size() && a.is_alias_of(list.get_bind_task(i).m_bind_info.m_accessor)==false; ++i) ; return i<list.size() ? list.get_bind_task(i).m_by_position : -1; } SQLSMALLINT binder::find_column_by_target(const const_accessor &a) const { return find_column_or_parameter_by_target(m_columns, a); } sqlreturn binder::do_put_parameters(statement &s) { return m_parameters.put(); } sqlreturn binder::do_get_parameters(statement &s) { return sqlreturn(SQL_ERROR); } sqlreturn binder::binder_lists::do_get_columns_or_parameters(statement &s, bool type_is_columns) { if (type_is_columns==false) DebugBreak(); //TODO: get_parameters not implemented yet!!! size_t i; sqlreturn rc; for (i=0; i<m_elements.size() && rc.ok(); ++i) { bind_task &b(m_elements[i]); if (b.m_bind_info.m_helper) { rc=b.m_bind_info.m_helper->get_data(b.m_bind_info, s); } if (b.m_cache) { memcpy(b.m_cache, b.m_bind_info.m_target_ptr, b.m_bind_info.m_target_size); *b.m_cache_len_ind_p=*b.m_bind_info.m_len_ind_p; } } return rc; } sqlreturn binder::do_get_columns(statement &s) { return m_columns.do_get_columns_or_parameters(s, true); } data_type_info no_column; tstring binder::dump_columns(TCHAR quote_char) const { size_t i; tstring rc; for (i=0; i<m_columns.size(); ++i) { if (rc.length()>0) rc.append(_T(", ")); if (quote_char) rc.append(1, quote_char); rc.append(m_columns.get_bind_task(i).m_by_name); if (quote_char) rc.append(1, quote_char); } return rc; } const data_type_info &binder::get_column(SQLSMALLINT pos) const { return m_columns.is_valid_column_index(pos) ? m_columns.get_bind_task_for_column(pos)->m_bind_info : no_column; } sqlreturn binder::get_column_length(SQLSMALLINT pos, SQLLEN &value) const { const data_type_info i=get_column(pos); if (&i==&no_column) return sqlreturn(_("no such column"), odbc::err_no_such_column); else if (i.m_len_ind_p==0) return sqlreturn(_("column not bound"), odbc::err_column_not_bound); value=*i.m_len_ind_p; return sqlreturn(SQL_SUCCESS); } //-----------------------------------------------------------------------------------------------------------// //-----------------------------------------------------------------------------------------------------------// // look up types typedef vector<data_type_info> data_type_info_register; data_type_info_register &get_data_type_info_register() { static data_type_info_register s_map; return s_map; } data_type_info_register::const_iterator find_data_type_info(prop_t type) { data_type_info_register::const_iterator rc=find(get_data_type_info_register().begin(), get_data_type_info_register().end(), type); return rc; } void data_type_lookup::add(const data_type_info &i, const data_type_registrar *) { #ifdef REGISTER_IS_A_SET pair<data_type_info_register::iterator, bool> insertion=get_data_type_info_register().insert(i); if (insertion.second==false) { lw_err() << _("Type cannot be inserted twice! ") << litwindow::s2tstring(i.m_type->get_type_name()) << endl; } #endif get_data_type_info_register().push_back(i); } sqlreturn data_type_lookup::get(prop_t type, data_type_info &i) { data_type_info_register &the_map(get_data_type_info_register()); data_type_info_register::const_iterator data=find_data_type_info(type); if (data==the_map.end()) data=find_if(the_map.begin(), the_map.end(), boost::bind(&data_type_info::can_handle, _1, type)); if (data==the_map.end()) return sqlreturn(_("There is no registered SQL binder for type ")+s2tstring(type->get_type_name()), odbc::err_no_such_type); i=*data; return sqlreturn(SQL_SUCCESS); } data_type_info::data_type_info(prop_t type, SQLSMALLINT c_type, SQLSMALLINT sql_type, size_t col_size, extended_bind_helper *bhelper) { m_sql_type=sql_type; m_c_type=c_type; m_type=type; m_helper=bhelper; m_column_size=(SQLUINTEGER)col_size; } namespace { static register_data_type<long> tlong(SQL_C_SLONG, SQL_INTEGER); static register_data_type<int> tint(SQL_C_SLONG, SQL_INTEGER); static register_data_type<short> tshort(SQL_C_SSHORT, SQL_INTEGER); static register_data_type<unsigned long> tulong(SQL_C_ULONG, SQL_INTEGER); static register_data_type<unsigned int>tuint(SQL_C_ULONG, SQL_INTEGER); static register_data_type<unsigned short> tushort(SQL_C_USHORT, SQL_INTEGER); #define LWODBC_SQL_C_BOOL SQL_C_CHAR static register_data_type<bool> tbool(/*LWODBC_SQL_C_BOOL*/SQL_C_BIT, SQL_CHAR); static register_data_type<char> tchar(SQL_C_CHAR, SQL_VARCHAR, 0); static register_data_type<wchar_t> twchar(SQL_C_WCHAR, SQL_WVARCHAR, 0); static register_data_type<TIMESTAMP_STRUCT> ttimestampstruct(SQL_C_TIMESTAMP, SQL_TIMESTAMP); static register_data_type<float> tfloat(SQL_C_FLOAT, SQL_REAL); static register_data_type<double> tdouble(SQL_C_DOUBLE, SQL_DOUBLE); static register_data_type<double> tdouble2(SQL_C_DOUBLE, SQL_FLOAT); static register_data_type<TIME_STRUCT> ttime_struct(SQL_C_TIME, SQL_TIME); struct tuuid_bind_helper:public extended_bind_helper { // unfortunately for us, uuid stores the uuid bytes in a different order // than used by ODBC (under Windows at least) virtual SQLULEN prepare_bind_buffer(data_type_info &info, statement &s, bind_type bind_howto) const { info.m_target_ptr=0; info.m_target_size=16; return 16; } virtual sqlreturn get_data(data_type_info &info, statement &s) const { typed_accessor<uuid> a=dynamic_cast_accessor<uuid>(info.m_accessor); if (info.m_len_ind_p && (*info.m_len_ind_p==SQL_NULL_DATA || *info.m_len_ind_p==0)) { a.set(uuid()); } else { boost::uint8_t guiddata[16]; boost::uint8_t *p=guiddata; const boost::uint8_t *g=(const boost::uint8_t*)info.m_target_ptr; *p++=g[3]; *p++=g[2]; *p++=g[1]; *p++=g[0]; *p++=g[5]; *p++=g[4]; *p++=g[7]; *p++=g[6]; memcpy(p, g+8, 8); uuid temp; std::copy(guiddata+0, guiddata+16, temp.begin()); a.set(temp); } return sqlreturn(SQL_SUCCESS); } sqlreturn put_data(data_type_info &info) const { if (info.m_len_ind_p==0 || (*info.m_len_ind_p!=SQL_NULL_DATA && *info.m_len_ind_p!=SQL_DEFAULT_PARAM)) { typed_accessor<uuid> a=dynamic_cast_accessor<uuid>(info.m_accessor); if (info.m_target_size<16) return sqlreturn(_("String data right truncation (tstring)"), err_data_right_truncated, _T("22001")); uuid val(a.get()); uuid::iterator src=val.begin(); boost::uint8_t *dst=(boost::uint8_t*)info.m_target_ptr; dst[3]=*src++; dst[2]=*src++; dst[1]=*src++; dst[0]=*src++; dst[5]=*src++; dst[4]=*src++; dst[7]=*src++; dst[6]=*src++; memcpy(dst+8, src, 8); } return sqlreturn(SQL_SUCCESS); } SQLINTEGER get_length(data_type_info &info) const { return 16; } } g_uuid_bind_helper; static register_data_type<uuid> tuuid(SQL_C_GUID, SQL_GUID, 0, &g_uuid_bind_helper); struct tstring_bind_helper:public extended_bind_helper { virtual SQLULEN prepare_bind_buffer(data_type_info &info, statement &s, bind_type bind_howto) const { SQLSMALLINT pos=info.m_position; SQLULEN sz; info.m_target_ptr=0; // tell the binder we need an intermediate buffer sqlreturn rc; if (bind_howto==bindto) { if (info.m_sql_type==SQL_TVARCHAR) sz=maximum_text_column_length_retrieved; else { rc=s.get_column_size(pos, sz); if (sz==0) sz=maximum_text_column_length_retrieved; // use default maximum size } } else { if (info.m_column_size==0) { typed_const_accessor<tstring> ta=dynamic_cast_accessor<tstring>(info.m_accessor); sz=SQLINTEGER(ta.get_ptr() ? ta.get_ptr()->length() : ta.get().length()); } else sz=info.m_column_size; } sz+=1; // trailing \0 character sz*=sizeof(TCHAR); // might be unicode representation info.m_target_size=rc.ok() ? sz : 0; // tell the binder the size of the intermediate buffer return sz; } virtual sqlreturn get_data(data_type_info &info, statement &s) const { sqlreturn rc; typed_accessor<tstring> a=dynamic_cast_accessor<tstring>(info.m_accessor); if (info.m_len_ind_p && (*info.m_len_ind_p==SQL_NULL_DATA || *info.m_len_ind_p==0)) a.set(_T("")); else a.set(tstring((const TCHAR*)info.m_target_ptr)); return sqlreturn(SQL_SUCCESS); } sqlreturn put_data(data_type_info &info) const { bool data_truncated=false; // if (info.m_len_ind_p) // *info.m_len_ind_p=SQL_NTS; if (info.m_len_ind_p==0 || (*info.m_len_ind_p!=SQL_NULL_DATA && *info.m_len_ind_p!=SQL_DEFAULT_PARAM)) { typed_accessor<tstring> a=dynamic_cast_accessor<tstring>(info.m_accessor); tstring *s=a.get_ptr(); size_t required_length; if (s) { required_length=s->length()*sizeof(TCHAR)+sizeof(TCHAR); if (required_length>info.m_target_size) { required_length=info.m_target_size; data_truncated=true; } memcpy(info.m_target_ptr, s->c_str(), required_length); } else { // needs temporary tstring tstring temp; a.get(temp); required_length=temp.length()*sizeof(TCHAR)+sizeof(TCHAR); if (required_length>info.m_target_size) { required_length=info.m_target_size; data_truncated=true; } memcpy(info.m_target_ptr, temp.c_str(), required_length); } } return data_truncated ? sqlreturn(_("String data right truncation (tstring)"), err_data_right_truncated, _T("22001")) : sqlreturn(SQL_SUCCESS); } SQLINTEGER get_length(data_type_info &info) const { return SQL_NTS; } } g_tstring_bind_helper; static register_data_type<tstring> ttstring(SQL_C_TCHAR, SQL_TVARCHAR, 0, &g_tstring_bind_helper); }; }; }; using namespace std; template <> litwindow::tstring litwindow::converter<TIMESTAMP_STRUCT>::to_string(const TIMESTAMP_STRUCT &v) { tstringstream str; str << setfill(_T('0')) << setw(4) << v.year << _T('-') << setw(2) << (unsigned)v.month << _T('-') << setw(2) << (unsigned)v.day << _T(' ') << setw(2) << (unsigned)v.hour << _T(':') << setw(2) << (unsigned)v.minute << _T(':') << setw(2) << (unsigned)v.second << _T('.') << v.fraction; return str.str(); } LWL_IMPLEMENT_ACCESSOR(TIMESTAMP_STRUCT);
35
285
0.716624
hajokirchhoff
554449e60a821f16c728c8c7d5f120483a2d48bd
3,792
cpp
C++
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
1
2022-03-26T01:48:11.000Z
2022-03-26T01:48:11.000Z
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
null
null
null
Example/Example.cpp
davemc0/Particle
04d9bbe19e21b9024c81eb21708425e4a1ebc361
[ "CC0-1.0" ]
null
null
null
// Example.cpp - An example of the Particle System API in OpenGL // // Copyright 1999-2006, 2022 by David K. McAllister #include "Particle/pAPI.h" using namespace PAPI; // OpenGL #include "GL/glew.h" // This needs to come after GLEW #include "GL/freeglut.h" // For C++17 execution policy to get parallelism of particle actions #include <execution> ParticleContext_t P; // A water fountain spraying upward void ComputeParticles() { // Set the state of the new particles to be generated pSourceState S; S.Velocity(PDCylinder(pVec(0.0f, -0.01f, 0.25f), pVec(0.0f, -0.01f, 0.27f), 0.021f, 0.019f)); S.Color(PDLine(pVec(0.8f, 0.9f, 1.0f), pVec(1.0f, 1.0f, 1.0f))); // Generate particles along a very small line in the nozzle P.Source(200, PDLine(pVec(0.f, 0.f, 0.f), pVec(0.f, 0.f, 0.4f)), S); P.ParticleLoop(std::execution::par_unseq, [&](Particle_t& p_) { // Gravity P.Gravity(p_, pVec(0.f, 0.f, -0.01f)); // Bounce particles off a disc of radius 5 P.Bounce(p_, 0.f, 0.5f, 0.f, PDDisc(pVec(0.f, 0.f, 0.f), pVec(0.f, 0.f, 1.f), 5.f)); // Kill particles below Z=-3 P.Sink(p_, false, PDPlane(pVec(0.f, 0.f, -3.f), pVec(0.f, 0.f, 1.f))); // Move particles to their new positions P.Move(p_, true, false); }); P.CommitKills(); } // Draw each particle as a point using vertex arrays // To draw as textured point sprites just call glEnable(GL_POINT_SPRITE) before calling this function. void DrawGroupAsPoints() { size_t cnt = P.GetGroupCount(); if (cnt < 1) return; const float* ptr; size_t flstride, pos3Ofs, posB3Ofs, size3Ofs, vel3Ofs, velB3Ofs, color3Ofs, alpha1Ofs, age1Ofs, up3Ofs, rvel3Ofs, upB3Ofs, mass1Ofs, data1Ofs; cnt = P.GetParticlePointer(ptr, flstride, pos3Ofs, posB3Ofs, size3Ofs, vel3Ofs, velB3Ofs, color3Ofs, alpha1Ofs, age1Ofs, up3Ofs, rvel3Ofs, upB3Ofs, mass1Ofs, data1Ofs); if (cnt < 1) return; glEnable(GL_POINT_SMOOTH); glPointSize(4); glEnableClientState(GL_COLOR_ARRAY); glColorPointer(4, GL_FLOAT, int(flstride) * sizeof(float), ptr + color3Ofs); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, int(flstride) * sizeof(float), ptr + pos3Ofs); glDrawArrays(GL_POINTS, 0, (GLsizei)cnt); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_COLOR_ARRAY); } void Draw() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Set up the view glLoadIdentity(); gluLookAt(0, -12, 3, 0, 0, 0, 0, 0, 1); // Draw the ground glColor3ub(0, 115, 0); glPushMatrix(); glTranslatef(0, 0, -1); glutSolidCylinder(5, 1, 20, 20); glPopMatrix(); // Do what the particles do ComputeParticles(); // Draw the particles DrawGroupAsPoints(); glutSwapBuffers(); } void Reshape(int w, int h) { glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(40, w / double(h), 1, 100); glMatrixMode(GL_MODELVIEW); } int main(int argc, char** argv) { glutInit(&argc, argv); // Make a standard 3D window glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE); glutInitWindowSize(800, 800); glutCreateWindow("Particle Example"); glutDisplayFunc(Draw); glutIdleFunc(Draw); glutReshapeFunc(Reshape); // We want depth buffering, etc. glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); // Make a particle group int particleHandle = P.GenParticleGroups(1, 50000); P.CurrentGroup(particleHandle); P.TimeStep(0.1f); try { glutMainLoop(); } catch (PError_t& Er) { std::cerr << "Particle API exception: " << Er.ErrMsg << std::endl; throw Er; } return 0; }
26.893617
151
0.64847
davemc0
5545628e382e2f84e9ad33d63a872f72b56334fc
1,281
hpp
C++
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
3
2016-02-24T09:22:16.000Z
2021-04-06T03:04:21.000Z
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
null
null
null
include/cql/cql_uuid.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
6
2015-04-26T07:16:44.000Z
2020-11-23T06:31:07.000Z
/* * File: cql_uuid_t.hpp * Author: mc * * Created on September 26, 2013, 12:35 PM */ #ifndef CQL_UUID_HPP_ #define CQL_UUID_HPP_ #include <functional> namespace cql { class cql_uuid_t; } namespace std { // template<> // struct hash<cql::cql_uuid_t>; } namespace cql { class cql_uuid_t { public: // TODO: This is currently implemented as simple long // but soon we switch to official UUID implementation // as described here: // http://www.ietf.org/rfc/rfc4122.txt static cql_uuid_t create(); friend bool operator <(const cql_uuid_t& left, const cql_uuid_t& right); private: cql_uuid_t(unsigned long uuid): _uuid(uuid) { } unsigned long _uuid; // friend struct std::hash<cql_uuid_t>; }; } // namespace std { // template<> // struct hash<cql::cql_uuid_t> { // public: // typedef // cql::cql_uuid_t // argument_type; // typedef // size_t // result_type; // size_t // operator ()(const cql::cql_uuid_t& id) const { // return // ((id._uuid * 3169) << 16) + // ((id._uuid * 23) << 8) + // id._uuid; // } // }; // } #endif /* CQL_UUID_HPP_ */
18.042254
64
0.551132
ncbi
5546642ce4eec804341472684f579415e01994e1
641
cpp
C++
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
4
2022-01-03T08:45:55.000Z
2022-01-06T19:57:11.000Z
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
simplefvm/src/FVMSolver/CoeffsPartsCommon/DataExchanger/DataExchangerP.cpp
artvns/SimpleFvm
5a8eca332d6780e738c0bc6c8c2b787b47b5b20d
[ "MIT" ]
null
null
null
#include "DataExchangerP.h" namespace fvmsolver { DataExchangerP::DataExchangerP(uPtrDataPort spData) : spData_(std::move(spData)), data_(*spData_) { } void DataExchangerP::assignCurrentCellValues(size_t step) { size_t numUw_ = data_.getNumUStarW(step) - 1; size_t numUe_ = data_.getNumUStarE(step) - 1; size_t numVn_ = data_.getNumVStarN(step) - 1; size_t numVs_ = data_.getNumVStarS(step) - 1; dw_var_ = data_.get_deU(numUw_); de_var_ = data_.get_deU(numUe_); dn_var_ = data_.get_deV(numVn_); ds_var_ = data_.get_deV(numVs_); } }
27.869565
63
0.631825
artvns
554761e1a836a0c8b0f900513094b1f845556219
5,192
cpp
C++
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
src/physics/ycolshape.cpp
sivarajankumar/smoothernity
a4c7d290ca601bddf680ef040f3235dc7b029a6b
[ "MIT" ]
null
null
null
#include "yphysres.h" #include "ycolshape.hpp" #include "pmem.hpp" struct ycolshapes_t { int count; ycolshape_t *pool; }; static ycolshapes_t g_ycolshapes; int ycolshape_init(int count) { size_t size_max, align_max; ycolshape_t *cs; #define FIND_SIZES(t) \ if (sizeof(t) > size_max) size_max = sizeof(t); \ if (PMEM_ALIGNOF(t) > align_max) align_max = PMEM_ALIGNOF(t); size_max = align_max = 0; FIND_SIZES(btBoxShape); FIND_SIZES(btHeightfieldTerrainShape); FIND_SIZES(btCompoundShape); FIND_SIZES(btSphereShape); #undef FIND_SIZES g_ycolshapes.count = count; g_ycolshapes.pool = (ycolshape_t*)pmem_alloc(PMEM_ALIGNOF(ycolshape_t), sizeof(ycolshape_t) * count); if (!g_ycolshapes.pool) return YPHYSRES_CANNOT_INIT; for (int i = 0; i < count; ++i ) { cs = ycolshape_get(i); cs->vacant = 1; cs->shape_box = 0; cs->shape_sphere = 0; cs->shape_hmap = 0; cs->shape_comp = 0; cs->shape_convex = 0; cs->shape = 0; cs->data = 0; cs->comp = cs->comp_children = cs->comp_next = cs->comp_prev = 0; cs->vehs = 0; cs->rbs = 0; } for (int i = 0; i < count; ++i) if (!(ycolshape_get(i)->data = (char*)pmem_alloc(align_max, size_max))) return YPHYSRES_CANNOT_INIT; return YPHYSRES_OK; } void ycolshape_done(void) { ycolshape_t *cs; if (!g_ycolshapes.pool) return; for (int i = 0; i < g_ycolshapes.count; ++i) { cs = ycolshape_get(i); if (cs->data) { ycolshape_free(cs); pmem_free(cs->data); } } pmem_free(g_ycolshapes.pool); g_ycolshapes.pool = 0; } ycolshape_t * ycolshape_get(int colshapei) { if (colshapei >= 0 && colshapei < g_ycolshapes.count) return g_ycolshapes.pool + colshapei; else return 0; } int ycolshape_free(ycolshape_t *cs) { if (cs->vacant == 1) return YPHYSRES_INVALID_CS; if (cs->comp_children || cs->vehs || cs->rbs) return YPHYSRES_CS_HAS_REFS; cs->vacant = 1; if (cs->comp) { try { cs->comp->shape_comp->removeChildShape(cs->shape); } catch (...) { return YPHYSRES_INTERNAL; } if (cs->comp->comp_children == cs) cs->comp->comp_children = cs->comp_next; if (cs->comp_prev) cs->comp_prev->comp_next = cs->comp_next; if (cs->comp_next) cs->comp_next->comp_prev = cs->comp_prev; cs->comp = 0; cs->comp_prev = 0; cs->comp_next = 0; } if (cs->shape) { try { cs->shape->~btCollisionShape(); } catch (...) { return YPHYSRES_INTERNAL; } } cs->shape = 0; cs->shape_convex = 0; cs->shape_box = 0; cs->shape_hmap = 0; cs->shape_comp = 0; return YPHYSRES_OK; } int ycolshape_alloc_box(ycolshape_t *cs, float *size) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_box = new (cs->data) btBoxShape(btVector3(size[0], size[1], size[2])); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_box; cs->shape_convex = cs->shape_box; return YPHYSRES_OK; } int ycolshape_alloc_sphere(ycolshape_t *cs, float r) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_sphere = new (cs->data) btSphereShape(r); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_sphere; cs->shape_convex = cs->shape_sphere; return YPHYSRES_OK; } int ycolshape_alloc_hmap(ycolshape_t *cs, float *hmap, int width, int length, float hmin, float hmax, float *scale) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_hmap = new (cs->data) btHeightfieldTerrainShape(width, length, hmap, 1, hmin, hmax, 1, PHY_FLOAT, false); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape_hmap->setLocalScaling(btVector3(scale[0], scale[1], scale[2])); cs->shape = cs->shape_hmap; return YPHYSRES_OK; } int ycolshape_alloc_comp(ycolshape_t *cs) { if (!cs->vacant) return YPHYSRES_INVALID_CS; cs->vacant = 0; try { cs->shape_comp = new (cs->data) btCompoundShape(); } catch (...) { return YPHYSRES_INTERNAL; } cs->shape = cs->shape_comp; return YPHYSRES_OK; } int ycolshape_comp_add(ycolshape_t *prt, float *matrix, ycolshape_t *chd) { if (!prt->shape_comp || !chd->shape || chd->shape_comp || chd->comp) return YPHYSRES_INVALID_CS; chd->comp = prt; chd->comp_next = prt->comp_children; if (prt->comp_children) prt->comp_children->comp_prev = chd; prt->comp_children = chd; try { btTransform tm; tm.setFromOpenGLMatrix(matrix); prt->shape_comp->addChildShape(tm, chd->shape); } catch (...) { return YPHYSRES_INTERNAL; } return YPHYSRES_OK; }
27.764706
79
0.578005
sivarajankumar
554a6cc43c83e5ad46f4ae32c3288a1875b434a5
782
cpp
C++
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
src/client/src/ImagingException.cpp
don-reba/peoples-note
c22d6963846af833c55f4294dd0474e83344475d
[ "BSD-2-Clause" ]
null
null
null
#include "stdafx.h" #include "ImagingException.h" #include "Tools.h" using namespace std; using namespace Tools; ImagingException::ImagingException(HRESULT result) : error (::GetLastError()) , result (result) { DWORD flags (FORMAT_MESSAGE_FROM_SYSTEM|FORMAT_MESSAGE_FROM_HMODULE|FORMAT_MESSAGE_IGNORE_INSERTS); HMODULE source (GetModuleHandle(L"imaging.dll")); vector<wchar_t> buffer(100); ::FormatMessage ( flags // dwFlags , source // lpSource , error // dwMessageId , 0 // dwLanguageId , &buffer[0] // pBuffer , buffer.size() // nSize , NULL // Arguments ); message = ConvertToAnsi(&buffer[0]); } const char * ImagingException::what() const { return message.c_str(); }
24.4375
104
0.643223
don-reba
55500631f687f3ca724aa7dc4096cbb61ef2bf1b
1,385
cpp
C++
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
src/main.cpp
marangisto/dro
d5c7ff5a3d4a321f75288f4dc1417dc30cdca854
[ "MIT" ]
null
null
null
#include <gpio.h> #include <textio.h> #include <usart.h> #include <hardware/tm1637.h> #include <button.h> static const pin_t LED = PA5; static const pin_t PROBE = PA8; static const int SERIAL_USART = 2; static const pin_t SERIAL_TX = PA2; static const pin_t SERIAL_RX = PA3; static const interrupt_t SERIAL_ISR = interrupt::USART2; static const int AUX_TIMER_NO = 7; static const interrupt_t AUX_TIMER_ISR = interrupt::TIM7; using led = output_t<LED>; using probe = output_t<PROBE>; using aux = tim_t<AUX_TIMER_NO>; using disp0 = tm1637_t<4, 1, 1, PC6, PC8>; using disp1 = tm1637_t<4, 1, 2, PA11, PA12>; using disp2 = tm1637_t<4, 1, 3, PB11, PB12>; using serial = usart_t<SERIAL_USART, SERIAL_TX, SERIAL_RX>; template<typename DISPLAY> void write(float x) { char str[8]; sprintf(str, "%7.4f", x); DISPLAY::write_string(str); } int main() { led::setup(); probe::setup(); serial::setup<230400>(); interrupt::set<SERIAL_ISR>(); interrupt::enable(); printf<serial>("DRO Version 0.1\n"); disp0::setup<10000>(); disp1::setup<10000>(); disp2::setup<10000>(); for (uint16_t i = 0;; ++i) { write<disp0>(static_cast<float>(i) * 0.1239); write<disp1>(static_cast<float>(i) * 3.12378); write<disp2>(static_cast<float>(i) * 17.08); } }
23.083333
60
0.625993
marangisto
55554a9d591a8c787954592b1ccf0f098e863c22
695
cpp
C++
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
1
2021-12-25T16:37:53.000Z
2021-12-25T16:37:53.000Z
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
1
2022-03-07T11:46:27.000Z
2022-03-07T11:46:27.000Z
src/samarium/physics/Spring.cpp
strangeQuark1041/samarium
7e4d107e719d54b55b16d63707595a27f357fb6d
[ "MIT" ]
null
null
null
/* * SPDX-License-Identifier: MIT * Copyright (c) 2022 Jai Bellare * See <https://opensource.org/licenses/MIT/> or LICENSE.md * Project homepage: https://github.com/strangeQuark1041/samarium */ #include "Spring.hpp" namespace sm { [[nodiscard]] auto Spring::length() const noexcept -> f64 { return math::distance(p1.pos, p2.pos); } void Spring::update() noexcept { const auto vec = p2.pos - p1.pos; const auto spring = (vec.length() - rest_length) * stiffness; auto damp = Vector2::dot(vec.normalized(), p2.vel - p1.vel) * damping; const auto force = vec.with_length(spring + damp); p1.apply_force(force); p2.apply_force(-force); } } // namespace sm
26.730769
100
0.666187
strangeQuark1041
55566650381b23567922169592f96bac20617ea6
948
cpp
C++
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
Leetcode/Day019/unique_path_obstacle.cpp
SujalAhrodia/Practice_2020
59b371ada245ed8253d12327f18deee3e47f31d6
[ "MIT" ]
null
null
null
class Solution { public: int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); vector<vector<unsigned int>> dp(m, vector<unsigned int> (n,0)); if(obstacleGrid[0][0] == 1) return 0; dp[0][0]=1; //first row for(int i=1; i<n; i++) { if(obstacleGrid[0][i] == 0 && dp[0][i-1]==1) dp[0][i]=1; } //first column for(int i=1; i<m; i++) { if(obstacleGrid[i][0] == 0 && dp[i-1][0]==1) dp[i][0]=1; } for(int i=1; i<m; i++) { for(int j=1; j<n; j++) { if(obstacleGrid[i][j] == 0) dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } };
23.7
71
0.369198
SujalAhrodia
555eb04b23df36f8bbe34884d1adb71ad6759a83
2,712
cpp
C++
src/camera/CameraParams.cpp
huskyroboticsteam/PY2020
cd6368d85866204dbdca6aefacac69059e780aa2
[ "Apache-2.0" ]
11
2019-10-03T01:17:16.000Z
2020-10-25T02:38:32.000Z
src/camera/CameraParams.cpp
huskyroboticsteam/PY2020
cd6368d85866204dbdca6aefacac69059e780aa2
[ "Apache-2.0" ]
53
2019-10-03T02:11:04.000Z
2021-06-05T03:11:55.000Z
src/camera/CameraParams.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
3
2019-09-20T04:09:29.000Z
2020-08-18T22:25:20.000Z
#include "CameraParams.h" #include <opencv2/core.hpp> namespace cam { ////////////// CONSTRUCTORS ////////////// CameraParams::CameraParams() { } void CameraParams::init(const cv::Mat& camera_matrix, const cv::Mat& dist_coeff, cv::Size image_size) { if (camera_matrix.size() != cv::Size(3, 3)) { throw std::invalid_argument("Camera matrix must be 3x3"); } int n_coeffs = dist_coeff.rows * dist_coeff.cols; if (!(n_coeffs == 4 || n_coeffs == 5 || n_coeffs == 8 || n_coeffs == 12 || n_coeffs == 14)) { throw std::invalid_argument( "Number of distortion coefficients must be 4, 5, 8, 12, or 14"); } if (image_size.empty()) { throw std::invalid_argument("Image size must not be empty"); } dist_coeff.reshape(1, {n_coeffs, 1}).copyTo(this->_dist_coeff); camera_matrix.copyTo(this->_camera_matrix); this->_image_size = image_size; } CameraParams::CameraParams(const cv::Mat& camera_matrix, const cv::Mat& dist_coeff, cv::Size image_size) { init(camera_matrix, dist_coeff, image_size); } CameraParams::CameraParams(const CameraParams& other) { cv::Mat newCam, newDist; other._camera_matrix.copyTo(newCam); other._dist_coeff.copyTo(newDist); this->_camera_matrix = newCam; this->_dist_coeff = newDist; this->_image_size = other._image_size; } bool CameraParams::empty() const { return _camera_matrix.empty() || _dist_coeff.empty() || _image_size.empty(); } ////////////// ACCESSORS ///////////////// cv::Mat CameraParams::getCameraMatrix() const { return _camera_matrix; } cv::Mat CameraParams::getDistCoeff() const { return _dist_coeff; } cv::Size CameraParams::getImageSize() const { return _image_size; } ////////////// SERIALIZATION ////////////// void CameraParams::readFromFileNode(const cv::FileNode& file_node) { cv::Mat cam, dist; file_node[KEY_CAMERA_MATRIX] >> cam; file_node[KEY_DIST_COEFFS] >> dist; int w, h; w = (int)file_node[KEY_IMAGE_WIDTH]; h = (int)file_node[KEY_IMAGE_HEIGHT]; cv::Size size(w, h); // call init to do validation init(cam, dist, size); } void CameraParams::writeToFileStorage(cv::FileStorage& file_storage) const { file_storage << "{"; file_storage << KEY_IMAGE_WIDTH << _image_size.width; file_storage << KEY_IMAGE_HEIGHT << _image_size.height; file_storage << KEY_CAMERA_MATRIX << _camera_matrix; file_storage << KEY_DIST_COEFFS << _dist_coeff; file_storage << "}"; } void read(const cv::FileNode& node, CameraParams& params, const CameraParams& default_value) { if (node.empty()) { params = default_value; } else { params.readFromFileNode(node); } } void write(cv::FileStorage& fs, const std::string& name, const CameraParams& params) { params.writeToFileStorage(fs); } } // namespace cam
26.851485
94
0.696165
huskyroboticsteam
5561aca0f75c7279a4e60441e8f0e6ae404732fd
9,253
cpp
C++
src/heuristics/rcHeuristics/RCModelFactory.cpp
Songtuan-Lin/pandaPIengine
be019b16fec6f679fa3db31b97ccbe9491769d65
[ "BSD-3-Clause" ]
5
2021-04-06T22:06:47.000Z
2021-07-20T14:56:13.000Z
src/heuristics/rcHeuristics/RCModelFactory.cpp
Songtuan-Lin/pandaPIengine
be019b16fec6f679fa3db31b97ccbe9491769d65
[ "BSD-3-Clause" ]
2
2021-04-07T12:17:39.000Z
2021-09-03T10:30:26.000Z
src/heuristics/rcHeuristics/RCModelFactory.cpp
Songtuan-Lin/pandaPIengine
be019b16fec6f679fa3db31b97ccbe9491769d65
[ "BSD-3-Clause" ]
6
2021-06-16T13:41:06.000Z
2022-03-30T07:13:18.000Z
/* * RCModelFactory.cpp * * Created on: 09.02.2020 * Author: dh */ #include "RCModelFactory.h" namespace progression { RCModelFactory::RCModelFactory(Model* htn) { this->htn = htn; } RCModelFactory::~RCModelFactory() { // TODO Auto-generated destructor stub } Model* RCModelFactory::getRCmodelSTRIPS() { return this->getRCmodelSTRIPS(1); } Model* RCModelFactory::getRCmodelSTRIPS(int costsMethodActions) { Model* rc = new Model(); rc->isHtnModel = false; rc->numStateBits = htn->numStateBits + htn->numActions + htn->numTasks; rc->numVars = htn->numVars + htn->numActions + htn->numTasks; // first part might be SAS+ rc->numActions = htn->numActions + htn->numMethods; rc->numTasks = rc->numActions; rc->precLists = new int*[rc->numActions]; rc->addLists = new int*[rc->numActions]; rc->delLists = new int*[rc->numActions]; rc->numPrecs = new int[rc->numActions]; rc->numAdds = new int[rc->numActions]; rc->numDels = new int[rc->numActions]; // add new prec and add effect to actions for(int i = 0; i < htn->numActions; i++) { rc->numPrecs[i] = htn->numPrecs[i] + 1; rc->precLists[i] = new int[rc->numPrecs[i]]; for(int j = 0; j < rc->numPrecs[i] - 1; j++) { rc->precLists[i][j] = htn->precLists[i][j]; } rc->precLists[i][rc->numPrecs[i] - 1] = t2tdr(i); rc->numAdds[i] = htn->numAdds[i] + 1; rc->addLists[i] = new int[rc->numAdds[i]]; for(int j = 0; j < rc->numAdds[i] - 1; j++) { rc->addLists[i][j] = htn->addLists[i][j]; } rc->addLists[i][rc->numAdds[i] - 1] = t2bur(i); rc->numDels[i] = htn->numDels[i]; rc->delLists[i] = new int[rc->numDels[i]]; for(int j = 0; j < rc->numDels[i]; j++) { rc->delLists[i][j] = htn->delLists[i][j]; } } // create actions for methods for(int im = 0; im < htn->numMethods; im++) { int ia = htn->numActions + im; rc->numPrecs[ia] = htn->numDistinctSTs[im]; rc->precLists[ia] = new int[rc->numPrecs[ia]]; for(int ist = 0; ist < htn->numDistinctSTs[im]; ist++) { int st = htn->sortedDistinctSubtasks[im][ist]; rc->precLists[ia][ist] = t2bur(st); } rc->numAdds[ia] = 1; rc->addLists[ia] = new int[1]; rc->addLists[ia][0] = t2bur(htn->decomposedTask[im]); rc->numDels[ia] = 0; rc->delLists[ia] = nullptr; } // set names of state features rc->factStrs = new string[rc->numStateBits]; for(int i = 0; i < htn->numStateBits; i++) { rc->factStrs[i] = htn->factStrs[i]; } for(int i = 0; i < htn->numActions; i++) { rc->factStrs[t2tdr(i)] = "tdr-" + htn->taskNames[i]; } for(int i = 0; i < htn->numTasks; i++) { rc->factStrs[t2bur(i)] = "bur-" + htn->taskNames[i]; } // set action names rc->taskNames = new string[rc->numTasks]; for(int i = 0; i < htn->numActions; i++) { rc->taskNames[i] = htn->taskNames[i]; } for(int im = 0; im < htn->numMethods; im++) { int ia = htn->numActions + im; rc->taskNames[ia] = htn->methodNames[im] + "@" + htn->taskNames[htn->decomposedTask[im]]; } // set variable names rc->varNames = new string[rc->numVars]; for(int i = 0; i < htn->numVars; i++) { rc->varNames[i] = htn->varNames[i]; } for(int i = 0; i < htn->numActions; i++) { // todo: the index transformation does not use the functions // defined above and needs to be redone when changing them int inew = htn->numVars + i; rc->varNames[inew] = "tdr-" + htn->taskNames[i]; } for(int i = 0; i < htn->numTasks; i++) { // todo: transformation needs to be redone when changing them int inew = htn->numVars + htn->numActions + i; rc->varNames[inew] = "bur-" + htn->taskNames[i]; } // set indices of first and last bit rc->firstIndex = new int[rc->numVars]; rc->lastIndex = new int[rc->numVars]; for(int i = 0; i < htn->numVars; i++) { rc->firstIndex[i] = htn->firstIndex[i]; rc->lastIndex[i] = htn->lastIndex[i]; } for(int i = htn->numVars; i < rc->numVars; i++) { rc->firstIndex[i] = rc->lastIndex[i - 1] + 1; rc->lastIndex[i] = rc->firstIndex[i]; } // set action costs rc->actionCosts = new int[rc->numActions]; for(int i = 0; i < htn->numActions; i++) { rc->actionCosts[i] = htn->actionCosts[i]; } for(int i = htn->numActions; i < rc->numActions; i++) { rc->actionCosts[i] = costsMethodActions; } set<int> precless; for(int i = 0; i < rc->numActions; i++) { if (rc->numPrecs[i] == 0) { precless.insert(i); } } rc->numPrecLessActions = precless.size(); rc->precLessActions = new int[rc->numPrecLessActions]; int j = 0; for(int pl : precless) { rc->precLessActions[j++] = pl; } rc->isPrimitive = new bool[rc->numActions]; for(int i = 0; i < rc->numActions; i++) rc->isPrimitive[i] = true; createInverseMappings(rc); set<int> s; for(int i = 0; i < htn->s0Size; i++) { s.insert(htn->s0List[i]); } for(int i = 0; i < htn->numActions; i++) { s.insert(t2tdr(i)); } rc->s0Size = s.size(); rc->s0List = new int[rc->s0Size]; int i = 0; for (int f : s) { rc->s0List[i++] = f; } rc->gSize = 1 + htn->gSize; rc->gList = new int[rc->gSize]; for(int i = 0; i < htn->gSize; i++) { rc->gList[i] = htn->gList[i]; } rc->gList[rc->gSize - 1] = t2bur(htn->initialTask); #ifndef NDEBUG for(int i = 0; i < rc->numActions; i++) { set<int> prec; for(int j = 0; j < rc->numPrecs[i]; j++) { prec.insert(rc->precLists[i][j]); } assert(prec.size() == rc->numPrecs[i]); // precondition contained twice? set<int> add; for(int j = 0; j < rc->numAdds[i]; j++) { add.insert(rc->addLists[i][j]); } assert(add.size() == rc->numAdds[i]); // add contained twice? set<int> del; for(int j = 0; j < rc->numDels[i]; j++) { del.insert(rc->delLists[i][j]); } assert(del.size() == rc->numDels[i]); // del contained twice? } // are subtasks represented in preconditions? for(int i = 0; i < htn->numMethods; i++) { for(int j = 0; j < htn->numSubTasks[i]; j++) { int f = t2bur(htn->subTasks[i][j]); bool contained = false; int mAction = htn->numActions + i; for(int k = 0; k < rc->numPrecs[mAction]; k++) { if(rc->precLists[mAction][k] == f) { contained = true; break; } } assert(contained); // is subtask contained in the respective action's preconditions? } } // are preconditions represented in subtasks? for(int i = htn->numActions; i < rc->numActions; i++) { int m = i - htn->numActions; for(int j = 0; j < rc->numPrecs[i]; j++) { int f = rc->precLists[i][j]; int task = f - (htn->numStateBits + htn->numActions); bool contained = false; for(int k = 0; k < htn->numSubTasks[m]; k++) { int subtask = htn->subTasks[m][k]; if(subtask == task) { contained = true; break; } } assert(contained); } } #endif return rc; } void RCModelFactory::createInverseMappings(Model* c){ set<int>* precToActionTemp = new set<int>[c->numStateBits]; for (int i = 0; i < c->numActions; i++) { for (int j = 0; j < c->numPrecs[i]; j++) { int f = c->precLists[i][j]; precToActionTemp[f].insert(i); } } c->precToActionSize = new int[c->numStateBits]; c->precToAction = new int*[c->numStateBits]; for (int i = 0; i < c->numStateBits; i++) { c->precToActionSize[i] = precToActionTemp[i].size(); c->precToAction[i] = new int[c->precToActionSize[i]]; int cur = 0; for (int ac : precToActionTemp[i]) { c->precToAction[i][cur++] = ac; } } delete[] precToActionTemp; } /* * The original state bits are followed by one bit per action that is set iff * the action is reachable from the top. Then, there is one bit for each task * indicating that task has been reached bottom-up. */ int RCModelFactory::t2tdr(int task) { return htn->numStateBits + task; } int RCModelFactory::t2bur(int task) { return htn->numStateBits + htn->numActions + task; } pair<int, int> RCModelFactory::rcStateFeature2HtnIndex(string s) { //cout << "searching index for \"" << s << "\"" << endl; s = s.substr(0, s.length() - 2); // ends with "()" due to grounded representation int type = -1; int index = -1; if((s.rfind("bur-", 0) == 0)) { type = fTask; s = s.substr(4, s.length() - 4); for(int i = 0; i < htn->numTasks; i++) { if(s.compare(su.toLowerString(su.cleanStr(htn->taskNames[i]))) == 0) { index = i; #ifndef NDEBUG // the name has been cleaned, check whether it is unique for(int j = i + 1; j < htn->numTasks; j++) { assert(s.compare(su.toLowerString(su.cleanStr(htn->taskNames[j]))) != 0); } #endif break; } } } else { type = fFact; for(int i = 0; i < htn->numStateBits; i++) { if(s.compare(su.toLowerString(su.cleanStr(htn->factStrs[i]))) == 0) { index = i; #ifndef NDEBUG // the name has been cleaned, check whether it is unique for(int j = i + 1; j < htn->numStateBits; j++) { assert(s.compare(su.toLowerString(su.cleanStr(htn->factStrs[j]))) != 0); } #endif break; } } } //cout << "Type " << type << endl; //cout << "Index " << index << endl; return make_pair(type, index); } } /* namespace progression */
28.915625
93
0.584675
Songtuan-Lin
5563e17227c0e9ac9e3f36e11978115c10de87cf
3,764
cpp
C++
src/vismethods/boxplot.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
null
null
null
src/vismethods/boxplot.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
3
2021-11-02T22:24:04.000Z
2021-11-29T18:01:51.000Z
src/vismethods/boxplot.cpp
jakobtroidl/Barrio
55c447325f2e83a21b39c54cdca37b2779d0569c
[ "MIT" ]
null
null
null
#include "boxplot.h" Boxplot::Boxplot(Boxplot* boxplot) { m_datacontainer = boxplot->m_datacontainer; m_global_vis_parameters = boxplot->m_global_vis_parameters; } Boxplot::Boxplot(GlobalVisParameters* visparams, DataContainer* datacontainer) { m_global_vis_parameters = visparams; m_datacontainer = datacontainer; } Boxplot::~Boxplot() { } QString Boxplot::createJSONString(QList<int>* selectedObjects) { QJsonArray document; for (auto i : *selectedObjects) { Object* mito = m_datacontainer->getObject(i); std::vector<int>* mito_indices = mito->get_indices_list(); std::vector<VertexData>* vertices = m_datacontainer->getMesh()->getVerticesList(); QJsonObject mito_json; QJsonArray mito_distances; for (auto j : *mito_indices) { VertexData vertex = vertices->at(j); double distance_to_cell = vertex.distance_to_cell; if (distance_to_cell < 1000.0) { mito_distances.push_back(QJsonValue::fromVariant(distance_to_cell)); } } mito_json.insert("key", mito->getName().c_str()); mito_json.insert("value", mito_distances); document.push_back(mito_json); } QJsonDocument doc(document); return doc.toJson(QJsonDocument::Indented); } QWebEngineView* Boxplot::initVisWidget(int ID, SpecificVisParameters params) { m_settings = params.settings; bool normalized = m_settings.value("normalized").toBool(); QString json = createJSONString(&m_global_vis_parameters->selected_objects); m_data = new BoxplotData(json, m_datacontainer, m_global_vis_parameters, normalized); setSpecificVisParameters(params); m_web_engine_view = new QWebEngineView(); QWebChannel* channel = new QWebChannel(m_web_engine_view->page()); m_web_engine_view->page()->setWebChannel(channel); channel->registerObject(QStringLiteral("boxplot_data"), m_data); m_web_engine_view->load(getHTMLPath(m_index_filename)); return m_web_engine_view; } QWebEngineView* Boxplot::getWebEngineView() { return m_web_engine_view; } bool Boxplot::update() { QString json = createJSONString(&m_global_vis_parameters->selected_objects); m_data->setJSONString(json); return true; } Boxplot* Boxplot::clone() { return new Boxplot(this); } bool Boxplot::update_needed() { return true; } VisType Boxplot::getType() { return VisType::BOXPLOT; } void Boxplot::setSpecificVisParameters(SpecificVisParameters params) { m_data->setColors(params.colors); } BoxplotData::BoxplotData(QString json_data, DataContainer* data_container, GlobalVisParameters* global_vis_parameters, bool normalized) { m_json_string = json_data; m_datacontainer = data_container; m_global_vis_parameters = global_vis_parameters; m_normalized = normalized; } BoxplotData::~BoxplotData() { } Q_INVOKABLE QString BoxplotData::getData() { return Q_INVOKABLE m_json_string; } Q_INVOKABLE QString BoxplotData::getColormap() { return Q_INVOKABLE m_colors; } Q_INVOKABLE bool BoxplotData::getNormalized() { return Q_INVOKABLE m_normalized; } Q_INVOKABLE void BoxplotData::setHighlightedFrame(const QString& name) { int hvgx = m_datacontainer->getIndexByName(name); if (!m_global_vis_parameters->highlighted_group_boxes.contains(hvgx)) { m_global_vis_parameters->highlighted_group_boxes.append(hvgx); } m_global_vis_parameters->needs_update = true; return Q_INVOKABLE void(); } Q_INVOKABLE void BoxplotData::removeHighlightedFrame(const QString& name_to_remove) { int hvgx_id = m_datacontainer->getIndexByName(name_to_remove); QVector<int>* highlighted = &m_global_vis_parameters->highlighted_group_boxes; if (highlighted->contains(hvgx_id)) { QMutableVectorIterator<int> it(*highlighted); while (it.hasNext()) { if (it.next() == hvgx_id) { it.remove(); } } } m_global_vis_parameters->needs_update = true; return Q_INVOKABLE void(); }
24.283871
135
0.772848
jakobtroidl
5568cae4112ad35a5722916126cef4f92baa52be
5,227
hpp
C++
libmikroxml/mikroxml/mikroxml.hpp
rantingmong/svgrenderer
082879b448a2c241f69e383620b59e307298bb77
[ "MIT" ]
1
2021-03-29T19:30:47.000Z
2021-03-29T19:30:47.000Z
libmikroxml/mikroxml/mikroxml.hpp
rantingmong/svgrenderer
082879b448a2c241f69e383620b59e307298bb77
[ "MIT" ]
null
null
null
libmikroxml/mikroxml/mikroxml.hpp
rantingmong/svgrenderer
082879b448a2c241f69e383620b59e307298bb77
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <utki/Buf.hpp> #include <utki/Exc.hpp> namespace mikroxml{ class Parser{ enum class State_e{ IDLE, TAG, TAG_SEEK_GT, TAG_EMPTY, DECLARATION, DECLARATION_END, COMMENT, COMMENT_END, ATTRIBUTES, ATTRIBUTE_NAME, ATTRIBUTE_SEEK_TO_EQUALS, ATTRIBUTE_SEEK_TO_VALUE, ATTRIBUTE_VALUE, CONTENT, REF_CHAR, DOCTYPE, DOCTYPE_BODY, DOCTYPE_TAG, DOCTYPE_ENTITY_NAME, DOCTYPE_ENTITY_SEEK_TO_VALUE, DOCTYPE_ENTITY_VALUE, DOCTYPE_SKIP_TAG, SKIP_UNKNOWN_EXCLAMATION_MARK_CONSTRUCT } state = State_e::IDLE; void parseIdle(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseTagEmpty(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseTagSeekGt(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDeclaration(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDeclarationEnd(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseComment(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseCommentEnd(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributes(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributeName(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributeSeekToEquals(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributeSeekToValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseAttributeValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseContent(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseRefChar(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctype(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeBody(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeSkipTag(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeEntityName(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeEntitySeekToValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseDoctypeEntityValue(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void parseSkipUnknownExclamationMarkConstruct(utki::Buf<char>::const_iterator& i, utki::Buf<char>::const_iterator& e); void handleAttributeParsed(); void processParsedTagName(); void processParsedRefChar(); std::vector<char> buf; std::vector<char> name; //general variable for storing name of something (attribute name, entity name, etc.) std::vector<char> refCharBuf; char attrValueQuoteChar; State_e stateAfterRefChar; unsigned lineNumber = 1; std::map<std::string, std::vector<char>> doctypeEntities; public: Parser(); class Exc : public utki::Exc{ public: Exc(const std::string& message) : utki::Exc(message){} }; class MalformedDocumentExc : public Exc{ public: MalformedDocumentExc(unsigned lineNumber, const std::string& message); }; virtual void onElementStart(const utki::Buf<char> name) = 0; /** * @brief Element end. * @param name - name of the element which has ended. Name is empty if empty element has ended. */ virtual void onElementEnd(const utki::Buf<char> name) = 0; /** * @brief Attributes section end notification. * This callback is called when all attributes of the last element have been parsed. * @param isEmptyElement - indicates weather the element is empty element or not. */ virtual void onAttributesEnd(bool isEmptyElement) = 0; /** * @brief Attribute parsed notification. * This callback may be called after 'onElementStart' notification. It can be called several times, once for each parsed attribute. * @param name - name of the parsed attribute. * @param value - value of the parsed attribute. */ virtual void onAttributeParsed(const utki::Buf<char> name, const utki::Buf<char> value) = 0; /** * @brief Content parsed notification. * This callback may be called after 'onAttributesEnd' notification. * @param str - parsed content. */ virtual void onContentParsed(const utki::Buf<char> str) = 0; /** * @brief feed UTF-8 data to parser. * @param data - data to be fed to parser. */ void feed(const utki::Buf<char> data); /** * @brief feed UTF-8 data to parser. * @param data - data to be fed to parser. */ void feed(const utki::Buf<std::uint8_t> data){ this->feed(utki::wrapBuf(reinterpret_cast<const char*>(&*data.begin()), data.size())); } /** * @brief Parse in string. * @param str - string to parse. */ void feed(const std::string& str); /** * @brief Finalize parsing after all data has been fed. */ void end(); virtual ~Parser()noexcept{} }; }
35.080537
132
0.726229
rantingmong
556b6070e185d3ad180455bf7f53800ef7ee2f7e
165
cpp
C++
319-bulb-switcher/319-bulb-switcher.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
319-bulb-switcher/319-bulb-switcher.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
319-bulb-switcher/319-bulb-switcher.cpp
shreydevep/DSA
688af414c1fada1b82a4b4e9506747352007c894
[ "MIT" ]
null
null
null
class Solution { public: int bulbSwitch(int n) { int cnt = 0; for(int i=1;i*i<=n;++i){ cnt++; } return cnt; } };
15
31
0.406061
shreydevep
5571b7ca836a9d01adde6967d32f705483a08ef8
5,851
cpp
C++
tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp
kitsudaiki/libKitsunemimiCommon
65c60deddf9fb813035fc2f3251c5ae5c8f7423f
[ "MIT" ]
null
null
null
tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp
kitsudaiki/libKitsunemimiCommon
65c60deddf9fb813035fc2f3251c5ae5c8f7423f
[ "MIT" ]
49
2020-08-24T18:09:35.000Z
2022-02-13T22:19:39.000Z
tests/unit_tests/libKitsunemimiCommon/statemachine_test.cpp
tobiasanker/libKitsunemimiCommon
d40d1314db0a6d7e04afded09cb4934e01828ac4
[ "MIT" ]
1
2020-08-29T14:30:41.000Z
2020-08-29T14:30:41.000Z
/** * @file statemachine_test.cpp * * @author Tobias Anker <[email protected]> * * @copyright MIT License */ #include "statemachine_test.h" #include <libKitsunemimiCommon/statemachine.h> namespace Kitsunemimi { Statemachine_Test::Statemachine_Test() : Kitsunemimi::CompareTestHelper("Statemachine_Test") { createNewState_test(); addTransition_test(); goToNextState_test(); setInitialChildState_test(); addChildState_test(); getCurrentStateId_test(); isInState_test(); } /** * createNewState_test */ void Statemachine_Test::createNewState_test() { Statemachine statemachine; TEST_EQUAL(statemachine.createNewState(SOURCE_STATE), true); TEST_EQUAL(statemachine.createNewState(SOURCE_STATE), false); } /** * setCurrentState_test */ void Statemachine_Test::setCurrentState_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); TEST_EQUAL(statemachine.setCurrentState(SOURCE_STATE), true); TEST_EQUAL(statemachine.setCurrentState(FAIL), false); } /** * addTransition_test */ void Statemachine_Test::addTransition_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE), true); TEST_EQUAL(statemachine.addTransition(FAIL, GO, NEXT_STATE), false); TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, FAIL), false); TEST_EQUAL(statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE), false); } /** * goToNextState_test */ void Statemachine_Test::goToNextState_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE); TEST_EQUAL(statemachine.goToNextState(FAIL), false); TEST_EQUAL(statemachine.goToNextState(GO), true); TEST_EQUAL(statemachine.goToNextState(GO), false); } /** * setInitialChildState_test */ void Statemachine_Test::setInitialChildState_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); TEST_EQUAL(statemachine.setInitialChildState(SOURCE_STATE, NEXT_STATE), true); TEST_EQUAL(statemachine.setInitialChildState(FAIL, NEXT_STATE), false); TEST_EQUAL(statemachine.setInitialChildState(SOURCE_STATE, FAIL), false); } /** * addChildState_test */ void Statemachine_Test::addChildState_test() { Statemachine statemachine; statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); TEST_EQUAL(statemachine.addChildState(SOURCE_STATE, NEXT_STATE), true); TEST_EQUAL(statemachine.addChildState(FAIL, NEXT_STATE), false); TEST_EQUAL(statemachine.addChildState(SOURCE_STATE, FAIL), false); } /** * getCurrentStateId_test */ void Statemachine_Test::getCurrentStateId_test() { Statemachine statemachine; TEST_EQUAL(statemachine.getCurrentStateId(), 0); // init state statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); statemachine.createNewState(CHILD_STATE); statemachine.createNewState(TARGET_STATE); // build state-machine statemachine.addChildState(NEXT_STATE, CHILD_STATE); statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE); statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE); statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE); TEST_EQUAL(statemachine.getCurrentStateId(), SOURCE_STATE); statemachine.goToNextState(GO); TEST_EQUAL(statemachine.getCurrentStateId(), CHILD_STATE); statemachine.goToNextState(GOGO); TEST_EQUAL(statemachine.getCurrentStateId(), TARGET_STATE); } /** * @brief getCurrentStateName_test */ void Statemachine_Test::getCurrentStateName_test() { Statemachine statemachine; TEST_EQUAL(statemachine.getCurrentStateId(), 0); // init state statemachine.createNewState(SOURCE_STATE, "SOURCE_STATE"); statemachine.createNewState(NEXT_STATE, "NEXT_STATE"); statemachine.createNewState(CHILD_STATE, "CHILD_STATE"); statemachine.createNewState(TARGET_STATE, "TARGET_STATE"); // build state-machine statemachine.addChildState(NEXT_STATE, CHILD_STATE); statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE); statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE); statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE); TEST_EQUAL(statemachine.getCurrentStateId(), SOURCE_STATE); statemachine.goToNextState(GO); TEST_EQUAL(statemachine.getCurrentStateName(), "CHILD_STATE"); statemachine.goToNextState(GOGO); TEST_EQUAL(statemachine.getCurrentStateName(), "TARGET_STATE"); } /** * isInState_test */ void Statemachine_Test::isInState_test() { Statemachine statemachine; TEST_EQUAL(statemachine.getCurrentStateId(), 0); // init state statemachine.createNewState(SOURCE_STATE); statemachine.createNewState(NEXT_STATE); statemachine.createNewState(CHILD_STATE); statemachine.createNewState(TARGET_STATE); // build state-machine statemachine.addChildState(NEXT_STATE, CHILD_STATE); statemachine.setInitialChildState(NEXT_STATE, CHILD_STATE); statemachine.addTransition(SOURCE_STATE, GO, NEXT_STATE); statemachine.addTransition(NEXT_STATE, GOGO, TARGET_STATE); TEST_EQUAL(statemachine.isInState(SOURCE_STATE), true); TEST_EQUAL(statemachine.isInState(FAIL), false); statemachine.goToNextState(GO); TEST_EQUAL(statemachine.isInState(CHILD_STATE), true); TEST_EQUAL(statemachine.isInState(NEXT_STATE), true); TEST_EQUAL(statemachine.isInState(SOURCE_STATE), false); } } // namespace Kitsunemimi
26.595455
82
0.766194
kitsudaiki
5574c5de3bab02af2bbfed26f5cfe2ba8ae4a69e
5,927
cpp
C++
globe/globe_shader.cpp
MarkY-LunarG/LunarGlobe
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
2
2018-06-20T15:19:38.000Z
2018-07-13T15:13:30.000Z
globe/globe_shader.cpp
MarkY-LunarG/LunarGlobe
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
25
2018-07-27T23:02:01.000Z
2019-03-15T17:00:05.000Z
globe/globe_shader.cpp
MarkY-LunarG/LunarGravity
d32a6145eebc68ad4d7e28bdd4fab88cbdd33545
[ "Apache-2.0" ]
null
null
null
// // Project: LunarGlobe // SPDX-License-Identifier: Apache-2.0 // // File: globe/globe_shader.cpp // Copyright(C): 2018-2019; LunarG, Inc. // Author(s): Mark Young <[email protected]> // #include <cstring> #include <fstream> #include <string> #include <sstream> #include "globe_logger.hpp" #include "globe_event.hpp" #include "globe_submit_manager.hpp" #include "globe_shader.hpp" #include "globe_texture.hpp" #include "globe_resource_manager.hpp" #include "globe_app.hpp" #if defined(VK_USE_PLATFORM_WIN32_KHR) const char directory_symbol = '\\'; #else const char directory_symbol = '/'; #endif static const char main_shader_func_name[] = "main"; GlobeShader* GlobeShader::LoadFromFile(VkDevice vk_device, const std::string& shader_name, const std::string& directory) { GlobeShaderStageInitData shader_data[GLOBE_SHADER_STAGE_ID_NUM_STAGES] = {{}, {}, {}, {}, {}, {}}; for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) { std::string full_shader_name = directory; full_shader_name += directory_symbol; full_shader_name += shader_name; switch (stage) { case GLOBE_SHADER_STAGE_ID_VERTEX: full_shader_name += "-vs.spv"; break; case GLOBE_SHADER_STAGE_ID_TESSELLATION_CONTROL: full_shader_name += "-cs.spv"; break; case GLOBE_SHADER_STAGE_ID_TESSELLATION_EVALUATION: full_shader_name += "-es.spv"; break; case GLOBE_SHADER_STAGE_ID_GEOMETRY: full_shader_name += "-gs.spv"; break; case GLOBE_SHADER_STAGE_ID_FRAGMENT: full_shader_name += "-fs.spv"; break; case GLOBE_SHADER_STAGE_ID_COMPUTE: full_shader_name += "-cp.spv"; break; default: continue; } std::ifstream* infile = nullptr; std::string line; std::stringstream strstream; size_t shader_spv_size; infile = new std::ifstream(full_shader_name.c_str(), std::ifstream::in | std::ios::binary); if (nullptr == infile || infile->fail()) { continue; } strstream << infile->rdbuf(); infile->close(); delete infile; // Read the file contents shader_spv_size = strstream.str().size(); shader_data[stage].spirv_content.resize((shader_spv_size / sizeof(uint32_t))); memcpy(shader_data[stage].spirv_content.data(), strstream.str().c_str(), shader_spv_size); shader_data[stage].valid = true; } return new GlobeShader(vk_device, shader_name, shader_data); } GlobeShader::GlobeShader(VkDevice vk_device, const std::string& shader_name, const GlobeShaderStageInitData shader_data[GLOBE_SHADER_STAGE_ID_NUM_STAGES]) : _initialized(true), _vk_device(vk_device), _shader_name(shader_name) { GlobeLogger& logger = GlobeLogger::getInstance(); uint32_t num_loaded_shaders = 0; for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) { if (shader_data[stage].valid) { _shader_data[stage].vk_shader_flag = static_cast<VkShaderStageFlagBits>(1 << stage); VkShaderModuleCreateInfo shader_module_create_info; shader_module_create_info.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO; shader_module_create_info.pNext = nullptr; shader_module_create_info.codeSize = shader_data[stage].spirv_content.size() * sizeof(uint32_t); shader_module_create_info.pCode = shader_data[stage].spirv_content.data(); shader_module_create_info.flags = 0; VkResult vk_result = vkCreateShaderModule(vk_device, &shader_module_create_info, NULL, &_shader_data[stage].vk_shader_module); if (VK_SUCCESS != vk_result) { _initialized = false; _shader_data[stage].valid = false; std::string error_msg = "GlobeTexture::Read failed to read shader "; error_msg += shader_name; error_msg += " with error "; error_msg += vk_result; logger.LogError(error_msg); } else { num_loaded_shaders++; _shader_data[stage].valid = true; } } else { _shader_data[stage].valid = false; } } if (num_loaded_shaders == 0 && _initialized) { _initialized = false; } } GlobeShader::~GlobeShader() { if (_initialized) { for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) { if (_shader_data[stage].valid) { vkDestroyShaderModule(_vk_device, _shader_data[stage].vk_shader_module, nullptr); _shader_data[stage].valid = false; _shader_data[stage].vk_shader_module = VK_NULL_HANDLE; } } _initialized = false; } } bool GlobeShader::GetPipelineShaderStages(std::vector<VkPipelineShaderStageCreateInfo>& pipeline_stages) const { if (!_initialized) { return false; } VkPipelineShaderStageCreateInfo cur_stage_create_info = {}; cur_stage_create_info.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO; cur_stage_create_info.pName = main_shader_func_name; for (uint32_t stage = 0; stage < GLOBE_SHADER_STAGE_ID_NUM_STAGES; ++stage) { if (_shader_data[stage].valid) { cur_stage_create_info.stage = _shader_data[stage].vk_shader_flag; cur_stage_create_info.module = _shader_data[stage].vk_shader_module; pipeline_stages.push_back(cur_stage_create_info); } } return true; }
40.047297
112
0.62578
MarkY-LunarG
55769a005a140f772cd2ea9a01a12416aa6e3b4f
15,261
cpp
C++
software/imageread/xi_input_image.cpp
yhyoung/CHaiDNN
1877a81e0d1b44773af455b0eab4399636bbc181
[ "Apache-2.0" ]
288
2018-03-23T01:41:40.000Z
2022-03-03T08:52:54.000Z
software/imageread/xi_input_image.cpp
yhyoung/CHaiDNN
1877a81e0d1b44773af455b0eab4399636bbc181
[ "Apache-2.0" ]
171
2018-03-25T11:03:23.000Z
2022-01-29T14:16:59.000Z
software/imageread/xi_input_image.cpp
yhyoung/CHaiDNN
1877a81e0d1b44773af455b0eab4399636bbc181
[ "Apache-2.0" ]
154
2018-03-23T01:31:33.000Z
2022-03-04T14:26:40.000Z
/*---------------------------------------------------- Copyright 2017 Xilinx, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ----------------------------------------------------*/ #include "xi_input_image.hpp" void loadMeanTXT(float *ptrRetArray, const char* path, int nElems) { FILE* fp = fopen(path, "r"); if(fp == NULL) { printf("\n** Cannot open mean file (or) No mean file : %s **\n", path); //return NULL; } for(int i = 0; i < nElems; i++) { fscanf(fp, "%f ", ptrRetArray+i); } fclose(fp); } //int loadAndPrepareImage(cv::Mat &frame, short *inptr, float* mean_data, int img_w, int img_h, int img_channel, int resize_h, int resize_w, const char *mean_path, int mean_status) int loadAndPrepareImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; short *mean_ptr = (short *)xChangeHostInpLayer->mean; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //?? int mean_sub_flag = params_ptr[26]; int scale = 1; int h_off = 0; int w_off = 0; int mean_idx = 0; int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits; cv::Mat cv_img[1], cv_cropped_img[1]; if((resize_h != frame.rows) || (resize_w != frame.cols)) { cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w)); if(resize_h > height) { h_off = (resize_h - height) / 2; w_off = (resize_w - width) / 2; cv::Rect roi(w_off, h_off, height, width); cv_cropped_img[0] = cv_img[0](roi); } else cv_cropped_img[0] = cv_img[0]; } else { frame.copyTo(cv_cropped_img[0]); } #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif //float pixel; uchar pixel; int input_index=0; float float_val; short fxval; for (int h = 0; h < height; ++h) { const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h);//data; int img_index = 0; for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int ch = 0; ch < 4; ++ch) { if(ch < img_channel) { //pixel = static_cast<float>(ptr[img_index++]); pixel = ptr[img_index++]; short pixel1 = (short)pixel << fbits_input; if(mean_sub_flag == 1) mean_idx = ch; else mean_idx = (ch * resize_h + h + h_off) * resize_w + w + w_off; //float_val = (pixel - mean_ptr[mean_idx]) * scale; //short ival = (short)float_val; //fxval = ConvertToFP(float_val, ival, fbits_input); fxval = pixel1 - mean_ptr[mean_idx]; } else { float_val = 0; fxval = 0; in_ptr[input_index] = 0; } in_ptr[input_index] = fxval; #if FILE_WRITE float_val = ((float)fxval)/(1 << fbits_input); fprintf(fp,"%f ", float_val); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } // loadAndPrepareImage #if 0 int loadMeanSubtractedImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; float *mean_ptr = (float *)xChangeHostInpLayer->mean; float *variance_ptr = (float *)xChangeHostInpLayer->variance; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //?? int mean_sub_flag = params_ptr[26]; int scale = 1; int h_off = 0; int w_off = 0; int mean_idx = 0; int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits; cv::Mat cv_img[1], cv_cropped_img[1]; if((resize_h != frame.rows) || (resize_w != frame.cols)) { cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w)); if(resize_h > height) { h_off = (resize_h - height) / 2; w_off = (resize_w - width) / 2; cv::Rect roi(w_off, h_off, height, width); cv_cropped_img[0] = cv_img[0](roi); } else cv_cropped_img[0] = cv_img[0]; } else { frame.copyTo(cv_cropped_img[0]); } #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif //float pixel; uchar pixel; int input_index=0; float float_val; short fxval; for (int h = 0; h < height; ++h) { const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h);//data; int img_index = 0; for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int ch = 0; ch < 4; ++ch) { if(ch < img_channel) { //pixel = static_cast<float>(ptr[img_index++]); pixel = ptr[img_index++]; float in_val = pixel/255.0; float mean_val = mean_ptr[mean_idx]; int var_idx = (ch * resize_h + h + h_off) * resize_w + w + w_off; float var_val = variance_ptr[var_idx]; in_val = (in_val - mean_val)/var_val; short ival = (short)float_val; fxval = ConvertToFP(float_val, ival, fbits_input); } else { float_val = 0; fxval = 0; in_ptr[input_index] = 0; } in_ptr[input_index] = fxval; #if FILE_WRITE float_val = ((float)fxval)/(1 << fbits_input); fprintf(fp,"%f ", float_val); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } // loadAndPrepareImage #endif //int loadImage(cv::Mat &frame, char *inptr, float* mean_data, int img_w, int img_h, int img_channel, int resize_h, int resize_w, const char *mean_path, int mean_status) int loadImage(cv::Mat &frame, xChangeLayer *xChangeHostInpLayer) { char *in_ptr = (char *)xChangeHostInpLayer->in_ptrs[2]; float *mean_ptr = (float *)xChangeHostInpLayer->mean; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; int resize_h = xChangeHostInpLayer->resize_h;//params_ptr[0]; //?? how to handle int resize_w = xChangeHostInpLayer->resize_w;//params_ptr[1]; //?? int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits;//7;//convLayer_precision[0].in_fbits; int h_off = 0; int w_off = 0; cv::Mat cv_img[1], cv_cropped_img[1]; if((resize_h != frame.rows) || (resize_w != frame.cols)) { cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w)); if(resize_h > height) { h_off = (resize_h - height) / 2; w_off = (resize_w - width) / 2; cv::Rect roi(w_off, h_off, height, width); cv_cropped_img[0] = cv_img[0](roi); } else cv_cropped_img[0] = cv_img[0]; } else { frame.copyTo(cv_cropped_img[0]); } #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif char pixel; int input_index=0; for (int h = 0; h < height; ++h) { const uchar* ptr = cv_cropped_img[0].ptr<uchar>(h); int img_index = 0; for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { if(c < img_channel) { pixel = static_cast<char>(ptr[img_index++]); } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadImage int loadImagetoBuffptr1(const char *img_path, unsigned char *buff_ptr, int height, int width, int img_channel, int resize_h, int resize_w) { cv::Mat frame; frame = imread(img_path, 1); if(!frame.data) { std :: cout << "[ERROR] Image read failed - " << img_path << std :: endl; //fprintf(stderr,"image read failed\n"); //return -1; } int h_off = 0; int w_off = 0; cv::Mat cv_img[1], cv_cropped_img[1]; if((resize_h != frame.rows) || (resize_w != frame.cols)) { cv::resize(frame, cv_img[0], cv::Size(resize_h, resize_w)); if(resize_h > height) { h_off = (resize_h - height) / 2; w_off = (resize_w - width) / 2; cv::Rect roi(w_off, h_off, height, width); cv_cropped_img[0] = cv_img[0](roi); } else cv_cropped_img[0] = cv_img[0]; } else { frame.copyTo(cv_cropped_img[0]); } const uchar* ptr = cv_cropped_img[0].ptr<uchar>(0); for (int ind = 0; ind < height*width*img_channel; ind++) { buff_ptr[ind] = ptr[ind]; } } //loadImage int loadImagefromBuffptr(unsigned char *buff_ptr, xChangeLayer *xChangeHostInpLayer) { char *in_ptr = (char *)xChangeHostInpLayer->in_ptrs[2]; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif char pixel; int input_index=0; int img_index = 0; for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { if(c < img_channel) { pixel = buff_ptr[img_index++]; } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadImagefromBuffptr int loadDatafromBuffptr(short *buff_ptr, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; params_ptr[26] = 0; //mean_sub_flag #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif short pixel; int input_index=0; int img_index = 0; for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { if(c < img_channel) { pixel = buff_ptr[img_index++]; } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadDatafromBuffptr int loadData(const char *img_data_path, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; params_ptr[26] = 0; //making mean_sub_flag = 0; FILE* fp_img = fopen(img_data_path, "r"); if(fp_img == NULL) { fprintf(stderr, "\n** Cannot open mean file (or) No mean file : %s **\n", img_data_path); //return NULL; } int size_of_input = height*width*img_channel; short *in_buf = (short *)malloc(size_of_input*sizeof(short)); int fbits_input = xChangeHostInpLayer->qf_format.ip_fbits; float float_val; short fxval; for(int i = 0; i < height*width*img_channel; i++) { fscanf(fp_img, "%f ", &float_val); short ival = (short)float_val; fxval = ConvertToFP(float_val, ival, fbits_input); in_buf[i] = fxval; } fclose(fp_img); #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif short pixel; int input_index=0; int img_index1 = 0; int img_index = 0; for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { img_index1 = h*width + w; //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { img_index = img_index1 + c*(height*width); if(c < img_channel) { pixel = in_buf[img_index]; } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadData int loadDatatoBuffptr1(const char *img_data_path, float *inp_buff, int height, int width, int img_channel) { FILE* fp_img = fopen(img_data_path, "r"); if(fp_img == NULL) { fprintf(stderr, "\n** Cannot open mean file (or) No mean file : %s **\n", img_data_path); //return NULL; } float float_val; for(int i = 0; i < height*width*img_channel; i++) { fscanf(fp_img, "%f ", &float_val); inp_buff[i] = float_val; } fclose(fp_img); } //loadDatatoBuffptr int loadDatafromBuffptr1(short *inp_buff, xChangeLayer *xChangeHostInpLayer) { short *in_ptr = (short *)xChangeHostInpLayer->in_ptrs[2]; int *params_ptr = (int *)xChangeHostInpLayer->params; int height = params_ptr[0]; int width = params_ptr[1]; int img_channel = params_ptr[5]; params_ptr[26] = 0; //making mean_sub_flag = 0; int size_of_input = height*width*img_channel; #if FILE_WRITE FILE *fp = fopen("input.txt", "w"); #endif short pixel; int input_index=0; int img_index1 = 0; int img_index = 0; for (int h = 0; h < height; ++h) { for (int w = 0; w < width; ++w) { img_index1 = h*width + w; //TODO : Generic for 4 for (int c = 0; c < 4; ++c) { img_index = img_index1 + c*(height*width); if(c < img_channel) { pixel = inp_buff[img_index]; } else { pixel = 0; } in_ptr[input_index] = pixel; #if FILE_WRITE fprintf(fp,"%d ", pixel); #endif input_index++; }// Channels }// Image width #if FILE_WRITE fprintf(fp,"\n"); #endif }// Image Height #if FILE_WRITE fclose(fp); #endif } //loadDatafromBuffptr void inputImageRead(const char *img_path, xChangeLayer *xChangeHostInpLayer) //void inputImageRead(FILE **file_list, xChangeLayer *xChangeHostInpLayer) { #if EN_IO_PRINT cout<< "inputImageRead : " <<endl; #endif //char img_path[500]; //fscanf(*file_list, "%s", img_path); int num_mean_values; //read from params int status; //xChangeLayer *xChangeHostInpLayer = &lay_obj[imgId][layerId];// = &xChangeHostLayers[0]; //xChangeHostInpLayer.in_ptrs[0] = (char*)create_sdsalloc_mem(mem_size); //xChangeHostInpLayer.params = (char*)create_sdsalloc_mem(params_mem_size); int *scalar_conv_args = (int *)xChangeHostInpLayer->params; int mean_sub_flag = scalar_conv_args[26]; cv::Mat in_frame, out_frame; out_frame = imread(img_path, 1); if(!out_frame.data) { std :: cout << "[ERROR] Image read failed - " << img_path << std :: endl; //fprintf(stderr,"image read failed\n"); //return -1; } if(mean_sub_flag) { status = loadImage(out_frame, xChangeHostInpLayer); } else { status = loadAndPrepareImage(out_frame, xChangeHostInpLayer); } #if EN_IO_PRINT cout<< "inputImageRead done: " <<endl; #endif }
22.085384
180
0.636393
yhyoung
5578bfbd80af35e8b15a9510717a5a0cce4ba4cf
101
cc
C++
example/memcache/Item.cc
Conzxy/kanon
3440b0966153a0b8469e90b2a52df317aa4fe723
[ "MIT" ]
null
null
null
example/memcache/Item.cc
Conzxy/kanon
3440b0966153a0b8469e90b2a52df317aa4fe723
[ "MIT" ]
null
null
null
example/memcache/Item.cc
Conzxy/kanon
3440b0966153a0b8469e90b2a52df317aa4fe723
[ "MIT" ]
null
null
null
#include "Item.h" namespace memcache { std::atomic<u64> Item::s_cas_(0); } // namespace memcache
12.625
34
0.683168
Conzxy
5579482f0ec6190139c6f85f8691a06d2de5ff42
863
hpp
C++
plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/include/sge/opengl/xrandr/set_resolution.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // 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 SGE_OPENGL_XRANDR_SET_RESOLUTION_HPP_INCLUDED #define SGE_OPENGL_XRANDR_SET_RESOLUTION_HPP_INCLUDED #include <sge/opengl/xrandr/configuration_fwd.hpp> #include <sge/opengl/xrandr/mode_index.hpp> #include <sge/opengl/xrandr/optional_refresh_rate_fwd.hpp> #include <sge/opengl/xrandr/rotation.hpp> #include <awl/backends/x11/window/base_fwd.hpp> namespace sge::opengl::xrandr { void set_resolution( awl::backends::x11::window::base const &, sge::opengl::xrandr::configuration const &, sge::opengl::xrandr::mode_index, sge::opengl::xrandr::rotation, sge::opengl::xrandr::optional_refresh_rate const &); } #endif
30.821429
61
0.74971
cpreh
557a792be377471c08aeae8d211267379bea0f15
3,257
hpp
C++
tuo_units/TUO_Reg_Units_OPF_F.hpp
bc036/A3-TUO-Units
157f4f45317a19cf90d3f28b017b43de737f5bb3
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
tuo_units/TUO_Reg_Units_OPF_F.hpp
bc036/A3-TUO-Units
157f4f45317a19cf90d3f28b017b43de737f5bb3
[ "Naumen", "Condor-1.1", "MS-PL" ]
44
2019-09-24T17:11:29.000Z
2021-08-14T18:37:15.000Z
tuo_units/TUO_Reg_Units_OPF_F.hpp
bc036/A3-TUO-Units
157f4f45317a19cf90d3f28b017b43de737f5bb3
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
class O_T_TUO_Reg_Base_F:B_T_TUO_Reg_base_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Reg_base_F:B_A_TUO_Reg_base_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Reg_Base_F:B_W_TUO_Reg_base_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Rifleman_F:B_T_TUO_Rifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Rifleman_F:B_A_TUO_Rifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Rifleman_F:B_W_TUO_Rifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Rifleman_AT_F:B_T_TUO_Rifleman_AT_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Rifleman_AT_F:B_A_TUO_Rifleman_AT_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Rifleman_AT_F:B_W_TUO_Rifleman_AT_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Mark_F:B_T_TUO_Mark_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Mark_F:B_A_TUO_Mark_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Mark_F:B_W_TUO_Mark_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Engineer_F:B_T_TUO_Engineer_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Engineer_F:B_A_TUO_Engineer_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Engineer_F:B_W_TUO_Engineer_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Medic_F:B_T_TUO_Medic_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Medic_F:B_A_TUO_Medic_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Medic_F:B_W_TUO_Medic_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Leader_F:B_T_TUO_Leader_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Leader_F:B_A_TUO_Leader_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Leader_F:B_W_TUO_Leader_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Autorifleman_F:B_T_TUO_Autorifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Autorifleman_F:B_A_TUO_Autorifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Autorifleman_F:B_W_TUO_Autorifleman_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Heavy_Gunner_F:B_T_TUO_Heavy_Gunner_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_OPF_F"; }; class O_A_TUO_Heavy_Gunner_F:B_A_TUO_Heavy_Gunner_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_OPF_F"; }; class O_W_TUO_Heavy_Gunner_F:B_W_TUO_Heavy_Gunner_F { side=0; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_OPF_F"; }; class O_T_TUO_Grenadier_F:B_T_TUO_Grenadier_F { side=2; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_T_IND_F"; }; class O_A_TUO_Grenadier_F:B_A_TUO_Grenadier_F { side=2; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_A_IND_F"; }; class O_W_TUO_Grenadier_F:B_W_TUO_Grenadier_F { side=2; //OPF_F=0 BLU_F=1 IND_F=2 faction="TUO_W_IND_F"; };
21.713333
51
0.760823
bc036
557b88c28caf8c1a8e0b49aea2e46c1ae215bf71
1,675
cpp
C++
test/cli/minions_coverage_test.cpp
seqan/minions
58339454f992264b73197f1bf8c94e8f4b1c3c2f
[ "BSD-3-Clause" ]
null
null
null
test/cli/minions_coverage_test.cpp
seqan/minions
58339454f992264b73197f1bf8c94e8f4b1c3c2f
[ "BSD-3-Clause" ]
16
2021-09-29T13:00:06.000Z
2022-03-07T13:34:16.000Z
test/cli/minions_coverage_test.cpp
MitraDarja/Comparison
58339454f992264b73197f1bf8c94e8f4b1c3c2f
[ "BSD-3-Clause" ]
1
2022-01-09T22:36:43.000Z
2022-01-09T22:36:43.000Z
#include "cli_test.hpp" TEST_F(cli_test, no_options) { cli_test_result result = execute_app("minions coverage"); std::string expected { "minions-coverage\n" "================\n" " Try -h or --help for more information.\n" }; EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.out, expected); EXPECT_EQ(result.err, std::string{}); } TEST_F(cli_test, minimiser) { cli_test_result result = execute_app("minions coverage --method minimiser -k 19 -w 19 ", data("example1.fasta")); EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.out, std::string{}); EXPECT_EQ(result.err, std::string{}); } TEST_F(cli_test, gapped_minimiser) { cli_test_result result = execute_app("minions coverage --method minimiser -k 19 -w 19 --shape 524223", data("example1.fasta")); EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.out, std::string{}); EXPECT_EQ(result.err, std::string{}); } TEST_F(cli_test, modmer) { cli_test_result result = execute_app("minions coverage --method modmer -k 19 -w 2 ", data("example1.fasta")); EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.out, std::string{}); EXPECT_EQ(result.err, std::string{}); } TEST_F(cli_test, wrong_method) { cli_test_result result = execute_app("minions coverage --method submer -k 19", data("example1.fasta")); std::string expected { "Error. Incorrect command line input for coverage. Validation failed " "for option --method: Value submer is not one of [kmer,minimiser,modmer].\n" }; EXPECT_EQ(result.exit_code, 0); EXPECT_EQ(result.err, expected); EXPECT_EQ(result.out, std::string{}); }
31.018519
131
0.665672
seqan
5355b6e7c24675c87cabae20b628a3dd5351c293
479
cpp
C++
linux/cmd.cpp
Universefei/f8snippet
408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a
[ "Apache-2.0" ]
null
null
null
linux/cmd.cpp
Universefei/f8snippet
408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a
[ "Apache-2.0" ]
null
null
null
linux/cmd.cpp
Universefei/f8snippet
408ae26cf666861e3aa0f58fbdd89a93b3fb1a4a
[ "Apache-2.0" ]
null
null
null
string exe_cmd(const string& cmd) { int t_ret = 0; string t_result = ""; t_result.resize(1024); FILE* fp = popen(cmd.c_str(), "r"); fgets(&t_result[0], t_result.capacity(), fp); pclose(fp); return t_result; } string get_md5(const string& file) { char buf[128] = {'\0'}; string cmd = "md5sum "; cmd.append(file); cmd.append(" | awk '{printf $1}'"); FILE* fp = popen(cmd.c_str(), "r"); fgets(buf, sizeof(buf), fp); pclose(fp); return string(buf); }
21.772727
47
0.605428
Universefei
5368e5f9756762633f750c5c0ff8ef6f9882060e
1,151
cpp
C++
c++/zigzag_conversion.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/zigzag_conversion.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/zigzag_conversion.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
/* The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I G Y I R And then read line by line: "PAHNAPLSIIGYIR" Write the code that will take a string and make this conversion given a number of rows: string convert(string text, int nRows); convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR". */ /* * */ #include "helper.h" class Solution { public: string convert(string s, int nRows) { if (nRows <= 1) { return s; } vector<string> strs(nRows); string res; int row = 0, step = 1; for (char c: s) { strs[row].push_back(c); if (row == 0) { step = 1; } else if (row == nRows - 1) { step = -1; } row += step; } for (int j = 0; j < nRows; ++j) { res.append(strs[j]); } return res; } }; int main() { Solution s; cout << s.convert("PAYPALISHIRING", 3) << endl; return 0; }
20.192982
120
0.529105
SongZhao
536b253989e4c9c91ccb838702940a731c4b1c28
4,577
hpp
C++
include/foonathan/lex/token.hpp
foonathan/lex
2d0177d453f8c36afc78392065248de0b48c1e7d
[ "BSL-1.0" ]
142
2018-10-16T16:41:09.000Z
2021-12-13T20:04:50.000Z
include/foonathan/lex/token.hpp
foonathan/lex
2d0177d453f8c36afc78392065248de0b48c1e7d
[ "BSL-1.0" ]
null
null
null
include/foonathan/lex/token.hpp
foonathan/lex
2d0177d453f8c36afc78392065248de0b48c1e7d
[ "BSL-1.0" ]
10
2018-10-16T19:08:36.000Z
2021-03-19T14:36:29.000Z
// Copyright (C) 2018-2019 Jonathan Müller <[email protected]> // This file is subject to the license terms in the LICENSE file // found in the top-level directory of this distribution. #ifndef FOONATHAN_LEX_TOKEN_HPP_INCLUDED #define FOONATHAN_LEX_TOKEN_HPP_INCLUDED #include <foonathan/lex/spelling.hpp> #include <foonathan/lex/token_kind.hpp> namespace foonathan { namespace lex { template <class TokenSpec> class tokenizer; template <class TokenSpec> class token { public: constexpr token() noexcept : ptr_(nullptr), size_(0), kind_() {} constexpr token_kind<TokenSpec> kind() const noexcept { return kind_; } explicit constexpr operator bool() const noexcept { return !!kind(); } template <class Token> constexpr bool is(Token token = {}) const noexcept { return kind_.is(token); } template <template <typename> class Category> constexpr bool is_category() const noexcept { return kind_.template is_category<Category>(); } constexpr const char* name() const noexcept { return kind_.name(); } constexpr token_spelling spelling() const noexcept { return token_spelling(ptr_, size_); } constexpr std::size_t offset(const tokenizer<TokenSpec>& tokenizer) const noexcept { return static_cast<std::size_t>(ptr_ - tokenizer.begin_ptr()); } private: explicit constexpr token(token_kind<TokenSpec> kind, const char* ptr, std::size_t size) noexcept : ptr_(ptr), size_(size), kind_(kind) {} const char* ptr_; std::size_t size_; token_kind<TokenSpec> kind_; friend tokenizer<TokenSpec>; }; template <class Token, class Payload = void> class static_token; template <class Token> class static_token<Token, void> { static_assert(is_token<Token>::value, "must be a token"); public: template <class TokenSpec> explicit constexpr static_token(const token<TokenSpec>& token) : spelling_(token.spelling()) { FOONATHAN_LEX_PRECONDITION(token.is(Token{}), "token kind must match"); } constexpr operator Token() const noexcept { return Token{}; } template <class TokenSpec> constexpr token_kind<TokenSpec> kind() const noexcept { return token_kind<TokenSpec>::template of<Token>(); } explicit constexpr operator bool() const noexcept { return std::is_same<Token, error_token>::value; } template <class Other> constexpr bool is(Other = {}) const noexcept { return std::is_same<Token, Other>::value; } template <template <typename> class Category> constexpr bool is_category() const noexcept { return Category<Token>::value; } constexpr const char* name() const noexcept { return Token::name; } constexpr token_spelling spelling() const noexcept { return spelling_; } template <class TokenSpec> constexpr std::size_t offset(const tokenizer<TokenSpec>& tokenizer) const noexcept { return static_cast<std::size_t>(spelling_.data() - tokenizer.begin_ptr()); } private: token_spelling spelling_; }; template <class Token, class Payload> class static_token : public static_token<Token, void> { public: template <class TokenSpec> explicit constexpr static_token(const token<TokenSpec>& token, Payload payload) : static_token<Token, void>(token), payload_(static_cast<Payload&&>(payload)) {} constexpr Payload& value() & noexcept { return payload_; } constexpr const Payload& value() const& noexcept { return payload_; } constexpr Payload&& value() && noexcept { return static_cast<Payload&&>(payload_); } constexpr const Payload&& value() const&& noexcept { return static_cast<const Payload&&>(payload_); } private: Payload payload_; }; } // namespace lex } // namespace foonathan #endif // FOONATHAN_LEX_TOKEN_HPP_INCLUDED
26.923529
100
0.59078
foonathan
537be64c75a2acd632f61bb9e80b6d443b077e80
2,219
cpp
C++
Filesystem/Problem36/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
Filesystem/Problem36/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
Filesystem/Problem36/main.cpp
vegemil/ModernCppChallengeStudy
52c2bb22c76ae3f3a883ae479cd70ac27513e78d
[ "MIT" ]
null
null
null
// 36. Deleting files older than a given date // Write a function that, given the path to a directory and a duration, deletes all // the entries (files or subdirectories) older than the specified duration, in a // recursive manner. The duration can represent anything, such as days, hours, // minutes, seconds, and so on, or a combination of that, such as one hour and // twenty minutes. If the specified directory is itself older than the given duration, // it should be deleted entirely. // 36. 특정 날짜보다 오래된 파일들을 지우기 // 어떤 디렉토리에 대한 경로와 기간을 받아서, 정해진 기간보다 오래된 모든 것(파일들 또는 서브 // 디렉토리들)을 재귀적으로 삭제하는 함수를 작성하라. 기간은 일, 시간, 분, 초, 그외 등등, 또는 // 이 것 들의 조합인 한시간 그리고 이십분과 같이 어떤 것으로도 나타낼 수 있다. 만약에 특정 디렉 // 토리가 정해진 기간보다 오래 됐으면, 이 디렉토리 전체가 지워져야 한다 #include "gsl/gsl" // create `main` function for catch #define CATCH_CONFIG_MAIN #include "catch2/catch.hpp" // Redirect CMake's #define to C++ constexpr string constexpr auto TestName = PROJECT_NAME_STRING; #include <experimental/filesystem> #include <ctime> bool checkModifyDate(std::tm* time, const std::experimental::filesystem::path & p) { auto fileTime = std::experimental::filesystem::last_write_time(p); std::time_t cftime = decltype(fileTime)::clock::to_time_t(fileTime); std::time_t mtime = std::mktime(time); // time_t 형식으로 변경. std::cout << p.generic_string() << " "; if (cftime < mtime) { if (std::experimental::filesystem::remove(p) == false) { std::cout << "ERROR REMOVE FILE!" << std::endl; } else { std::cout << "REMOVE FILE SUCCESS!" << std::endl; } return false; } else { std::cout << "FILE SURVIVE!" << std::endl; return true; } } void checkDirectory(std::tm* time, const std::experimental::filesystem::path & p) { if (std::experimental::filesystem::is_directory(p)) { if (false == checkModifyDate(time, p)) { return; } } if (true == checkModifyDate(time, p)) { for (auto& p : std::experimental::filesystem::recursive_directory_iterator(p)) { checkModifyDate(time, p); } } } TEST_CASE("Deleting files older than a given date") { std::istringstream s("2018-10-01"); std::tm x = { 0, }; s >> std::get_time(&x, "%Y-%m-%d"); checkDirectory(&x, "C:\\Users\\euna501\\Downloads\\LINE WORKS"); }
28.448718
86
0.679585
vegemil
537cb69b0923b19595b35018463da84a46573bfc
472
cpp
C++
Engine/Source/Misc/Singleton.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
2
2022-01-11T21:15:31.000Z
2022-02-22T21:14:33.000Z
Engine/Source/Misc/Singleton.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
Engine/Source/Misc/Singleton.cpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
#include "Singleton.h" void SingletonCache::Store(const std::type_index& type, void* ptr) { //return; //using auto registers breaks this whole thing m_PointerCache[type] = ptr; } void* SingletonCache::Find(const std::type_index& type) { if(m_PointerCache.empty()) return nullptr; for (auto& pair : m_PointerCache) { if (pair.first == type) return pair.second; } return nullptr; } std::unordered_map<std::type_index, void*> SingletonCache::m_PointerCache;
20.521739
74
0.724576
wdrDarx
537e955672b76efb287ccd96dea5e70143e09d32
3,574
hpp
C++
chapter20/uncommentedString.hpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
2
2022-01-08T03:31:25.000Z
2022-03-09T01:21:54.000Z
chapter20/uncommentedString.hpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
null
null
null
chapter20/uncommentedString.hpp
not-sponsored/Sams-Cpp-in-24hrs-Exercises
2e63e2ca31f5309cc1d593f29c8b47037be150fb
[ "Fair" ]
1
2022-03-09T01:26:01.000Z
2022-03-09T01:26:01.000Z
/********************************************************* * * Part of the answer to exercise 1 in chapter 20 * * Modified 20.3 from Sams Teach Yourself C++ in 24 Hours by Rogers Cadenhead * and Jesse Liberty * * Compiled with g++ (GCC) 11.1.0 * *********************************************************/ #include <iostream> #include <string.h> using std::cout; using std::cin; class String { public: // constructors String(); String(const char *const); String(const String&); ~String(); // overloaded operators char& operator[](int offset); char operator[](int offset) const; String operator+(const String&); void operator+=(const String&); String& operator=(const String &); // general accessors int getLen() const { return len; } const char* getString() const { return value; } static int constructorCount; private: String(int); // private constructor char* value; int len; }; // default constructor creates 0 byte string String::String() { value = new char[1]; value[0] = '\0'; len = 0; cout << "\tDefault string constructor\n"; constructorCount++; } // private helper constructor only for class functions // creates a string of required size, null filled String::String(int len) { value = new char[len + 1]; int i; for (i = 0; i < len; i++) value[i] = '\0'; len = len; cout << "\tString(int) constructor\n"; constructorCount++; } String::String(const char* const cString) { len = strlen(cString); value = new char[len + 1]; int i; for (i = 0; i < len; i++) value[i] = cString[i]; value[len] = '\0'; cout << "\tString(char*) constructor\n"; constructorCount++; } String::String(const String& rhs) { len = rhs.getLen(); value = new char[len + 1]; int i; for (i = 0; i < len; i++) value[i] = rhs[i]; value[len] = '\0'; cout << "\tString(String&) constructor\n"; constructorCount++; } String::~String() { delete [] value; len = 0; cout << "\tString destructor\n"; } // operator equals, frees existing memory and copies string and size String& String::operator=(const String &rhs) { if (this == &rhs) return *this; delete [] value; len = rhs.getLen(); value = new char[len + 1]; int i; for (i = 0; i < len; i++) value[i] = rhs[i]; value[len] = '\0'; return *this; cout << "\tString operator=\n"; } // non-constant offset operator returns reference to character to be changed char& String::operator[](int offset) { if (offset > len) return value[len - 1]; else if (offset < 0 && abs(offset) <= len) return value[len + offset]; else if (offset < 0) return value[0]; else return value[offset]; } // constant offset operator for use on const objects (see copy constructor) char String::operator[](int offset) const { if (offset > len) return value[len - 1]; else if (offset < 0 && abs(offset) <= len) return value[len + offset]; else if (offset < 0) return value[0]; else return value[offset]; } // new string by adding current string to rhs String String::operator+(const String& rhs) { int totalLen = len + rhs.getLen(); int i, j; String temp(totalLen); for (i = 0; i < len; i++) temp[i] = value[i]; for (j = 0; j < rhs.getLen(); j++) temp[i] = rhs[j]; temp[totalLen] = '\0'; return temp; } // changes current string, returns nothing void String::operator+=(const String& rhs) { int rhsLen = rhs.getLen(); int totalLen = len + rhsLen; int i, j; String temp(totalLen); for (i = 0; i < len; i++) temp[i] = value[i]; for (j = 0; j < rhs.getLen(); j++) temp[i] = rhs[i - len]; temp[totalLen] = '\0'; *this = temp; } int String::constructorCount = 0;
21.023529
77
0.618355
not-sponsored
53830346afd4c02fa7869d8037de73ed1ec97ef6
11,459
cpp
C++
Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp
dfyzy/StealthTest
ff48d800ef073abd559048d81df7efd014c91cb7
[ "MIT" ]
null
null
null
Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp
dfyzy/StealthTest
ff48d800ef073abd559048d81df7efd014c91cb7
[ "MIT" ]
null
null
null
Plugins/SimpleMaterialUI/Source/SimpleMaterialUIEditor/Private/SmMarginCustomization.cpp
dfyzy/StealthTest
ff48d800ef073abd559048d81df7efd014c91cb7
[ "MIT" ]
null
null
null
#include "SmMarginCustomization.h" #include "PropertyHandle.h" #include "DetailLayoutBuilder.h" #include "Widgets/Input/SNumericEntryBox.h" #include "Editor.h" bool FSmMarginIdentifier::IsPropertyTypeCustomized(const IPropertyHandle& PropertyHandle) const { return PropertyHandle.IsValidHandle() && PropertyHandle.GetMetaDataProperty()->HasMetaData("SmMargin"); } void FSmMarginCustomization::GetSortedChildren(TSharedRef<IPropertyHandle> StructPropertyHandle, TArray<TSharedRef<IPropertyHandle>>& OutChildren) { OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Left")).ToSharedRef()); OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Top")).ToSharedRef()); OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Right")).ToSharedRef()); OutChildren.Add(StructPropertyHandle->GetChildHandle(TEXT("Bottom")).ToSharedRef()); } TSharedRef<SWidget> FSmMarginCustomization::MakeChildWidget(TSharedRef<IPropertyHandle>& StructurePropertyHandle, TSharedRef<IPropertyHandle>& PropertyHandle) { TOptional<float> MinValue, MaxValue, SliderMinValue, SliderMaxValue; float SliderExponent, Delta; int32 ShiftMouseMovePixelPerDelta = 1; bool SupportDynamicSliderMaxValue = false; bool SupportDynamicSliderMinValue = false; { FProperty* Property = PropertyHandle->GetProperty(); const FString& MetaUIMinString = Property->GetMetaData(TEXT("UIMin")); const FString& MetaUIMaxString = Property->GetMetaData(TEXT("UIMax")); const FString& SliderExponentString = Property->GetMetaData(TEXT("SliderExponent")); const FString& DeltaString = Property->GetMetaData(TEXT("Delta")); const FString& ShiftMouseMovePixelPerDeltaString = Property->GetMetaData(TEXT("ShiftMouseMovePixelPerDelta")); const FString& SupportDynamicSliderMaxValueString = Property->GetMetaData(TEXT("SupportDynamicSliderMaxValue")); const FString& SupportDynamicSliderMinValueString = Property->GetMetaData(TEXT("SupportDynamicSliderMinValue")); const FString& ClampMinString = Property->GetMetaData(TEXT("ClampMin")); const FString& ClampMaxString = Property->GetMetaData(TEXT("ClampMax")); // If no UIMin/Max was specified then use the clamp string const FString& UIMinString = MetaUIMinString.Len() ? MetaUIMinString : ClampMinString; const FString& UIMaxString = MetaUIMaxString.Len() ? MetaUIMaxString : ClampMaxString; float ClampMin = TNumericLimits<float>::Lowest(); float ClampMax = TNumericLimits<float>::Max(); if (!ClampMinString.IsEmpty()) { TTypeFromString<float>::FromString(ClampMin, *ClampMinString); } if (!ClampMaxString.IsEmpty()) { TTypeFromString<float>::FromString(ClampMax, *ClampMaxString); } float UIMin = TNumericLimits<float>::Lowest(); float UIMax = TNumericLimits<float>::Max(); TTypeFromString<float>::FromString(UIMin, *UIMinString); TTypeFromString<float>::FromString(UIMax, *UIMaxString); SliderExponent = float(1); if (SliderExponentString.Len()) { TTypeFromString<float>::FromString(SliderExponent, *SliderExponentString); } Delta = float(0); if (DeltaString.Len()) { TTypeFromString<float>::FromString(Delta, *DeltaString); } ShiftMouseMovePixelPerDelta = 1; if (ShiftMouseMovePixelPerDeltaString.Len()) { TTypeFromString<int32>::FromString(ShiftMouseMovePixelPerDelta, *ShiftMouseMovePixelPerDeltaString); //The value should be greater or equal to 1 // 1 is neutral since it is a multiplier of the mouse drag pixel if (ShiftMouseMovePixelPerDelta < 1) { ShiftMouseMovePixelPerDelta = 1; } } if (ClampMin >= ClampMax && (ClampMinString.Len() || ClampMaxString.Len())) { //UE_LOG(LogPropertyNode, Warning, TEXT("Clamp Min (%s) >= Clamp Max (%s) for Ranged Numeric"), *ClampMinString, *ClampMaxString); } const float ActualUIMin = FMath::Max(UIMin, ClampMin); const float ActualUIMax = FMath::Min(UIMax, ClampMax); MinValue = ClampMinString.Len() ? ClampMin : TOptional<float>(); MaxValue = ClampMaxString.Len() ? ClampMax : TOptional<float>(); SliderMinValue = (UIMinString.Len()) ? ActualUIMin : TOptional<float>(); SliderMaxValue = (UIMaxString.Len()) ? ActualUIMax : TOptional<float>(); if (ActualUIMin >= ActualUIMax && (MetaUIMinString.Len() || MetaUIMaxString.Len())) { //UE_LOG(LogPropertyNode, Warning, TEXT("UI Min (%s) >= UI Max (%s) for Ranged Numeric"), *UIMinString, *UIMaxString); } SupportDynamicSliderMaxValue = SupportDynamicSliderMaxValueString.Len() > 0 && SupportDynamicSliderMaxValueString.ToBool(); SupportDynamicSliderMinValue = SupportDynamicSliderMinValueString.Len() > 0 && SupportDynamicSliderMinValueString.ToBool(); } TWeakPtr<IPropertyHandle> WeakHandlePtr = PropertyHandle; return SNew(SNumericEntryBox<float>) .IsEnabled(this, &FMathStructCustomization::IsValueEnabled, WeakHandlePtr) .EditableTextBoxStyle(&FCoreStyle::Get().GetWidgetStyle<FEditableTextBoxStyle>("NormalEditableTextBox")) .Value(this, &FSmMarginCustomization::OnGetValue, WeakHandlePtr) .Font(IDetailLayoutBuilder::GetDetailFont()) .UndeterminedString(NSLOCTEXT("PropertyEditor", "MultipleValues", "Multiple Values")) .OnValueCommitted(this, &FSmMarginCustomization::OnValueCommitted, WeakHandlePtr) .OnValueChanged(this, &FSmMarginCustomization::OnValueChanged, WeakHandlePtr) .OnBeginSliderMovement(this, &FSmMarginCustomization::OnBeginSliderMovement) .OnEndSliderMovement(this, &FSmMarginCustomization::OnEndSliderMovement) .LabelVAlign(VAlign_Center) // Only allow spin on handles with one object. Otherwise it is not clear what value to spin .AllowSpin(PropertyHandle->GetNumOuterObjects() < 2) .ShiftMouseMovePixelPerDelta(ShiftMouseMovePixelPerDelta) .SupportDynamicSliderMaxValue(SupportDynamicSliderMaxValue) .SupportDynamicSliderMinValue(SupportDynamicSliderMinValue) .OnDynamicSliderMaxValueChanged(this, &FSmMarginCustomization::OnDynamicSliderMaxValueChanged) .OnDynamicSliderMinValueChanged(this, &FSmMarginCustomization::OnDynamicSliderMinValueChanged) .MinValue(MinValue) .MaxValue(MaxValue) .MinSliderValue(SliderMinValue) .MaxSliderValue(SliderMaxValue) .SliderExponent(SliderExponent) .Delta(Delta); } void FSmMarginCustomization::SetValue(float NewValue, EPropertyValueSetFlags::Type Flags, TWeakPtr<IPropertyHandle> WeakHandlePtr) { if (bPreserveScaleRatio) { // Get the value for each object for the modified component TArray<FString> OldValues; if (WeakHandlePtr.Pin()->GetPerObjectValues(OldValues) == FPropertyAccess::Success) { // Loop through each object and scale based on the new ratio for each object individually for (int32 OutputIndex = 0; OutputIndex < OldValues.Num(); ++OutputIndex) { float OldValue; TTypeFromString<float>::FromString(OldValue, *OldValues[OutputIndex]); // Account for the previous scale being zero. Just set to the new value in that case? float Ratio = OldValue == 0 ? NewValue : NewValue / OldValue; if (Ratio == 0) { Ratio = NewValue; } // Loop through all the child handles (each component of the math struct, like X, Y, Z...etc) for (int32 ChildIndex = 0; ChildIndex < SortedChildHandles.Num(); ++ChildIndex) { // Ignore scaling our selves. TSharedRef<IPropertyHandle> ChildHandle = SortedChildHandles[ChildIndex]; if (ChildHandle != WeakHandlePtr.Pin()) { // Get the value for each object. TArray<FString> ObjectChildValues; if (ChildHandle->GetPerObjectValues(ObjectChildValues) == FPropertyAccess::Success) { // Individually scale each object's components by the same ratio. for (int32 ChildOutputIndex = 0; ChildOutputIndex < ObjectChildValues.Num(); ++ChildOutputIndex) { float ChildOldValue; TTypeFromString<float>::FromString(ChildOldValue, *ObjectChildValues[ChildOutputIndex]); float ChildNewValue = ChildOldValue * Ratio; ObjectChildValues[ChildOutputIndex] = TTypeToString<float>::ToSanitizedString(ChildNewValue); } ChildHandle->SetPerObjectValues(ObjectChildValues); } } } } } } WeakHandlePtr.Pin()->SetValue(NewValue, Flags); } TOptional<float> FSmMarginCustomization::OnGetValue(TWeakPtr<IPropertyHandle> WeakHandlePtr) const { float NumericVal = 0; if (WeakHandlePtr.Pin()->GetValue(NumericVal) == FPropertyAccess::Success) { return TOptional<float>(NumericVal); } // Value couldn't be accessed. Return an unset value return TOptional<float>(); } void FSmMarginCustomization::OnValueCommitted(float NewValue, ETextCommit::Type CommitType, TWeakPtr<IPropertyHandle> WeakHandlePtr) { EPropertyValueSetFlags::Type Flags = EPropertyValueSetFlags::DefaultFlags; SetValue(NewValue, Flags, WeakHandlePtr); } void FSmMarginCustomization::OnValueChanged(float NewValue, TWeakPtr<IPropertyHandle> WeakHandlePtr) { if (bIsUsingSlider) { EPropertyValueSetFlags::Type Flags = EPropertyValueSetFlags::InteractiveChange; SetValue(NewValue, Flags, WeakHandlePtr); } } void FSmMarginCustomization::OnBeginSliderMovement() { bIsUsingSlider = true; GEditor->BeginTransaction(NSLOCTEXT("FMathStructCustomization", "SetVectorProperty", "Set Vector Property")); } void FSmMarginCustomization::OnEndSliderMovement(float NewValue) { bIsUsingSlider = false; GEditor->EndTransaction(); } void FSmMarginCustomization::OnDynamicSliderMaxValueChanged(float NewMaxSliderValue, TWeakPtr<SWidget> InValueChangedSourceWidget, bool IsOriginator, bool UpdateOnlyIfHigher) { for (TWeakPtr<SWidget>& Widget : NumericEntryBoxWidgetList) { TSharedPtr<SNumericEntryBox<float>> NumericBox = StaticCastSharedPtr<SNumericEntryBox<float>>(Widget.Pin()); if (NumericBox.IsValid()) { TSharedPtr<SSpinBox<float>> SpinBox = StaticCastSharedPtr<SSpinBox<float>>(NumericBox->GetSpinBox()); if (SpinBox.IsValid()) { if (SpinBox != InValueChangedSourceWidget) { if ((NewMaxSliderValue > SpinBox->GetMaxSliderValue() && UpdateOnlyIfHigher) || !UpdateOnlyIfHigher) { // Make sure the max slider value is not a getter otherwise we will break the link! verifySlow(!SpinBox->IsMaxSliderValueBound()); SpinBox->SetMaxSliderValue(NewMaxSliderValue); } } } } } if (IsOriginator) { OnNumericEntryBoxDynamicSliderMaxValueChanged.Broadcast((float)NewMaxSliderValue, InValueChangedSourceWidget, false, UpdateOnlyIfHigher); } } void FSmMarginCustomization::OnDynamicSliderMinValueChanged(float NewMinSliderValue, TWeakPtr<SWidget> InValueChangedSourceWidget, bool IsOriginator, bool UpdateOnlyIfLower) { for (TWeakPtr<SWidget>& Widget : NumericEntryBoxWidgetList) { TSharedPtr<SNumericEntryBox<float>> NumericBox = StaticCastSharedPtr<SNumericEntryBox<float>>(Widget.Pin()); if (NumericBox.IsValid()) { TSharedPtr<SSpinBox<float>> SpinBox = StaticCastSharedPtr<SSpinBox<float>>(NumericBox->GetSpinBox()); if (SpinBox.IsValid()) { if (SpinBox != InValueChangedSourceWidget) { if ((NewMinSliderValue < SpinBox->GetMinSliderValue() && UpdateOnlyIfLower) || !UpdateOnlyIfLower) { // Make sure the min slider value is not a getter otherwise we will break the link! verifySlow(!SpinBox->IsMinSliderValueBound()); SpinBox->SetMinSliderValue(NewMinSliderValue); } } } } } if (IsOriginator) { OnNumericEntryBoxDynamicSliderMinValueChanged.Broadcast((float)NewMinSliderValue, InValueChangedSourceWidget, false, UpdateOnlyIfLower); } }
38.844068
174
0.761498
dfyzy
5384176a24be9a050c35188a1a18a9ebb667084b
9,232
cpp
C++
betteryao/OTExtension/util/Miracl/zzn3.cpp
bt3ze/pcflib
c66cdc5957818cd5b3754430046cad91ce1a921d
[ "BSD-2-Clause" ]
null
null
null
betteryao/OTExtension/util/Miracl/zzn3.cpp
bt3ze/pcflib
c66cdc5957818cd5b3754430046cad91ce1a921d
[ "BSD-2-Clause" ]
null
null
null
betteryao/OTExtension/util/Miracl/zzn3.cpp
bt3ze/pcflib
c66cdc5957818cd5b3754430046cad91ce1a921d
[ "BSD-2-Clause" ]
null
null
null
/*************************************************************************** * Copyright 2013 CertiVox IOM Ltd. * * This file is part of CertiVox MIRACL Crypto SDK. * * The CertiVox MIRACL Crypto SDK provides developers with an * extensive and efficient set of cryptographic functions. * For further information about its features and functionalities please * refer to http://www.certivox.com * * * The CertiVox MIRACL Crypto SDK is free software: you can * redistribute it and/or modify it under the terms of the * GNU Affero General Public License as published by the * Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * * The CertiVox MIRACL Crypto SDK 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 Affero General Public License for more details. * * * You should have received a copy of the GNU Affero General Public * License along with CertiVox MIRACL Crypto SDK. * If not, see <http://www.gnu.org/licenses/>. * * You can be released from the requirements of the license by purchasing * a commercial license. Buying such a license is mandatory as soon as you * develop commercial activities involving the CertiVox MIRACL Crypto SDK * without disclosing the source code of your own applications, or shipping * the CertiVox MIRACL Crypto SDK with a closed source product. * * ***************************************************************************/ /* * MIRACL C++ Implementation file zzn3.cpp * * AUTHOR : M. Scott * * PURPOSE : Implementation of class ZZn3 (Arithmetic over n^3) * * WARNING: This class has been cobbled together for a specific use with * the MIRACL library. It is not complete, and may not work in other * applications * * Assumes p=1 mod 3 and p NOT 1 mod 8 * Irreducible is x^3+cnr (cubic non-residue) * */ #include "zzn3.h" using namespace std; // First find a cubic non-residue cnr, which is also a quadratic non-residue // X is precalculated sixth root of unity (cnr)^(p-1)/6 void ZZn3::get(ZZn& x,ZZn& y,ZZn& z) const {copy(fn.a,x.getzzn()); copy(fn.b,y.getzzn()); copy(fn.c,z.getzzn());} void ZZn3::get(ZZn& x) const {{copy(fn.a,x.getzzn());}} ZZn3& ZZn3::operator/=(const ZZn& x) { ZZn t=(ZZn)1/x; zzn3_smul(&fn,t.getzzn(),&fn); return *this; } ZZn3& ZZn3::operator/=(int i) { if (i==2) {zzn3_div2(&fn); return *this;} ZZn t=one()/i; zzn3_smul(&fn,t.getzzn(),&fn); return *this; } ZZn3& ZZn3::operator/=(const ZZn3& x) { *this*=inverse(x); return *this; } ZZn3 inverse(const ZZn3& w) {ZZn3 i=w; zzn3_inv(&i.fn); return i;} ZZn3 operator+(const ZZn3& x,const ZZn3& y) {ZZn3 w=x; w+=y; return w; } ZZn3 operator+(const ZZn3& x,const ZZn& y) {ZZn3 w=x; w+=y; return w; } ZZn3 operator-(const ZZn3& x,const ZZn3& y) {ZZn3 w=x; w-=y; return w; } ZZn3 operator-(const ZZn3& x,const ZZn& y) {ZZn3 w=x; w-=y; return w; } ZZn3 operator-(const ZZn3& x) {ZZn3 w; zzn3_negate((zzn3 *)&x.fn,&w.fn); return w; } ZZn3 operator*(const ZZn3& x,const ZZn3& y) { ZZn3 w=x; if (&x==&y) w*=w; else w*=y; return w; } ZZn3 operator*(const ZZn3& x,const ZZn& y) {ZZn3 w=x; w*=y; return w;} ZZn3 operator*(const ZZn& y,const ZZn3& x) {ZZn3 w=x; w*=y; return w;} ZZn3 operator*(const ZZn3& x,int y) {ZZn3 w=x; w*=y; return w;} ZZn3 operator*(int y,const ZZn3& x) {ZZn3 w=x; w*=y; return w;} ZZn3 operator/(const ZZn3& x,const ZZn3& y) {ZZn3 w=x; w/=y; return w;} ZZn3 operator/(const ZZn3& x,const ZZn& y) {ZZn3 w=x; w/=y; return w;} ZZn3 operator/(const ZZn3& x,int i) {ZZn3 w=x; w/=i; return w;} #ifndef MR_NO_RAND ZZn3 randn3(void) {ZZn3 w; zzn3_from_zzns(randn().getzzn(),randn().getzzn(),randn().getzzn(),&w.fn); return w;} #endif ZZn3 rhs(const ZZn3& x) { ZZn3 w; miracl *mip=get_mip(); int twist=mip->TWIST; int qnr=mip->cnr; // the cubic non-residue is also a quadratic non-residue w=x*x*x; if (twist) { if (twist==MR_QUARTIC_M) { w+=tx((ZZn3)getA())*x; } if (twist==MR_QUARTIC_D) { w+=txd((ZZn3)getA())*x; } if (twist==MR_SEXTIC_M || twist==MR_CUBIC_M) { w+=tx((ZZn3)getB()); } if (twist==MR_SEXTIC_D || twist==MR_CUBIC_D) { w+=txd((ZZn3)getB()); } if (twist==MR_QUADRATIC) { w+=qnr*qnr*getA()*x+(qnr*qnr*qnr)*getB(); } } else { w+=getA()*x+getB(); } return w; } BOOL is_on_curve(const ZZn3& x) { ZZn3 w; if (qr(rhs(x))) return TRUE; return FALSE; } BOOL qr(const ZZn3& x) { Big p=get_modulus(); ZZn3 r,t; t=r=x; t.powq(); r*=t; t.powq(); r*=t; // check x^[(p^3-1)/2] = 1 if (pow(r,(p-1)/2)==1) return TRUE; else return FALSE; } ZZn3 sqrt(const ZZn3& x) { ZZn3 r,w,t; Big p=get_modulus(); if (!qr(x)) return r; // oh boy this is clever! switch (get_mip()->pmod8) { case 5: r=(x+x); r.powq(); w=r*r; t=w*r; w*=t; r.powq(); r*=(w*(x+x)); r=pow(r,(p-5)/8); r*=t; w=r*r; w*=x; w+=w; r*=x; r*=(w-(ZZn)1); break; case 3: case 7: r=x; r.powq(); t=r*r; w=t*r; r.powq(); r*=(w*x); r=pow(r,(p-3)/4); r*=(t*x); break; default: break; } return r; } ZZn3 tx(const ZZn3& w) { ZZn3 u=w; zzn3_timesi(&u.fn); return u; } ZZn3 tx2(const ZZn3& w) { ZZn3 u=w; zzn3_timesi2(&u.fn); return u; } ZZn3 txd(const ZZn3& w) { ZZn3 u; ZZn wa,wb,wc; w.get(wa,wb,wc); u.set(wb,wc,(wa/get_mip()->cnr)); return u; } // regular ZZn3 powering ZZn3 pow(const ZZn3& x,const Big& k) { int i,j,nb,n,nbw,nzs; ZZn3 u,u2,t[16]; if (k==0) return (ZZn3)1; u=x; if (k==1) return u; // // Prepare table for windowing // u2=(u*u); t[0]=u; for (i=1;i<16;i++) t[i]=u2*t[i-1]; // Left to right method - with windows nb=bits(k); if (nb>1) for (i=nb-2;i>=0;) { n=window(k,i,&nbw,&nzs,5); for (j=0;j<nbw;j++) u*=u; if (n>0) u*=t[n/2]; i-=nbw; if (nzs) { for (j=0;j<nzs;j++) u*=u; i-=nzs; } } return u; } ZZn3 powl(const ZZn3& x,const Big& k) { ZZn3 A,B,two,y; int j,nb; two=(ZZn)2; y=two*x; // y=x; if (k==0) return (ZZn3)two; if (k==1) return y; // w8=two; // w9=y; A=y; B=y*y-two; nb=bits(k); //cout << "nb= " << nb << endl; for (j=nb-1;j>=1;j--) { if (bit(k,j-1)) { A*=B; A-=y; B*=B; B-=two; } else { B*=A; B-=y; A*=A; A-=two; } //cout << "1. int A= " << A << endl; } //cout << "1. B= " << B << endl; return A/2; // return (w8/2); } // double exponention - see Schoenmaker's method from Stam's thesis ZZn3 powl(const ZZn3& x,const Big& n,const ZZn3& y,const Big& m,const ZZn3& a) { ZZn3 A,B,C,T,two,vk,vl,va; int j,nb; two=(ZZn)2; vk=x+x; vl=y+y; va=a+a; nb=bits(n); if (bits(m)>nb) nb=bits(m); //cout << "nb= " << nb << endl; A=two; B=vk; C=vl; /* cout << "A= " << A << endl; cout << "B= " << B << endl; cout << "C= " << C << endl; cout << "vk= " << vk << endl; cout << "vl= " << vl << endl; cout << "va= " << va << endl; cout << "va*va-2= " << va*va-two << endl; */ for (j=nb;j>=1;j--) { if (bit(n,j-1)==0 && bit(m,j-1)==0) { B*=A; B-=vk; C*=A; C-=vl; A*=A; A-=two; } if (bit(n,j-1)==1 && bit(m,j-1)==0) { A*=B; A-=vk; C*=B; C-=va; B*=B; B-=two; } if (bit(n,j-1)==0 && bit(m,j-1)==1) { A*=C; A-=vl; B*=C; B-=va; C*=C; C-=two; } if (bit(n,j-1)==1 && bit(m,j-1)==1) { T=B*C-va; B*=A; B-=vk; C*=A; C-=vl; A=T; T=A*vl-B; B=A*vk-C; C=T; } } // return A; return (A/2); } #ifndef MR_NO_STANDARD_IO ostream& operator<<(ostream& s,const ZZn3& xx) { ZZn3 b=xx; ZZn x,y,z; b.get(x,y,z); s << "[" << x << "," << y << "," << z << "]"; return s; } #endif
23.313131
93
0.476603
bt3ze
53988aa7ba416ddd19afa84395af5a3fae8bd86d
1,714
cpp
C++
test/quiver/disjoint_set.cpp
Fytch/Quiver
572c59bbc7aaef0e61318d6d0feaf5771b38cfdb
[ "MIT" ]
null
null
null
test/quiver/disjoint_set.cpp
Fytch/Quiver
572c59bbc7aaef0e61318d6d0feaf5771b38cfdb
[ "MIT" ]
1
2018-11-28T12:55:50.000Z
2018-11-28T12:55:50.000Z
test/quiver/disjoint_set.cpp
Fytch/Quiver
572c59bbc7aaef0e61318d6d0feaf5771b38cfdb
[ "MIT" ]
1
2018-08-19T16:48:23.000Z
2018-08-19T16:48:23.000Z
/* * Quiver - A graph theory library * Copyright (C) 2018 Josua Rieder ([email protected]) * Distributed under the MIT License. * See the enclosed file LICENSE.txt for further information. */ #include <catch2/catch.hpp> #include <quiver.hpp> using namespace quiver; TEST_CASE("disjoint_set", "[quiver][fundamentals]") { const std::size_t N = 10; disjoint_set<> set(N); CHECK(set.sets() == N); for(std::size_t i = 0; i < N; ++i) { CHECK(set.find(i) == i); CHECK(set.cardinality(i) == 1); } set.unite(1, 2); set.unite(2, 3); set.unite(7, 6); set.unite(5, 6); CHECK(set.sets() == N - 4); CHECK(set.cardinality(0) == 1); CHECK(set.cardinality(1) == 3); CHECK(set.cardinality(2) == 3); CHECK(set.cardinality(3) == 3); CHECK(set.find(1) == set.find(2)); CHECK(set.find(1) == set.find(3)); CHECK(set.cardinality(4) == 1); CHECK(set.cardinality(5) == 3); CHECK(set.cardinality(6) == 3); CHECK(set.cardinality(7) == 3); CHECK(set.find(5) == set.find(6)); CHECK(set.find(5) == set.find(7)); CHECK(set.cardinality(8) == 1); CHECK(set.cardinality(9) == 1); set.unite(7, 2); set.unite(3, 9); CHECK(set.sets() == N - 6); CHECK(set.cardinality(0) == 1); CHECK(set.cardinality(4) == 1); CHECK(set.cardinality(8) == 1); CHECK(set.cardinality(1) == 7); CHECK(set.cardinality(2) == 7); CHECK(set.cardinality(3) == 7); CHECK(set.cardinality(5) == 7); CHECK(set.cardinality(6) == 7); CHECK(set.cardinality(7) == 7); CHECK(set.cardinality(9) == 7); CHECK(set.find(1) == set.find(2)); CHECK(set.find(1) == set.find(3)); CHECK(set.find(1) == set.find(5)); CHECK(set.find(1) == set.find(6)); CHECK(set.find(1) == set.find(7)); CHECK(set.find(1) == set.find(9)); }
23.805556
63
0.620187
Fytch
539b28bd3fd509a516e0026b76ec38fb73d66154
795
cpp
C++
demo/ref_object.cpp
bianc2018/Sim
8c37f65d28b99598c1c75a650e4da36a460cf600
[ "MIT" ]
1
2021-01-19T15:25:25.000Z
2021-01-19T15:25:25.000Z
demo/ref_object.cpp
bianc2018/Sim
8c37f65d28b99598c1c75a650e4da36a460cf600
[ "MIT" ]
null
null
null
demo/ref_object.cpp
bianc2018/Sim
8c37f65d28b99598c1c75a650e4da36a460cf600
[ "MIT" ]
null
null
null
#include "Logger.hpp" #include "TaskPool.hpp" #include "RefObject.hpp" class faketype { public: faketype() { SIM_LINFO("faketype() "<<SIM_HEX(this)); } ~faketype() { SIM_LINFO("~faketype " << SIM_HEX(this)); } }; sim::RefObject<faketype> temp; void* run(void* pd) { sim::RefObject<faketype> ref = temp; SIM_LINFO("ref count=" << ref.getcount()); return NULL; } int main(int argc, char* argv[]) { SIM_LOG_CONSOLE(sim::LInfo); SIM_FUNC_DEBUG(); sim::RefObject<faketype> ref(new faketype()); SIM_LINFO("ref count=" << ref.getcount()); sim::RefObject<faketype> ref1 = ref; temp = ref1; sim::TaskPool pool(8); for (int i = 0; i < 10000; ++i) pool.Post(run, NULL, NULL); while (ref.getcount() >3) { SIM_LINFO("ref count=" << ref.getcount()); } getchar(); return 0; }
17.666667
46
0.642767
bianc2018
53a00aa768d7073cafbf71f51d524ea23faded2c
669
cpp
C++
RapyutaTest.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
26
2019-04-05T07:10:15.000Z
2022-01-08T02:35:19.000Z
RapyutaTest.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
2
2019-04-25T15:47:54.000Z
2019-09-03T06:46:05.000Z
RapyutaTest.cpp
abhis2007/Algorithms-1
7637209c5aa52c1afd8be1884d018673d26f5c1f
[ "MIT" ]
8
2019-04-05T08:58:50.000Z
2020-07-03T01:53:58.000Z
#include <bits/stdc++.h> using namespace std; int main() { int n; cin >> n; int arr[n + 1]; for (int i = 1; i <= n; ++i) { cin >> arr[i]; } int dp[n + 1][n + 1]; memset(dp, sizeof(dp), 0); int res = INT_MIN; dp[1][0] = 0; dp[1][1] = arr[1]; for (int i = 2; i <= n; ++i) { for (int j = 0; j <= i; ++j) { if(j == 0){ dp[i][j] = 0; continue; } if(j == i) { dp[i][j] = arr[i] * j + dp[i - 1][j - 1]; } else { dp[i][j] = max(dp[i - 1][j], arr[i] * j + dp[i - 1][j - 1]); } res = max(res, dp[i][j]); } } cout << res; return 0; }
19.114286
73
0.355755
abhis2007
53a6d540c52e63dc58070a971baff80f27fd0f77
2,388
cpp
C++
client/include/game/CCheckpoints.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
368
2015-01-01T21:42:00.000Z
2022-03-29T06:22:22.000Z
client/include/game/CCheckpoints.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
92
2019-01-23T23:02:31.000Z
2022-03-23T19:59:40.000Z
client/include/game/CCheckpoints.cpp
MayconFelipeA/sampvoiceatt
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
[ "MIT" ]
179
2015-02-03T23:41:17.000Z
2022-03-26T08:27:16.000Z
/* Plugin-SDK (Grand Theft Auto San Andreas) source file Authors: GTA Community. See more here https://github.com/DK22Pac/plugin-sdk Do not delete this comment block. Respect others' work! */ #include "CCheckpoints.h" unsigned int MAX_NUM_CHECKPOINTS = 32; unsigned int &CCheckpoints::NumActiveCPts = *(unsigned int *)0xC7C6D4; CCheckpoint *CCheckpoints::m_aCheckPtArray = (CCheckpoint *)0xC7F158; // Converted from cdecl void CCheckpoints::DeleteCP(uint id,ushort type) 0x722FC0 void CCheckpoints::DeleteCP(unsigned int id, unsigned short type) { plugin::Call<0x722FC0, unsigned int, unsigned short>(id, type); } // Converted from cdecl void CCheckpoints::Init(void) 0x722880 void CCheckpoints::Init() { plugin::Call<0x722880>(); } // Converted from cdecl CCheckpoint* CCheckpoints::PlaceMarker(uint id,ushort type,CVector &posn,CVector &direction,float size,uchar red,uchar green,uchar blue,uchar alpha,ushort pulsePeriod,float pulseFraction,short rotateRate) 0x722C40 CCheckpoint* CCheckpoints::PlaceMarker(unsigned int id, unsigned short type, CVector& posn, CVector& direction, float size, unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha, unsigned short pulsePeriod, float pulseFraction, short rotateRate) { return plugin::CallAndReturn<CCheckpoint*, 0x722C40, unsigned int, unsigned short, CVector&, CVector&, float, unsigned char, unsigned char, unsigned char, unsigned char, unsigned short, float, short>(id, type, posn, direction, size, red, green, blue, alpha, pulsePeriod, pulseFraction, rotateRate); } // Converted from cdecl void CCheckpoints::Render(void) 0x726060 void CCheckpoints::Render() { plugin::Call<0x726060>(); } // Converted from cdecl void CCheckpoints::SetHeading(uint id,float angle) 0x722970 void CCheckpoints::SetHeading(unsigned int id, float angle) { plugin::Call<0x722970, unsigned int, float>(id, angle); } // Converted from cdecl void CCheckpoints::Shutdown(void) 0x7228F0 void CCheckpoints::Shutdown() { plugin::Call<0x7228F0>(); } // Converted from cdecl void CCheckpoints::Update(void) 0x7229C0 void CCheckpoints::Update() { plugin::Call<0x7229C0>(); } // Converted from cdecl void CCheckpoints::UpdatePos(uint id,CVector &posn) 0x722900 void CCheckpoints::UpdatePos(unsigned int id, CVector& posn) { plugin::Call<0x722900, unsigned int, CVector&>(id, posn); }
45.923077
302
0.760888
MayconFelipeA
53b778497d67824a758b505d8509133ac53883c4
5,833
hpp
C++
include/RavEngine/unordered_vector.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
48
2020-11-18T23:14:25.000Z
2022-03-11T09:13:42.000Z
include/RavEngine/unordered_vector.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
1
2020-11-17T20:53:10.000Z
2020-12-01T20:27:36.000Z
include/RavEngine/unordered_vector.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
3
2020-12-22T02:40:39.000Z
2021-10-08T02:54:22.000Z
#pragma once #include <vector> #include <phmap.h> #include <functional> namespace RavEngine { /** The Unordered Vector provides: - O(1) erase by iterator All other complexities for valid behaviors are identical to a regular vector. Elements must be moveable. Note that the order of elements cannot be guareneed. */ template<typename T, typename vec = std::vector<T>> class unordered_vector{ vec underlying; public: typedef typename decltype(underlying)::iterator iterator_type; typedef typename decltype(underlying)::const_iterator const_iterator_type; typedef typename decltype(underlying)::size_type index_type; typedef typename decltype(underlying)::size_type size_type; /** Erase by iterator. Complexity is O(1). @param it the iterator to erase */ inline const_iterator_type erase(iterator_type it){ *it = std::move(underlying.back()); underlying.pop_back(); return it; } /** @return the underlying vector. Do not modify! */ inline const decltype(underlying)& get_underlying() const{ return underlying; } /** Erase by iterator. Complexity is O(n) @param value the data to erase */ inline const_iterator_type erase(const T& value){ auto it = std::find(underlying.begin(),underlying.end(),value); underlying.erase(it); return it; } /** Add an item to the container @param value the data to add @return a reference to the pushed item @note references may become invalid if an item is erased from the container */ inline T& insert(const T& value){ underlying.push_back(value); return underlying.back(); } /** Add an item to the container @param value the data to add @return a reference to the emplaced item @note references may become invalid if an item is erased from the container */ template<typename ... A> inline T& emplace(A ... args){ underlying.emplace_back(args...); return underlying.back(); } inline T& operator[](index_type idx){ return underlying[idx]; } const inline T& operator[](index_type idx) const{ return underlying[idx]; } inline T& at(index_type idx){ return underlying.at(idx); } const inline T& at(index_type idx) const{ return underlying.at(idx); } inline const_iterator_type begin() const{ return underlying.begin(); } inline const_iterator_type end() const{ return underlying.end(); } inline iterator_type end(){ return underlying.end(); } inline iterator_type begin(){ return underlying.begin(); } inline size_type size() const{ return underlying.size(); } inline void reserve(size_t num){ underlying.reserve(num); } inline void resize(size_t num){ underlying.resize(num); } inline bool empty() const{ return underlying.empty(); } inline void clear(){ underlying.clear(); } }; /** The Unordered Contiguous Set provides: - O(1) erase by value - O(1) erase by iterator All other complexities are identical to a regular vector. Elements must be moveable and hashable. Hashes must not have collisions. An imperfect hash will result in unpredictable behavior. Note that the order of elements cannot be guareneed. */ template<typename T,typename vec = std::vector<T>, typename _hash = std::hash<T>> class unordered_contiguous_set : public unordered_vector<T,vec>{ protected: phmap::flat_hash_map<size_t, typename unordered_vector<T,vec>::size_type> offsets; public: typedef typename unordered_vector<T,vec>::iterator_type iterator_type; typedef typename unordered_vector<T,vec>::iterator_type iterator; typedef typename unordered_vector<T,vec>::const_iterator_type const_iterator_type; typedef typename unordered_vector<T,vec>::const_iterator_type const_iterator; // for redundancy typedef typename unordered_vector<T,vec>::size_type index_type; typedef typename unordered_vector<T,vec>::size_type size_type; /** @return the hash for an element. This container does not need to include the element */ inline constexpr size_t hash_for(const T& value) const{ auto hasher = _hash(); return hasher(value); } /** Erase by iterator @param it the iterator to remove */ inline void erase(const typename unordered_vector<T,vec>::iterator_type& it){ // remove from the offset cache auto hasher = _hash(); auto hash = hasher(*it); if (offsets.contains(hash)) { // only erase if the container has the value offsets.erase(hash); // pop from back auto i = unordered_vector<T,vec>::erase(it); // update offset cache hash = hasher(*i); offsets[hash] = std::distance(this->begin(), it); } } /** Erase by element hash @param size_t hash the hash of the element to remove */ constexpr inline void erase_by_hash(size_t hash){ auto it = this->begin() + offsets[hash]; erase(it); } /** Erase by value @param value item to remove */ inline void erase(const T& value){ auto valuehash = _hash()(value); if (offsets.contains(valuehash)) { auto it = this->begin() + offsets[valuehash]; erase(it); } } inline void insert(const T& value){ auto hashcode = _hash()(value); if (!this->offsets.contains(hashcode)){ offsets.emplace(hashcode,this->size()); unordered_vector<T,vec>::insert(value); } } inline void contains(const T& value){ auto valuehash = _hash()(value); return offsets.contains(valuehash); } }; }
27.64455
188
0.652323
Ravbug
53ba76c61e98337aadf73ebd3e280e4db93c4c91
1,827
cpp
C++
book/CH02/S16_Presenting_an_image.cpp
THISISAGOODNAME/vkCookBook
d022b4151a02c33e5c58534dc53ca39610eee7b5
[ "MIT" ]
5
2019-03-02T16:29:15.000Z
2021-11-07T11:07:53.000Z
book/CH02/S16_Presenting_an_image.cpp
THISISAGOODNAME/vkCookBook
d022b4151a02c33e5c58534dc53ca39610eee7b5
[ "MIT" ]
null
null
null
book/CH02/S16_Presenting_an_image.cpp
THISISAGOODNAME/vkCookBook
d022b4151a02c33e5c58534dc53ca39610eee7b5
[ "MIT" ]
2
2018-07-10T18:15:40.000Z
2020-01-03T04:02:32.000Z
// // Created by aicdg on 2017/6/19. // // // Chapter: 02 Image Presentation // Recipe: 16 Presenting an image #include "S16_Presenting_an_image.h" namespace VKCookbook { bool PresentImage(VkQueue queue, std::vector<VkSemaphore> rendering_semaphores, std::vector<PresentInfo> images_to_present) { VkResult result; std::vector<VkSwapchainKHR> swapchains; std::vector<uint32_t> image_indices; for( auto & image_to_present : images_to_present ) { swapchains.emplace_back( image_to_present.Swapchain ); image_indices.emplace_back( image_to_present.ImageIndex ); } VkPresentInfoKHR present_info = { VK_STRUCTURE_TYPE_PRESENT_INFO_KHR, // VkStructureType sType nullptr, // const void* pNext static_cast<uint32_t>(rendering_semaphores.size()), // uint32_t waitSemaphoreCount rendering_semaphores.data(), // const VkSemaphore * pWaitSemaphores static_cast<uint32_t>(swapchains.size()), // uint32_t swapchainCount swapchains.data(), // const VkSwapchainKHR * pSwapchains image_indices.data(), // const uint32_t * pImageIndices nullptr // VkResult* pResults }; result = vkQueuePresentKHR( queue, &present_info ); switch( result ) { case VK_SUCCESS: return true; default: return false; } } }
41.522727
116
0.509031
THISISAGOODNAME
53bf0759144880c94ad882e74dd18a42bbed8403
910
cpp
C++
lab2/Q1.cpp
jasonsie88/OOP-and-DS
fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28
[ "MIT" ]
null
null
null
lab2/Q1.cpp
jasonsie88/OOP-and-DS
fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28
[ "MIT" ]
null
null
null
lab2/Q1.cpp
jasonsie88/OOP-and-DS
fdf76d6e9b3c70e5c7a97401dfe93984b63e5e28
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; class Student { private: string name; string studentID; int score; public: Student(){ } Student(string name, string studentID, int score){ Student:: name=name; Student:: studentID=studentID; Student:: score=score; } string getName(){ return Student:: name; } string getStudentID(){ return Student:: studentID; } int getScore(){ return Student:: score; } }; int main() { string name; string studentID; int score; Student mStudent; cin >> name >> studentID >> score; mStudent = Student(name, studentID, score); cout << mStudent.getName() << "'s studentID is " << mStudent.getStudentID() << " and score is " << mStudent.getScore() << "." << endl; return 0; }
21.162791
80
0.552747
jasonsie88
53c1d1bfbc4f270184ff9e72daeba7920a071150
5,895
cpp
C++
source/QtCore/QFutureWatcherBaseSlots.cpp
kenny1818/qt4xhb
f62f40d8b17acb93761014317b52da9f919707d0
[ "MIT" ]
1
2021-03-07T10:44:03.000Z
2021-03-07T10:44:03.000Z
source/QtCore/QFutureWatcherBaseSlots.cpp
kenny1818/qt4xhb
f62f40d8b17acb93761014317b52da9f919707d0
[ "MIT" ]
null
null
null
source/QtCore/QFutureWatcherBaseSlots.cpp
kenny1818/qt4xhb
f62f40d8b17acb93761014317b52da9f919707d0
[ "MIT" ]
2
2020-07-19T03:28:08.000Z
2021-03-05T18:07:20.000Z
/* Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4 Copyright (C) 2021 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com> */ /* DO NOT EDIT THIS FILE - the content was created using a source code generator */ #include "QFutureWatcherBaseSlots.h" QFutureWatcherBaseSlots::QFutureWatcherBaseSlots( QObject * parent ) : QObject( parent ) { } QFutureWatcherBaseSlots::~QFutureWatcherBaseSlots() { } void QFutureWatcherBaseSlots::started() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "started()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::finished() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "finished()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::canceled() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "canceled()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::paused() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "paused()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::resumed() { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resumed()" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); hb_vmEvalBlockV( cb, 1, pSender ); hb_itemRelease( pSender ); } } void QFutureWatcherBaseSlots::resultReadyAt( int resultIndex ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resultReadyAt(int)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pResultIndex = hb_itemPutNI( NULL, resultIndex ); hb_vmEvalBlockV( cb, 2, pSender, pResultIndex ); hb_itemRelease( pSender ); hb_itemRelease( pResultIndex ); } } void QFutureWatcherBaseSlots::resultsReadyAt( int beginIndex, int endIndex ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "resultsReadyAt(int,int)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pBeginIndex = hb_itemPutNI( NULL, beginIndex ); PHB_ITEM pEndIndex = hb_itemPutNI( NULL, endIndex ); hb_vmEvalBlockV( cb, 3, pSender, pBeginIndex, pEndIndex ); hb_itemRelease( pSender ); hb_itemRelease( pBeginIndex ); hb_itemRelease( pEndIndex ); } } void QFutureWatcherBaseSlots::progressRangeChanged( int minimum, int maximum ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressRangeChanged(int,int)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pMinimum = hb_itemPutNI( NULL, minimum ); PHB_ITEM pMaximum = hb_itemPutNI( NULL, maximum ); hb_vmEvalBlockV( cb, 3, pSender, pMinimum, pMaximum ); hb_itemRelease( pSender ); hb_itemRelease( pMinimum ); hb_itemRelease( pMaximum ); } } void QFutureWatcherBaseSlots::progressValueChanged( int progressValue ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressValueChanged(int)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pProgressValue = hb_itemPutNI( NULL, progressValue ); hb_vmEvalBlockV( cb, 2, pSender, pProgressValue ); hb_itemRelease( pSender ); hb_itemRelease( pProgressValue ); } } void QFutureWatcherBaseSlots::progressTextChanged( const QString & progressText ) { QObject * object = qobject_cast< QObject * >( sender() ); PHB_ITEM cb = Qt4xHb::Signals_return_codeblock( object, "progressTextChanged(QString)" ); if( cb ) { PHB_ITEM pSender = Qt4xHb::Signals_return_qobject( object, "QFUTUREWATCHERBASE" ); PHB_ITEM pProgressText = hb_itemPutC( NULL, QSTRINGTOSTRING( progressText ) ); hb_vmEvalBlockV( cb, 2, pSender, pProgressText ); hb_itemRelease( pSender ); hb_itemRelease( pProgressText ); } } void QFutureWatcherBaseSlots_connect_signal( const QString & signal, const QString & slot ) { QFutureWatcherBase * obj = qobject_cast< QFutureWatcherBase * >( Qt4xHb::getQObjectPointerFromSelfItem() ); if( obj ) { QFutureWatcherBaseSlots * s = QCoreApplication::instance()->findChild<QFutureWatcherBaseSlots *>(); if( s == NULL ) { s = new QFutureWatcherBaseSlots(); s->moveToThread( QCoreApplication::instance()->thread() ); s->setParent( QCoreApplication::instance() ); } hb_retl( Qt4xHb::Signals_connection_disconnection( s, signal, slot ) ); } else { hb_retl( false ); } }
26.917808
110
0.674979
kenny1818
53cc3cee63f5e72f8f8ef2ed867e47459b546d2b
8,973
cpp
C++
CGALib/src/Model.cpp
jorge-jcc/MarioCraftv2
f0870721685452b2b39df1004f4be26f2dfb3629
[ "Xnet", "X11" ]
null
null
null
CGALib/src/Model.cpp
jorge-jcc/MarioCraftv2
f0870721685452b2b39df1004f4be26f2dfb3629
[ "Xnet", "X11" ]
null
null
null
CGALib/src/Model.cpp
jorge-jcc/MarioCraftv2
f0870721685452b2b39df1004f4be26f2dfb3629
[ "Xnet", "X11" ]
null
null
null
/* * Model.cpp * * Created on: 13/09/2016 * Author: rey */ #include "Headers/Model.h" #include "Headers/TimeManager.h" #include "Headers/mathUtil.h" Model::Model() { this->aabb.mins.x = FLT_MAX; this->aabb.mins.y = FLT_MAX; this->aabb.mins.z = FLT_MAX; this->aabb.maxs.x = -FLT_MAX; this->aabb.maxs.y = -FLT_MAX; this->aabb.maxs.z = -FLT_MAX; this->animationIndex = 0; } Model::~Model() { for (GLuint i = 0; i < this->meshes.size(); i++){ delete this->meshes[i]->bones; delete this->meshes[i]; } for (int i = 0; i < this->textureLoaded.size(); i++) delete this->textureLoaded[i]; } void Model::render(glm::mat4 parentTrans) { float runningTime = TimeManager::Instance().GetRunningTime(); //float runningTime = TimeManager::Instance().DeltaTime; for (GLuint i = 0; i < this->meshes.size(); i++) { this->meshes[i]->setShader(this->getShader()); this->meshes[i]->setPosition(this->getPosition()); this->meshes[i]->setScale(this->getScale()); this->meshes[i]->setOrientation(this->getOrientation()); if(scene->mNumAnimations > 0){ this->meshes[i]->bones->setAnimationIndex(this->animationIndex); if(this->meshes[i]->bones != nullptr){ shader_ptr->setInt("numBones", this->meshes[i]->bones->getNumBones()); std::vector<glm::mat4> transforms; this->meshes[i]->bones->bonesTransform(runningTime, transforms, scene); for (unsigned int j = 0; j < transforms.size(); j++) { std::stringstream ss; ss << "bones[" << j << "]"; shader_ptr->setMatrix4(ss.str(), 1, GL_FALSE, glm::value_ptr(m_GlobalInverseTransform * transforms[j])); } } else parentTrans = m_GlobalInverseTransform * parentTrans; } this->meshes[i]->render(parentTrans); glActiveTexture(GL_TEXTURE0); shader_ptr->setInt("numBones", 0); } } void Model::loadModel(const std::string & path) { // Lee el archivo via ASSIMP scene = importer.ReadFile(path.c_str(), aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_GenSmoothNormals | aiProcess_CalcTangentSpace); // Revisa errores if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) // if is Not Zero { std::cout << "ERROR::ASSIMP:: " << importer.GetErrorString() << std::endl; return; } CopyMat(scene->mRootNode->mTransformation, this->m_GlobalInverseTransform); this->m_GlobalInverseTransform = glm::inverse( this->m_GlobalInverseTransform); // Recupera el path del directorio del archivo. this->directory = path.substr(0, path.find_last_of('/')); // Se procesa el nodo raiz recursivamente. this->processNode(scene->mRootNode, scene); // Se crea la SBB this->sbb.c = glm::vec3((this->aabb.mins.x + this->aabb.maxs.x) / 2.0f, (this->aabb.mins.y + this->aabb.maxs.y) / 2.0f, (this->aabb.mins.z + this->aabb.maxs.z) / 2.0f); /*this->sbb.ratio = sqrt( pow(this->aabb.mins.x - this->aabb.maxs.x, 2) + pow(this->aabb.mins.y - this->aabb.maxs.y, 2) + pow(this->aabb.mins.z - this->aabb.maxs.z, 2)) / 2.0f;*/ float disX = fabs(this->aabb.mins.x - this->aabb.maxs.x); float disY = fabs(this->aabb.mins.y - this->aabb.maxs.y); float disZ = fabs(this->aabb.mins.z - this->aabb.maxs.z); float rtmp = std::max(disX, disY); rtmp = std::max(rtmp, disZ); this->sbb.ratio = rtmp / 2.f; // Se crea la obb this->obb.c = this->sbb.c; /*this->obb.e.x = aabb.maxs.x - aabb.mins.x; this->obb.e.y = aabb.maxs.y - aabb.mins.y; this->obb.e.z = aabb.maxs.z - aabb.mins.z;*/ this->obb.e = (aabb.maxs - aabb.mins) / 2.0f; this->obb.u = glm::quat(0.0, 0.0, 0.0, 1); } void Model::processNode(aiNode* node, const aiScene* scene) { // Procesa cada maya del nodo actual for (GLuint i = 0; i < node->mNumMeshes; i++) { aiMesh* mesh = scene->mMeshes[node->mMeshes[i]]; Mesh * meshModel = this->processMesh(mesh, scene); Bones * bones = new Bones(meshModel->getVAO(), mesh->mNumVertices); bones->loadBones(i, mesh); meshModel->bones = bones; this->meshes.push_back(meshModel); } for (GLuint i = 0; i < node->mNumChildren; i++) { this->processNode(node->mChildren[i], scene); } } Mesh * Model::processMesh(aiMesh* mesh, const aiScene* scene) { std::vector<AbstractModel::Vertex> vertices; std::vector<GLuint> indices; std::vector<Texture*> textures; // Recorre los vertices de cada maya for (GLuint i = 0; i < mesh->mNumVertices; i++) { AbstractModel::Vertex vertex; glm::vec3 vector; // Compute the AABB if (mesh->mVertices[i].x < aabb.mins.x) aabb.mins.x = mesh->mVertices[i].x; if (mesh->mVertices[i].x > aabb.maxs.x) aabb.maxs.x = mesh->mVertices[i].x; if (mesh->mVertices[i].y < aabb.mins.y) aabb.mins.y = mesh->mVertices[i].y; if (mesh->mVertices[i].y > aabb.maxs.y) aabb.maxs.y = mesh->mVertices[i].y; if (mesh->mVertices[i].z < aabb.mins.z) aabb.mins.z = mesh->mVertices[i].z; if (mesh->mVertices[i].z > aabb.maxs.z) aabb.maxs.z = mesh->mVertices[i].z; // Positions vector.x = mesh->mVertices[i].x; vector.y = mesh->mVertices[i].y; vector.z = mesh->mVertices[i].z; vertex.m_pos = vector; // Normals vector.x = mesh->mNormals[i].x; vector.y = mesh->mNormals[i].y; vector.z = mesh->mNormals[i].z; vertex.m_normal = vector; // Texture Coordinates if (mesh->mTextureCoords[0]) // Esto se ejecuta si la maya contiene texturas. { glm::vec2 vec; // Un vertice puede contener hasta 8 diferentes coordenadas de textura, unicamente se considera // que los modelos tiene una coordenada de textura por vertice, y corresponde a la primera en el arreglo. vec.x = mesh->mTextureCoords[0][i].x; vec.y = mesh->mTextureCoords[0][i].y; vertex.m_tex = vec; } else vertex.m_tex = glm::vec2(0.0f, 0.0f); vertices.push_back(vertex); } // Se recorre cada cara de la maya (una cara es un triangulo en la maya) y recupera su correspondiente indice del vertice. for (GLuint i = 0; i < mesh->mNumFaces; i++) { aiFace face = mesh->mFaces[i]; // Recupera todos los indices de la cara y los almacena en el vector de indices for (GLuint j = 0; j < face.mNumIndices; j++) indices.push_back(face.mIndices[j]); } // Process materials if (mesh->mMaterialIndex >= 0) { aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex]; // We assume a convention for sampler names in the shaders. Each diffuse texture should be named // as 'texture_diffuseN' where N is a sequential number ranging from 1 to MAX_SAMPLER_NUMBER. // Same applies to other texture as the following list summarizes: // Diffuse: texture_diffuseN // Specular: texture_specularN // Normal: texture_normalN // 1. Diffuse maps std::vector<Texture*> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE, "texture_diffuse"); textures.insert(textures.end(), diffuseMaps.begin(), diffuseMaps.end()); // 2. Specular maps std::vector<Texture*> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR, "texture_specular"); textures.insert(textures.end(), specularMaps.begin(), specularMaps.end()); // 3. Normal maps std::vector<Texture*> normalMaps = this->loadMaterialTextures(material, aiTextureType_NORMALS, "texture_normal"); textures.insert(textures.end(), normalMaps.begin(), normalMaps.end()); // 4. Height maps std::vector<Texture*> heightMaps = this->loadMaterialTextures(material, aiTextureType_HEIGHT, "texture_height"); textures.insert(textures.end(), heightMaps.begin(), heightMaps.end()); } Mesh * meshModel = new Mesh(vertices, indices, textures); // Regresa la maya de un objeto creado de los datos extraidos. return meshModel; } std::vector<Texture*> Model::loadMaterialTextures(aiMaterial* mat, aiTextureType type, std::string typeName) { std::vector<Texture*> textures; for (GLuint i = 0; i < mat->GetTextureCount(type); i++) { aiString str; mat->GetTexture(type, i, &str); // Verifica si la textura fue cargada antes y si es as�, continua con la siguiente iteracion: en caso controaio se salta la carga GLboolean skip = false; for (GLuint j = 0; j < textureLoaded.size(); j++) { if (textureLoaded[j]->getFileName() == str.C_Str()) { textures.push_back(textureLoaded[j]); skip = true; break; } } if (!skip) { std::string filename = std::string(str.C_Str()); filename = this->directory + '/' + filename; Texture * texture = new Texture(GL_TEXTURE_2D, filename); texture->load(); texture->setType(typeName); textures.push_back(texture); this->textureLoaded.push_back(texture); // Store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures. } } return textures; } bool Model::rayPicking(glm::vec3 init, glm::vec3 end, glm::vec3 &intersection) { return false; }
36.77459
146
0.657528
jorge-jcc